from pathlib import Path import sys,json,hashlib,concurrent.futures,time from urllib.parse import urlsplit,parse_qsl,urlencode sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch ROOT=Path(__file__).resolve().parents[2];RAW=ROOT/'docs/rebuild-v2/raw' plan=json.loads((ROOT/'docs/rebuild-v2/discovery-plan.json').read_text());all=json.loads((RAW/'cdx-all-html-captures.json').read_text());attempts={json.loads(x)['url'] for x in (RAW/'requests.jsonl').read_text().splitlines()} def norm(url): u=urlsplit(url);q=[(k,v) for k,v in parse_qsl(u.query) if k!='sid'];return u.path+('?' +urlencode(sorted(q)) if q else '') def saveplan(): (ROOT/'docs/rebuild-v2/discovery-plan.json').write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n') def work(item): dest=ROOT/item['rawFile'] if dest.exists() and dest.stat().st_size>500:return versions=[r for r in all[1:] if isinstance(r,list) and norm(r[2])==item['normalizedPath']] # Prefer the most recent documented pre-2015 version of each distinct body. unique={} for r in versions: if r[1]<'20150101':unique[r[5]]=r ordered=sorted(unique.values(),key=lambda r:r[1],reverse=True) candidates=[] for r in ordered: for original in [r[2],'http://www.videoreg.ru'+item['normalizedPath'],'http://videoreg.ru'+item['normalizedPath']]: candidates.append((r[1],original)) for ts,original in candidates: url='https://web.archive.org/web/'+ts+'id_/'+original if url in attempts:continue attempts.add(url);name='pages/'+hashlib.sha256(url.encode()).hexdigest()[:20]+'.html';rec=fetch(url,name,30) if rec['httpStatus']=='200' and rec['bytes']>500: item['rawFile']=rec['raw'];item['snapshot']=ts;item['replayUrl']=rec['effectiveUrl'];return time.sleep(.35) with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex: for _ in ex.map(work,[x for x in plan if x['disposition']=='fetch']):saveplan() saveplan();print('RECOVERED',sum((ROOT/x['rawFile']).exists() and (ROOT/x['rawFile']).stat().st_size>500 for x in plan if x['disposition']=='fetch'),flush=True)