#!/usr/bin/env python3
# spear.cx: Krypto-DB-Threads abrufen (Seite 1), HTML+Text speichern
import subprocess, json, os, re, html, time

CD = os.path.expanduser('~/krypto-angriff')
COOKIE = os.path.expanduser('~/.hermes/cache/scratch/mode_leaks/spear_cookies.txt')
THREADS_DIR = CD + '/spear_threads'
os.makedirs(THREADS_DIR, exist_ok=True)

d = json.load(open(CD + '/spear_crypto_threads.json'))
urls = set()
for kw, ls in d.items():
    for l in ls:
        u = l['url']
        if u.endswith('action=lastpost') or re.search(r'\?page=\d+', u):
            continue
        urls.add(u)

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

manifest = {}
for i, u in enumerate(sorted(urls)):
    slug = re.sub(r'[^A-Za-z0-9]+', '-', u.split('spear.cx/')[1])[:90]
    fn = THREADS_DIR + '/' + slug + '.html'
    if os.path.exists(fn):
        manifest[u] = fn
        continue
    b = curl(u)
    if len(b) < 500 or 'One or more errors have occurred' in b[:2000]:
        time.sleep(2)
        b = curl(u)
    open(fn, 'w').write(b)
    manifest[u] = fn
    print(slug[:70], len(b), flush=True)
    time.sleep(2.5)
json.dump(manifest, open(THREADS_DIR + '/manifest.json', 'w'), indent=1)
print('DONE', len(manifest), flush=True)
