h-seftom 2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
H_seftom.py ADDED
@@ -0,0 +1,1246 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ H_seftom.py —— 五平台统一视频下载器(单文件程序)
4
+
5
+ 支持:央视频 / 微信公众号 / 哔哩哔哩 / 快手 / 抖音,以及任意未知站点的通用嗅探。
6
+
7
+ 用法:
8
+ python H_seftom.py "<链接或分享文字>" # 下载到桌面
9
+ python H_seftom.py "<链接1>" "<链接2>" ... # 批量
10
+ python H_seftom.py "<链接>" -o "D:/视频" # 指定目录
11
+ python H_seftom.py "<链接>" --detect # 只判定来源,不下载
12
+ python H_seftom.py "<链接>" --as bilibili # 强制指定平台
13
+ python H_seftom.py "<链接>" --force # 覆盖同名文件
14
+ python H_seftom.py -h # 完整帮助
15
+
16
+ 结构(三层,职责清晰):
17
+ 1. 判定层 detect_source():域名 → 作品 ID → 文案关键词,三级判定,
18
+ 返回 (平台, 判定依据, 规范化链接),不做任何网络试错。
19
+ 2. 分派层 HANDLERS 字典:判定后直接查表调用对应处理器,不逐个尝试。
20
+ 3. 平台层:每个处理器只负责「拿到最高清晰度直链 + 生成文件名」,
21
+ 下载、进度、重试、ftyp 校验、失败清理由统一函数 download() 承担。
22
+
23
+ 平台要点:
24
+ 央视频 playvinfo 接口 + cKey 8.1 签名(AES-128-CBC),直取 CDN mp4。
25
+ 公众号 解析文章 HTML 里的 mp_video_trans_info,取 mpvideo.qpic.cn 直链,
26
+ 按 height 选最高清晰度;旧的 /mp/videoplayer 匿名接口已失效。
27
+ B站 playurl 用 fnval=1(durl 单文件 muxed),匿名 720P 且免 ffmpeg;
28
+ 支持 b23.tv 短链、BV/av 号、多 P;设 BILI_SESSDATA 可上 1080P+。
29
+ 快手 移动端分享页 v.m.chenzhongtech.com/fw/photo/{id} 内嵌无水印直链,
30
+ 优先 hd 高清档;接口版会触发验证码,所以只抓 HTML。
31
+ 抖音 无头 Edge 打开视频页,抖音下发访客 cookie,截获 aweme/detail 响应,
32
+ 按码率选最高可播直链;无需账号、cookie、签名。
33
+ 通用 未知站点自己嗅探:
34
+ ① 静态解析页面(<video>/<source>/og:video/JSON-LD/JS 里的媒体直链)
35
+ ② 解析不到就用无头 Edge 打开页面,拦截网络响应里的 video/*、m3u8
36
+ ③ 拿到 m3u8 就自己下分片(支持 AES-128 解密、master 选最高码率)并拼接
37
+
38
+ 兜底策略:任何平台在本程序失败后,会自动改用 yt-dlp 再试一次(前提是本机装了
39
+ yt-dlp);两边都失败才报错。加 --no-fallback 可关闭,加 --yt-dlp 可直接走 yt-dlp。
40
+
41
+ 依赖:pycryptodome(央视频签名 + HLS 解密)、playwright(抖音 / 通用嗅探,复用系统 Edge)。
42
+ yt-dlp 既作为独立通道(--as ytdlp),也作为任何失败后的自动兜底。单文件发行版
43
+ H_seftom.pyz 内已打包 yt-dlp;源码运行时会优先用同目录 vendor/yt_dlp,没有就用
44
+ pip 装的那份。
45
+ HLS 若本机有 ffmpeg 会自动封装成 mp4,否则保留 .ts(播放器可直接播放)。
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ import argparse
51
+ import json
52
+ import os
53
+ import re
54
+ import shutil
55
+ import ssl
56
+ import subprocess
57
+ import sys
58
+ import tempfile
59
+ import time
60
+ import traceback
61
+ import urllib.parse
62
+ import urllib.request
63
+ import uuid
64
+ from concurrent.futures import ThreadPoolExecutor
65
+
66
+ __version__ = "2.3"
67
+
68
+
69
+ def _prog_name() -> str:
70
+ """显示用的程序名:随调用方式变化(python H_seftom.py / .pyz / pip 装好的 h-seftom)。"""
71
+ name = os.path.basename(sys.argv[0] or "").strip()
72
+ for ext in (".exe", ".pyz", ".py", ".PY", ".EXE", ".PYZ"):
73
+ if name.endswith(ext):
74
+ name = name[: -len(ext)]
75
+ break
76
+ return name or "H_seftom"
77
+
78
+
79
+ PROG = _prog_name()
80
+
81
+ # 内置 yt-dlp:优先用随程序携带的 vendor/yt_dlp(源码运行时生效;
82
+ # 打包成 .pyz 后 yt_dlp 就在压缩包根目录,import 直接命中)。
83
+ _HERE = os.path.dirname(os.path.abspath(__file__))
84
+ for _p in (os.path.join(_HERE, "vendor"), _HERE):
85
+ if os.path.isdir(os.path.join(_p, "yt_dlp")) and _p not in sys.path:
86
+ sys.path.insert(0, _p)
87
+
88
+ # 本机桌面被 OneDrive 重定向到这里
89
+ OUT_DIR = r"D:\Downloads\OneDrive\Desktop"
90
+
91
+ UA_DESKTOP = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
92
+ "(KHTML, like Gecko) Chrome/120.0 Safari/537.36")
93
+ UA_MOBILE = ("Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) "
94
+ "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 "
95
+ "Safari/604.1")
96
+ UA_WX = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
97
+ "(KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 MicroMessenger/7.0.20")
98
+
99
+
100
+ class DownloadError(Exception):
101
+ """可预期的失败(用于给出干净的提示,不打印堆栈)。"""
102
+
103
+
104
+ # ============================ 通用工具 ============================
105
+ def fmt_size(n: int) -> str:
106
+ if n >= 1 << 30:
107
+ return f"{n / (1 << 30):.2f} GB"
108
+ return f"{n / (1 << 20):.1f} MB"
109
+
110
+
111
+ def sanitize(name: str, limit: int = 100) -> str:
112
+ """清理成合法文件名,并限制长度(避免 Windows 长路径)。"""
113
+ name = re.sub(r'[\\/:*?"<>|\r\n\t]', "_", (name or "").strip())
114
+ name = re.sub(r"\s+", " ", name).strip().strip(".").strip()
115
+ if len(name) > limit:
116
+ name = name[:limit].rstrip()
117
+ return name or "video"
118
+
119
+
120
+ def unique_path(path: str) -> str:
121
+ """同名文件存在时追加 (2)(3)…,不覆盖已有文件。"""
122
+ if not os.path.exists(path):
123
+ return path
124
+ stem, ext = os.path.splitext(path)
125
+ i = 2
126
+ while os.path.exists(f"{stem} ({i}){ext}"):
127
+ i += 1
128
+ return f"{stem} ({i}){ext}"
129
+
130
+
131
+ def _urlopen(url: str, headers: dict | None = None, timeout: int = 30, verify: bool = True):
132
+ req = urllib.request.Request(url, headers=headers or {})
133
+ if verify:
134
+ return urllib.request.urlopen(req, timeout=timeout)
135
+ return urllib.request.urlopen(req, timeout=timeout,
136
+ context=ssl._create_unverified_context())
137
+
138
+
139
+ def _is_cert_error(e: Exception) -> bool:
140
+ return isinstance(getattr(e, "reason", e), ssl.SSLError)
141
+
142
+
143
+ def http_get(url: str, headers: dict | None = None, timeout: int = 30, retries: int = 2):
144
+ """带轻量重试的 GET(返回 response 对象)。
145
+
146
+ 少部分站点证书链不完整,遇到证书错误时降级为不校验再试一次
147
+ (只影响取页面/取直链,最终文件仍有 ftyp 校验)。
148
+ """
149
+ last = None
150
+ verify = True
151
+ for attempt in range(retries + 1):
152
+ try:
153
+ return _urlopen(url, headers, timeout, verify)
154
+ except Exception as e: # noqa: BLE001
155
+ last = e
156
+ if verify and _is_cert_error(e):
157
+ verify = False
158
+ continue
159
+ if attempt < retries:
160
+ time.sleep(1.0 + attempt)
161
+ raise DownloadError(f"网络请求失败:{last}")
162
+
163
+
164
+ def http_json(url: str, headers: dict | None = None, timeout: int = 30):
165
+ raw = http_get(url, headers, timeout).read().decode("utf-8", "ignore")
166
+ try:
167
+ return json.loads(raw.strip().strip("()"))
168
+ except json.JSONDecodeError:
169
+ raise DownloadError(f"接口返回非 JSON:{raw[:200]}")
170
+
171
+
172
+ def follow_redirect(url: str, headers: dict | None = None) -> str:
173
+ try:
174
+ return http_get(url, headers, timeout=20).geturl()
175
+ except Exception: # noqa: BLE001
176
+ return url
177
+
178
+
179
+ # ============================ 统一下载 ============================
180
+ def download(url: str, out_path: str, headers: dict | None = None,
181
+ force: bool = False, retries: int = 3, timeout: int = 60) -> str:
182
+ """流式下载 + 进度 + 重试 + ftyp 校验。返回最终文件路径。"""
183
+ if os.path.exists(out_path) and os.path.getsize(out_path) > 0 and not force:
184
+ print(f"SKIP: 已存在 {out_path}({fmt_size(os.path.getsize(out_path))},--force 可覆盖)")
185
+ return out_path
186
+ out_path = unique_path(out_path) if not force else out_path
187
+ os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
188
+
189
+ last_err = None
190
+ verify = True
191
+ attempt = 0
192
+ while attempt < retries:
193
+ attempt += 1
194
+ try:
195
+ with _urlopen(url, headers, timeout, verify) as r, open(out_path, "wb") as f:
196
+ total = int(r.headers.get("Content-Length") or 0)
197
+ done, t0 = 0, time.time()
198
+ while True:
199
+ chunk = r.read(1 << 22)
200
+ if not chunk:
201
+ break
202
+ f.write(chunk)
203
+ done += len(chunk)
204
+ spd = done / max(time.time() - t0, 0.001) / (1 << 20)
205
+ if total:
206
+ pct = min(done * 100 // total, 100)
207
+ print(f"\r {pct:3d}% {fmt_size(done)} / {fmt_size(total)} "
208
+ f"{spd:5.1f} MB/s", end="", flush=True)
209
+ else:
210
+ print(f"\r {fmt_size(done)} {spd:5.1f} MB/s", end="", flush=True)
211
+ print()
212
+
213
+ size = os.path.getsize(out_path)
214
+ with open(out_path, "rb") as f:
215
+ head = f.read(16)
216
+ if size == 0:
217
+ raise DownloadError("下载内容为空")
218
+ if b"ftyp" not in head and not out_path.lower().endswith(".m3u8"):
219
+ raise DownloadError(f"文件头异常 {head[:8]!r},可能不是可播放 MP4")
220
+ print(f"OK: {out_path} ({fmt_size(size)})")
221
+ return out_path
222
+ except Exception as e: # noqa: BLE001
223
+ last_err = e
224
+ try:
225
+ if os.path.exists(out_path):
226
+ os.remove(out_path)
227
+ except OSError:
228
+ pass
229
+ if verify and _is_cert_error(e): # 证书问题:不校验重试,不计入失败次数
230
+ verify = False
231
+ attempt -= 1
232
+ continue
233
+ if attempt < retries:
234
+ print(f"\n [!] 第 {attempt} 次失败({e}),重试…")
235
+ time.sleep(1.5 * attempt)
236
+ raise DownloadError(f"下载失败:{last_err}")
237
+
238
+
239
+ # ============================ 央视频 ============================
240
+ YSP_API = "https://playvv.yangshipin.cn/playvinfo"
241
+
242
+
243
+ def yangshipin(url: str, out_dir: str, force: bool = False) -> str:
244
+ try:
245
+ from Crypto.Cipher import AES
246
+ from Crypto.Util.Padding import pad
247
+ except ImportError:
248
+ raise DownloadError("需要 pycryptodome:pip install pycryptodome")
249
+
250
+ m = re.search(r"vid=([a-z0-9]+)", url)
251
+ if not m:
252
+ html = http_get(url, {"User-Agent": UA_DESKTOP}).read().decode("utf-8", "ignore")
253
+ m = re.search(r"vid=([a-z0-9]+)", html) or re.search(r'"vid":"([a-z0-9]+)"', html)
254
+ if not m:
255
+ raise DownloadError("无法从链接解析 video id")
256
+ vid = m.group(1)
257
+ guid = uuid.uuid4().hex
258
+
259
+ def ckey(rnd: str) -> str:
260
+ tr = (f"|{vid}|{rnd}|mg3c3b04ba|1.3.5|{guid}|4330701|"
261
+ "https://m.yangshipin.cn/|mozilla/5.0 (iphone; cpu||Mozilla|Netscape|iPhone|")
262
+ pr = 0
263
+ for ch in tr:
264
+ pr = ((pr << 5) - pr + ord(ch)) & 0xFFFFFFFF
265
+ if pr >= 0x80000000:
266
+ pr -= 0x100000000
267
+ key = bytes.fromhex("4e2918885fd98109869d14e0231a0bf4")
268
+ iv = bytes.fromhex("16b17e519ddd0ce5b79d7a63a4dd801c")
269
+ enc = AES.new(key, AES.MODE_CBC, iv).encrypt(pad(f"|{pr}{tr}".encode(), 16, style="pkcs7"))
270
+ return "--01" + enc.hex().upper()
271
+
272
+ hdr = {"User-Agent": UA_MOBILE, "Referer": "https://m.yangshipin.cn/", "Accept": "*/*"}
273
+ probe = http_json(f"{YSP_API}?{urllib.parse.urlencode({'vid': vid, 'platform': '4330701', 'otype': 'json'})}", hdr)
274
+ cur = str(probe.get("curTime") or int(time.time()))
275
+
276
+ params = {
277
+ "charge": "0", "defaultfmt": "auto", "otype": "json", "guid": guid,
278
+ "flowid": f"{guid}_4330701", "platform": "4330701", "sdtfrom": "v7007",
279
+ "defnpayver": "1", "appVer": "1.3.5", "host": "m.yangshipin.cn",
280
+ "ehost": f"https://m.yangshipin.cn/portrait_video?vid={vid}",
281
+ "refer": "m.yangshipin.cn", "sphttps": "1", "sphls": "1",
282
+ "_rnd": cur, "spwm": "4", "vid": vid, "defn": "fhd",
283
+ "encryptVer": "8.1", "cKey": ckey(cur),
284
+ }
285
+ data = http_json(f"{YSP_API}?{urllib.parse.urlencode(params)}", hdr)
286
+
287
+ vi = (data.get("vl", {}).get("vi") or [None])[0]
288
+ if not vi:
289
+ raise DownloadError(f"未取到视频信息:{json.dumps(data, ensure_ascii=False)[:200]}")
290
+ ui = vi.get("ul", {}).get("ui", [])
291
+ base = ui[0].get("url", "") if ui else ""
292
+ fn, vkey = vi.get("fn"), vi.get("fvkey")
293
+ if not (base and fn and vkey):
294
+ raise DownloadError("直链字段缺失(fn / fvkey / url)")
295
+
296
+ title = vi.get("ti") or vid
297
+ vurl = f"{base}{fn}?vkey={vkey}&platform=2"
298
+ ext = ".m3u8" if fn.lower().endswith(".m3u8") else ".mp4"
299
+ print(f" 标题: {title}")
300
+ print(f" 清晰度: {vi.get('defn') or 'fhd'}")
301
+ return download(vurl, os.path.join(out_dir, sanitize(title) + ext),
302
+ {"User-Agent": UA_MOBILE, "Referer": "https://m.yangshipin.cn/"}, force)
303
+
304
+
305
+ # ============================ 微信公众号 ============================
306
+ def weixin(url: str, out_dir: str, force: bool = False) -> str:
307
+ html = http_get(url, {"User-Agent": UA_MOBILE}).read().decode("utf-8", "ignore")
308
+
309
+ title = ""
310
+ for pat in (r'property="og:title" content="([^"]+)"', r"var msg_title = '(.*?)'"):
311
+ m = re.search(pat, html)
312
+ if m:
313
+ title = m.group(1).strip()
314
+ break
315
+
316
+ infos = re.findall(
317
+ r"format_id: '(\d+)' \* 1 \|\| 0,.*?height: '(\d+)'.*?"
318
+ r"url: \('(http://mpvideo\.qpic\.cn/[^']+)'\)", html, re.S)
319
+ if not infos:
320
+ raise DownloadError("文章里没找到视频(可能无视频、需登录或已被删除)")
321
+
322
+ fmt_id, height, vurl = max(infos, key=lambda x: int(x[1]))
323
+ vurl = vurl.replace("\\x26amp;", "&").replace("http://", "https://", 1)
324
+ if not title:
325
+ title = "微信视频"
326
+ print(f" 标题: {title}")
327
+ print(f" 清晰度: {height}p (format {fmt_id})")
328
+ return download(vurl, os.path.join(out_dir, sanitize(title) + ".mp4"),
329
+ {"User-Agent": UA_WX, "Referer": "https://mp.weixin.qq.com/"}, force)
330
+
331
+
332
+ # ============================ 哔哩哔哩 ============================
333
+ BILI_UA = UA_DESKTOP
334
+ BILI_BV_RE = r"(BV[0-9A-Za-z]{10})"
335
+
336
+
337
+ def bilibili_id(text: str) -> str | None:
338
+ m = re.search(BILI_BV_RE, text)
339
+ if m:
340
+ return m.group(1)
341
+ m = re.search(r"\bav(\d+)", text, re.I)
342
+ if m:
343
+ return "av" + m.group(1)
344
+ m = re.search(r"https?://b23\.tv/[\w\-]+", text)
345
+ if m:
346
+ final = follow_redirect(m.group(0), {"User-Agent": BILI_UA})
347
+ mm = re.search(BILI_BV_RE, final) or re.search(r"/video/av(\d+)", final) \
348
+ or re.search(r"\bav(\d+)", final, re.I)
349
+ if mm:
350
+ g = mm.group(1)
351
+ return g if g.lower().startswith("bv") else "av" + g
352
+ return None
353
+
354
+
355
+ def bilibili(url: str, out_dir: str, force: bool = False) -> str:
356
+ bid = bilibili_id(url)
357
+ if not bid:
358
+ raise DownloadError("无法解析 B站视频 ID(BV 号 / av 号 / b23.tv 短链)")
359
+
360
+ pm = re.search(r"[?&]p=(\d+)", url)
361
+ page_no = int(pm.group(1)) if pm else 1
362
+
363
+ hdrs = {"User-Agent": BILI_UA, "Referer": "https://www.bilibili.com/"}
364
+ sessdata = os.environ.get("BILI_SESSDATA", "").strip()
365
+ if sessdata:
366
+ hdrs["Cookie"] = f"SESSDATA={sessdata}"
367
+
368
+ key = f"bvid={bid}" if bid.startswith("BV") else f"aid={bid[2:]}"
369
+ v = http_json(f"https://api.bilibili.com/x/web-interface/view?{key}", hdrs)
370
+ if v.get("code") != 0:
371
+ raise DownloadError(f"获取视频信息失败:code={v.get('code')} {v.get('message')}")
372
+
373
+ vd = v["data"]
374
+ title = vd.get("title") or bid
375
+ pages = vd.get("pages") or [{"cid": vd.get("cid"), "part": ""}]
376
+ if not 1 <= page_no <= len(pages):
377
+ page_no = 1
378
+ page = pages[page_no - 1]
379
+ cid = page.get("cid") or vd.get("cid")
380
+ if len(pages) > 1:
381
+ title = f"{title}_P{page_no}"
382
+ if page.get("part"):
383
+ title += f"_{page['part']}"
384
+
385
+ # fnval=1 → durl(muxed 单文件),免 ffmpeg;匿名最高 720P
386
+ pd = http_json(f"https://api.bilibili.com/x/player/playurl?{key}&cid={cid}"
387
+ "&qn=112&fnval=1&fourk=1", hdrs).get("data") or {}
388
+ durl = pd.get("durl") or []
389
+ if not durl:
390
+ hint = "" if sessdata else "(番剧/付费内容需设置 BILI_SESSDATA)"
391
+ raise DownloadError(f"未取到视频流{hint}")
392
+
393
+ accept = pd.get("accept_description") or []
394
+ quality = pd.get("quality")
395
+ qmap = dict(zip(pd.get("accept_quality") or [], accept))
396
+ qname = qmap.get(quality) or (accept[0] if accept else f"qn{quality}")
397
+
398
+ print(f" 标题: {title}")
399
+ print(f" 清晰度: {qname} | 分段: {len(durl)}")
400
+ out = os.path.join(out_dir, sanitize(title) + ".mp4")
401
+
402
+ if len(durl) == 1:
403
+ return download(durl[0]["url"], out, hdrs, force)
404
+
405
+ # 极少见的多段:逐段下载后按序拼接
406
+ out = unique_path(out) if not force else out
407
+ os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
408
+ parts, size = [], 0
409
+ try:
410
+ for i, seg in enumerate(durl):
411
+ tp = f"{out}.part{i}"
412
+ download(seg["url"], tp, hdrs, force=True)
413
+ parts.append(tp)
414
+ with open(out, "wb") as fo:
415
+ for tp in parts:
416
+ with open(tp, "rb") as fi:
417
+ while True:
418
+ c = fi.read(1 << 22)
419
+ if not c:
420
+ break
421
+ fo.write(c)
422
+ size += len(c)
423
+ finally:
424
+ for tp in parts:
425
+ try:
426
+ os.remove(tp)
427
+ except OSError:
428
+ pass
429
+ with open(out, "rb") as f:
430
+ head = f.read(16)
431
+ if b"ftyp" not in head:
432
+ raise DownloadError("分段拼接后文件头异常")
433
+ print(f"OK: {out} ({fmt_size(size)})")
434
+ return out
435
+
436
+
437
+ # ============================ 快手 ============================
438
+ KS_ID_RE = r"(?:short-video/|fw/photo/|photoId=)([0-9A-Za-z]{15,40})"
439
+
440
+
441
+ def kuaishou_id(text: str) -> str | None:
442
+ m = re.search(KS_ID_RE, text)
443
+ if m:
444
+ return m.group(1)
445
+ m = re.search(r"https?://(?:v\.kuaishou\.com|www\.kuaishou\.com/f)/[\w\-]+/?", text)
446
+ if not m:
447
+ return None
448
+ final = follow_redirect(m.group(0), {"User-Agent": UA_MOBILE})
449
+ m = re.search(KS_ID_RE, final)
450
+ return m.group(1) if m else None
451
+
452
+
453
+ def kuaishou(url: str, out_dir: str, force: bool = False) -> str:
454
+ pid = kuaishou_id(url)
455
+ if not pid:
456
+ raise DownloadError("无法解析快手视频 ID(photoId / v.kuaishou.com 短链)")
457
+
458
+ share = f"https://v.m.chenzhongtech.com/fw/photo/{pid}"
459
+ html = http_get(share, {"User-Agent": UA_MOBILE}).read().decode("utf-8", "ignore")
460
+
461
+ title = pid
462
+ m = re.search(r'"caption"\s*:\s*"([^"]{2,200})"', html)
463
+ if m:
464
+ title = m.group(1)
465
+
466
+ urls = re.findall(r'https?://[^"\'\s<>]+?\.mp4[^"\'\s<>]*', html)
467
+ if not urls:
468
+ raise DownloadError("页面内没有 mp4 直链(可能是图文/直播/触发验证)")
469
+
470
+ seen, hd, normal = set(), [], []
471
+ for u in urls:
472
+ if u in seen:
473
+ continue
474
+ seen.add(u)
475
+ (hd if ("photo-video-mz" in u or "_hd" in u or "hd15" in u) else normal).append(u)
476
+ vurl = hd[0] if hd else normal[0]
477
+
478
+ print(f" 标题: {title}")
479
+ print(f" 清晰度: {'高清' if hd else '基础'}")
480
+ return download(vurl, os.path.join(out_dir, sanitize(title) + ".mp4"),
481
+ {"User-Agent": UA_MOBILE, "Referer": "https://v.m.chenzhongtech.com/"}, force)
482
+
483
+
484
+ # ============================ 抖音 ============================
485
+ DOUYIN_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
486
+ "(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36")
487
+ DOUYIN_ID_RE = r"(?:video/|note/|modal_id=)(\d{15,})"
488
+
489
+
490
+ def douyin_id(text: str) -> str | None:
491
+ m = re.search(DOUYIN_ID_RE, text) or re.fullmatch(r"\s*(\d{15,})\s*", text)
492
+ if m:
493
+ return m.group(1)
494
+ m = re.search(r"https?://v\.douyin\.com/[\w\-]+/?", text)
495
+ if not m:
496
+ return None
497
+ final = follow_redirect(m.group(0), {"User-Agent": DOUYIN_UA})
498
+ m = re.search(DOUYIN_ID_RE, final)
499
+ return m.group(1) if m else None
500
+
501
+
502
+ def _douyin_pick_best(detail: dict) -> tuple[str | None, str, str]:
503
+ """按码率选最高且可播放的直链(参考 yt-dlp 的 _parse_aweme_video_app)。"""
504
+ v = detail.get("video", {}) or {}
505
+ desc = (detail.get("desc") or "").strip()
506
+ author = (detail.get("author") or {}).get("nickname", "")
507
+
508
+ urls: list[str] = []
509
+ pa = v.get("play_addr") or {}
510
+ if pa.get("url_list"):
511
+ urls.extend(pa["url_list"])
512
+ for br in sorted((v.get("bit_rate") or []), key=lambda x: -(x.get("bit_rate") or 0)):
513
+ bpa = br.get("play_addr") or {}
514
+ # bytevc1 / bytevc2 是字节自研 h265/vvc,普通播放器打不开
515
+ if bpa.get("url_list") and "bytevc" not in bpa.get("url_key", ""):
516
+ urls.extend(bpa["url_list"])
517
+ da = v.get("download_addr") or {}
518
+ if da.get("url_list"):
519
+ urls.extend(da["url_list"])
520
+ return (urls[0] if urls else None), desc, author
521
+
522
+
523
+ def douyin(url: str, out_dir: str, force: bool = False) -> str:
524
+ try:
525
+ from playwright.sync_api import sync_playwright
526
+ except ImportError:
527
+ raise DownloadError("需要 playwright:pip install playwright(复用系统 Edge,无需 install chromium)")
528
+
529
+ aid = douyin_id(url)
530
+ if not aid:
531
+ raise DownloadError("无法解析抖音作品 ID")
532
+
533
+ found: dict = {}
534
+ media: list[str] = []
535
+
536
+ def on_response(resp):
537
+ try:
538
+ u = resp.url
539
+ if "aweme/v1/web/aweme/detail" in u:
540
+ j = resp.json()
541
+ if j.get("aweme_detail"):
542
+ found["d"] = j["aweme_detail"]
543
+ elif "douyinvod" in u and u not in media:
544
+ media.append(u)
545
+ except Exception: # noqa: BLE001
546
+ pass
547
+
548
+ with sync_playwright() as p:
549
+ browser = None
550
+ for ch in ("msedge", "chrome"):
551
+ try:
552
+ browser = p.chromium.launch(channel=ch, headless=True,
553
+ args=["--mute-audio"])
554
+ break
555
+ except Exception: # noqa: BLE001
556
+ continue
557
+ if browser is None:
558
+ try:
559
+ browser = p.chromium.launch(headless=True, args=["--mute-audio"])
560
+ except Exception: # noqa: BLE001
561
+ raise DownloadError("找不到可用浏览器(Edge/Chrome),或执行 playwright install chromium")
562
+
563
+ ctx = browser.new_context(locale="zh-CN", user_agent=DOUYIN_UA)
564
+ try:
565
+ page = ctx.new_page()
566
+ page.on("response", on_response)
567
+ page.goto(f"https://www.douyin.com/video/{aid}",
568
+ wait_until="domcontentloaded", timeout=60000)
569
+ for _ in range(25):
570
+ if found.get("d"):
571
+ break
572
+ page.wait_for_timeout(1000)
573
+
574
+ detail = found.get("d")
575
+ if detail:
576
+ vurl, desc, author = _douyin_pick_best(detail)
577
+ print(f" 标题: {desc[:60] or aid}")
578
+ if author:
579
+ print(f" 作者: {author}")
580
+ else:
581
+ vurl, desc = (media[0] if media else None), aid
582
+ if not vurl:
583
+ raise DownloadError("没抓到视频地址(图文作品暂不支持)")
584
+
585
+ out = os.path.join(out_dir, sanitize(desc or aid) + ".mp4")
586
+ if not force:
587
+ out = unique_path(out)
588
+ os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
589
+
590
+ print(" 下载中…")
591
+ resp = ctx.request.get(vurl, headers={"Referer": "https://www.douyin.com/"},
592
+ timeout=180000)
593
+ body = resp.body()
594
+ with open(out, "wb") as f:
595
+ f.write(body)
596
+ with open(out, "rb") as f:
597
+ head = f.read(16)
598
+ if not body:
599
+ raise DownloadError("下载内容为空")
600
+ if b"ftyp" not in head:
601
+ raise DownloadError(f"文件头异常 {head[:8]!r},可能不是可播放 MP4")
602
+ print(f"OK: {out} ({fmt_size(len(body))})")
603
+ return out
604
+ finally:
605
+ browser.close()
606
+
607
+
608
+ # ============================ 通用嗅探(未知站点,不求外援) ============================
609
+ MEDIA_EXT_RE = re.compile(
610
+ r"https?://[^\s\"'<>\\]+?\.(?:mp4|m3u8|flv|webm|mov)(?:\?[^\s\"'<>\\]*)?", re.I)
611
+ HLS_EXT = (".m3u8",)
612
+
613
+ OG_VIDEO_RE = re.compile(
614
+ r"<meta[^>]+(?:property|name)=[\"']og:video(?::(?:url|secure_url))?[\"'][^>]*>", re.I)
615
+ MEDIA_ATTR_PATTERNS = (
616
+ r'<(?:video|source|audio)[^>]*?\ssrc\s*=\s*["\']([^"\']+)["\']',
617
+ r'"contentUrl"\s*:\s*"([^"]+)"',
618
+ r'"(?:playUrl|videoUrl|video_url|play_url|file)"\s*:\s*"([^"\\]*'
619
+ r'\.(?:mp4|m3u8)[^"\\]*)"',
620
+ )
621
+
622
+
623
+ def _unescape_url(u: str) -> str:
624
+ u = (u or "").strip().strip("\"'")
625
+ u = (u.replace("\\/", "/").replace("\\u002F", "/").replace("\\u002f", "/")
626
+ .replace("&amp;", "&").replace("\\x26amp;", "&").replace("&#38;", "&"))
627
+ if u.startswith("//"):
628
+ u = "https:" + u
629
+ return u
630
+
631
+
632
+ def _is_media_url(u: str) -> bool:
633
+ return bool(MEDIA_EXT_RE.fullmatch(u.split("#")[0]))
634
+
635
+
636
+ def _page_title(html: str) -> str:
637
+ for pat in (r'property=["\']og:title["\'][^>]*content=["\']([^"\']+)',
638
+ r"<title[^>]*>(.*?)</title>"):
639
+ m = re.search(pat, html, re.I | re.S)
640
+ if m:
641
+ t = re.sub(r"\s+", " ", m.group(1)).strip()
642
+ if t:
643
+ return t
644
+ return ""
645
+
646
+
647
+ def _collect_candidates(html: str, base: str) -> list[str]:
648
+ """从页面里收集所有可能的媒体直链(去重、补全相对路径、反转义)。"""
649
+ raw: list[str] = []
650
+ for tag in OG_VIDEO_RE.findall(html):
651
+ cm = re.search(r'content=["\']([^"\']+)["\']', tag, re.I)
652
+ if cm:
653
+ raw.append(cm.group(1))
654
+ for pat in MEDIA_ATTR_PATTERNS:
655
+ raw.extend(re.findall(pat, html, re.I))
656
+ raw.extend(MEDIA_EXT_RE.findall(html))
657
+
658
+ out, seen = [], set()
659
+ for c in raw:
660
+ u = _unescape_url(c)
661
+ if not u.lower().startswith(("http://", "https://")):
662
+ u = urllib.parse.urljoin(base, u)
663
+ u = u.split("#")[0]
664
+ if not _is_media_url(u) or u in seen:
665
+ continue
666
+ seen.add(u)
667
+ out.append(u)
668
+ return out
669
+
670
+
671
+ def probe_media(url: str, headers: dict) -> tuple[str, int]:
672
+ """探测直链是否可播:返回 (类型, 字节数)。类型 = hls / mp4 / bad。"""
673
+ try:
674
+ if any(e in url.lower().split("?")[0] for e in HLS_EXT):
675
+ txt = http_get(url, headers, timeout=15).read(512).decode("utf-8", "ignore")
676
+ return ("hls", 0) if "#EXTM3U" in txt else ("bad", 0)
677
+ h = dict(headers, Range="bytes=0-1023")
678
+ r = http_get(url, h, timeout=15)
679
+ ct = (r.headers.get("Content-Type") or "").lower()
680
+ total = 0
681
+ m = re.search(r"/(\d+)\s*$", r.headers.get("Content-Range") or "")
682
+ if m:
683
+ total = int(m.group(1))
684
+ elif r.headers.get("Content-Length"):
685
+ total = int(r.headers["Content-Length"])
686
+ if "video" in ct or "octet-stream" in ct or "mp4" in ct:
687
+ return "mp4", total
688
+ if "mpegurl" in ct or "m3u8" in ct:
689
+ return "hls", 0
690
+ return "bad", total
691
+ except Exception: # noqa: BLE001
692
+ return "bad", 0
693
+
694
+
695
+ def _score(kind: str, url: str, size: int) -> float:
696
+ s = size / (1 << 20)
697
+ s += {"mp4": 1000, "hls": 900}.get(kind, 0)
698
+ low = url.lower()
699
+ for hd, bonus in (("1080", 300), ("2160", 350), ("720", 200), ("hd", 60)):
700
+ if hd in low:
701
+ s += bonus
702
+ break
703
+ return s
704
+
705
+
706
+ def _pick_candidate(cands: list[str], headers: dict) -> dict | None:
707
+ """探测所有候选,按「可播 + 清晰度」评分选最优。"""
708
+ best, best_score = None, -1.0
709
+ for u in cands[:24]: # 限制探测数量,避免慢
710
+ kind, size = probe_media(u, headers)
711
+ if kind == "bad":
712
+ continue
713
+ sc = _score(kind, u, size)
714
+ if sc > best_score:
715
+ best, best_score = {"kind": kind, "url": u, "size": size}, sc
716
+ return best
717
+
718
+
719
+ def _browser_sniff(url: str, wait_ms: int = 9000) -> tuple[list[str], str, str]:
720
+ """无头 Edge 打开页面,拦截网络响应里的媒体地址。返回 (候选, cookie, 标题)。"""
721
+ try:
722
+ from playwright.sync_api import sync_playwright
723
+ except ImportError:
724
+ return [], "", ""
725
+
726
+ hits: list[str] = []
727
+ state: dict = {"title": ""}
728
+
729
+ def on_response(resp):
730
+ try:
731
+ u, ct = resp.url, (resp.headers.get("content-type") or "").lower()
732
+ path = u.lower().split("?")[0]
733
+ if ("video/" in ct or "mpegurl" in ct
734
+ or path.endswith((".mp4", ".m3u8", ".flv", ".webm"))):
735
+ if u not in hits:
736
+ hits.append(u)
737
+ except Exception: # noqa: BLE001
738
+ pass
739
+
740
+ with sync_playwright() as p:
741
+ browser = None
742
+ for ch in ("msedge", "chrome"):
743
+ try:
744
+ browser = p.chromium.launch(channel=ch, headless=True,
745
+ args=["--mute-audio",
746
+ "--autoplay-policy=no-user-gesture-required"])
747
+ break
748
+ except Exception: # noqa: BLE001
749
+ continue
750
+ if browser is None:
751
+ try:
752
+ browser = p.chromium.launch(headless=True,
753
+ args=["--autoplay-policy=no-user-gesture-required"])
754
+ except Exception: # noqa: BLE001
755
+ return [], "", ""
756
+ ctx = browser.new_context(locale="zh-CN", user_agent=UA_DESKTOP)
757
+ try:
758
+ page = ctx.new_page()
759
+ page.on("response", on_response)
760
+ page.goto(url, wait_until="domcontentloaded", timeout=60000)
761
+ # 触发自动播放 + 轻微滚动,逼出懒加载的视频源
762
+ for _ in range(wait_ms // 1000):
763
+ page.wait_for_timeout(1000)
764
+ try:
765
+ page.evaluate(
766
+ "() => {document.querySelectorAll('video').forEach(v => {"
767
+ "v.muted = true; v.play && v.play().catch(() => {});});"
768
+ "window.scrollBy(0, 400);}")
769
+ except Exception: # noqa: BLE001
770
+ pass
771
+ state["title"] = (page.title() or "").strip()
772
+ # 有些站点直接给 <video>,但请求没走缓存,补一次
773
+ try:
774
+ srcs = page.evaluate(
775
+ "() => Array.from(document.querySelectorAll('video,source'))"
776
+ ".map(e => e.currentSrc || e.src).filter(Boolean)")
777
+ hits.extend([s for s in srcs if s not in hits])
778
+ except Exception: # noqa: BLE001
779
+ pass
780
+ cookies = "; ".join(f"{c['name']}={c['value']}" for c in ctx.cookies())
781
+ finally:
782
+ browser.close()
783
+ return hits, cookies, state["title"]
784
+
785
+
786
+ def _hls_text(url: str, headers: dict) -> str:
787
+ return http_get(url, headers, timeout=25).read().decode("utf-8", "ignore")
788
+
789
+
790
+ def hls_download(url: str, out_path: str, headers: dict, force: bool = False) -> str:
791
+ """下载 HLS:master 选最高码率 → 分片并发下载(AES-128 解密)→ 拼接。
792
+
793
+ 本机有 ffmpeg 就封装成 mp4,否则保留 .ts。
794
+ """
795
+ txt = _hls_text(url, headers)
796
+ if "#EXTM3U" not in txt:
797
+ raise DownloadError("m3u8 内容无效")
798
+
799
+ if "#EXT-X-STREAM-INF" in txt: # master playlist,挑最高带宽
800
+ lines = [ln.strip() for ln in txt.splitlines()]
801
+ best, best_bw = None, -1
802
+ for i, ln in enumerate(lines):
803
+ if not ln.startswith("#EXT-X-STREAM-INF"):
804
+ continue
805
+ m = re.search(r"BANDWIDTH=(\d+)", ln)
806
+ bw = int(m.group(1)) if m else 0
807
+ for nxt in lines[i + 1:]:
808
+ if nxt and not nxt.startswith("#"):
809
+ if bw > best_bw:
810
+ best_bw, best = bw, urllib.parse.urljoin(url, nxt)
811
+ break
812
+ if best:
813
+ url = best
814
+ txt = _hls_text(url, headers)
815
+ print(f" HLS 码率: {best_bw // 1000} kbps")
816
+
817
+ cur_key = cur_iv = init_uri = None
818
+ segs: list[tuple[str, str | None, str | None]] = []
819
+ for ln in (x.strip() for x in txt.splitlines()):
820
+ if ln.startswith("#EXT-X-KEY"):
821
+ m = re.search(r"METHOD=([A-Z0-9-]+)", ln)
822
+ method = m.group(1) if m else ""
823
+ if method == "NONE":
824
+ cur_key = cur_iv = None
825
+ elif "AES-128" in method:
826
+ um = re.search(r'URI="([^"]+)"', ln)
827
+ vm = re.search(r"IV=0x([0-9A-Fa-f]+)", ln)
828
+ cur_key = urllib.parse.urljoin(url, um.group(1)) if um else None
829
+ cur_iv = vm.group(1) if vm else None
830
+ else:
831
+ raise DownloadError(f"不支持的分片加密方式:{method}")
832
+ elif ln.startswith("#EXT-X-MAP"):
833
+ um = re.search(r'URI="([^"]+)"', ln)
834
+ if um:
835
+ init_uri = urllib.parse.urljoin(url, um.group(1))
836
+ elif ln and not ln.startswith("#"):
837
+ segs.append((urllib.parse.urljoin(url, ln), cur_key, cur_iv))
838
+ if not segs:
839
+ raise DownloadError("m3u8 里没有分片")
840
+
841
+ print(f" 分片: {len(segs)} 个{'(AES-128 加密)' if any(s[1] for s in segs) else ''}")
842
+
843
+ try:
844
+ from Crypto.Cipher import AES
845
+ except ImportError:
846
+ AES = None
847
+ if any(s[1] for s in segs) and AES is None:
848
+ raise DownloadError("分片已加密,需要 pycryptodome:pip install pycryptodome")
849
+
850
+ tmpdir = tempfile.mkdtemp(prefix="hls_")
851
+ key_cache: dict[str, bytes] = {}
852
+ total = [0]
853
+ t0 = time.time()
854
+
855
+ def fetch(job):
856
+ idx, (seg_url, kurl, iv) = job
857
+ last = None
858
+ for attempt in range(3):
859
+ try:
860
+ data = http_get(seg_url, headers, timeout=60).read()
861
+ break
862
+ except Exception as e: # noqa: BLE001
863
+ last = e
864
+ time.sleep(1 + attempt)
865
+ else:
866
+ raise DownloadError(f"分片 {idx} 下载失败:{last}")
867
+ if kurl:
868
+ if kurl not in key_cache:
869
+ key_cache[kurl] = http_get(kurl, headers, timeout=25).read()
870
+ ivb = bytes.fromhex(iv) if iv else idx.to_bytes(16, "big")
871
+ data = AES.new(key_cache[kurl], AES.MODE_CBC, ivb).decrypt(data)
872
+ p = os.path.join(tmpdir, f"{idx:06d}.part")
873
+ with open(p, "wb") as f:
874
+ f.write(data)
875
+ total[0] += len(data)
876
+ spd = total[0] / max(time.time() - t0, .001) / (1 << 20)
877
+ print(f"\r {len(os.listdir(tmpdir))}/{len(segs)} 片 "
878
+ f"{fmt_size(total[0])} {spd:.1f} MB/s", end="", flush=True)
879
+ return p
880
+
881
+ parts = []
882
+ try:
883
+ with ThreadPoolExecutor(max_workers=8) as ex:
884
+ parts = list(ex.map(fetch, enumerate(segs)))
885
+ print()
886
+
887
+ has_ffmpeg = bool(shutil.which("ffmpeg"))
888
+ out = os.path.join(os.path.dirname(out_path) or ".",
889
+ os.path.splitext(os.path.basename(out_path))[0] + ".ts")
890
+ if os.path.exists(out) and not force:
891
+ out = unique_path(out)
892
+ os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
893
+
894
+ with open(out, "wb") as fo:
895
+ if init_uri:
896
+ fo.write(http_get(init_uri, headers, timeout=30).read())
897
+ for p in parts:
898
+ with open(p, "rb") as fi:
899
+ shutil.copyfileobj(fi, fo, 1 << 22)
900
+
901
+ if has_ffmpeg:
902
+ mp4 = os.path.splitext(out)[0] + ".mp4"
903
+ r = subprocess.run(["ffmpeg", "-y" if force else "-n", "-i", out,
904
+ "-c", "copy", "-bsf:a", "aac_adtstoasc", mp4],
905
+ capture_output=True)
906
+ if r.returncode == 0 and os.path.exists(mp4):
907
+ os.remove(out)
908
+ out = mp4
909
+ finally:
910
+ shutil.rmtree(tmpdir, ignore_errors=True)
911
+
912
+ size = os.path.getsize(out)
913
+ if size == 0:
914
+ raise DownloadError("拼接结果为空")
915
+ print(f"OK: {out} ({fmt_size(size)})")
916
+ return out
917
+
918
+
919
+ class _QuietYTDLP:
920
+ """吞掉 yt-dlp 自己的日志,统一由本程序输出。"""
921
+
922
+ def debug(self, msg):
923
+ pass
924
+
925
+ def info(self, msg):
926
+ pass
927
+
928
+ def warning(self, msg):
929
+ pass
930
+
931
+ def error(self, msg):
932
+ pass
933
+
934
+
935
+ def _ytdlp_progress(d: dict) -> None:
936
+ """yt-dlp 下载进度(替换它自带的输出,保持和本程序一致的样式)。"""
937
+ if d.get("status") == "downloading":
938
+ done = d.get("downloaded_bytes") or 0
939
+ total = d.get("total_bytes") or d.get("total_bytes_estimate") or 0
940
+ if total:
941
+ print(f"\r {min(done * 100 // total, 100):3d}% {fmt_size(done)} / {fmt_size(total)}",
942
+ end="", flush=True)
943
+ else:
944
+ print(f"\r {fmt_size(done)}", end="", flush=True)
945
+ elif d.get("status") == "finished":
946
+ print()
947
+
948
+
949
+ def yt_dlp_dl(url: str, out_dir: str, force: bool = False) -> str:
950
+ """yt-dlp 通道(已内置):独立可用,也是任何平台失败后的自动兜底。"""
951
+ try:
952
+ import yt_dlp
953
+ from yt_dlp.utils import DownloadError as YtError
954
+ except ImportError:
955
+ raise DownloadError(
956
+ "未找到 yt-dlp:单文件版本应内置;源码版请 pip install yt-dlp,"
957
+ "或把 yt_dlp 放到 vendor/ 后用 make_pyz.py 重新打包")
958
+
959
+ os.makedirs(out_dir, exist_ok=True)
960
+ # 没有 ffmpeg 时只能要「音视频同在一个文件」的格式,否则 yt-dlp 会因无法合并而中止
961
+ if shutil.which("ffmpeg"):
962
+ fmt = "b[ext=mp4]/b/bv*+ba"
963
+ else:
964
+ fmt = ("b[ext=mp4][acodec!=none][vcodec!=none]/"
965
+ "b[acodec!=none][vcodec!=none]/b[ext=mp4]/b")
966
+ opts = {
967
+ "outtmpl": os.path.join(out_dir, "%(title).90s.%(ext)s"),
968
+ "quiet": True, "no_warnings": True, "noprogress": True,
969
+ "retries": 3, "noplaylist": True, "overwrites": force,
970
+ "format": fmt, "merge_output_format": "mp4",
971
+ "progress_hooks": [_ytdlp_progress], "logger": _QuietYTDLP(),
972
+ }
973
+ print(" [yt-dlp] 解析中…")
974
+ try:
975
+ with yt_dlp.YoutubeDL(opts) as ydl:
976
+ info = ydl.extract_info(url, download=True)
977
+ if info.get("_type") == "playlist" and info.get("entries"):
978
+ info = info["entries"][0]
979
+ path = ydl.prepare_filename(info)
980
+ except YtError as e:
981
+ msg = re.sub(r"^ERROR:\s*", "", str(e)).strip()
982
+ if "ffmpeg" in msg.lower():
983
+ msg += "(安装 ffmpeg 后可下此站的分离音视频流)"
984
+ raise DownloadError(msg)
985
+ if not os.path.exists(path):
986
+ raise DownloadError("yt-dlp 已执行但未找到输出文件")
987
+ print(f"OK: {path} ({fmt_size(os.path.getsize(path))})")
988
+ return path
989
+
990
+
991
+ def has_ytdlp() -> bool:
992
+ try:
993
+ import yt_dlp # noqa: F401
994
+ return True
995
+ except ImportError:
996
+ return False
997
+
998
+
999
+ def generic(url: str, out_dir: str, force: bool = False) -> str:
1000
+ """未知站点通用下载:静态解析 → 浏览器抓包 → 直链 / HLS 分片。"""
1001
+ hdrs = {"User-Agent": UA_DESKTOP}
1002
+ final_url, html, title = url, "", ""
1003
+
1004
+ # 输入本身就是媒体直链
1005
+ if _is_media_url(url):
1006
+ name = urllib.parse.unquote(os.path.basename(urllib.parse.urlparse(url).path))
1007
+ title = os.path.splitext(name)[0] or "video"
1008
+ print(f" 直接媒体链接: {title}")
1009
+ h = dict(hdrs, Referer=url)
1010
+ if any(e in url.lower().split("?")[0] for e in HLS_EXT):
1011
+ return hls_download(url, os.path.join(out_dir, sanitize(title) + ".ts"), h, force)
1012
+ return download(url, os.path.join(out_dir, sanitize(title) + ".mp4"), h, force)
1013
+
1014
+ try:
1015
+ resp = http_get(url, dict(hdrs, Referer=url))
1016
+ html = resp.read().decode("utf-8", "ignore")
1017
+ final_url = resp.geturl()
1018
+ title = _page_title(html)
1019
+ print(f" 页面: {final_url[:120]}")
1020
+ if title:
1021
+ print(f" 标题: {title}")
1022
+ except Exception as e: # noqa: BLE001
1023
+ print(f" 页面读取失败({e}),直接转浏览器嗅探")
1024
+
1025
+ cookie = ""
1026
+ best = _pick_candidate(_collect_candidates(html, final_url), hdrs)
1027
+
1028
+ if not best:
1029
+ print(" 静态解析未命中,启动无头浏览器嗅探…")
1030
+ hits, cookie, btitle = _browser_sniff(final_url)
1031
+ title = title or btitle
1032
+ if hits:
1033
+ print(f" 嗅探到 {len(hits)} 个候选地址")
1034
+ h2 = dict(hdrs)
1035
+ if cookie:
1036
+ h2["Cookie"] = cookie
1037
+ best = _pick_candidate(hits, h2)
1038
+
1039
+ if not best:
1040
+ raise DownloadError("页面里没有可嗅探到的视频源(可能是 DRM/加密流或纯图文)")
1041
+
1042
+ print(f" 选中: {best['kind'].upper()} {best['url'][:120]}")
1043
+ h = dict(hdrs, Referer=final_url)
1044
+ if cookie:
1045
+ h["Cookie"] = cookie
1046
+ if not title:
1047
+ title = urllib.parse.urlparse(final_url).hostname or "video"
1048
+
1049
+ if best["kind"] == "hls":
1050
+ return hls_download(best["url"], os.path.join(out_dir, sanitize(title) + ".ts"), h, force)
1051
+ return download(best["url"], os.path.join(out_dir, sanitize(title) + ".mp4"), h, force)
1052
+
1053
+
1054
+ # ============================ 判定层 ============================
1055
+ SOURCE_NAMES = {
1056
+ "yangshipin": "央视频",
1057
+ "weixin": "微信公众号",
1058
+ "bilibili": "哔哩哔哩",
1059
+ "kuaishou": "快手",
1060
+ "douyin": "抖音",
1061
+ "generic": "通用嗅探(未知站点)",
1062
+ "ytdlp": "yt-dlp 通道(内置)",
1063
+ }
1064
+
1065
+ # 域名后缀 -> 平台。按 hostname 精确后缀比对,避免文案提到别家名字就误判。
1066
+ DOMAIN_RULES = (
1067
+ ("mp.weixin.qq.com", "weixin"),
1068
+ ("yangshipin.cn", "yangshipin"),
1069
+ ("yangshipin.com", "yangshipin"),
1070
+ ("bilibili.com", "bilibili"),
1071
+ ("b23.tv", "bilibili"),
1072
+ ("kuaishou.com", "kuaishou"),
1073
+ ("chenzhongtech.com", "kuaishou"),
1074
+ ("gifshow.com", "kuaishou"),
1075
+ ("kwaicdn.com", "kuaishou"),
1076
+ ("douyin.com", "douyin"),
1077
+ ("iesdouyin.com", "douyin"),
1078
+ )
1079
+
1080
+ URL_RE = re.compile(r"https?://[^\s\u4e00-\u9fff\"'<>))】]+", re.I)
1081
+
1082
+
1083
+ def extract_urls(text: str) -> list[str]:
1084
+ return URL_RE.findall(text or "")
1085
+
1086
+
1087
+ def detect_source(text: str) -> tuple[str | None, str, str]:
1088
+ """判定来源,返回 (平台, 依据, 规范化链接)。三级判定,不做网络试错。"""
1089
+ text = (text or "").strip()
1090
+ if not text:
1091
+ return None, "输入为空", ""
1092
+
1093
+ urls = extract_urls(text)
1094
+
1095
+ # ① 域名匹配(最可靠)
1096
+ for u in urls:
1097
+ try:
1098
+ host = (urllib.parse.urlparse(u).hostname or "").lower()
1099
+ except ValueError:
1100
+ continue
1101
+ if not host:
1102
+ continue
1103
+ for suffix, src in DOMAIN_RULES:
1104
+ if host == suffix or host.endswith("." + suffix):
1105
+ return src, f"域名 {host}", u
1106
+
1107
+ fallback = urls[0] if urls else text
1108
+
1109
+ # ② 作品 ID 特征
1110
+ m = re.search(BILI_BV_RE, text)
1111
+ if m:
1112
+ return "bilibili", f"BV 号 {m.group(1)}", fallback
1113
+ m = re.search(r"\bav(\d+)", text, re.I)
1114
+ if m:
1115
+ return "bilibili", f"av 号 av{m.group(1)}", fallback
1116
+ m = re.search(r"(?<!\d)(\d{19})(?!\d)", text)
1117
+ if m:
1118
+ return "douyin", f"抖音作品 ID {m.group(1)}", fallback
1119
+
1120
+ # ③ 分享文案关键词兜底
1121
+ low = text.lower()
1122
+ for kws, src in (
1123
+ (("抖音", "douyin"), "douyin"),
1124
+ (("快手", "kuaishou"), "kuaishou"),
1125
+ (("哔哩哔哩", "b站", "bilibili"), "bilibili"),
1126
+ (("央视频", "yangshipin"), "yangshipin"),
1127
+ (("公众号", "mp.weixin"), "weixin"),
1128
+ ):
1129
+ if any(k in low for k in kws):
1130
+ return src, f"文案关键词「{kws[0]}」", fallback
1131
+
1132
+ if urls:
1133
+ return "generic", f"未知站点 {urls[0][:60]},走通用嗅探", urls[0]
1134
+ return None, "未识别到链接或作品 ID", ""
1135
+
1136
+
1137
+ # 平台 -> 处理器(判定后直接查表,不逐个尝试)
1138
+ HANDLERS = {
1139
+ "yangshipin": yangshipin,
1140
+ "weixin": weixin,
1141
+ "bilibili": bilibili,
1142
+ "kuaishou": kuaishou,
1143
+ "douyin": douyin,
1144
+ "generic": generic,
1145
+ "ytdlp": yt_dlp_dl,
1146
+ }
1147
+
1148
+
1149
+ # ============================ 主流程 ============================
1150
+ def build_parser() -> argparse.ArgumentParser:
1151
+ p = argparse.ArgumentParser(
1152
+ prog=PROG,
1153
+ formatter_class=argparse.RawDescriptionHelpFormatter,
1154
+ description="统一视频下载器:央视频 / 微信公众号 / 哔哩哔哩 / 快手 / 抖音 + 未知站点通用嗅探",
1155
+ epilog="""示例:
1156
+ python H_seftom.py "https://www.bilibili.com/video/BV1xx411c7mD"
1157
+ python H_seftom.py "7.88 复制打开抖音… https://v.douyin.com/xxxx/" -o D:/视频
1158
+ python H_seftom.py "<链接>" --detect # 只看来源判定
1159
+ python H_seftom.py "BV1xx411c7mD" --as bilibili
1160
+ """,
1161
+ )
1162
+ p.add_argument("items", nargs="*", metavar="链接/分享文字",
1163
+ help="视频链接或分享文案,可给多个(每个之间用空格分隔)")
1164
+ p.add_argument("-o", "--out", default=OUT_DIR, metavar="目录",
1165
+ help=f"保存目录(默认 {OUT_DIR})")
1166
+ p.add_argument("-d", "--detect", action="store_true",
1167
+ help="只判定来源并打印,不下载")
1168
+ p.add_argument("--as", dest="force_src", choices=sorted(HANDLERS), metavar="平台",
1169
+ help="强制指定平台:" + " / ".join(sorted(HANDLERS)))
1170
+ p.add_argument("-f", "--force", action="store_true", help="覆盖同名文件(默认自动改名保留旧的)")
1171
+ p.add_argument("--yt-dlp", dest="use_ytdlp", action="store_true",
1172
+ help="直接用 yt-dlp 下载(跳过本程序自己的解析)")
1173
+ p.add_argument("--no-fallback", action="store_true",
1174
+ help="禁用自动兜底(默认本程序失败后会自动改用 yt-dlp 再试一次)")
1175
+ p.add_argument("-V", "--version", action="version", version=f"{PROG} {__version__}")
1176
+ return p
1177
+
1178
+
1179
+ def run_one(item: str, args: argparse.Namespace) -> str | None:
1180
+ """处理单个输入,返回输出路径(detect 模式返回 None)。"""
1181
+ if args.force_src:
1182
+ src, why, canon = args.force_src, "手动指定 --as", (extract_urls(item) or [item])[0]
1183
+ else:
1184
+ src, why, canon = detect_source(item)
1185
+
1186
+ if not src:
1187
+ raise DownloadError(f"无法识别视频来源({why})")
1188
+
1189
+ print(f"[来源] {SOURCE_NAMES.get(src, src)} ← {why}")
1190
+ if args.detect:
1191
+ if canon:
1192
+ print(f"[链接] {canon[:200]}")
1193
+ return None
1194
+
1195
+ target = canon or item
1196
+ print(f"[链接] {target[:200]}")
1197
+ print(f"[目录] {args.out}")
1198
+
1199
+ if args.use_ytdlp:
1200
+ return yt_dlp_dl(target, args.out, args.force)
1201
+
1202
+ try:
1203
+ return HANDLERS[src](target, args.out, args.force)
1204
+ except DownloadError as e:
1205
+ # 本程序处理不了时,自动换 yt-dlp 再试一次(本身就是 yt-dlp 通道就不重复)
1206
+ if src == "ytdlp" or args.no_fallback or not has_ytdlp():
1207
+ raise
1208
+ print(f" [!] 本程序未能下载({e})")
1209
+ print(" → 自动改用 yt-dlp 再试一次…")
1210
+ try:
1211
+ return yt_dlp_dl(target, args.out, args.force)
1212
+ except Exception as e2: # noqa: BLE001
1213
+ raise DownloadError(f"{e};yt-dlp 兜底也失败:{e2}")
1214
+
1215
+
1216
+ def main(argv: list[str] | None = None) -> int:
1217
+ args = build_parser().parse_args(argv)
1218
+ if not args.items:
1219
+ build_parser().print_help()
1220
+ return 2
1221
+
1222
+ ok, fail = 0, 0
1223
+ for idx, item in enumerate(args.items, 1):
1224
+ if len(args.items) > 1:
1225
+ print(f"\n===== [{idx}/{len(args.items)}] =====")
1226
+ try:
1227
+ run_one(item, args)
1228
+ ok += 1
1229
+ except KeyboardInterrupt:
1230
+ print("\n已中断")
1231
+ return 130
1232
+ except DownloadError as e:
1233
+ print(f"ERROR: {e}")
1234
+ fail += 1
1235
+ except Exception as e: # noqa: BLE001
1236
+ print(f"ERROR: 未预期异常 {type(e).__name__}: {e}")
1237
+ traceback.print_exc(limit=3)
1238
+ fail += 1
1239
+
1240
+ if len(args.items) > 1:
1241
+ print(f"\n完成:成功 {ok} 个,失败 {fail} 个")
1242
+ return 0 if fail == 0 else 1
1243
+
1244
+
1245
+ if __name__ == "__main__":
1246
+ sys.exit(main())