Files
videoreg.ru/scripts/rebuild-v2/fetch.py
T
2026-10-26 19:08:48 +03:00

27 lines
2.1 KiB
Python

#!/usr/bin/env python3
import argparse,hashlib,json,subprocess,time,re
from pathlib import Path
from urllib.parse import urlencode
ROOT=Path(__file__).resolve().parents[2]
RAW=ROOT/'docs/rebuild-v2/raw';RAW.mkdir(parents=True,exist_ok=True)
def fetch(url,name,timeout=65):
rate_flag=RAW/'wayback-rate-limit.json'
if 'web.archive.org' in url and rate_flag.exists():raise RuntimeError('Wayback HTTP429 stop marker exists; no further requests on currentIP, no bypass.')
dest=RAW/name;headers=dest.with_suffix(dest.suffix+'.headers')
started=time.time()
r=subprocess.run(['curl','--compressed','-sS','-L','--max-time',str(timeout),'-D',str(headers),'-o',str(dest),'-w','%{http_code}\n%{url_effective}',url],capture_output=True,text=True)
if not dest.exists():dest.write_bytes(b'')
b=dest.read_bytes();parts=r.stdout.splitlines()
object_dir=RAW/'objects';object_dir.mkdir(exist_ok=True)
object_file=object_dir/(hashlib.sha256(b).hexdigest()+'.bin')
if not object_file.exists():object_file.write_bytes(b)
rec=dict(url=url,raw=str(dest.relative_to(ROOT)),immutableRaw=str(object_file.relative_to(ROOT)),sha256=hashlib.sha256(b).hexdigest(),bytes=len(b),httpStatus=parts[0] if parts else None,effectiveUrl=parts[1] if len(parts)>1 else None,curlExit=r.returncode,error=r.stderr.strip(),checkedAt=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),seconds=round(time.time()-started,2))
with (RAW/'requests.jsonl').open('a') as f:f.write(json.dumps(rec,ensure_ascii=False)+'\n')
if 'web.archive.org' in url and rec['httpStatus']=='429':
retry=re.findall(r'(?im)^retry-after:\s*(.*)$',headers.read_text(errors='replace'))
rate_flag.write_text(json.dumps(dict(url=url,observedAt=rec['checkedAt'],retryAfterRaw=retry,action='Stop all Wayback requests on currentIP; no bypass'),indent=2)+'\n')
print(json.dumps({k:rec[k] for k in ['raw','httpStatus','bytes','curlExit','error']}),flush=True)
return rec
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('url');p.add_argument('name');p.add_argument('--timeout',type=int,default=65);a=p.parse_args();fetch(a.url,a.name,a.timeout)