Files

34 lines
2.2 KiB
Python

from pathlib import Path
import json,sys,hashlib,concurrent.futures
from urllib.parse import urlsplit
sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch
from importlib.machinery import SourceFileLoader
m=SourceFileLoader('corpus',str(Path(__file__).parent/'download-corpus.py'))
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={r['url'] for r in [json.loads(x) for x in (RAW/'requests.jsonl').read_text().splitlines()]}
# Existing successful captures are immutable and reused, not re-fetched.
for path,name in [('/auto.shtml','auto-20070228153116.html'),('/faq.shtml','faq-www.html')]:
for item in plan:
if item['normalizedPath']==path:item['rawFile']='docs/rebuild-v2/raw/'+name
def norm(url):
from urllib.parse import parse_qsl,urlencode
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 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'] and r[1]<'20150101']
candidates=[(item['snapshot'],'http://www.videoreg.ru:80'+item['normalizedPath'])]
if versions:
r=versions[-1];candidates.append((r[1],'http://www.videoreg.ru:80'+item['normalizedPath']))
for i,(ts,url) in enumerate(candidates):
replay='https://web.archive.org/web/'+ts+'id_/'+url
if replay in attempts:continue
name='pages/'+hashlib.sha256((item['normalizedPath']+ts+str(i)).encode()).hexdigest()[:16]+'.html'
result=fetch(replay,name,45)
if result['httpStatus']=='200' and result['bytes']>500:
item['rawFile']=result['raw'];item['snapshot']=ts;item['replayUrl']=replay;return
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:list(ex.map(work,[x for x in plan if x['disposition']=='fetch']))
(ROOT/'docs/rebuild-v2/discovery-plan.json').write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n')
print('recovered bodies',sum((ROOT/x['rawFile']).exists() and (ROOT/x['rawFile']).stat().st_size>500 for x in plan if x['disposition']=='fetch'),flush=True)