Compare commits

...
8 Commits
14 changed files with 933 additions and 196 deletions

No files matched your search

+1
View File
@@ -7,3 +7,4 @@ rsa.json
.venv/
_dist/
*.zip
_build_exe/
+68 -22
View File
@@ -1,7 +1,26 @@
# 资源信息抓取工具 v1.7.1
# 资源信息抓取工具 v1.7.3
从米哈游 dispatch 抓 `query_cur_region`,再按设备展开成「每台设备一份」的 region_info JSON(文件名 = 设备 + 实得版本),
并额外生成 **RS 直更**文件(`<设备>_version.txt` / `version.txt` / `rs.json`)。
**v1.7.3 更新:输出不再散落一地,编辑配置不再卡死**
- **每次抓取单独一个文件夹**:输出根目录下按时间戳建一个目录(如 `out/20261121-172005/`),`json/`、`txt/`、`index.json` 全在里面,根目录只留一个个运行批次,不再堆成一片。想恢复旧行为:命令行加 `--no-run-dir`,或把 `config.json` 的 `output.runDir` 设成 `false`。
- **「编辑 config.json」不再卡死**:以前是 `os.startfile()` 交给系统默认程序打开 `.json`,机器上没有关联程序(或关联到会阻塞的编辑器)时按钮就跟死了一样。现在直接弹内置编辑窗口:白底等宽字体、`Ctrl+S` 保存、保存前校验 JSON 语法(报错会告诉你第几行第几列),另有「另存为」和「用系统程序打开」(后者放到后台线程,不阻塞界面)。
- **打包强制校验 rsa.json**:`build.py` 找不到 `rsa.json` 直接报错退出(它被 `.gitignore` 忽略,之前缺了也会照打,出来的 exe 一跑就是「读取 rsa.json 失败」)。
- **控制台编码兜底**:cmd 是 GBK 时,摘要里的 `✓` 之类字符会抛 `UnicodeEncodeError` 把命令行版直接干掉;现在输出流非 UTF-8 时自动降级成「无法编码就打 ?」,不会再崩。
- `_build_exe/` 加入 `.gitignore`(打包中间产物不再进仓库)。
**v1.7.2 更新:下载不再「卡死」,界面换成白色简约** —— 以前只要 CDN 那边一卡住(发了个 `Content-Length` 就不再发数据),一个文件要 `60s 超时 × 3 次重试 × 8 个分块` 才肯认输,这期间进度条一动不动、整个下载队列像死机。现在:
- 建连 6s、单次读 5s、另有 5s「一字节都没收到就判卡住」的看门狗;卡住就换连接重来,单个文件总重试预算 40s 封顶(实测同场景从 **197 秒 → 12 秒**返回失败,不再拖死队列)。
- 点「停止」和「暂停」直接掐掉在途连接,**3 秒内**全部收手(以前要等读超时才回来)。
- 分块下载每块写独立 `<文件名>.part.N`,成功后按序拼装 —— 不再让 16 个线程抢一个文件句柄,出错也不会留半截数据。
- 失败原因写清楚:`连接卡住:5s 内没有收到数据(已放弃这个文件)`,不再落回单流白等一轮。
- 下载管理器一次插几千行改为分批(每帧 300 行)、进度只刷有变化的行、调度线程去重,6800 个文件的队列照样能点。
- **界面整体换成白色简约**:主窗口、资源下载窗口、下载管理器统一白底 + `#f7f8fa` 表头 + `#e6e8eb` 描边,按钮/复选框扁平化,进度条改 8px 圆润蓝条。
- 顺手修掉 `config.json` 里 `transfer.files / threads / chunks` 一直没生效的问题(`self.cfg` 之前根本没定义,异常被吞掉后永远按 4 并发跑),「下载到」输入框里改的目录现在也真的会被用上。
**v1.7.1 更新:资源下载窗口不再卡死** —— 之前一打开「资源下载」会把六七千个文件行一次性塞进列表,界面卡到像死机。现在只在展开时才建子行:点设备行左边三角展开看文件夹(每台几十个文件夹),再展开文件夹才分批(每批 300 行)填文件;消息泵每轮最多处理 120 条,界面全程能操作。实测打开 0.03 秒、扫描 6.8 秒、展开设备 0.02 秒、展开 603 个文件的文件夹 0.07 秒,全程 0 次「未响应」。
**v1.6.0 更新:下载修好 + 按文件夹分组 + 客户端数据(client_design_data)** —— 上次「全部下载失败」是下载窗口拿到了失效的会话对象;现在每个文件都会重试、404 单独标「CDN 上不存在」。列表不再平铺几千行:设备 → 文件夹 → 文件,点文件夹勾上就下整个文件夹。另新增「客户端数据」分组(与 `client_game_res` 同级的 `client_design_data`,含 `AssetBundles/data_versions` 与它列出的 blk,7.2 分支约 534 个 / 1.2 GB)。 —— 抓完点「资源下载」,列表按 Android / iOS / Win / PS5 分成几个大类,点设备行勾上(☑)就下该设备的热更资源,多台一起勾也行;档位、体积统计、镜像目录结构(与 CDN 一致)都在。
@@ -86,26 +105,29 @@ G:\资源信息抓取工具\
## 输出
每次抓取会新建一个带时间戳的文件夹(v1.7.3),一次运行的产物全在里面:
```
out\
├─ json\ ← 所有 .json
│ ├─ CNRELAndroid7.2.0.json 9060 B 详细版(_meta / rs / response 全字段)
│ ├─ index.json 本次抓取一览
│ └─ 7.2.0\
│ ├─ CNRELAndroid7.2.0.json 1973 B 每台设备一份(对齐 cbt 结构)
│ ├─ CNRELiOS7.2.0.json 1974 B
│ ├─ CNRELWin7.2.0.json 1976 B
│ ├─ CNRELPS57.2.0.json 1972 B
│ ├─ CNRELEDITOR7.2.0.json 953 B
│ ├─ CNRELSERVER7.2.0.json 961 B
│ └─ rs.json 3507 B RS 各段的汇总
└─ txt\ ← 所有 .txt
└─ 7.2.0\
├─ Android_version.txt 654 B RS 直更(res 段,按设备)
├─ iOS_version.txt 655 B
├─ PC_version.txt 657 B
├─ PS5_version.txt 653 B
└─ version.txt 590 B RS 直更(client 段)
└─ 20261121-172005\ ← 本次运行(时间戳;加 --no-run-dir 或 output.runDir=false 可关掉)
├─ json\ ← 所有 .json
│ ├─ CNRELAndroid7.2.0.json 9060 B 详细版(_meta / rs / response 全字段)
│ ├─ index.json 本次抓取一览
│ └─ 7.2.0\
│ ├─ CNRELAndroid7.2.0.json 1973 B 每台设备一份(对齐 cbt 结构)
│ ├─ CNRELiOS7.2.0.json 1974 B
│ ├─ CNRELWin7.2.0.json 1976 B
│ ├─ CNRELPS57.2.0.json 1972 B
│ ├─ CNRELEDITOR7.2.0.json 953 B
│ ├─ CNRELSERVER7.2.0.json 961 B
│ └─ rs.json 3507 B RS 各段的汇总
└─ txt\ ← 所有 .txt
└─ 7.2.0\
├─ Android_version.txt 654 B RS 直更(res 段,按设备)
├─ iOS_version.txt 655 B
├─ PC_version.txt 657 B
├─ PS5_version.txt 653 B
└─ version.txt 590 B RS 直更(client 段)
```
`.json` 与 `.txt` 分开放(默认开启);要旧版混排加 `--no-split`。
@@ -225,12 +247,36 @@ RS 直更文件格式与 `F:\RS\<版本>\<设备>_version.txt` 一致:
## 源码方式运行(可选)
`工具\` 里是同一套 Python 源码,需要 `G:\getcur\.venv\Scripts\python.exe`(自带 requests / rsa / protobuf),
以及 `G:\getcur\dispatch.py`、`G:\getcur\rsa.json`(key_id 1–5 私钥)。脚本会依次找:自身目录 → 上级目录 →
环境变量 `GETCUR_HOME` → `G:\getcur`,所以整个文件夹可以搬走。
`工具\` 里是同一套 Python 源码,需要 Python 3.9+ 与 `requirements.txt` 里的依赖(requests / urllib3 / rsa / protobuf),
以及 `dispatch.py`、`rsa.json`(key_id 1–5 私钥)和 `proto/` 下生成的 `QueryCurrRegionHttpRsp_pb2.py`。脚本会依次找:自身目录 → 上级目录 →
环境变量 `GETCUR_HOME` → `G:\getcur`,所以整个文件夹可以搬走(越前面的目录优先级越高,脚本所在目录永远排第一)。
exe 已内嵌 `rsa.json`、`devices.json`、`config.json` 的副本;同目录放了同名文件时**优先用外面的**,方便改。
## 自己打包成 exe
仓库不带二进制产物(`_dist/` 已 ignore),要 exe 就本地打一次:
```
python -m pip install pyinstaller
python build.py (或双击 打包.bat)
```
产物:
```
_dist\gui\资源信息抓取工具.exe ← 图形界面(双击这个,或双击 打开抓取工具.bat)
_dist\cli\资源信息抓取工具-命令行.exe ← 命令行版(或双击 命令行抓取.bat)
```
- **目录版**,双击即开,不需要解包到 `%TEMP%`;发给别人时把整个文件夹压成 zip 一起发(exe 离不开同目录的 `_internal\`)。
- 加 `--onefile` 可出单文件 exe,但它每次启动都要解包到 `%TEMP%`,遇到中文用户名或杀软拦截会报
`Could not create temporary directory`,不推荐。
- 目录名 `gui` / `cli` 保持 ASCII,是为了让 `.bat` 用通配符找 exe,不受控制台代码页影响。
- 打包需要 `proto\`(`QueryCurrRegionHttpRsp_pb2.py` 等)——项目里没有就把 getcur 项目的 `proto` 目录拷到项目根,
或设 `GETCUR_HOME` 指过去。`rsa.json` 若在项目根会被打进包内。
- `打开抓取工具.bat` / `命令行抓取.bat` 会优先用 `_dist\` 里的 exe,回退到项目根的 exe,都没有就提示先打包。
## License
MIT © 2026 蓝色大肥鱼
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""把工具打包成 Windows 可执行文件(PyInstaller,目录版,免解包)。
用法(在项目根目录):
python 打包.py # 产物:_dist\\资源信息抓取工具\\资源信息抓取工具.exe
python 打包.py --onefile # 单文件 exe(启动时要解包到 %TEMP%,杀软/中文用户名环境偶发失败)
要点:
- 目录版(默认)不写临时目录,双击即开,最稳;要发给别人就压整个文件夹。
- 依赖 `proto/` 里的 pb2 模块(本仓库不含,需从 getcur 项目拷一份到项目根 `proto\\`,
或用环境变量 GETCUR_HOME 指向它所在的父目录)。
- rsa.json 若在项目根会被打进包内(它被 .gitignore 忽略,属于本地文件)。
"""
from __future__ import annotations
import os
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent
TOOLS = ROOT / "工具"
STAGE = ROOT / "_build_exe" / "_stage"
PROTO_DST = STAGE / "proto"
BUILD_WORK = ROOT / "_build_exe" / "work"
SPEC = ROOT / "_build_exe" / "spec"
DIST = ROOT / "_dist"
SOURCES = ("fetch_devices_gui.py", "fetch_devices.py", "dispatch.py", "appconfig.py",
"region_fanout.py", "resdown.py", "resdown_gui.py", "dl_manager.py",
"config.json", "devices.json")
HIDDEN = ("dispatch", "appconfig", "fetch_devices", "region_fanout", "dl_manager",
"resdown", "resdown_gui", "proto", "proto.ForceUpdateInfo_pb2",
"proto.QueryCurrRegionHttpRsp_pb2", "proto.QueryRegionListHttpRsp_pb2")
def find_proto() -> Path:
"""proto 包所在目录:项目根 → GETCUR_HOME → G:\\getcur。"""
candidates = [ROOT / "proto"]
home = os.environ.get("GETCUR_HOME")
if home:
candidates.append(Path(home) / "proto")
candidates.append(Path(r"G:\getcur\proto"))
for cand in candidates:
if (cand / "QueryCurrRegionHttpRsp_pb2.py").exists():
return cand
raise SystemExit(
"找不到 proto/(需要 QueryCurrRegionHttpRsp_pb2.py 等)。\n"
"把 getcur 项目的 proto 目录拷到本目录下,或设置 GETCUR_HOME。")
def prepare_proto() -> Path:
"""proto 是命名空间包(没有 __init__.py),补一个让 PyInstaller 当普通包收集。"""
src = find_proto()
if PROTO_DST.exists():
shutil.rmtree(PROTO_DST)
PROTO_DST.mkdir(parents=True)
for p in src.glob("*.py"):
shutil.copy2(p, PROTO_DST / p.name)
(PROTO_DST / "__init__.py").write_text("", encoding="utf-8")
return PROTO_DST
def require_rsa() -> Path:
"""rsa.json 必须存在:缺了它加密响应解不开,打包出来的 exe 一跑就报错。"""
for cand in (ROOT / "rsa.json", TOOLS / "rsa.json"):
if cand.exists():
return cand
raise SystemExit(
"缺少 rsa.json(RSA 私钥,.gitignore 忽略的本地文件)。\n"
"把 rsa.json 放到项目根目录或 工具\\ 目录后再打包,或用 --rsa 指定。")
def common_args() -> list[str]:
proto = prepare_proto()
args = [
"--noconfirm", "--clean",
"--paths", str(TOOLS),
"--paths", str(proto.parent),
"--distpath", str(DIST),
"--workpath", str(BUILD_WORK),
"--specpath", str(SPEC),
]
for mod in HIDDEN:
args += ["--hidden-import", mod]
sep = ";" if sys.platform == "win32" else ":"
for path in (TOOLS / "config.json", TOOLS / "devices.json", require_rsa()):
args += ["--add-data", "%s%s%s" % (path, sep, ".")]
return args
def unblock(path: Path) -> None:
"""去掉 Zone.Identifier(「文件来自其他计算机」标记),少一次 SmartScreen 拦截。
不能替代代码签名:没有签名证书时 Windows 仍可能提示「未知发布者」,
但本地打包/本地复制过来的文件去掉这个流之后通常就直接开了。
"""
if sys.platform != "win32":
return
try:
subprocess.run(["powershell", "-NoProfile", "-Command",
"Unblock-File -LiteralPath '%s'" % path], capture_output=True)
except OSError:
pass
def build(entry: Path, name: str, args: list[str], *, windowed: bool, onefile: bool) -> None:
cmd = [sys.executable, "-m", "PyInstaller", *args,
*(["--onefile"] if onefile else []),
"--windowed" if windowed else "--console", "--name", name, str(entry)]
print("\n>>>", name, flush=True)
proc = subprocess.run(cmd, cwd=str(ROOT))
if proc.returncode != 0:
raise SystemExit("打包失败:%s(exit %d)" % (name, proc.returncode))
def main() -> int:
onefile = "--onefile" in sys.argv
for name in SOURCES:
if not (TOOLS / name).exists():
raise SystemExit("缺少 工具/%s" % name)
try:
branch = subprocess.run(["git", "-C", str(ROOT), "branch", "--show-current"],
capture_output=True, text=True).stdout.strip()
except OSError:
branch = ""
if branch:
print("当前分支:%s" % branch)
args = common_args()
DIST.mkdir(parents=True, exist_ok=True)
build(TOOLS / "fetch_devices_gui.py", "资源信息抓取工具", args, windowed=True, onefile=onefile)
build(TOOLS / "fetch_devices.py", "资源信息抓取工具-命令行", args, windowed=False, onefile=onefile)
# 目录换成 ASCII 名(gui / cli),.bat 里就能用通配符找 exe,不必写中文
if not onefile:
for old, new in ((DIST / "资源信息抓取工具", DIST / "gui"),
(DIST / "资源信息抓取工具-命令行", DIST / "cli")):
if old.exists():
if new.exists():
shutil.rmtree(new)
old.rename(new)
# exe 旁边放一份 config.json / devices.json,方便直接改(优先于包内副本)
targets = [DIST] if onefile else [DIST / "gui", DIST / "cli"]
for dest in targets:
for fn in ("config.json", "devices.json"):
shutil.copy2(TOOLS / fn, dest / fn)
# 去掉「网络文件」标记,减少 SmartScreen 的「未知发布者」拦截
for exe in DIST.rglob("*.exe"):
unblock(exe)
print("\n产物:")
for p in sorted(DIST.rglob("*.exe")):
print(" %-52s %7.2f MB" % (str(p.relative_to(DIST)), p.stat().st_size / 1048576))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+4
View File
@@ -0,0 +1,4 @@
requests>=2.28
urllib3>=1.26
rsa>=4.9
protobuf>=3.20
+10 -1
View File
@@ -1,6 +1,15 @@
@echo off
setlocal
chcp 65001 >nul
"%~dp0资源信息抓取工具-命令行.exe" %*
set "EXE="
for %%F in ("%~dp0_dist\cli\*.exe") do set "EXE=%%~fF"
if not defined EXE for %%F in ("%~dp0*.exe") do if not "%%~nF"=="%EXE%" set "EXE=%%~fF"
if not defined EXE (
echo [x] cli exe not found - build it first:
echo python build.py
pause
exit /b 1
)
"%EXE%" %*
echo.
pause
+5 -2
View File
@@ -9,7 +9,7 @@ config.json 放在 exe / 脚本同目录(其次内部打包副本)。
{
"_说明": "...",
"output": { "dir": "out", "splitJsonTxt": true, "versionDir": true },
"output": { "dir": "out", "runDir": true, "splitJsonTxt": true, "versionDir": true },
"transfer": {
"threads": 16,
"chunks": 8,
@@ -37,6 +37,7 @@ TEMPLATE: Dict[str, Any] = {
"命令行参数会覆盖这里的值。",
"_字段说明": {
"output.dir": "输出目录,相对路径按 exe 所在目录算",
"output.runDir": "true=每次抓取在输出目录下建一个时间戳文件夹(json\\、txt\\、index.json 全在里面),false=直接写输出目录",
"output.splitJsonTxt": "true=json 与 txt 分开放(json\\版本\\、txt\\版本\\)",
"output.versionDir": "true=按版本号建子目录(7.2.0\\),false=平铺",
"network.retries/backoff/timeout": "失败重试次数 / 退避秒 / 单次超时秒",
@@ -51,7 +52,7 @@ TEMPLATE: Dict[str, Any] = {
"entries[].version": "协议键,必须和 dispatchSeed 配套(写 4.6.0 也能拿到 7.2 数据)",
"entries[].dispatchSeed": "抓包得到的一次性种子,缺了这条就抓不了",
},
"output": {"dir": "out", "splitJsonTxt": True, "versionDir": True},
"output": {"dir": "out", "runDir": True, "splitJsonTxt": True, "versionDir": True},
"network": {"retries": 3, "backoff": 2.0, "timeout": 15, "noProxy": True},
"fanout": {
"enable": True,
@@ -149,6 +150,8 @@ def as_defaults(cfg: Dict[str, Any]) -> Dict[str, Any]:
out["split"] = o["splitJsonTxt"]
if isinstance(o.get("versionDir"), bool):
out["version_dir"] = o["versionDir"]
if isinstance(o.get("runDir"), bool):
out["no_run_dir"] = not o["runDir"]
n = cfg.get("network") or {}
if isinstance(n.get("retries"), int):
+2 -1
View File
@@ -23,7 +23,8 @@
"output": {
"dir": "out",
"splitJsonTxt": true,
"versionDir": true
"versionDir": true,
"runDir": true
},
"network": {
"retries": 3,
+93 -37
View File
@@ -19,19 +19,22 @@ from typing import Any, Callable, Dict, List, Optional, Tuple
import resdown
# ---------------------------------------------------------------- 配色
# ---------------------------------------------------------------- 配色(白色简约)
BG = "#11151c"
BG2 = "#161b24"
BG3 = "#1c2330"
FG = "#e6edf7"
FGD = "#93a2b8"
ACC = "#4f8cf7"
OK = "#3fb950"
WARN = "#d29922"
BAD = "#f85149"
BG = "#ffffff"
BG2 = "#ffffff"
BG3 = "#f4f5f7"
BORDER = "#e6e8eb"
FG = "#1f2328"
FGD = "#6b7280"
ACC = "#2f6feb"
SEL = "#eaf1fe"
OK = "#1a7f37"
WARN = "#9a6700"
BAD = "#cf222e"
CELLS = 12 # 进度条格数
ROW_BATCH = 300 # 每次往树里插多少行(一次插几千行会把界面卡住好几秒)
def human(n: float) -> str:
@@ -151,6 +154,7 @@ class DownloadManager(tk.Toplevel):
self.out_root = out_root
self.threads = threads
self.concurrency = tk.IntVar(value=max(1, min(16, concurrency)))
self._conc = max(1, min(16, concurrency)) # 调度线程只读这个普通 int
self.q: "queue.Queue[Tuple[str, Any]]" = queue.Queue()
self.tasks: List[Task] = []
@@ -164,25 +168,29 @@ class DownloadManager(tk.Toplevel):
self.missing_count = 0
self.bytes_done = 0
self.bytes_total = 0
# 待插入的行(一次 insert 几千行会让窗口卡死,按批喂给 Treeview)
self._pending_rows: List[Tuple[str, Tuple[str, ...]]] = []
# 同一时间只允许一个调度线程在跑(以前每次空闲都 spawn,线程会越堆越多)
self._sched_running = False
self._summary_t = 0.0
self._build()
self._add_tasks(items)
self.protocol("WM_DELETE_WINDOW", self._on_close)
self.after(120, self._pump)
self.after(250, self.start_all)
# ------------------------------------------------------------ 布局
def _build(self) -> None:
top = tk.Frame(self, bg=BG)
top = tk.Frame(self, bg=BG, highlightthickness=1, highlightbackground=BORDER)
top.pack(fill="x", padx=10, pady=(10, 4))
def btn(text: str, cmd: Callable[[], None], width: int = 10) -> tk.Button:
b = tk.Button(top, text=text, command=cmd, width=width, bg=BG3, fg=FG,
activebackground=ACC, activeforeground="#fff",
relief="flat", bd=0, padx=8, pady=5,
font=("Microsoft YaHei UI", 9))
b.pack(side="left", padx=(0, 6))
activebackground="#e8eaee", activeforeground=FG,
relief="flat", bd=0, padx=8, pady=5, highlightthickness=0,
cursor="hand2", font=("Microsoft YaHei UI", 9))
b.pack(side="left", padx=(6 if text == "开始" else 0, 6), pady=6)
return b
self.btn_start = btn("开始", self.start_all, 8)
@@ -194,9 +202,12 @@ class DownloadManager(tk.Toplevel):
tk.Label(top, text="并发文件", bg=BG, fg=FGD,
font=("Microsoft YaHei UI", 9)).pack(side="left", padx=(10, 4))
tk.Spinbox(top, from_=1, to=16, width=4, textvariable=self.concurrency,
bg=BG3, fg=FG, buttonbackground=BG3, relief="flat",
insertbackground=FG).pack(side="left")
spin = tk.Spinbox(top, from_=1, to=16, width=4, textvariable=self.concurrency,
bg=BG3, fg=FG, buttonbackground=BG3, relief="flat",
highlightthickness=1, highlightbackground=BORDER,
insertbackground=FG, command=self._sync_conc)
spin.pack(side="left")
spin.bind("<KeyRelease>", lambda e: self._sync_conc())
self.lbl_threads = tk.Label(top, text="每文件 %d 线程" % self.threads, bg=BG, fg=FGD,
font=("Microsoft YaHei UI", 9))
self.lbl_threads.pack(side="left", padx=(10, 0))
@@ -209,13 +220,19 @@ class DownloadManager(tk.Toplevel):
style.theme_use("clam")
except tk.TclError:
pass
style.configure("Dl.Treeview", background=BG2, fieldbackground=BG2, foreground=FG,
rowheight=24, borderwidth=0, font=("Microsoft YaHei UI", 9))
style.configure("Dl.Treeview.Heading", background=BG3, foreground=FGD,
relief="flat", font=("Microsoft YaHei UI", 9, "bold"))
style.map("Dl.Treeview", background=[("selected", "#24405f")],
foreground=[("selected", "#ffffff")])
style.configure("Dl.Treeview", background="#ffffff", fieldbackground="#ffffff",
foreground=FG, rowheight=26, borderwidth=0,
font=("Microsoft YaHei UI", 9))
style.configure("Dl.Treeview.Heading", background="#f7f8fa", foreground=FGD,
relief="flat", borderwidth=0, padding=(6, 6),
font=("Microsoft YaHei UI", 9, "bold"))
style.map("Dl.Treeview.Heading", background=[("active", "#eff1f4")])
style.map("Dl.Treeview", background=[("selected", SEL)],
foreground=[("selected", FG)])
style.layout("Dl.Treeview", [("Dl.Treeview.treearea", {"sticky": "nswe"})])
style.configure("Dl.Horizontal.TProgressbar", troughcolor="#f0f1f3", background=ACC,
bordercolor="#f0f1f3", lightcolor=ACC, darkcolor=ACC,
borderwidth=0, thickness=8)
self.tree = ttk.Treeview(body, columns=self.COLS, show="headings",
style="Dl.Treeview", selectmode="extended")
@@ -230,7 +247,8 @@ class DownloadManager(tk.Toplevel):
self.tree.bind("<Double-1>", lambda e: self.open_folder())
self.tree.bind("<Button-3>", self._on_right_click)
self.menu = tk.Menu(self, tearoff=0)
self.menu = tk.Menu(self, tearoff=0, bg="#ffffff", fg=FG, activebackground=SEL,
activeforeground=FG, bd=0)
self.menu.add_command(label="复制下载链接", command=self._copy_links)
self.menu.add_command(label="复制本地路径", command=self._copy_paths)
self.menu.add_command(label="打开所在文件夹", command=self.open_folder)
@@ -238,19 +256,21 @@ class DownloadManager(tk.Toplevel):
self.menu.add_command(label="重试选中", command=self.retry_selected)
self.menu.add_command(label="移除选中", command=self.remove_selected)
bottom = tk.Frame(self, bg=BG)
bottom = tk.Frame(self, bg=BG, highlightthickness=1, highlightbackground=BORDER)
bottom.pack(fill="x", padx=10, pady=(2, 8))
self.pbar = ttk.Progressbar(bottom, mode="determinate", maximum=1000)
self.pbar.pack(fill="x", pady=(0, 4))
self.pbar = ttk.Progressbar(bottom, mode="determinate", maximum=1000,
style="Dl.Horizontal.TProgressbar")
self.pbar.pack(fill="x", pady=(6, 6), padx=6)
self.lbl_sum = tk.Label(bottom, text="准备中…", bg=BG, fg=FGD, anchor="w",
font=("Microsoft YaHei UI", 9))
self.lbl_sum.pack(fill="x")
self.lbl_sum.pack(fill="x", padx=6, pady=(0, 6))
# ------------------------------------------------------------ 任务表
def _add_tasks(self, items: List[Tuple[str, Dict[str, Any]]]) -> None:
seen = set()
dests = set()
rows: List[Tuple[str, Tuple[str, ...]]] = []
for label, item in items:
rel = item.get("rel") or item.get("name") or ""
key = (label, rel)
@@ -266,11 +286,28 @@ class DownloadManager(tk.Toplevel):
self.tasks.append(task)
self.by_iid[iid] = task
self.bytes_total += task.size
self.tree.insert("", "end", iid=iid, values=(
rows.append((iid, (
"%s · %s" % (task.name, label), human(task.size),
bar(0) + " 0%", "—", "—", task.state))
bar(0) + " 0%", "—", "—", task.state)))
# 只建对象,插行交给 _drain_rows 分批做(几千条一次 insert 会卡死窗口)
self._pending_rows.extend(rows)
self._drain_rows()
self._refresh_summary()
def _drain_rows(self) -> None:
"""每帧最多插 ROW_BATCH 行,剩下的下一帧继续。"""
if not self._pending_rows:
return
batch = self._pending_rows[:ROW_BATCH]
del self._pending_rows[:ROW_BATCH]
try:
for iid, values in batch:
self.tree.insert("", "end", iid=iid, values=values)
except tk.TclError:
return
if self._pending_rows and not self.closed:
self.after(1, self._drain_rows)
# ------------------------------------------------------------ 调度
def start_all(self) -> None:
@@ -349,16 +386,32 @@ class DownloadManager(tk.Toplevel):
t._last_t = 0.0
t._last_got = 0
def _sync_conc(self) -> None:
"""主线程里把 Spinbox 的值抄成普通 int(tk 变量不能在子线程读)。"""
try:
self._conc = max(1, min(16, int(self.concurrency.get())))
except Exception: # noqa: BLE001
pass
def _spawn_scheduler(self) -> None:
if self._sched_running or self.closed:
return
self._sched_running = True
threading.Thread(target=self._scheduler, daemon=True).start()
def _scheduler(self) -> None:
try:
self._scheduler_loop()
finally:
self._sched_running = False
def _scheduler_loop(self) -> None:
while not self.closed:
if self.paused:
return
with self.lock:
idle = [t for t in self.tasks if t.state == "排队中"]
slots = max(0, self.concurrency.get() - self.running)
slots = max(0, self._conc - self.running)
if not idle and self.running == 0:
return
if not idle or slots <= 0:
@@ -397,7 +450,7 @@ class DownloadManager(tk.Toplevel):
return
dirty = set()
try:
for _ in range(400):
for _ in range(600):
kind, payload = self.q.get_nowait()
if kind == "tick":
iid, got = payload
@@ -416,10 +469,12 @@ class DownloadManager(tk.Toplevel):
pass
for iid in dirty:
self._refresh_row(iid)
self._refresh_summary()
if self.running == 0:
if dirty or time.time() - self._summary_t >= 0.4:
self._refresh_summary()
if dirty:
# 有变化才要调度(以前每帧都问一次,空闲时也一直 spawn 线程)
self._maybe_start_more()
self.after(150, self._pump)
self.after(120 if dirty else 200, self._pump)
def _maybe_start_more(self) -> None:
if self.paused:
@@ -480,6 +535,7 @@ class DownloadManager(tk.Toplevel):
self._refresh_summary()
def _refresh_summary(self) -> None:
self._summary_t = time.time()
alive = [t for t in self.tasks if t.state != "已完成"]
total = sum(t.size for t in self.tasks) or 0
done = sum(t.got for t in self.tasks)
+45 -2
View File
@@ -48,6 +48,22 @@ SECRET_FIELDS = ("client_secret_key", "region_custom_config_encrypted",
"client_region_custom_config_encrypted", "secret_key")
def _safe_console() -> None:
"""控制台不是 UTF-8(cmd 默认 GBK/936)时,print 里的 ✓ 之类的字符会抛
UnicodeEncodeError 把进程直接干掉。这里把两个输出流降级成「无法编码就换成 ?」,
只在非 UTF-8 编码时动手,避免反过来把中文变成乱码。"""
for stream in (sys.stdout, sys.stderr):
try:
enc = (getattr(stream, "encoding", "") or "").lower()
if enc and "utf" not in enc:
stream.reconfigure(errors="replace") # type: ignore[attr-defined]
except Exception: # noqa: BLE001 - 老版本/重定向流没有 reconfigure
pass
_safe_console()
# --------------------------------------------------------------------------- #
# 配置
# --------------------------------------------------------------------------- #
@@ -140,6 +156,22 @@ def safe_name(s: str, fallback: str = "unknown") -> str:
return s or fallback
def make_run_dir(root: str) -> str:
"""在输出根目录下建「本次运行」的文件夹,如 out/20261121-172005。
这样一次抓取产出的 json/、txt/、index.json 全在一个文件夹里,
输出根目录不会越跑越乱。同一秒内重复运行会追加 _2、_3 后缀。
"""
base = os.path.abspath(root)
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
cand = os.path.join(base, stamp)
n = 1
while os.path.exists(cand):
n += 1
cand = os.path.join(base, "%s_%d" % (stamp, n))
return cand
def branch_of(region_info: Dict[str, Any]) -> str:
"""从 resource_url / data_url 末尾取分支号,如 .../client_game_res/7.2_live → 7.2_live。"""
for key in ("resource_url", "data_url"):
@@ -474,7 +506,9 @@ def parse_args(argv: Optional[List[str]] = None,
p.add_argument("--config-json", default=appconfig.CONFIG_NAME,
help="总配置文件(默认 config.json,放在程序同目录)")
p.add_argument("-c", "--config", help="设备配置(默认 devices.json,其次 versions.json)")
p.add_argument("-o", "--out", default="out", help="输出根目录(默认 out)")
p.add_argument("-o", "--out", default="out", help="输出根目录(默认 out,每次运行在其下建时间戳子目录)")
p.add_argument("--no-run-dir", action="store_true",
help="不建时间戳子目录,所有文件直接写进输出根目录(旧行为)")
p.add_argument("--only", action="append", default=[],
help="只抓指定设备(可重复,也支持逗号分隔),如 --only CNRELAndroid,CNRELWin")
p.add_argument("--no-rs", action="store_true",
@@ -594,16 +628,25 @@ def main(argv: Optional[List[str]] = None) -> int:
try:
keys = dispatch.load_keys(args.rsa)
except Exception as exc: # noqa: BLE001
print(f"[!] 读取 RSA 私钥失败({args.rsa}):{exc}")
tried = dispatch.resolve_path(args.rsa)
print(f"[!] 读取 RSA 私钥失败({args.rsa} → {tried}):{exc}")
print(" 加密响应无法解密;如果是明文响应仍可继续。")
print(" 修法:把 rsa.json 放到 exe 旁边或输出根目录,或用 --rsa 指定绝对路径。")
keys = None
session, proxy_note = make_session(args)
if proxy_note:
print(f"[i] {proxy_note}")
# 每次运行单独一个文件夹,json / txt / index.json 全在里面,根目录不再散落一堆文件
os.makedirs(args.out, exist_ok=True)
if not args.no_run_dir:
args.out = make_run_dir(args.out)
os.makedirs(args.out, exist_ok=True)
print(f"[i] 输出目录:{args.out}")
started = time.time()
if args.from_url:
dev = args.device or "UNKNOWN"
entry = {"device": dev, "version": dev, "dispatchSeed": "from-url"}
+183 -39
View File
@@ -18,9 +18,13 @@ from datetime import datetime
from tkinter import filedialog, messagebox, ttk
_HERE = os.path.dirname(os.path.abspath(__file__))
for _cand in (_HERE, os.path.dirname(_HERE), os.environ.get("GETCUR_HOME", ""),
r"G:\getcur"):
if _cand and os.path.isdir(_cand) and _cand not in sys.path:
# 倒着 insert(0):让最可信的路径最终排在最前面(以前 G:\getcur 这个兜底路径
# 会盖掉脚本旁边的同名模块,机器上刚好有那个目录时就会加载到别人的代码)
for _cand in (r"G:\getcur", os.environ.get("GETCUR_HOME", ""),
os.path.dirname(_HERE), _HERE):
if _cand and os.path.isdir(_cand):
if _cand in sys.path:
sys.path.remove(_cand) # 已经在 sys.path 里也要挪到最前面
sys.path.insert(0, _cand)
import fetch_devices as core # noqa: E402
@@ -28,6 +32,16 @@ import dispatch # noqa: E402
import appconfig # noqa: E402
import region_fanout # noqa: E402
# 白色简约配色(和 dl_manager / resdown_gui 保持一致)
BG = "#ffffff"
BG2 = "#f4f5f7"
BG3 = "#fafafa"
BORDER = "#e6e8eb"
FG = "#1f2328"
FGD = "#6b7280"
ACC = "#2f6feb"
SEL = "#eaf1fe"
class Args:
"""把 CLI 参数塞成对象,直接复用 fetch_one()。"""
@@ -62,13 +76,14 @@ class App(tk.Tk):
self.title("资源信息抓取工具")
self.geometry("980x600")
self.minsize(880, 520)
self.configure(bg="#11151c")
self.configure(bg=BG)
self.log_q: "queue.Queue[str]" = queue.Queue()
self.running = False
self.stop_flag = False
self.last_records: dict = {}
self.session = None
self.run_dir = None # 本次运行的输出目录(输出根目录下的时间戳文件夹)
base = dispatch.app_dir()
self.cfg = appconfig.load()
@@ -90,64 +105,172 @@ class App(tk.Tk):
style.theme_use("clam")
except tk.TclError:
pass
style.configure(".", background="#11151c", foreground="#e6e9ef")
style.configure("Treeview", background="#161b24", fieldbackground="#161b24",
foreground="#e6e9ef", rowheight=24, borderwidth=0)
style.configure("Treeview.Heading", background="#1d2430", foreground="#9fb0c8")
style.map("Treeview", background=[("selected", "#2b3a52")])
style.configure("TButton", padding=(10, 6))
style.configure(".", background=BG, foreground=FG, font=("Microsoft YaHei UI", 9))
style.configure("App.Treeview", background="#ffffff", fieldbackground="#ffffff",
foreground=FG, rowheight=26, borderwidth=0)
style.configure("App.Treeview.Heading", background="#f7f8fa", foreground=FGD,
relief="flat", borderwidth=0, padding=(6, 5),
font=("Microsoft YaHei UI", 9, "bold"))
style.map("App.Treeview.Heading", background=[("active", "#eff1f4")])
style.map("App.Treeview", background=[("selected", SEL)], foreground=[("selected", FG)])
style.configure("App.TButton", padding=(12, 6), relief="flat", borderwidth=0,
background=BG2, foreground=FG)
style.map("App.TButton",
background=[("active", "#e8eaee"), ("pressed", "#dfe3e8")])
top = tk.Frame(self, bg="#11151c")
top = tk.Frame(self, bg=BG, highlightthickness=1, highlightbackground=BORDER)
top.pack(fill="x", padx=12, pady=(12, 6))
tk.Label(top, text="输出目录", bg="#11151c", fg="#9fb0c8").pack(side="left")
tk.Entry(top, textvariable=self.out_dir, bg="#161b24", fg="#e6e9ef",
insertbackground="#e6e9ef", relief="flat").pack(side="left", fill="x",
expand=True, padx=8, ipady=5)
ttk.Button(top, text="选择…", command=self._pick_dir).pack(side="left")
tk.Label(top, text="输出目录", bg=BG, fg=FGD).pack(side="left", padx=(8, 0))
tk.Entry(top, textvariable=self.out_dir, bg="#ffffff", fg=FG,
insertbackground=FG, relief="flat", highlightthickness=1,
highlightbackground=BORDER, highlightcolor=ACC).pack(
side="left", fill="x", expand=True, padx=8, ipady=5)
ttk.Button(top, text="选择…", command=self._pick_dir,
style="App.TButton").pack(side="left", padx=(0, 8))
self.cloud_var = tk.BooleanVar(
value=bool((self.cfg.get("fanout") or {}).get("cloudFallbackWithPc")))
tk.Checkbutton(top, text="云客户端用 PC 清单占位", variable=self.cloud_var,
bg="#11151c", fg="#9fb0c8", selectcolor="#161b24",
activebackground="#11151c", activeforeground="#e6e9ef",
relief="flat", bd=0).pack(side="left", padx=(10, 0))
bg=BG, fg=FGD, selectcolor="#ffffff",
activebackground=BG, activeforeground=FG,
relief="flat", bd=0, highlightthickness=0,
cursor="hand2").pack(side="left", padx=(4, 8))
cols = ("device", "version", "branch", "data", "res", "file", "state")
heads = {"device": "设备 / 展开", "version": "实得版本", "branch": "分支", "data": "数据版本",
"res": "资源版本", "file": "输出文件", "state": "状态"}
widths = {"device": 190, "version": 120, "branch": 95, "data": 105, "res": 105,
"file": 260, "state": 90}
self.tree = ttk.Treeview(self, columns=cols, show="tree headings", height=14)
self.tree = ttk.Treeview(self, columns=cols, show="tree headings", height=12,
style="App.Treeview")
self.tree.column("#0", width=0, stretch=False)
for c in cols:
self.tree.heading(c, text=heads[c])
self.tree.column(c, width=widths[c], anchor="w")
self.tree.pack(fill="both", expand=True, padx=12, pady=6)
self.log = tk.Text(self, height=8, bg="#0d1117", fg="#8fa6c4", relief="flat",
insertbackground="#8fa6c4")
self.log = tk.Text(self, height=6, bg=BG3, fg="#374151", relief="flat",
highlightthickness=1, highlightbackground=BORDER,
insertbackground=FG, font=("Consolas", 9))
self.log.pack(fill="both", expand=False, padx=12, pady=(0, 6))
bar = tk.Frame(self, bg="#11151c")
bar = tk.Frame(self, bg=BG, highlightthickness=1, highlightbackground=BORDER)
bar.pack(fill="x", padx=12, pady=(0, 12))
self.btn_all = ttk.Button(bar, text="全部抓取", command=lambda: self._start(None))
self.btn_all.pack(side="left")
ttk.Button(bar, text="只抓选中", command=self._start_selected).pack(side="left", padx=6)
ttk.Button(bar, text="打开输出目录", command=self._open_dir).pack(side="left", padx=6)
ttk.Button(bar, text="资源下载", command=self._open_resdown).pack(side="left", padx=6)
ttk.Button(bar, text="刷新配置", command=self._reload_config).pack(side="left", padx=6)
ttk.Button(bar, text="编辑 config.json", command=self._edit_config).pack(side="left", padx=6)
tk.Label(bar, textvariable=self.status, bg="#11151c", fg="#9fb0c8").pack(side="right")
self.btn_all = ttk.Button(bar, text="全部抓取", command=lambda: self._start(None),
style="App.TButton")
self.btn_all.pack(side="left", padx=(8, 6), pady=8)
for text, cmd in (("只抓选中", self._start_selected),
("打开输出目录", self._open_dir),
("资源下载", self._open_resdown),
("刷新配置", self._reload_config),
("编辑 config.json", self._edit_config)):
ttk.Button(bar, text=text, command=cmd, style="App.TButton").pack(
side="left", padx=(0, 6), pady=8)
tk.Label(bar, textvariable=self.status, bg=BG, fg=FGD).pack(side="right", padx=(0, 8))
# ---------------- 配置文件 ----------------
def _edit_config(self) -> None:
"""在内置窗口里改配置。
以前这里用 os.startfile() 交给系统默认程序打开 .json —— 机器上要是没有
关联程序(或关联到会阻塞的编辑器),双击按钮就跟卡死一样。现在直接用
tkinter 自己弹一个编辑框,保存时顺便校验 JSON,不再依赖系统关联。
"""
path = self.cfg_path or appconfig.resolve_path()
try:
if not os.path.exists(path):
path = appconfig.write_template()
os.startfile(path) # noqa: S606 - 本地文件
except Exception as exc: # noqa: BLE001
messagebox.showerror("打不开配置文件", f"{path}\n{exc}")
return
win = tk.Toplevel(self)
win.title(f"编辑 {os.path.basename(path)}")
win.configure(bg=BG)
win.geometry("760x560")
win.transient(self)
head = tk.Frame(win, bg=BG, highlightthickness=1, highlightbackground=BORDER)
head.pack(fill="x")
tk.Label(head, text=path, bg=BG, fg=FGD, anchor="w",
font=("Consolas", 9)).pack(side="left", padx=10, pady=8)
body = tk.Frame(win, bg=BG)
body.pack(fill="both", expand=True, padx=10, pady=(8, 0))
text = tk.Text(body, wrap="none", undo=True, bg="#fafafa", fg="#374151",
relief="flat", font=("Consolas", 9), insertbackground=FG)
yscroll = ttk.Scrollbar(body, orient="vertical", command=text.yview)
xscroll = ttk.Scrollbar(win, orient="horizontal", command=text.xview)
text.configure(yscrollcommand=yscroll.set, xscrollcommand=xscroll.set)
text.pack(side="left", fill="both", expand=True)
yscroll.pack(side="right", fill="y")
xscroll.pack(fill="x", padx=10)
try:
with open(path, "r", encoding="utf-8") as fp:
text.insert("1.0", fp.read())
except Exception as exc: # noqa: BLE001
messagebox.showerror("读取失败", f"{path}\n{exc}", parent=win)
hint = tk.Label(win, text="Ctrl+S 保存并重新加载", bg=BG, fg=FGD, anchor="w")
hint.pack(fill="x", padx=10, pady=(4, 0))
bar = tk.Frame(win, bg=BG, highlightthickness=1, highlightbackground=BORDER)
bar.pack(fill="x", pady=(8, 0))
tk.Label(bar, textvariable=self.status, bg=BG, fg=FGD).pack(side="right", padx=(0, 10))
def save() -> None:
raw = text.get("1.0", "end-1c")
try:
json.loads(raw)
except json.JSONDecodeError as exc:
messagebox.showerror("JSON 格式不对", f"第 {exc.lineno} 行第 {exc.colno} 列:{exc.msg}",
parent=win)
return
try:
with open(path, "w", encoding="utf-8") as fp:
fp.write(raw)
except Exception as exc: # noqa: BLE001
messagebox.showerror("保存失败", f"{path}\n{exc}", parent=win)
return
self.cfg = appconfig.load()
self._log(f"[i] 已保存 {path}")
win.destroy()
for text_label, cmd in (("保存", save), ("另存为…", lambda: self._config_save_as(win, text)),
("用系统程序打开", lambda: self._config_open_external(path)),
("关闭", win.destroy)):
ttk.Button(bar, text=text_label, command=cmd, style="App.TButton").pack(
side="left", padx=(8, 0), pady=8)
win.bind("<Control-s>", lambda _e: save())
win.bind("<Escape>", lambda _e: win.destroy())
text.focus_set()
def _config_save_as(self, parent, widget) -> None:
raw = widget.get("1.0", "end-1c")
path = filedialog.asksaveasfilename(parent=parent, defaultextension=".json",
initialfile="config.json",
filetypes=[("JSON", "*.json"), ("所有文件", "*.*")])
if not path:
return
try:
with open(path, "w", encoding="utf-8") as fp:
fp.write(raw)
except Exception as exc: # noqa: BLE001
messagebox.showerror("保存失败", f"{path}\n{exc}", parent=parent)
return
self._log(f"[i] 已另存为 {path}")
def _config_open_external(self, path) -> None:
"""可选:仍交给系统默认程序,但放到后台线程里,绝不阻塞界面。"""
def run() -> None:
try:
os.startfile(path) # noqa: S606 - 本地文件
except Exception as exc: # noqa: BLE001
self._log(f"[!] 用系统程序打开失败:{exc}")
threading.Thread(target=run, daemon=True).start()
def _reload_config(self) -> None:
try:
@@ -186,9 +309,15 @@ class App(tk.Tk):
self.out_dir.set(d)
def _open_dir(self) -> None:
d = self.out_dir.get()
d = self.run_dir or self.out_dir.get()
os.makedirs(d, exist_ok=True)
os.startfile(d) # noqa: S606 - 本地目录
try:
os.startfile(d) # noqa: S606 - 本地目录
except Exception as exc: # noqa: BLE001
messagebox.showerror("打不开目录", f"{d}\n{exc}")
return
self.status.set(f"已打开:{os.path.basename(d)}")
def _open_resdown(self) -> None:
"""打开「资源下载」窗口:抓过的设备才有清单可下。"""
@@ -203,7 +332,8 @@ class App(tk.Tk):
if not region_info:
# fetch_one 返回的是摘要,完整 region_info 在落盘的详细版 JSON 里
rel = rec.get("file") or ""
path = rel if os.path.isabs(rel) else os.path.join(self.out_dir.get(), rel)
path = rel if os.path.isabs(rel) else os.path.join(
self.run_dir or self.out_dir.get(), rel)
try:
with open(path, "r", encoding="utf-8") as fp:
doc = json.load(fp)
@@ -238,8 +368,8 @@ class App(tk.Tk):
if note:
self._log(f"[i] {note}")
self.session = session
base_out = self.out_dir.get()
default_dir = base_out
base_out = self.run_dir or self.out_dir.get()
default_dir = os.path.join(base_out, "资源")
try:
import resdown_gui
@@ -272,8 +402,19 @@ class App(tk.Tk):
out = self.cfg.get("output") or {}
fan = self.cfg.get("fanout") or {}
rs = self.cfg.get("rs") or {}
# 每次抓取单独建一个时间戳文件夹,json/txt/index.json 都收在里面
run_dir = None
if out.get("runDir", True):
try:
run_dir = core.make_run_dir(self.out_dir.get())
os.makedirs(run_dir, exist_ok=True)
except Exception as exc: # noqa: BLE001
self._log(f"[!] 建输出目录失败,改用根目录:{exc}")
run_dir = None
self.run_dir = run_dir or self.out_dir.get()
self._log(f"[i] 输出目录:{self.run_dir}")
args = Args(
self.out_dir.get(),
self.run_dir,
retries=int(net.get("retries", 3)),
backoff=float(net.get("backoff", 2.0)),
timeout=float(net.get("timeout", 15)),
@@ -293,7 +434,10 @@ class App(tk.Tk):
keys = dispatch.load_keys("rsa.json")
self._log("已加载 rsa.json")
except Exception as exc: # noqa: BLE001
tried = dispatch.resolve_path("rsa.json")
self._log(f"[!] 读取 rsa.json 失败:{exc}")
self._log(f" 查找位置:{tried}")
self._log(" 修法:把 rsa.json 放到 exe 旁边,或用 --rsa / config.json 里的 rs 指向它")
session, note = core.make_session(args)
if note:
@@ -349,7 +493,7 @@ class App(tk.Tk):
# ---------------- 工具 ----------------
def _write_index(self, entries) -> None:
out = self.out_dir.get()
out = self.run_dir or self.out_dir.get()
split = bool(self.cfg.get("output", {}).get("splitJsonTxt", True))
idx_dir = os.path.join(out, "json") if split else out
devices = []
+290 -77
View File
@@ -95,61 +95,262 @@ CHUNK_THREADS = 16 # 同时进行的分块请求数
CHUNK_COUNT = 8 # 每个文件切成几块
CHUNK_MIN_BYTES = 4 << 20 # 小于 4 MiB 不折腾分块
try: # requests 由调用方负责带进来,但异常类型要用
import requests
except Exception: # noqa: BLE001 - 没有 requests 时只认自己的 _Stalled
requests = None # type: ignore[assignment]
# ---- 抗卡死参数 -------------------------------------------------------------
# 以前是 timeout=60 且失败要重试 3 次:一个卡住的连接要 60s×3 才超时,
# 这期间该文件的线程全占着、进度条不动,用户看到的就是「下载卡死」。
CONNECT_TIMEOUT = 6.0 # 建连超时(秒)
READ_TIMEOUT = 5.0 # 单次读超时(秒):服务器不发数据最多等这么久
STALL_LIMIT = 5.0 # 看门狗:这么多秒没收到任何字节就判为卡住,换连接重试
RETRY_ATTEMPTS = 3 # 单流重试次数上限
RETRY_BUDGET = 40.0 # 单个文件的总重试预算(秒),超了直接判失败
PROGRESS_MIN_INTERVAL = 0.12 # 进度回调最短间隔,别把消息队列塞满
class _Aborted(Exception):
"""用户点了停止。"""
class _Stalled(Exception):
"""连接卡住了:超过 STALL_LIMIT 一秒数据都没收到。"""
class _NoRange(Exception):
"""服务器没按 Range 返回(HTTP 200),分块没意义。"""
_STALLISH = ((requests.exceptions.Timeout, requests.exceptions.ConnectionError, _Stalled)
if requests is not None else (_Stalled,))
# 正在读的响应登记表:点停止时顺手把 socket 掐掉,不用干等读超时
_ACTIVE: Dict[int, Any] = {}
_ACTIVE_LOCK = threading.Lock()
def _sock_of(resp: Any) -> Any:
"""尽量从 urllib3/requests 的层层包装里挖出底层 socket。"""
for path in (("raw", "_connection", "sock"),
("raw", "_fp", "fp", "raw", "_sock"),
("raw", "_fp", "raw", "_sock")):
obj = resp
try:
for attr in path:
obj = getattr(obj, attr)
except Exception: # noqa: BLE001
continue
if obj is not None:
return obj
return None
def _register(resp: Any) -> None:
with _ACTIVE_LOCK:
_ACTIVE[id(resp)] = (resp, _sock_of(resp))
def _unregister(resp: Any) -> None:
with _ACTIVE_LOCK:
_ACTIVE.pop(id(resp), None)
def _abort_all() -> None:
"""把所有还在读的连接掐掉(点停止时调)。"""
with _ACTIVE_LOCK:
items = list(_ACTIVE.values())
for resp, sock in items:
try:
if sock is not None:
sock.shutdown(2) # SHUT_RDWR;Windows 上不一定立刻踢醒 recv,但无害
except Exception: # noqa: BLE001
pass
try:
resp.close()
except Exception: # noqa: BLE001
pass
def _timeout() -> Tuple[float, float]:
return (CONNECT_TIMEOUT, READ_TIMEOUT)
def _rm(path: str) -> None:
try:
os.remove(path)
except OSError:
pass
class _StopWatch:
"""后台 0.2s 轮询一次 stop,真被点了就把在途连接全掐掉。
Windows 上 shutdown 不一定能立刻踢醒阻塞在 recv 的线程,所以真正的
响应时延上限是 READ_TIMEOUT(5s);这里做的是尽量提前收手。
"""
def __init__(self, stop: Optional[Callable[[], bool]], interval: float = 0.2) -> None:
self._stop = stop
self._interval = interval
self._event = threading.Event()
self._thread: Optional[threading.Thread] = None
def __enter__(self) -> "_StopWatch":
if not self._stop:
return self
def loop() -> None:
while not self._event.wait(self._interval):
try:
if self._stop():
_abort_all()
return
except Exception: # noqa: BLE001
return
self._thread = threading.Thread(target=loop, name="resdown-stopwatch", daemon=True)
self._thread.start()
return self
def __exit__(self, *exc: Any) -> None:
self._event.set()
def _stream_to_handle(session: Any, url: str, headers: Optional[Dict[str, str]], fp: Any,
progress=None, name: str = "", want: int = 0,
stop: Optional[Callable[[], bool]] = None,
counter: Optional[list] = None,
require_206: bool = False, expect: int = 0) -> int:
"""开一次请求并把 body 写进 fp,返回本次写下的字节数。
- 读超时 5s + 无数据看门狗 5s:卡住的连接很快就会被判定,不会拖死整队。
- stop 一被点就抛 _Aborted(已经在读的响应会由 _StopWatch 掐掉)。
- counter=[共享字节, 锁] 用于分块下载时汇总全局进度。
- expect>0 时校验「到底收到多少」:服务器给了 Content-Length 却提前断开
以前会被当成成功(分块文件是短的),拼出来再 md5 不符白下一遍;
现在直接按卡住处理,换连接重来。
"""
resp = session.get(url, headers=headers or {}, stream=True, timeout=_timeout())
_register(resp)
wrote = 0
try:
resp.raise_for_status()
if require_206 and getattr(resp, "status_code", 206) != 206:
raise _NoRange("CDN 未按 Range 返回(HTTP %s)" % getattr(resp, "status_code", "?"))
last_data = time.monotonic()
last_push = 0.0
for block in resp.iter_content(CHUNK):
if stop and stop():
raise _Aborted()
now = time.monotonic()
if not block:
if now - last_data > STALL_LIMIT:
raise _Stalled("连接卡住")
continue
fp.write(block)
wrote += len(block)
last_data = now
total = wrote
if counter is not None:
with counter[1]:
counter[0] += len(block)
total = counter[0]
if progress is not None and now - last_push >= PROGRESS_MIN_INTERVAL:
last_push = now
progress(name, total, want or total)
if wrote == 0:
raise _Stalled("连接卡住")
if expect and wrote < expect:
raise _Stalled("连接提前结束(%d/%d 字节)" % (wrote, expect))
return wrote
finally:
_unregister(resp)
try:
resp.close()
except Exception: # noqa: BLE001
pass
def _range_download(session, url, part, size, progress=None, name="", stop=None,
threads=CHUNK_THREADS, chunks=CHUNK_COUNT):
"""切成多块并发下载;返回 (ok, 写入字节, 异常)。"""
n = max(1, min(int(chunks or 1), max(1, size // CHUNK_MIN_BYTES))) if size else 1
step = int(math.ceil(size / n))
done = [0]
lock = threading.Lock()
"""切成多块并发下载;返回 (ok, 写入字节, 异常)。
with open(part, "wb") as fp:
fp.truncate(size)
每块写自己的 ``<part>.<i>`` 文件,全部成功后再按序拼装。以前 16 个线程
共享一个句柄 seek/write 抢全局锁,既慢又容易在出错时留下半截数据。
"""
n = max(1, min(int(chunks or 1), max(1, int(size // CHUNK_MIN_BYTES)))) if size else 1
step = int(math.ceil(size / n)) if size else 0
counter: list = [0, threading.Lock()]
pieces = ["%s.%d" % (part, i) for i in range(n)]
errors: List[BaseException] = []
def worker(idx):
def worker(idx: int) -> None:
start = idx * step
end = min(size, start + step) - 1
if start > end:
return
headers = {"Range": "bytes=%d-%d" % (start, end)}
for attempt in range(1, 4):
for attempt in range(1, 3):
if stop and stop():
raise _Aborted()
try:
with session.get(url, headers=headers, stream=True, timeout=60) as resp:
resp.raise_for_status()
if resp.status_code != 206 and size > step:
raise RuntimeError("CDN 未按 Range 返回(HTTP %s)" % resp.status_code)
pos = start
with open(part, "r+b") as fp:
for block in resp.iter_content(CHUNK):
if stop and stop():
raise RuntimeError("已停止")
if not block:
continue
with lock:
fp.seek(pos)
fp.write(block)
done[0] += len(block)
pos += len(block)
if progress and done[0] % (CHUNK * 4) < CHUNK:
progress(name, done[0], size)
with open(pieces[idx], "wb") as fp:
_stream_to_handle(session, url, headers, fp, progress=progress,
name=name, want=size, stop=stop,
counter=counter, require_206=size > step,
expect=end - start + 1)
return
except Exception as exc:
if stop and stop():
raise RuntimeError("已停止") from exc
except (_NoRange, _Aborted):
raise
except BaseException as exc: # noqa: BLE001
status = getattr(getattr(exc, "response", None), "status_code", None)
if status in (400, 403, 404, 410):
raise # CDN 上没有这文件,不要重试
if attempt == 3:
if status in (400, 403, 404, 410) or attempt >= 2:
raise
time.sleep(min(2 * attempt, 5))
if isinstance(exc, _STALLISH):
time.sleep(0.3) # 卡住的连接换个新的立刻重来
else:
time.sleep(min(2 * attempt, 5))
watch = _StopWatch(stop).__enter__()
pool = None
try:
with ThreadPoolExecutor(max_workers=max(1, min(threads, n))) as pool:
list(pool.map(worker, range(n)))
except Exception as exc:
return False, done[0], exc
return True, size, None
pool = ThreadPoolExecutor(max_workers=max(1, min(int(threads or 1), n)))
futures = [pool.submit(worker, i) for i in range(n)]
for fut in futures:
try:
fut.result()
except BaseException as exc: # noqa: BLE001
if not errors:
errors.append(exc)
for other in futures:
other.cancel()
break
if errors:
return False, counter[0], errors[0]
total = 0
with open(part, "wb") as out:
for piece in pieces:
with open(piece, "rb") as src:
while True:
block = src.read(CHUNK)
if not block:
break
out.write(block)
total += len(block)
return True, total, None
finally:
watch.__exit__(None, None, None)
if pool is not None:
try:
pool.shutdown(wait=False, cancel_futures=True)
except TypeError: # Python < 3.9
pool.shutdown(wait=False)
for piece in pieces:
_rm(piece)
@@ -505,59 +706,71 @@ def download(session: Any, item: Dict[str, Any], dest_root: str,
def once(use_chunk: bool) -> Dict[str, Any]:
got = 0
if use_chunk and want >= CHUNK_MIN_BYTES and item.get("url"):
ok, got_chunk, exc = _range_download(session, item["url"], part, want,
progress=progress, name=name, stop=stop,
threads=threads, chunks=chunks)
ok, got, exc = _range_download(session, item["url"], part, want,
progress=progress, name=name, stop=stop,
threads=threads, chunks=chunks)
if ok:
os.replace(part, dest)
return {"ok": True, "bytes": got_chunk}
if os.path.exists(part):
try:
os.remove(part)
except OSError:
pass
return {"ok": True, "bytes": got}
_rm(part)
if stop and stop():
return {"ok": False, "error": "已停止", "bytes": got_chunk}
return {"ok": False, "error": "已停止", "bytes": got}
status = getattr(getattr(exc, "response", None), "status_code", None)
if status == 404:
return {"ok": False, "missing": True, "error": "CDN 上不存在(404)", "bytes": 0}
# 分块失败 → 落回单流再试
if status in (400, 403, 404, 410):
return {"ok": False, "missing": True,
"error": "CDN 上不存在(HTTP %s)" % status, "bytes": 0}
if isinstance(exc, _STALLISH):
# 连接卡住:换一批新连接立刻再来一轮;还是卡就直接报失败,
# 不再落回单流白等一遍(以前就是这里把 20s 拖成 200s)。
ok, got, exc = _range_download(session, item["url"], part, want,
progress=progress, name=name, stop=stop,
threads=threads, chunks=chunks)
if ok:
os.replace(part, dest)
return {"ok": True, "bytes": got}
_rm(part)
if stop and stop():
return {"ok": False, "error": "已停止", "bytes": got}
if isinstance(exc, _STALLISH):
return {"ok": False, "bytes": got,
"error": "连接卡住:%.0fs 内没有收到数据(已放弃这个文件)" % STALL_LIMIT}
# 其它情况(例如服务器不认 Range)→ 落回单流再试
last: Optional[Exception] = None
for attempt in range(1, 4):
stalled = False
deadline = time.monotonic() + RETRY_BUDGET
for attempt in range(1, RETRY_ATTEMPTS + 1):
got = 0
watch = _StopWatch(stop).__enter__()
try:
with session.get(item["url"], stream=True, timeout=60) as resp:
resp.raise_for_status()
with open(part, "wb") as fp:
for block in resp.iter_content(CHUNK):
if stop and stop():
fp.close()
try:
os.remove(part)
except OSError:
pass
return {"ok": False, "error": "已停止", "bytes": got}
if not block:
continue
fp.write(block)
got += len(block)
if progress:
progress(name, got, want or got)
with open(part, "wb") as fp:
got = _stream_to_handle(session, item["url"], None, fp,
progress=progress, name=name,
want=want, stop=stop, expect=want)
os.replace(part, dest)
return {"ok": True, "bytes": got}
except _Aborted:
_rm(part)
return {"ok": False, "error": "已停止", "bytes": got}
except Exception as exc: # noqa: BLE001
last = exc
if os.path.exists(part):
try:
os.remove(part)
except OSError:
pass
_rm(part)
if stop and stop():
return {"ok": False, "error": "已停止", "bytes": got}
status = getattr(getattr(exc, "response", None), "status_code", None)
if status == 404:
return {"ok": False, "missing": True, "error": "CDN 上不存在(404)", "bytes": 0}
if status in (400, 403, 404, 410):
return {"ok": False, "missing": True,
"error": "CDN 上不存在(HTTP %s)" % status, "bytes": 0}
if time.monotonic() > deadline:
break # 总预算用完,别再无止境地重试
if isinstance(exc, _STALLISH) and attempt >= 2:
stalled = True
break # 卡住的连接只给一次换连接的机会
time.sleep(min(2 * attempt, 5))
finally:
watch.__exit__(None, None, None)
if stalled:
return {"ok": False, "bytes": got,
"error": "连接卡住:%.0fs 内没有收到数据(已放弃这个文件)" % STALL_LIMIT}
return {"ok": False, "error": "%s: %s" % (type(last).__name__, last), "bytes": got}
first = once(use_chunk=True)
+50 -14
View File
@@ -19,11 +19,13 @@ import resdown # noqa: E402
CHECKED = "☑"
UNCHECKED = "☐"
BG = "#11151c"
BG2 = "#161b24"
FG = "#d8dee9"
DIM = "#7c8798"
ACCENT = "#4f8cf7"
BG = "#ffffff"
BG2 = "#f4f5f7"
FG = "#1f2328"
DIM = "#6b7280"
ACCENT = "#2f6feb"
BORDER = "#e6e8eb"
SEL = "#eaf1fe"
def human(n: Optional[float]) -> str:
@@ -56,6 +58,17 @@ class ResDownWindow(tk.Toplevel):
self.session = session
self.out_root = out_root
self.file_version = file_version
# 读 config.json:并发文件数 / 每文件线程 / 分块数 从这里来(以前 self.cfg 根本没定义,
# 一直被 except 兜成默认 4,配置里写的 16 线程 / 8 块完全没生效)
self.cfg: Dict[str, Any] = {}
try:
import appconfig
self.cfg = appconfig.load() or {}
defaults = appconfig.as_defaults(self.cfg)
appconfig.apply_transfer(defaults)
except Exception: # noqa: BLE001
self.cfg = {}
self.queue: "queue.Queue[tuple]" = queue.Queue()
self.scanning = False
self.downloading = False
@@ -123,7 +136,24 @@ class ResDownWindow(tk.Toplevel):
wrap = tk.Frame(self, bg=BG)
wrap.pack(fill="both", expand=True, padx=12)
cols = ("size", "tier", "kind", "state")
self.tree = ttk.Treeview(wrap, columns=cols, show="tree headings", height=16)
style = ttk.Style(self)
try:
style.theme_use("clam")
except tk.TclError:
pass
style.configure("Rd.Treeview", background="#ffffff", fieldbackground="#ffffff",
foreground=FG, rowheight=26, borderwidth=0,
font=("Microsoft YaHei UI", 9))
style.configure("Rd.Treeview.Heading", background="#f7f8fa", foreground=DIM,
relief="flat", borderwidth=0, padding=(6, 6),
font=("Microsoft YaHei UI", 9, "bold"))
style.map("Rd.Treeview.Heading", background=[("active", "#eff1f4")])
style.map("Rd.Treeview", background=[("selected", SEL)], foreground=[("selected", FG)])
style.configure("Rd.Horizontal.TProgressbar", troughcolor="#f0f1f3", background=ACCENT,
bordercolor="#f0f1f3", lightcolor=ACCENT, darkcolor=ACCENT,
borderwidth=0, thickness=8)
self.tree = ttk.Treeview(wrap, columns=cols, show="tree headings", height=16,
style="Rd.Treeview")
self.tree.heading("#0", text="设备 / 文件夹 / 文件")
self.tree.column("#0", width=620, anchor="w")
for c, t, w in (("size", "大小", 100), ("tier", "档位", 110),
@@ -143,21 +173,26 @@ class ResDownWindow(tk.Toplevel):
("全不选", lambda: self._select_all(False)),
("开始下载", self._start), ("停止", self._stop),
("打开目录", self._open_dir)):
tk.Button(bar, text=text, command=cmd, bg=BG2, fg=FG, activebackground="#1e2632",
activeforeground=ACCENT, bd=0, padx=12, pady=5).pack(side="left", padx=(0, 8))
tk.Button(bar, text=text, command=cmd, bg=BG2, fg=FG,
activebackground="#e8eaee", activeforeground=FG,
bd=0, highlightthickness=0, padx=12, pady=5,
cursor="hand2").pack(side="left", padx=(0, 8))
self.status = tk.StringVar(value="点「扫描清单」列出各设备的资源(F5)")
tk.Label(self, textvariable=self.status, bg=BG, fg=DIM, anchor="w").pack(fill="x", padx=12)
self.pbar = ttk.Progressbar(self, mode="determinate", maximum=100, value=0)
self.pbar = ttk.Progressbar(self, mode="determinate", maximum=100, value=0,
style="Rd.Horizontal.TProgressbar")
self.pbar.pack(fill="x", padx=12, pady=(2, 6))
self.log = tk.Text(self, height=7, bg=BG2, fg=FG, insertbackground=FG, relief="flat")
self.log = tk.Text(self, height=7, bg="#fafafa", fg="#374151", insertbackground=FG,
relief="flat", bd=0, highlightthickness=1,
highlightbackground=BORDER, font=("Consolas", 9))
self.log.pack(fill="x", padx=12, pady=(4, 10))
# 右键菜单:单条 / 多条都能复制下载链接
self.menu = tk.Menu(self, tearoff=0, bg=BG2, fg=FG, activebackground="#1e2632",
activeforeground=ACCENT, bd=0)
self.menu = tk.Menu(self, tearoff=0, bg="#ffffff", fg=FG, activebackground=SEL,
activeforeground=FG, bd=0)
self.menu.add_command(label="复制下载链接", command=self._copy_links)
self.menu.add_command(label="复制本地路径", command=self._copy_paths)
self.menu.add_command(label="复制 MD5", command=self._copy_md5)
@@ -477,13 +512,14 @@ class ResDownWindow(tk.Toplevel):
import dl_manager
if self.dl_win is not None and getattr(self.dl_win, "winfo_exists", lambda: 0)():
self.dl_win.destroy()
root = (self.dir_var.get() or "").strip() or self.out_root
conc = 4
try:
conc = int(self.cfg.get("transfer", {}).get("files", 4) or 4)
conc = int((self.cfg.get("transfer") or {}).get("files", 4) or 4)
except Exception: # noqa: BLE001
conc = 4
self.dl_win = dl_manager.open_manager(
self, self.session, self.out_root, picked,
self, self.session, root, picked,
concurrency=max(1, min(16, conc)),
threads=resdown.CHUNK_THREADS)
self.status.set("已交给下载管理器:%d 个文件 / %s" % (len(picked), human(total)))
+7
View File
@@ -0,0 +1,7 @@
@echo off
setlocal
chcp 65001 >nul
cd /d "%~dp0"
python build.py %*
echo.
pause
+11 -1
View File
@@ -1,2 +1,12 @@
@echo off
start "" "%~dp0资源信息抓取工具.exe"
setlocal
set "EXE="
for %%F in ("%~dp0_dist\gui\*.exe") do set "EXE=%%~fF"
if not defined EXE for %%F in ("%~dp0*.exe") do set "EXE=%%~fF"
if not defined EXE (
echo [x] exe not found - build it first:
echo python build.py ^(or double-click build.bat^)
pause
exit /b 1
)
start "" "%EXE%"