mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: Windows增加发送视频 dy下载脚本
This commit is contained in:
1 parent
ebea992b10
commit
b171818df5
8 files changed
+1262
-64
No files matched your search
@@ -260,12 +260,55 @@ function sleep(milliseconds) {
|
||||
return new Promise((resolve) => setTimeout(resolve, milliseconds))
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 Apple Silicon macOS 上,若宿主的默认 python3 是 x86_64(Rosetta 2),
|
||||
* 直接启动会把 P_TRANSLATED 标志遗传给子进程 Google Chrome,导致抖音页面卡在加载中。
|
||||
* 这里优先选用缓存 venv 的原生 Python,并通过 /usr/bin/arch -arm64 强制切换为原生 arm64。
|
||||
*/
|
||||
/** WindowsApps 下的是 Microsoft Store 别名,执行不成脚本,探测时要跳过。 */
|
||||
function isStoreAliasPath(value) {
|
||||
return /[\\/]WindowsApps[\\/]/i.test(String(value || ''))
|
||||
}
|
||||
|
||||
/** 在 PATH 中按顺序找第一个真实存在的可执行文件。 */
|
||||
function findOnPath(names) {
|
||||
const dirs = String(process.env.PATH || '')
|
||||
.split(path.delimiter)
|
||||
.filter((dir) => dir && !isStoreAliasPath(dir))
|
||||
for (const name of names) {
|
||||
for (const dir of dirs) {
|
||||
for (const ext of ['.exe', '.EXE', '']) {
|
||||
const candidate = path.join(dir, name + ext)
|
||||
try {
|
||||
if (fsSync.existsSync(candidate) && fsSync.statSync(candidate).isFile()) return candidate
|
||||
} catch {
|
||||
// 目录不可读就跳过,继续下一个候选。
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** 配置为空或是默认名时,按 py -3 → python 的顺序探测。 */
|
||||
function resolveWindowsPython(pythonPath) {
|
||||
const configured = expandHome(pythonPath)
|
||||
const looksDefault = !configured || configured === 'python' || configured === 'python3'
|
||||
if (!looksDefault && !isStoreAliasPath(configured)) {
|
||||
return { file: configured, prefixArgs: [] }
|
||||
}
|
||||
const py = findOnPath(['py'])
|
||||
if (py) return { file: py, prefixArgs: ['-3'] }
|
||||
const python = findOnPath(['python'])
|
||||
if (python) return { file: python, prefixArgs: [] }
|
||||
return { file: 'python', prefixArgs: [] }
|
||||
}
|
||||
|
||||
// Apple Silicon 上 x86_64 的 python3 会把 P_TRANSLATED 传给 Chrome,页面卡加载;
|
||||
// 优先用 venv 原生解释器并经 /usr/bin/arch -arm64 强制原生运行。
|
||||
function resolvePythonInvocation(pythonPath, scriptPath, args) {
|
||||
if (process.platform === 'win32') {
|
||||
const resolved = resolveWindowsPython(pythonPath)
|
||||
return {
|
||||
file: resolved.file,
|
||||
args: [...resolved.prefixArgs, scriptPath, ...args]
|
||||
}
|
||||
}
|
||||
if (process.platform !== 'darwin') {
|
||||
return { file: pythonPath, args: [scriptPath, ...args] }
|
||||
}
|
||||
@@ -414,10 +457,10 @@ async function resolveAndDownloadVideo(url, config, options = {}) {
|
||||
} catch (error) {
|
||||
stdout = String((error && error.stdout) || '')
|
||||
if (!stdout.trim()) {
|
||||
return parseFailure(
|
||||
temporaryCookieFile ? 'Cookie 文件不可用或解析超时' : describeExecError(error),
|
||||
temporaryCookieFile ? 'COOKIE_OR_TIMEOUT' : errorType(error)
|
||||
)
|
||||
// 别把失败统一报成「Cookie 不可用」,否则 ENOENT 和脚本退出码都被盖掉。
|
||||
const reason = describeExecError(error)
|
||||
const withMode = temporaryCookieFile ? `${reason}(Cookie 模式)` : reason
|
||||
return parseFailure(withMode, temporaryCookieFile ? 'COOKIE_OR_TIMEOUT' : errorType(error))
|
||||
}
|
||||
} finally {
|
||||
if (temporaryCookieFile) {
|
||||
|
||||
@@ -20,10 +20,14 @@ const DEFAULT_SCRIPT_PATH = 'scripts/douyin.py'
|
||||
/** 画质白名单;空串表示「最高」,不传 `-q` 给脚本。 */
|
||||
const QUALITY_VALUES = ['', '1080', '720', '540']
|
||||
|
||||
// Windows 的 python3.exe 通常是 Microsoft Store 别名,执行不成脚本。
|
||||
const DEFAULT_PYTHON_PATH =
|
||||
typeof process !== 'undefined' && process.platform === 'win32' ? 'python' : 'python3'
|
||||
|
||||
const DEFAULT_CONFIG = {
|
||||
configVersion: 1,
|
||||
enabled: false,
|
||||
pythonPath: 'python3',
|
||||
pythonPath: DEFAULT_PYTHON_PATH,
|
||||
scriptPath: DEFAULT_SCRIPT_PATH,
|
||||
quality: '720',
|
||||
/** 排障开关:显示浏览器窗口以观察实际页面状态。 */
|
||||
@@ -214,18 +218,29 @@ function parseSavedPath(stdout) {
|
||||
// 去掉尾部的「(N 个文件)」之类附注,它不属于路径。
|
||||
rest = rest.replace(/\s*[((][^(())]*[))]\s*$/, '').trim()
|
||||
if (!rest) continue
|
||||
if (rest[0] !== '/') continue
|
||||
if (!isAbsoluteMediaPath(rest)) continue
|
||||
return rest
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// 绝对路径判定:POSIX `/x`、Windows `C:\x` / `C:/x`、UNC `\\server\share`。
|
||||
function isAbsoluteMediaPath(value) {
|
||||
if (typeof value !== 'string') return false
|
||||
const text = value.trim()
|
||||
if (!text) return false
|
||||
if (text.startsWith('/')) return true // POSIX
|
||||
if (/^[A-Za-z]:[\\/]/.test(text)) return true // C:\ 或 C:/
|
||||
if (text.startsWith('\\\\')) return true // UNC \\server\share
|
||||
return false
|
||||
}
|
||||
|
||||
function parseDownloadedResult(stdout) {
|
||||
const results = parseResolveJson(stdout)
|
||||
const video = pickVideoResult(results)
|
||||
if (video) {
|
||||
const saved = Array.isArray(video.saved)
|
||||
? video.saved.find((value) => typeof value === 'string' && value.startsWith('/'))
|
||||
? video.saved.find((value) => isAbsoluteMediaPath(value))
|
||||
: null
|
||||
if (saved) return { ok: true, meta: video, path: saved }
|
||||
if (video.error) return { ok: false, message: video.error, errorType: 'DOWNLOAD_FAILED' }
|
||||
@@ -346,6 +361,7 @@ module.exports = {
|
||||
extractDouyinUrl,
|
||||
parseResolveJson,
|
||||
parseSavedPath,
|
||||
isAbsoluteMediaPath,
|
||||
parseDownloadedResult,
|
||||
renderCaption,
|
||||
shouldHandle,
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
用 urllib 从镜像拉 wheel,再交给 pip 本地安装 —— 绕开 pip 自己那层网络栈。
|
||||
|
||||
python fetch_wheels.py <目标目录> [包名 ...]
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
MIRRORS = [
|
||||
"https://pypi.tuna.tsinghua.edu.cn/simple",
|
||||
"https://mirrors.aliyun.com/pypi/simple",
|
||||
]
|
||||
|
||||
DEFAULT_PACKAGES = ["requests", "playwright"]
|
||||
|
||||
WHEEL_RE = re.compile(r'href="([^"#]+\.whl)[^"]*"')
|
||||
VER_RE = re.compile(r'-(\d+(?:\.\d+)*)')
|
||||
|
||||
# 部分镜像对浏览器 UA 返回 403,用 pip 自己的才放行。
|
||||
USER_AGENT = "pip/26.1.2"
|
||||
|
||||
|
||||
def page_links(mirror: str, package: str) -> list[str]:
|
||||
"""索引页 href 是相对路径,用 urljoin 归一。"""
|
||||
url = f"{mirror}/{package}/"
|
||||
ctx = ssl.create_default_context()
|
||||
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=30, context=ctx) as resp:
|
||||
html = resp.read().decode("utf-8", "replace")
|
||||
return [urllib.parse.urljoin(url, href) for href in WHEEL_RE.findall(html)]
|
||||
|
||||
|
||||
def wheel_key(name: str) -> tuple:
|
||||
"""排序键:越靠后越优先。"""
|
||||
base = name.rsplit("/", 1)[-1].lower()
|
||||
pure = 1 if ("none-any" in base) else 0
|
||||
win_amd64 = 1 if "win_amd64" in base else 0
|
||||
cp313 = 1 if "cp313" in base else 0
|
||||
abi3 = 1 if "abi3" in base else 0
|
||||
return (pure, win_amd64, abi3, cp313)
|
||||
|
||||
|
||||
def version_key(url: str) -> tuple:
|
||||
"""从文件名取版本号数字段。"""
|
||||
m = VER_RE.search(url.rsplit("/", 1)[-1])
|
||||
if not m:
|
||||
return ()
|
||||
return tuple(int(part) for part in m.group(1).split("."))
|
||||
|
||||
|
||||
def pick(links: list[str]) -> str | None:
|
||||
"""挑一个 Windows x64 / cp313 可用的 wheel。"""
|
||||
candidates = []
|
||||
for link in links:
|
||||
low = link.lower()
|
||||
if "macosx" in low or "manylinux" in low or "musllinux" in low:
|
||||
continue
|
||||
if "win32" in low or "win_arm64" in low:
|
||||
continue
|
||||
if "none-any.whl" in low or "win_amd64.whl" in low:
|
||||
candidates.append(link)
|
||||
if not candidates:
|
||||
return None
|
||||
candidates.sort(key=lambda url: (wheel_key(url), version_key(url)))
|
||||
return candidates[-1]
|
||||
|
||||
|
||||
def download(url: str, dest_dir: Path) -> Path:
|
||||
name = url.rsplit("/", 1)[-1].split("#")[0]
|
||||
target = dest_dir / name
|
||||
if target.exists() and target.stat().st_size > 0:
|
||||
print(f" cached {name}")
|
||||
return target
|
||||
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
data = resp.read()
|
||||
target.write_bytes(data)
|
||||
print(f" saved {name} ({len(data)//1024} KB)")
|
||||
return target
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
return 2
|
||||
dest = Path(sys.argv[1]).expanduser()
|
||||
packages = sys.argv[2:] or DEFAULT_PACKAGES
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
failed = []
|
||||
for package in packages:
|
||||
print(f"[{package}]")
|
||||
chosen = None
|
||||
for mirror in MIRRORS:
|
||||
try:
|
||||
links = page_links(mirror, package)
|
||||
except Exception as exc:
|
||||
print(f" mirror {mirror} failed: {type(exc).__name__}")
|
||||
continue
|
||||
chosen = pick(links)
|
||||
if chosen:
|
||||
print(f" mirror {mirror}")
|
||||
break
|
||||
if not chosen:
|
||||
print(" no compatible wheel found")
|
||||
failed.append(package)
|
||||
continue
|
||||
try:
|
||||
download(chosen, dest)
|
||||
except Exception as exc:
|
||||
print(f" download failed: {type(exc).__name__} {exc}")
|
||||
failed.append(package)
|
||||
|
||||
if failed:
|
||||
print("FAILED: " + ", ".join(failed))
|
||||
return 1
|
||||
print(f"OK -> {dest}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -16,6 +16,7 @@ const {
|
||||
extractDouyinUrl,
|
||||
parseResolveJson,
|
||||
parseSavedPath,
|
||||
isAbsoluteMediaPath,
|
||||
parseDownloadedResult,
|
||||
renderCaption,
|
||||
shouldHandle,
|
||||
@@ -190,6 +191,31 @@ test('从 JSON 下载结果同时提取作品元数据和保存路径', () => {
|
||||
)
|
||||
})
|
||||
|
||||
test('Windows 盘符路径同样算绝对路径', () => {
|
||||
const winPath = 'C:\\fixture\\Downloads\\张三 - 标题 - 730.mp4'
|
||||
assert.equal(isAbsoluteMediaPath(winPath), true)
|
||||
assert.equal(isAbsoluteMediaPath('C:/fixture/a.mp4'), true)
|
||||
assert.equal(isAbsoluteMediaPath('\\\\server\\share\\a.mp4'), true)
|
||||
assert.equal(isAbsoluteMediaPath('Downloads/a.mp4'), false)
|
||||
assert.equal(isAbsoluteMediaPath(''), false)
|
||||
assert.equal(isAbsoluteMediaPath(null), false)
|
||||
|
||||
// 只认 '/' 开头会把 Windows 的 ✅ 行整条丢掉
|
||||
const stdout = [
|
||||
' ✓ 解析成功:video | 张三 | 标题',
|
||||
' ✅ ' + winPath,
|
||||
' 5.2MB | MP4'
|
||||
].join('\n')
|
||||
assert.equal(parseSavedPath(stdout), winPath)
|
||||
|
||||
const json = JSON.stringify([
|
||||
{ url: 'https://v.douyin.com/fixture123', ok: true, type: 'video', saved: [winPath] }
|
||||
])
|
||||
const parsed = parseDownloadedResult(json)
|
||||
assert.equal(parsed.ok, true)
|
||||
assert.equal(parsed.path, winPath)
|
||||
})
|
||||
|
||||
test('JSON 下载失败保留脚本错误,图集保持不支持状态', () => {
|
||||
assert.deepEqual(
|
||||
parseDownloadedResult(
|
||||
@@ -247,7 +273,8 @@ test('默认配置符合约定', () => {
|
||||
const config = normalizeConfig(undefined)
|
||||
assert.equal(config.configVersion, 1)
|
||||
assert.equal(config.enabled, false)
|
||||
assert.equal(config.pythonPath, 'python3')
|
||||
// Windows 的 python3.exe 通常是 Microsoft Store 的应用执行别名,默认改用 python。
|
||||
assert.equal(config.pythonPath, process.platform === 'win32' ? 'python' : 'python3')
|
||||
assert.equal(config.scriptPath, 'scripts/douyin.py')
|
||||
assert.equal(config.quality, '720')
|
||||
assert.equal(config.showUi, false)
|
||||
|
||||
Reference in new issue
Block a user