#!/usr/bin/python3
import subprocess, time, re, json, os, html as H
COOKIE = os.path.expanduser('~/.hermes/cache/scratch/mode_leaks/spear_cookies.txt')
OUT = 'spear_dt_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):
    curl(['-D','/tmp/spear_hdr2.txt','-o','/tmp/spear_body2.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'])
    for _ in range(3):
        hdr=open('/tmp/spear_hdr2.txt').read()
        m=re.search(r'[Ll]ocation: (\S+)',hdr)
        if not m:
            b=open('/tmp/spear_body2.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)
            curl(['-D','/tmp/spear_hdr2.txt','-o','/tmp/spear_body2.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'])
            continue
        return curl([m.group(1).strip()]).stdout
    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 = json.load(open(OUT)) if os.path.exists(OUT) else {}
key = get_key()
print('key:',bool(key),flush=True)
for kw in ['tradingview','myfxbook','forexfactory','mql5','forex leads','day trading','trading signal','binary options','pocket option','ftmo']:
    if kw in results: print(kw,'done',flush=True); continue
    body = search(kw,key)
    results[kw]=parse(body)
    print(kw,len(results[kw]),'hits',flush=True)
    json.dump(results,open(OUT,'w'),indent=1)
    time.sleep(20)
print('FERTIG')
