Files

51 lines
3.1 KiB
Python

#!/usr/bin/env python3
"""Torrent for a full-client release tree, web-seeded from the update server (BEP 19).
make_torrent.py --tree <dir containing OctoWoW/> --files <manifest.json> --release 20261124 --out X.torrent
The file set and order come from the release manifest (the same 4949 files as install.txt), never from a live client
folder, so user data (WTF, Cache) and later updates are never in it. One read pass makes the SHA-1 pieces and checks
every file's SHA-256 against the manifest; any mismatch stops. Web seed: <base>/install/<release>/ (+ torrent name
"OctoWoW" + path), the same tree OctoUpdater/octo-install.sh use, so the torrent completes even with no peers.
"""
import argparse, hashlib, json, os, time
def benc(x):
if isinstance(x, int): return b'i%de' % x
if isinstance(x, str): x = x.encode()
if isinstance(x, bytes): return b'%d:%s' % (len(x), x)
if isinstance(x, list): return b'l' + b''.join(map(benc, x)) + b'e'
if isinstance(x, dict): return b'd' + b''.join(benc(k) + benc(x[k]) for k in sorted(x)) + b'e'
raise TypeError(x)
def main():
a = argparse.ArgumentParser()
a.add_argument('--tree', required=True); a.add_argument('--files', required=True); a.add_argument('--release', required=True)
a.add_argument('--out', required=True); a.add_argument('--piece', type=int, default=16 << 20)
a.add_argument('--webseed', default='https://dl.hybridgateway.eu/octo/install/{release}/')
a.add_argument('--tracker', action='append', default=[])
x = a.parse_args()
rows = sorted(json.load(open(x.files)), key=lambda r: r['path'])
pieces = []; buf = bytearray(); total = 0; files = []; t0 = time.time()
for n, r in enumerate(rows):
p = os.path.join(x.tree, r['path']); h = hashlib.sha256(); size = 0
with open(p, 'rb') as f:
for b in iter(lambda: f.read(8 << 20), b''):
h.update(b); size += len(b); buf += b
while len(buf) >= x.piece:
pieces.append(hashlib.sha1(buf[:x.piece]).digest()); del buf[:x.piece]
if size != r['size'] or h.hexdigest() != r['sha256']: raise SystemExit(f'{r["path"]} does not match the release manifest')
total += size; files.append({'length': size, 'path': r['path'].split('/')[1:]})
if n % 500 == 0: print(f' {n}/{len(rows)} files, {total / 1e9:.1f} GB, {time.time() - t0:.0f} s', flush=True)
if buf: pieces.append(hashlib.sha1(buf).digest())
info = {'name': 'OctoWoW', 'piece length': x.piece, 'pieces': b''.join(pieces), 'files': files}
t = {'info': info, 'url-list': [x.webseed.format(release=x.release)], 'creation date': int(time.time()),
'created by': 'OctoWoW make_torrent.py', 'comment': f'OctoWoW client release {x.release} (web-seeded by dl.hybridgateway.eu)'}
if x.tracker: t['announce'] = x.tracker[0]; t['announce-list'] = [[u] for u in x.tracker]
open(x.out, 'wb').write(benc(t))
ih = hashlib.sha1(benc(info)).hexdigest()
print(f'{x.out}: {len(files)} files, {total} bytes, {len(pieces)} pieces, infohash {ih}')
print(f'magnet:?xt=urn:btih:{ih}&dn=OctoWoW&ws={t["url-list"][0]}' + ''.join(f'&tr={u}' for u in x.tracker))
if __name__ == '__main__': main()