The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
fix(i18n): 内置分类与预设名改为 View 层按上下文翻译 #1107
XiaoYouChR8566a3b09f34
diff --git a/GLOSSARY.md b/GLOSSARY.mdindex 70055b20..cb72cc9f 100644--- a/GLOSSARY.md+++ b/GLOSSARY.md@@ -370,6 +370,14 @@ _Avoid_: 发版、打包、release(指 App)用户最近一次填写的自定义地址独立保存,切换到其他模式再切回时仍在。_Avoid_: 与 Proxy Site 混淆+**Headers Preset**:+可复用的默认 HTTP 请求头集合。当前选中的一份在新建 Task 时作为初始请求头拷贝进 Task;修改或删除预设不影响已有 Task。+_Avoid_: 默认请求头、header template++**Identity Preset**:+按域名通配规则为请求匹配客户端指纹与 User-Agent 的预设。启用时按主机名自动生效,也可在 Task 选项中显式指定。+_Avoid_: Identity Rule、client preset、UA 规则+### GitHub 加速**Proxy Site**:diff --git a/app/config/cfg.py b/app/config/cfg.pyindex 49c583e6..a716acdc 100644--- a/app/config/cfg.py+++ b/app/config/cfg.py@@ -10,6 +10,7 @@ from urllib.request import getproxiesfrom app.config.serializers import PathSerializerfrom app.config.paths import APP_DATA_DIR, DOWNLOAD_DIR+from app.i18n import Nfrom qfluentwidgets import (QConfig,ConfigItem,@@ -245,7 +246,7 @@ class HeadersPresetListValidator(ConfigValidator):def correct(self, value) -> list:presets = [i for i in value if self._isValid(i)] if isinstance(value, list) else []- return presets or [{"name": "默认", "headers": dict(BASE_HEADERS)}]+ return presets or [{"name": N("Presets", "默认"), "headers": dict(BASE_HEADERS)}]class Config(QConfig):@@ -375,7 +376,7 @@ class Config(QConfig):)identityPresets = ConfigItem("Network", "IdentityPresets",- [{"name": "百度网盘客户端", "clientProfile": "raw",+ [{"name": N("Presets", "百度网盘客户端"), "clientProfile": "raw","userAgent": "pan.baidu.com", "hosts": ["*.pcs.baidu.com"],"isEnabled": True}],IdentityPresetListValidator(), JsonConfigSerializer(list, list),diff --git a/app/services/category_service.py b/app/services/category_service.pyindex 5b481545..27637a34 100644--- a/app/services/category_service.py+++ b/app/services/category_service.py@@ -5,9 +5,9 @@ from pathlib import Pathfrom typing import Any, TYPE_CHECKINGfrom uuid import uuid4-from app.signal import Signal-from app.config.cfg import cfg+from app.i18n import N+from app.signal import Signalif TYPE_CHECKING:from app.models.task import Task@@ -16,7 +16,7 @@ if TYPE_CHECKING:CATEGORY_PRESETS: list[dict[str, Any]] = [{"categoryId": "cat_video",- "name": "视频",+ "name": N("Categories", "视频"),"icon": "VIDEO","folder": "{default}/Video","extensions": [@@ -27,7 +27,7 @@ CATEGORY_PRESETS: list[dict[str, Any]] = [},{"categoryId": "cat_audio",- "name": "音频",+ "name": N("Categories", "音频"),"icon": "MUSIC","folder": "{default}/Audio","extensions": [@@ -37,7 +37,7 @@ CATEGORY_PRESETS: list[dict[str, Any]] = [},{"categoryId": "cat_image",- "name": "图片",+ "name": N("Categories", "图片"),"icon": "PHOTO","folder": "{default}/Images","extensions": [@@ -47,7 +47,7 @@ CATEGORY_PRESETS: list[dict[str, Any]] = [},{"categoryId": "cat_subtitle",- "name": "字幕",+ "name": N("Categories", "字幕"),"icon": "CHAT","folder": "{default}/Subtitles","extensions": [@@ -57,7 +57,7 @@ CATEGORY_PRESETS: list[dict[str, Any]] = [},{"categoryId": "cat_document",- "name": "文档",+ "name": N("Categories", "文档"),"icon": "DOCUMENT","folder": "{default}/Documents","extensions": [@@ -68,7 +68,7 @@ CATEGORY_PRESETS: list[dict[str, Any]] = [},{"categoryId": "cat_archive",- "name": "压缩包",+ "name": N("Categories", "压缩包"),"icon": "ZIP_FOLDER","folder": "{default}/Archives","extensions": [@@ -80,7 +80,7 @@ CATEGORY_PRESETS: list[dict[str, Any]] = [},{"categoryId": "cat_program",- "name": "程序",+ "name": N("Categories", "程序"),"icon": "APPLICATION","folder": "{default}/Programs","extensions": [@@ -91,7 +91,7 @@ CATEGORY_PRESETS: list[dict[str, Any]] = [},{"categoryId": "cat_other",- "name": "其他",+ "name": N("Categories", "其他"),"icon": "HELP","extensions": [],},diff --git a/app/view/components/category_settings.py b/app/view/components/category_settings.pyindex 7d7a949a..ef5c9d35 100644--- a/app/view/components/category_settings.py+++ b/app/view/components/category_settings.py@@ -1,6 +1,6 @@from __future__ import annotations-from PySide6.QtCore import QT_TRANSLATE_NOOP as N, QCoreApplication, Signal+from PySide6.QtCore import QCoreApplication, Signalfrom PySide6.QtWidgets import QHBoxLayout, QWidgetfrom qfluentwidgets import (BodyLabel, FluentIcon, IconWidget, IndicatorPosition,@@ -12,16 +12,6 @@ from app.view.components.setting_card_group import CollapsibleSettingCardfrom app.services.category_service import Category-N("Categories", "视频")-N("Categories", "音频")-N("Categories", "图片")-N("Categories", "字幕")-N("Categories", "文档")-N("Categories", "压缩包")-N("Categories", "程序")-N("Categories", "其他")-N("Categories", "未命名分类")-def toCategoryName(category: Category) -> str:return QCoreApplication.translate("Categories", category.name)diff --git a/app/view/components/option_cards.py b/app/view/components/option_cards.pyindex 0aaa997f..8e533876 100644--- a/app/view/components/option_cards.py+++ b/app/view/components/option_cards.py@@ -183,7 +183,7 @@ class ClientProfileCard(OptionCard):if presets:menu.addSeparator()for preset in presets:- action = Action(preset["name"], self)+ action = Action(QCoreApplication.translate("Presets", preset["name"]), self)action.triggered.connect(lambda _=False, p=preset: self._onPickPreset(p))menu.addAction(action)@@ -217,7 +217,7 @@ class ClientProfileCard(OptionCard):def _onPickPreset(self, preset: dict) -> None:self._value = preset["clientProfile"]self._userAgent = preset["userAgent"]- self.button.setText(preset["name"])+ self.button.setText(QCoreApplication.translate("Presets", preset["name"]))def _presetLabelFor(self, clientProfile: str, userAgent: str) -> str:if not userAgent:@@ -225,7 +225,7 @@ class ClientProfileCard(OptionCard):from app.config.cfg import cfgfor preset in cfg.identityPresets.value:if preset["clientProfile"] == clientProfile and preset["userAgent"] == userAgent:- return preset["name"]+ return QCoreApplication.translate("Presets", preset["name"])return ""diff --git a/app/view/components/setting_cards.py b/app/view/components/setting_cards.pyindex 6b32a0ae..90e4c3a0 100644--- a/app/view/components/setting_cards.py+++ b/app/view/components/setting_cards.py@@ -493,7 +493,8 @@ class PresetRowWidget(QWidget):self._preset = presetself.iconWidget = IconWidget(FluentIcon.VPN, self)- self.nameLabel = StrongBodyLabel(preset.get("name", ""), self)+ self.nameLabel = StrongBodyLabel(+ QCoreApplication.translate("Presets", preset.get("name", "")), self)self.descLayout = QHBoxLayout()self.switchButton = SwitchButton(self)self.editButton = PrimaryToolButton(FluentIcon.EDIT, self)@@ -706,7 +707,8 @@ class IdentitySettingCard(CollapsibleSettingCard):presets = list(cfg.identityPresets.value)if index < 0 or index >= len(presets):return- name = presets[index].get("name", self.tr("未命名预设"))+ rawName = presets[index].get("name", "")+ name = QCoreApplication.translate("Presets", rawName) if rawName else self.tr("未命名预设")dialog = MessageBox(self.tr("删除预设"),self.tr("确定要删除 {0} 吗?").format(name),@@ -737,7 +739,8 @@ class HeadersPresetRow(QWidget):self._onEdit = onEditself._onRemove = onRemove- self.radioButton = RadioButton(preset["name"], self)+ self.radioButton = RadioButton(+ QCoreApplication.translate("Presets", preset["name"]), self)self.countLabel = CaptionLabel(self.tr("{0} 条标头").format(len(preset["headers"])), self)self.editButton = PrimaryToolButton(FluentIcon.EDIT, self)@@ -821,7 +824,7 @@ class HeadersPresetSettingCard(CollapsibleSettingCard):self._rowWidgets.append(row)self.viewLayout.addWidget(self.buttonContainer)- self.choiceLabel.setText(presets[current]["name"])+ self.choiceLabel.setText(QCoreApplication.translate("Presets", presets[current]["name"]))def _onPick(self, index: int) -> None:cfg.set(cfg.currentHeadersPreset, index)@@ -851,7 +854,8 @@ class HeadersPresetSettingCard(CollapsibleSettingCard):def _onRemoveClicked(self, index: int) -> None:from qfluentwidgets import MessageBoxpresets = list(cfg.headersPresets.value)- name = presets[index].get("name", self.tr("未命名预设"))+ rawName = presets[index].get("name", "")+ name = QCoreApplication.translate("Presets", rawName) if rawName else self.tr("未命名预设")dialog = MessageBox(self.tr("删除预设"),self.tr("确定要删除 {0} 吗?").format(name),@@ -876,7 +880,7 @@ class HeadersPresetSettingCard(CollapsibleSettingCard):for i, r in enumerate(self._rowWidgets):r.radioButton.setChecked(i == newCurrent)r.removeButton.setEnabled(canRemove)- self.choiceLabel.setText(presets[newCurrent]["name"])+ self.choiceLabel.setText(QCoreApplication.translate("Presets", presets[newCurrent]["name"]))class SelectFileCard(SettingCard):diff --git a/app/view/dialogs/category_edit.py b/app/view/dialogs/category_edit.pyindex d9bc825e..45b636f8 100644--- a/app/view/dialogs/category_edit.py+++ b/app/view/dialogs/category_edit.py@@ -8,6 +8,7 @@ from qfluentwidgets import (SubtitleLabel, ToolButton, ToolTipFilter,)+from app.i18n import Nfrom app.services.category_service import Categoryfrom app.view.components.category_settings import toCategoryNamefrom app.view.components.token_line_edit import TokenLineEdit@@ -91,7 +92,7 @@ class CategoryEditDialog(MessageBoxBase):self.folderEdit.setText(selected)def category(self) -> Category:- name = self.nameEdit.text().strip() or "未命名分类"+ name = self.nameEdit.text().strip() or N("Categories", "未命名分类")extensions = [ext for token in self.extensionsEdit.tokens()if (ext := token.strip().lstrip(".").lower())diff --git a/app/view/dialogs/headers_preset_edit.py b/app/view/dialogs/headers_preset_edit.pyindex bcab3d83..0afa8d30 100644--- a/app/view/dialogs/headers_preset_edit.py+++ b/app/view/dialogs/headers_preset_edit.py@@ -1,6 +1,6 @@from __future__ import annotations-from PySide6.QtCore import Qt+from PySide6.QtCore import QCoreApplication, Qtfrom PySide6.QtWidgets import QHBoxLayoutfrom qfluentwidgets import InfoBar, LineEdit, MessageBoxBase@@ -13,6 +13,7 @@ class HeadersPresetEditDialog(MessageBoxBase):def __init__(self, parent=None, *, preset: dict):super().__init__(parent)+ self._preset = presetself.nameEdit = LineEdit(self)self.editor = HeadersEditor(self, defaults=BASE_HEADERS)self.scrollArea = ScrollArea(self.widget)@@ -26,7 +27,7 @@ class HeadersPresetEditDialog(MessageBoxBase):self.yesButton.setText(self.tr("确定"))self.cancelButton.setText(self.tr("取消"))self.nameEdit.setPlaceholderText(self.tr("预设名称"))- self.nameEdit.setText(preset["name"])+ self.nameEdit.setText(QCoreApplication.translate("Presets", preset["name"]))self.editor.setHeaders(preset["headers"])def _initLayout(self) -> None:@@ -56,7 +57,10 @@ class HeadersPresetEditDialog(MessageBoxBase):super().done(code)def preset(self) -> dict:+ name = self.nameEdit.text().strip() or self.tr("未命名预设")+ if name == QCoreApplication.translate("Presets", self._preset["name"]):+ name = self._preset["name"]return {- "name": self.nameEdit.text().strip() or self.tr("未命名预设"),+ "name": name,"headers": self.editor.headers(),}diff --git a/app/view/dialogs/preset_edit.py b/app/view/dialogs/preset_edit.pyindex 43dae24e..be9a9e6c 100644--- a/app/view/dialogs/preset_edit.py+++ b/app/view/dialogs/preset_edit.py@@ -1,5 +1,6 @@from __future__ import annotations+from PySide6.QtCore import QCoreApplicationfrom PySide6.QtWidgets import QHBoxLayoutfrom qfluentwidgets import (BodyLabel, DropDownPushButton, FluentIcon, InfoBar, LineEdit,@@ -70,7 +71,7 @@ class PresetEditDialog(MessageBoxBase):self._refreshProfileLabel()if self._preset is None:return- self.nameEdit.setText(self._preset.get("name", ""))+ self.nameEdit.setText(QCoreApplication.translate("Presets", self._preset.get("name", "")))self.hostsEdit.setTokens(self._preset.get("hosts", []))self.uaEdit.setText(self._preset.get("userAgent", ""))@@ -111,8 +112,11 @@ class PresetEditDialog(MessageBoxBase):return Falsedef preset(self) -> dict:+ name = self.nameEdit.text().strip() or self.tr("未命名预设")+ if self._preset and name == QCoreApplication.translate("Presets", self._preset.get("name", "")):+ name = self._preset["name"]result = {- "name": self.nameEdit.text().strip() or self.tr("未命名预设"),+ "name": name,"clientProfile": self._profileValue,"userAgent": self.uaEdit.text().strip(),"hosts": self.hostsEdit.tokens(),diff --git a/docs/adr/0033-builtin-names-persist-source-key.md b/docs/adr/0033-builtin-names-persist-source-key.mdnew file mode 100644index 00000000..65d78863--- /dev/null+++ b/docs/adr/0033-builtin-names-persist-source-key.md@@ -0,0 +1,3 @@+# 内置可编辑名称在配置中持久化源文 key++内置分类(Category)与预设(Headers Preset、Identity Preset)的名称在配置中保留规范中文源文,由逻辑层通过 `N(context, text)` 标注并经 `ENGINE_CONTEXTS` 同步到 Android;桌面端与 Android 端的 View 层在展示时按当前语言查表翻译,编辑页保存时若用户输入未偏离初始译文则回写原中文 key。选择该方案而非引入 `builtInKey` / `customName` 字段拆分,是为了零迁移修复已有用户配置、天然兼容 Android 运行时切换语言,并把逻辑层与 UI 语言彻底解耦。diff --git a/features/bili_pack/config.py b/features/bili_pack/config.pyindex da062071..366e0382 100644--- a/features/bili_pack/config.py+++ b/features/bili_pack/config.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGfrom app.config.cfg import ConfigItem, OptionsConfigItem, OptionsValidator+from app.i18n import Nfrom app.models.pack import PackConfigif TYPE_CHECKING:@@ -13,10 +14,10 @@ if TYPE_CHECKING:QUALITY_VALUES = [16, 32, 64, 74, 80, 112, 116, 120, 125, 126, 127]QUALITY_LABELS = ["360P", "480P", "720P", "720P60", "1080P", "1080P+",- "1080P60", "4K", "HDR", "杜比视界", "8K",+ "1080P60", "4K", "HDR", N("BilibiliConfig", "杜比视界"), "8K",]AUDIO_QUALITY_VALUES = [30216, 30232, 30280, 30250, 30251]-AUDIO_QUALITY_LABELS = ["64K", "132K", "192K", "杜比全景声", "Hi-Res"]+AUDIO_QUALITY_LABELS = ["64K", "132K", "192K", N("BilibiliConfig", "杜比全景声"), "Hi-Res"]class BilibiliConfig(PackConfig):@@ -45,10 +46,10 @@ class BilibiliConfig(PackConfig):BilibiliLoginSettingCard(self._account, group),ComboBoxSettingCard(self.defaultQuality, FluentIcon.VIDEO, self.tr("默认画质"),self.tr("选择偏好的视频画质"),- texts=QUALITY_LABELS, parent=group),+ texts=[self.tr(x) for x in QUALITY_LABELS], parent=group),ComboBoxSettingCard(self.defaultAudioQuality, FluentIcon.MUSIC, self.tr("默认音质"),self.tr("选择偏好的音质"),- texts=AUDIO_QUALITY_LABELS, parent=group),+ texts=[self.tr(x) for x in AUDIO_QUALITY_LABELS], parent=group),ComboBoxSettingCard(self.defaultDanmaku, FluentIcon.CHAT, self.tr("默认弹幕"),self.tr("选择默认下载的弹幕格式"),texts=[self.tr("不下载"), "ASS", "XML"], parent=group),diff --git a/scripts/sync_i18n_res.py b/scripts/sync_i18n_res.pyindex ce784f0a..1ddde1f2 100644--- a/scripts/sync_i18n_res.py+++ b/scripts/sync_i18n_res.py@@ -23,8 +23,11 @@ I18N_DIR = ASSETS_DIR / "i18n"QRC_PATH = ASSETS_DIR / "resources.qrc"RESOURCES_RCC = ASSETS_DIR / "resources.rcc"-ENGINE_CONTEXTS = ["TaskErrors", "BinaryRuntime", "TaskState",- "TrackBar", "YtDlpDraftCard", "StreamSelectCard"]+ENGINE_CONTEXTS = [+ "TaskErrors", "BinaryRuntime", "TaskState",+ "TrackBar", "YtDlpDraftCard", "StreamSelectCard",+ "Categories", "Presets",+]ANDROID_RES_DIR = REPO / "android" / "app" / "src" / "main" / "res"ANDROID_I18N_KT = (@@ -105,9 +108,9 @@ def updateQrcI18n() -> None:QRC_PATH.write_text(text, encoding="utf-8")-def readCatalog(locale: str) -> dict[str, tuple[str, str]]:+def readCatalog(locale: str) -> dict[str, tuple[str, str, str]]:root = ET.parse(I18N_DIR / f"gd3.{locale}.ts").getroot()- entries: dict[str, tuple[str, str]] = {}+ entries: dict[str, tuple[str, str, str]] = {}for context in root.findall("context"):ctxName = context.findtext("name")if ctxName not in ENGINE_CONTEXTS:@@ -126,7 +129,7 @@ def readCatalog(locale: str) -> dict[str, tuple[str, str]]:if source and text:digest = hashlib.sha1(source.encode("utf-8")).hexdigest()[:8]resName = f"engine_{ctxName.lower()}_{digest}"- entries[resName] = (source, text)+ entries[resName] = (ctxName, source, text)return entries@@ -144,7 +147,7 @@ def buildAndroidStrings() -> None:raise SystemExit(f"No messages found for contexts {ENGINE_CONTEXTS}")nameToSource = {}- for name, (text, _) in source.items():+ for name, (_, text, _) in source.items():if name in nameToSource:raise SystemExit(f"resourceName collision: {text!r} vs {nameToSource[name]!r}")nameToSource[name] = text@@ -157,7 +160,7 @@ def buildAndroidStrings() -> None:target.mkdir(parents=True, exist_ok=True)xmlLines = ["<!-- Generated by scripts/sync_i18n_res.py -->", "<resources>"]for resource in sorted(entries):- text = escapeAndroidString(entries[resource][1])+ text = escapeAndroidString(entries[resource][2])xmlLines.append(f' <string name="{resource}" formatted="false">{text}</string>')@@ -174,7 +177,9 @@ def buildAndroidStrings() -> None:"internal val engineStrings: Map<String, Int> = mapOf(",]for resource in sorted(source):- text = source[resource][0].replace("\\", "\\\\").replace('"', '\\"')+ ctxName, rawText, _ = source[resource]+ text = rawText.replace("\\", "\\\\").replace('"', '\\"')+ ktLines.append(f' "{ctxName}:{text}" to R.string.{resource},')ktLines.append(f' "{text}" to R.string.{resource},')ktLines.append(")")ANDROID_I18N_KT.write_text("\n".join(ktLines) + "\n", encoding="utf-8")