#!/usr/bin/env python3
# spear.cx Forex-Suche via POST + my_post_key (goldsammler1)
import subprocess, time, re, json, os, html as H

COOKIE = os.path.expanduser('~/.hermes/cache/scratch/mode_leaks/spear_cookies.txt')
OUT = os.path.expanduser('~/investoren-daten/forex/spear_hits.json')
UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'

def curl(args):
    return subprocess.run(['curl', '-s', '-m', '90', '-A', UA, '-b', COOKIE, '-c', COOKIE,
                           '--compressed'] + args, capture_output=True, text=True)

def get_key():
    h = curl(['https://spear.cx/search.php']).stdout
    m = re.search(r'my_post_key = "([a-f0-9]{32})"', h)
    return m.group(1) if m else None

def search(kw, key):
    h = curl(['-D', '/tmp/spear_hdr.txt', '-o', '/tmp/spear_body.html', '-X', 'POST',
              'https://spear.cx/search.php', '--data',
              f'my_post_key={key}&action=do_search&keywords={kw.replace(" ", "+")}&postthread=1&showresults=threads&submit=Search']).stdout
    for _ in range(3):
        hdr = open('/tmp/spear_hdr.txt').read()
        m = re.search(r'[Ll]ocation: (\S+)', hdr)
        if not m:
            # flood?
            b = open('/tmp/spear_body.html', errors='replace').read()
            mm = re.search(r'(\d+)\s*seconds', b)
            w = int(mm.group(1)) + 3 if mm else 35
            print(f'{kw}: flood {w}s', flush=True); time.sleep(w)
            h = curl(['-D', '/tmp/spear_hdr.txt', '-o', '/tmp/spear_body.html', '-X', 'POST',
                      'https://spear.cx/search.php', '--data',
                      f'my_post_key={key}&action=do_search&keywords={kw.replace(" ", "+")}&postthread=1&showresults=threads&submit=Search']).stdout
            continue
        loc = m.group(1).strip()
        body = curl([loc]).stdout
        return body
    return ''

def parse(h):
    out = []
    for m in re.finditer(r'href="((?:https://spear\.cx/)?Thread-[^"?]+)\?highlight=[^"]*"[^>]*id="tid_(\d+)"[^>]*>([^<]+)<', h):
        u = m.group(1)
        if not u.startswith('http'):
            u = 'https://spear.cx/' + u
        out.append({'tid': m.group(2), 'u': u, 't': H.unescape(m.group(3)).strip()})
    return out

results = {}
if os.path.exists(OUT):
    results = json.load(open(OUT))

key = get_key()
print('key:', bool(key), flush=True)
for kw in ['forex', 'trader', 'ic markets', 'octafx', 'roboforex', 'metatrader', 'trading signal', 'fxcm', 'exness', 'fbs']:
    if kw in results:
        print(kw, 'done', flush=True); continue
    body = search(kw, key)
    ls = parse(body)
    results[kw] = ls
    print(kw, len(ls), 'threads', flush=True)
    for l in ls: print('  ', l['t'][:70], '|', l['u'][:90], flush=True)
    json.dump(results, open(OUT, 'w'), indent=1, ensure_ascii=False)
    time.sleep(35)
print('DONE')
