#!/usr/bin/env python3
# spear.cx Krypto-Suche per curl + Login-Cookie (goldsammler1), 33s-Rate-Limit
import subprocess, time, re, json, os, html
CD = os.path.expanduser('~/krypto-angriff')
COOKIE = os.path.expanduser('~/.hermes/cache/scratch/mode_leaks/spear_cookies.txt')
OUT = CD + '/spear_crypto_threads.json'
KWS = ['bitcoin', 'crypto', 'krypto', 'coinpayments', 'coingate', 'binance', 'coinbase', 'wallet', 'coinmarketcap', 'btc-echo', 'telegram']
def curl(url):
    cmd = ['curl', '-s', '-m', '40', '-L', '-A', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', '-b', COOKIE, url]
    p = subprocess.run(cmd, capture_output=True, text=True)
    return p.stdout
# Login-Check
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(6):
        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
        url = url.split('&')[0]
        t = html.unescape(title.strip())
        if t and url not in seen:
            seen.add(url); links.append({'url': url, 't': t})
    res[kw] = links
    json.dump(res, open(OUT, 'w'), indent=1, ensure_ascii=False)
    print(kw, '->', len(links), flush=True)
    time.sleep(33)
print('DONE', flush=True)
