File size: 5,497 Bytes
4ad9219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#!/usr/bin/env python3
"""获取已找到的公开发布者源视频;仅下载,不自动替换官方损坏媒体。"""
import concurrent.futures
import hashlib
import json
import os
from pathlib import Path
import shutil
import threading
import time
import urllib.request
import yt_dlp

ROOT = Path(__file__).resolve().parents[1]
DEST = ROOT / 'data/media_recovery/_Dl3Yr1CjZY.format137.mp4'
PARTS = DEST.with_suffix('.range-parts')
PROOF = ROOT / 'provenance/youtube_candidate_full_download.json'
EXPECTED_SIZE = 1618721135
BLOCK = 16 * 1024**2
LOCK = threading.Lock()


def sha(path):
    digest = hashlib.sha256()
    with path.open('rb') as stream:
        for block in iter(lambda: stream.read(4 * 1024**2), b''):
            digest.update(block)
    return digest.hexdigest()


def atomic(path, value):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')


def main():
    if DEST.exists() and PROOF.exists():
        saved = json.loads(PROOF.read_text())
        if saved.get('completed') and DEST.stat().st_size == EXPECTED_SIZE and sha(DEST) == saved['sha256']:
            print(json.dumps({'already_verified': True, 'sha256': saved['sha256']}), flush=True)
            return
    PARTS.mkdir(parents=True, exist_ok=True)
    started = time.time()
    # 签名下载地址只保留于内存,不写入日志、回执或版本库。
    class Quiet:
        def debug(self, message): pass
        def warning(self, message): pass
        def error(self, message): pass
    with yt_dlp.YoutubeDL({'quiet': True, 'skip_download': True, 'proxy': 'http://127.0.0.1:8118',
                          'logger': Quiet()}) as ydl:
        info = ydl.extract_info('https://www.youtube.com/watch?v=_Dl3Yr1CjZY', download=False)
    fmt = next(f for f in info['formats'] if f['format_id'] == '137')
    assert fmt['filesize'] == EXPECTED_SIZE and fmt['width'] == 1920 and fmt['height'] == 1080
    url = fmt['url']
    receipt = dict(candidate_id=info['id'], format_id='137', bytes_expected=EXPECTED_SIZE,
                   public_source='https://www.youtube.com/watch?v=_Dl3Yr1CjZY',
                   completed=False, started_at=started, parts={},
                   scope='source_recovery_candidate_only_not_automatic_benchmark_replacement')
    if PROOF.exists():
        previous = json.loads(PROOF.read_text())
        receipt['parts'] = previous.get('parts', {})

    def transfer(index):
        first = index * BLOCK
        last = min(EXPECTED_SIZE, first + BLOCK) - 1
        path = PARTS / f'{index:05d}.part'
        old = receipt['parts'].get(str(index))
        if old and path.exists() and path.stat().st_size == last-first+1 and sha(path) == old['sha256']:
            return
        for attempt in range(12):
            try:
                while shutil.disk_usage(PARTS).free < 80 * 1024**3 + BLOCK:
                    time.sleep(30)
                opener = urllib.request.build_opener(urllib.request.ProxyHandler({'https': 'http://127.0.0.1:8118'}))
                request = urllib.request.Request(url, headers={'Range': f'bytes={first}-{last}', 'User-Agent': 'Mozilla/5.0'})
                with opener.open(request, timeout=180) as response:
                    assert response.status == 206
                    assert response.headers['Content-Range'] == f'bytes {first}-{last}/{EXPECTED_SIZE}'
                    content = response.read(last-first+2)
                assert len(content) == last-first+1
                path.write_bytes(content)
                with LOCK:
                    receipt['parts'][str(index)] = dict(first=first, last=last, sha256=hashlib.sha256(content).hexdigest())
                    receipt.update(updated_at=time.time(), bytes_received=sum(p['last']-p['first']+1 for p in receipt['parts'].values()))
                    atomic(PROOF, receipt)
                    print(json.dumps({'part': index, 'bytes_received': receipt['bytes_received'], 'expected': EXPECTED_SIZE}), flush=True)
                return
            except Exception as exc:
                # 异常字符串可能包含签名URL,故只记录类型和分块号。
                print(json.dumps({'part': index, 'attempt': attempt, 'error_type': type(exc).__name__}), flush=True)
                if attempt == 11:
                    raise RuntimeError(f'候选源分块下载未完成:{index}') from None
                time.sleep(min(30, 2**attempt))

    count = (EXPECTED_SIZE + BLOCK - 1)//BLOCK
    with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
        list(pool.map(transfer, range(count)))
    with DEST.open('wb') as out:
        for index in range(count):
            with (PARTS / f'{index:05d}.part').open('rb') as stream:
                shutil.copyfileobj(stream, out, 4 * 1024**2)
    assert DEST.stat().st_size == EXPECTED_SIZE
    digest = sha(DEST)
    receipt.update(completed=True, sha256=digest, path=str(DEST.relative_to(ROOT)),
                   elapsed_seconds=time.time()-started, finished_at=time.time())
    atomic(PROOF, receipt)
    # 整体文件及分块哈希已保存,仅回收本脚本创建的传输块。
    for index in range(count):
        (PARTS / f'{index:05d}.part').unlink()
    PARTS.rmdir()
    print(json.dumps({'completed': True, 'bytes': EXPECTED_SIZE, 'sha256': digest}), flush=True)


if __name__ == '__main__':
    os.environ['CUDA_VISIBLE_DEVICES'] = '0,1,2,3'
    main()