File size: 1,589 Bytes
88248d0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | """Download the four source revisions, verifying hashes before installing each PDF."""
import argparse
from hashlib import sha256
import os
from pathlib import Path
from tempfile import NamedTemporaryFile
from urllib.request import Request, urlopen
from unblind import rows
def fetch(directory):
directory.mkdir(parents=True, exist_ok=True)
for book in rows("sources.jsonl"):
if book["issue"] is not None:
continue
target = directory / f'wsp{book["series"]}.pdf'
if target.exists():
if sha256(target.read_bytes()).hexdigest() != book["sha256"]:
raise ValueError(f"Existing file differs from the source revision: {target}")
continue
request = Request(book["url"], headers={"User-Agent":"Folio-Kestrel PDF orientation evaluation"})
with urlopen(request, timeout=90) as response:
data = response.read(book["bytes"]+1)
if len(data) != book["bytes"] or sha256(data).hexdigest() != book["sha256"]:
raise ValueError(f"Source revision differs: {book['url']}")
tmp = None
try:
with NamedTemporaryFile(dir=directory, delete=False) as f:
tmp = Path(f.name)
f.write(data)
os.link(tmp,target)
finally:
if tmp is not None:
tmp.unlink(missing_ok=True)
print(target,flush=True)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("directory", type=Path)
fetch(parser.parse_args().directory)
|