#!/usr/bin/env python3
# PRESALE-JAGD: spear.cx Thread-Suche nach ICO-/Presale-Listen (goldsammler1, 33s-Limit)
import subprocess, time, re, json, os, html

COOKIE = os.path.expanduser('~/.hermes/cache/scratch/mode_leaks/spear_cookies.txt')
OUT = os.path.expanduser('~/investoren-daten/presale/spear_presale_threads.json')

KWS = ['presale', 'ico', 'ido', 'launchpad', 'ico investors',
       'ico database', 'token sale', 'coinlist', 'airdrop']

def curl(url):
    cmd = ['curl', '-s', '-m', '40', '-L', '-A', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', '-b', COOKIE, url]
    return subprocess.run(cmd, capture_output=True, text=True).stdout

b = curl('https://spear.cx/member.php?action=profile&uid=9233')
logged = 'goldsammler' in b.lower() or 'Log out' in b or 'Ausloggen' in b
print('login_ok:', logged, flush=True)

res = json.load(open(OUT)) if os.path.exists(OUT) else {}
for kw in KWS:
    if kw in res:
        continue
    body = ''
    for att in range(8):
        body = curl('https://spear.cx/search.php?action=do_search&keywords=' + kw.replace(' ', '+') + '&postthread=1&forums[]=all&findthreadst=1&postdate=0&pddir=1&sortby=lastpost&sortordr=desc&showresults=threads&submit=Search')
        m = re.search(r'wait another (\d+) seconds', body)
        if m:
            print(kw, 'flood', m.group(1), flush=True); time.sleep(int(m.group(1)) + 4); continue
        break
    links, seen = [], set()
    for href, title in re.findall(r'href="(https?://spear\.cx/Thread-[^\"]+|Thread-[^\"]+)"[^>]*>([^<]{1,200})', body):
        url = href if href.startswith('http') else 'https://spear.cx/' + href
        u = url.split('&')[0]
        if u not in seen and 'action=lastpost' not in url:
            seen.add(u); links.append({'u': u, 't': html.unescape(title.strip())})
    res[kw] = links
    print(kw, len(links), flush=True)
    json.dump(res, open(OUT, 'w'), indent=1, ensure_ascii=False)
    time.sleep(34)
print('FERTIG', flush=True)
