The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(Identity): 按域名自动匹配身份预设,支持自定义 TLS 指纹与 UA
XiaoYouChRa740daf1b918
diff --git a/app/client.py b/app/client.pyindex 40123d80..dc564801 100644--- a/app/client.py+++ b/app/client.py@@ -75,10 +75,25 @@ def toEmulation(profile: str, sourceUa: str = "") -> Emulation | None:return Emulation(profile=PROFILES_BY_FAMILY["chrome"][0][2], platform=host)+def matchIdentityPreset(host: str) -> dict | None:+ for preset in cfg.identityPresets.value:+ if not preset.get("isEnabled", True):+ continue+ for pattern in preset.get("hosts", []):+ if pattern.startswith("*."):+ suffix = pattern[2:]+ if host == suffix or host.endswith("." + suffix):+ return preset+ elif host == pattern:+ return preset+ return None++def buildClient(*,emulation: Emulation | None = ...,headers: dict | None = None,+ userAgent: str | None = None,timeout: int | None = None,) -> Client:resolved = toEmulation("") if emulation is ... else emulation@@ -93,12 +108,17 @@ def buildClient(if headers:if resolved is not None:- config["headers"] = {+ filtered = {k: v for k, v in headers.items()if k.lower() != "user-agent" and not k.lower().startswith("sec-ch-ua")}+ if userAgent:+ filtered["user-agent"] = userAgent+ config["headers"] = filteredelse:- if not any(k.lower() == "user-agent" for k in headers):+ if userAgent:+ headers = {**headers, "user-agent": userAgent}+ elif not any(k.lower() == "user-agent" for k in headers):major = PROFILES_BY_FAMILY["chrome"][0][1][0]headers = {**headers,@@ -106,6 +126,8 @@ def buildClient(f"(KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36",}config["headers"] = headers+ elif userAgent:+ config["headers"] = {"user-agent": userAgent}if timeout is not None:config["timeout"] = timedelta(seconds=timeout)diff --git a/app/config/cfg.py b/app/config/cfg.pyindex c0a49254..858b3cb7 100644--- a/app/config/cfg.py+++ b/app/config/cfg.py@@ -151,6 +151,29 @@ class ClientProfileValidator(ConfigValidator):return value if self.validate(value) else "auto"+class IdentityPresetListValidator(ConfigValidator):+ REQUIRED_KEYS = {"name", "clientProfile", "userAgent", "hosts"}++ def _isValidPreset(self, item) -> bool:+ return (+ isinstance(item, dict)+ and self.REQUIRED_KEYS <= item.keys()+ and isinstance(item["name"], str)+ and isinstance(item["clientProfile"], str)+ and isinstance(item["userAgent"], str)+ and isinstance(item["hosts"], list)+ and all(isinstance(h, str) for h in item["hosts"])+ )++ def validate(self, value) -> bool:+ return isinstance(value, list) and all(self._isValidPreset(item) for item in value)++ def correct(self, value) -> list:+ if not isinstance(value, list):+ return []+ return [item for item in value if self._isValidPreset(item)]++class HeadersValidator(ConfigValidator):def validate(self, value) -> bool:return isinstance(value, dict) and bool(value) and all(@@ -256,6 +279,13 @@ class Config(QConfig):"Network", "DefaultHeaders", dict(BASE_HEADERS),HeadersValidator(), JsonConfigSerializer(dict, lambda: dict(BASE_HEADERS)),)+ identityPresets = ConfigItem(+ "Network", "IdentityPresets",+ [{"name": "百度网盘客户端", "clientProfile": "raw",+ "userAgent": "pan.baidu.com", "hosts": ["*.pcs.baidu.com"],+ "isEnabled": True}],+ IdentityPresetListValidator(), JsonConfigSerializer(list, list),+ )cfg = Config()diff --git a/app/models/task.py b/app/models/task.pyindex 510ad985..b5f8811d 100644--- a/app/models/task.py+++ b/app/models/task.py@@ -58,6 +58,7 @@ class TaskOptions:default_factory=lambda: dict(cfg.defaultRequestHeaders.value))clientProfile: str = ""+ userAgent: str = ""sourceUserAgent: str = ""subworkerCount: int = field(default_factory=lambda: cfg.preBlockNum.value)diff --git a/app/services/feature_service.py b/app/services/feature_service.pyindex b393f9f0..1c1846c6 100644--- a/app/services/feature_service.py+++ b/app/services/feature_service.py@@ -1,6 +1,8 @@from __future__ import annotations+from dataclasses import replacefrom typing import TYPE_CHECKING+from urllib.parse import urlparsefrom PySide6.QtCore import QObject@@ -45,6 +47,19 @@ class FeatureService(QObject):toggle.connect(self._registerFileAssociations)async def parse(self, options: TaskOptions) -> Task:+ if not options.clientProfile:+ from app.client import matchIdentityPreset+ host = urlparse(options.url).hostname or ""+ preset = matchIdentityPreset(host)+ if preset is not None:+ kwargs = {}+ if preset["clientProfile"]:+ kwargs["clientProfile"] = preset["clientProfile"]+ if preset["userAgent"]:+ kwargs["userAgent"] = preset["userAgent"]+ if kwargs:+ options = replace(options, **kwargs)+for parser in self._parsers:if parser.match(options):task = await parser.parse(options)diff --git a/app/view/components/editors.py b/app/view/components/editors.pyindex 88f6468a..acedc8af 100644--- a/app/view/components/editors.py+++ b/app/view/components/editors.py@@ -363,8 +363,8 @@ class TokenLineEdit(QWidget):HEADER_SUGGESTIONS: Final[list[str]] = [- "Accept", "Accept-Encoding", "Accept-Language", "Authorization",- "Cache-Control", "Cookie", "Origin", "Range", "Referer", "User-Agent",+ "accept", "accept-encoding", "accept-language", "authorization",+ "cache-control", "cookie", "origin", "range", "referer", "user-agent",]diff --git a/app/view/components/option_cards.py b/app/view/components/option_cards.pyindex 03ef568a..ab416d34 100644--- a/app/view/components/option_cards.py+++ b/app/view/components/option_cards.py@@ -4,7 +4,7 @@ from PySide6.QtCore import QCoreApplication, Qtfrom PySide6.QtGui import QColor, QPainterfrom PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QSizePolicy, QWidgetfrom qfluentwidgets import (- Action, BodyLabel, FluentIcon, IconWidget, LineEdit, Slider,+ Action, BodyLabel, FluentIcon, IconWidget, LineEdit, RoundMenu, Slider,ToolTipFilter, TransparentToolButton, isDarkTheme,)@@ -30,6 +30,41 @@ def toProfileLabel(value: str) -> str:return f"{head} {version}" if version else value+def buildProfileMenu(parent, onPick, *, includeAuto: bool = True) -> RoundMenu:+ from app.client import profileFamilies, profileVersions++ menu = RoundMenu(parent=parent)++ if includeAuto:+ action = Action(FluentIcon.ROBOT, toProfileLabel("auto"), parent)+ action.triggered.connect(lambda checked=False: onPick("auto"))+ menu.addAction(action)+ else:+ action = Action(toProfileLabel(""), parent)+ action.triggered.connect(lambda checked=False: onPick(""))+ menu.addAction(action)++ rawAction = Action(FluentIcon.CANCEL, toProfileLabel("raw"), parent)+ rawAction.triggered.connect(lambda checked=False: onPick("raw"))+ menu.addAction(rawAction)++ menu.addSeparator()++ for family in profileFamilies():+ submenu = RoundMenu(PROFILE_FAMILY_LABELS.get(family, family), parent)+ latest = Action(toProfileLabel(family), parent)+ latest.triggered.connect(lambda checked=False, v=family: onPick(v))+ submenu.addAction(latest)+ submenu.addSeparator()+ for name in profileVersions(family):+ action = Action(toProfileLabel(name), parent)+ action.triggered.connect(lambda checked=False, v=name: onPick(v))+ submenu.addAction(action)+ menu.addMenu(submenu)++ return menu++class OptionCard(QWidget):def options(self) -> dict:@@ -125,35 +160,33 @@ class SubworkerCountCard(OptionCard):class ClientProfileCard(OptionCard):- def __init__(self, parent=None, *, initial: str = ""):- from qfluentwidgets import DropDownPushButton, RoundMenu- from app.client import profileFamilies, profileVersions+ def __init__(self, parent=None, *, initial: str = "", initialUserAgent: str = ""):+ from qfluentwidgets import DropDownPushButton+ from app.config.cfg import cfgsuper().__init__(parent)self.setFixedHeight(50)self._value = initial+ self._userAgent = initialUserAgentself.iconWidget = IconWidget(FluentIcon.ROBOT, self)self.iconWidget.setFixedSize(16, 16)self.titleLabel = BodyLabel(self.tr("模拟身份"), self)- self.button = DropDownPushButton(toProfileLabel(initial), self)++ label = self._presetLabelFor(initial, initialUserAgent) or toProfileLabel(initial)+ self.button = DropDownPushButton(label, self)self.button.setMinimumWidth(200)- menu = RoundMenu(parent=self)- for value, icon in (("auto", FluentIcon.ROBOT), ("raw", FluentIcon.CANCEL)):- action = Action(icon, toProfileLabel(value), self)- action.triggered.connect(lambda _=False, v=value: self._onPick(v))- menu.addAction(action)- for family in profileFamilies():- submenu = RoundMenu(PROFILE_FAMILY_LABELS.get(family, family), self)- latest = Action(toProfileLabel(family), self)- latest.triggered.connect(lambda _=False, v=family: self._onPick(v))- submenu.addAction(latest)- submenu.addSeparator()- for name in profileVersions(family):- action = Action(toProfileLabel(name), self)- action.triggered.connect(lambda _=False, v=name: self._onPick(v))- submenu.addAction(action)- menu.addMenu(submenu)+ menu = buildProfileMenu(self, self._onPick, includeAuto=True)++ presets = cfg.identityPresets.value+ if presets:+ menu.addSeparator()+ for preset in presets:+ action = Action(preset["name"], self)+ action.triggered.connect(+ lambda _=False, p=preset: self._onPickPreset(p))+ menu.addAction(action)+self.button.setMenu(menu)layout = QHBoxLayout(self)@@ -165,16 +198,35 @@ class ClientProfileCard(OptionCard):layout.addWidget(self.button)def options(self) -> dict:- return {"clientProfile": self._value}+ result = {"clientProfile": self._value}+ if self._userAgent:+ result["userAgent"] = self._userAgent+ return resultdef reset(self) -> None:self._value = ""+ self._userAgent = ""self.button.setText(toProfileLabel(""))def _onPick(self, value: str) -> None:self._value = value+ self._userAgent = ""self.button.setText(toProfileLabel(value))+ def _onPickPreset(self, preset: dict) -> None:+ self._value = preset["clientProfile"]+ self._userAgent = preset["userAgent"]+ self.button.setText(preset["name"])++ def _presetLabelFor(self, clientProfile: str, userAgent: str) -> str:+ if not userAgent:+ return ""+ from app.config.cfg import cfg+ for preset in cfg.identityPresets.value:+ if preset["clientProfile"] == clientProfile and preset["userAgent"] == userAgent:+ return preset["name"]+ return ""+class UrlEditCard(OptionCard):diff --git a/app/view/components/setting_cards.py b/app/view/components/setting_cards.pyindex fbe90be0..4b8ee69f 100644--- a/app/view/components/setting_cards.py+++ b/app/view/components/setting_cards.py@@ -15,7 +15,7 @@ from qfluentwidgets import (ConfigItem, FluentIcon, BodyLabel, CaptionLabel,RadioButton, ComboBox, LineEdit, ToolButton, ToolTipFilter,PrimaryPushButton, InfoBar, InfoBarPosition,- IconWidget,+ IconWidget, TransparentToolButton,)from app.view.components.setting_card_group import CollapsibleSettingCard@@ -370,58 +370,232 @@ class SelectFolderSettingCard(SettingCard):self.pathChanged.emit(path)-class ClientProfileSettingCard(SettingCard):+class PresetRowWidget(QWidget):+ editRequested = Signal(int)+ removeRequested = Signal(int)+ toggled = Signal(int, bool)++ def __init__(self, index: int, preset: dict, parent=None):+ from qfluentwidgets import IconWidget, PrimaryToolButton, SwitchButton, StrongBodyLabel, ToolButton+ super().__init__(parent)+ self._index = index+ self._preset = preset++ self.iconWidget = IconWidget(FluentIcon.VPN, self)+ self.nameLabel = StrongBodyLabel(preset.get("name", ""), self)+ self.descLayout = QHBoxLayout()+ self.switchButton = SwitchButton(self)+ self.editButton = PrimaryToolButton(FluentIcon.EDIT, self)+ self.removeButton = ToolButton(FluentIcon.DELETE, self)++ self._initWidget(preset)+ self._initLayout()+ self._bind()++ def _initWidget(self, preset: dict) -> None:+ self.iconWidget.setFixedSize(16, 16)+ self.switchButton.setChecked(preset.get("isEnabled", True))+ self.switchButton.setOnText("")+ self.switchButton.setOffText("")+ self.editButton.setToolTip(self.tr("编辑"))+ self.editButton.installEventFilter(ToolTipFilter(self.editButton))+ self.removeButton.setToolTip(self.tr("删除"))+ self.removeButton.installEventFilter(ToolTipFilter(self.removeButton))+ self._refreshOpacity(preset.get("isEnabled", True))++ def _initLayout(self) -> None:+ from app.view.components.labels import IconBodyLabel+ from app.view.components.option_cards import toProfileLabel++ self.descLayout.setContentsMargins(0, 0, 0, 0)+ self.descLayout.setSpacing(0)++ hosts = self._preset.get("hosts", [])+ if hosts:+ self.descLayout.addWidget(+ IconBodyLabel(", ".join(hosts[:3]), FluentIcon.GLOBE, self, size=12))+ self.descLayout.addSpacing(8)+ profile = self._preset.get("clientProfile", "")+ if profile:+ self.descLayout.addWidget(+ IconBodyLabel(toProfileLabel(profile), FluentIcon.FINGERPRINT, self, size=12))+ self.descLayout.addSpacing(8)+ ua = self._preset.get("userAgent", "")+ if ua:+ display = ua if len(ua) <= 24 else ua[:21] + "..."+ self.descLayout.addWidget(+ IconBodyLabel(display, FluentIcon.PEOPLE, self, size=12))+ self.descLayout.addStretch(1)++ textLayout = QVBoxLayout()+ textLayout.setContentsMargins(0, 0, 0, 0)+ textLayout.setSpacing(2)+ textLayout.addWidget(self.nameLabel)+ textLayout.addLayout(self.descLayout)++ layout = QHBoxLayout(self)+ layout.setContentsMargins(48, 8, 24, 8)+ layout.setSpacing(12)+ layout.addWidget(self.iconWidget)+ layout.addLayout(textLayout, 1)+ layout.addWidget(self.switchButton)+ layout.addWidget(self.editButton)+ layout.addWidget(self.removeButton)++ def _bind(self) -> None:+ self.editButton.clicked.connect(lambda: self.editRequested.emit(self._index))+ self.removeButton.clicked.connect(lambda: self.removeRequested.emit(self._index))+ self.switchButton.checkedChanged.connect(+ lambda checked: self._onToggled(checked))++ def _onToggled(self, checked: bool) -> None:+ self._refreshOpacity(checked)+ self.toggled.emit(self._index, checked)++ def _refreshOpacity(self, enabled: bool) -> None:+ self.nameLabel.setEnabled(enabled)+ for i in range(self.descLayout.count()):+ w = self.descLayout.itemAt(i).widget()+ if w:+ w.setEnabled(enabled)+++class IdentitySettingCard(CollapsibleSettingCard):def __init__(self, parent=None):from qfluentwidgets import DropDownPushButtonfrom app.view.components.option_cards import toProfileLabel- super().__init__(FluentIcon.ROBOT, self.tr("模拟身份"), self.tr("浏览器 TLS 指纹与 User-Agent"), parent)- self.button = DropDownPushButton(toProfileLabel(cfg.clientProfile.value), self)++ super().__init__(FluentIcon.ROBOT, self.tr("模拟身份"),+ self.tr("TLS 指纹与 User-Agent 预设"), parent=parent)+ self._rowWidgets: list[PresetRowWidget] = []++ from qfluentwidgets import IconWidget+ from app.view.components.labels import IconBodyLabel++ self.choiceLabel = BodyLabel(self)+ self.profileButton = DropDownPushButton(toProfileLabel(cfg.clientProfile.value), self.view)+ self.profileButton.setMinimumWidth(200)++ self.profileWidget = QWidget(self.view)+ self.profileLayout = QHBoxLayout(self.profileWidget)+ self.profileIcon = IconWidget(FluentIcon.ROBOT, self.profileWidget)+ self.profileIcon.setFixedSize(16, 16)+ self.profileTitleLabel = BodyLabel(self.tr("全局默认"), self.profileWidget)+ self.profileDescLabel = CaptionLabel(self.tr("未被预设匹配时使用"), self.profileWidget)++ self.buttonContainer = QWidget(self.view)+ self.buttonLayout = QHBoxLayout(self.buttonContainer)+ from qfluentwidgets import PrimaryPushButton+ self.addButton = PrimaryPushButton(FluentIcon.ADD, self.tr("添加预设"), self.buttonContainer)+self._initWidget()self._initLayout()self._bind()+ self._reload()def _initWidget(self) -> None:- from qfluentwidgets import Action, RoundMenu- from app.client import profileFamilies, profileVersions- from app.view.components.option_cards import PROFILE_FAMILY_LABELS, toProfileLabel-- self.button.setMinimumWidth(200)- menu = RoundMenu(parent=self)-- for value, icon in (("auto", FluentIcon.ROBOT), ("raw", FluentIcon.CANCEL)):- action = Action(icon, toProfileLabel(value), self)- action.triggered.connect(lambda checked=False, v=value: self._onPick(v))- menu.addAction(action)-- for family in profileFamilies():- submenu = RoundMenu(PROFILE_FAMILY_LABELS.get(family, family), self)- latest = Action(toProfileLabel(family), self)- latest.triggered.connect(lambda checked=False, v=family: self._onPick(v))- submenu.addAction(latest)- submenu.addSeparator()- for name in profileVersions(family):- action = Action(toProfileLabel(name), self)- action.triggered.connect(lambda checked=False, v=name: self._onPick(v))- submenu.addAction(action)- menu.addMenu(submenu)-- self.button.setMenu(menu)+ from app.view.components.option_cards import buildProfileMenu++ self.profileButton.setMenu(+ buildProfileMenu(self, self._onPick, includeAuto=True)+ )+ self._refreshChoiceLabel()def _initLayout(self) -> None:- self.hBoxLayout.addWidget(self.button, 0, Qt.AlignmentFlag.AlignRight)- self.hBoxLayout.addSpacing(16)+ self.addWidget(self.choiceLabel)++ profileTextLayout = QVBoxLayout()+ profileTextLayout.setContentsMargins(0, 0, 0, 0)+ profileTextLayout.setSpacing(2)+ profileTextLayout.addWidget(self.profileTitleLabel)+ profileTextLayout.addWidget(self.profileDescLabel)++ self.profileLayout.setContentsMargins(48, 12, 24, 12)+ self.profileLayout.setSpacing(12)+ self.profileLayout.addWidget(self.profileIcon)+ self.profileLayout.addLayout(profileTextLayout, 1)+ self.profileLayout.addWidget(self.profileButton)++ self.buttonLayout.setContentsMargins(48, 8, 24, 8)+ self.buttonLayout.addStretch(1)+ self.buttonLayout.addWidget(self.addButton)++ self.viewLayout.setSpacing(0)+ self.viewLayout.setContentsMargins(0, 0, 0, 0)+ self.addGroupWidget(self.profileWidget)def _bind(self) -> None:cfg.clientProfile.valueChanged.connect(self._onProfileChanged)+ self.addButton.clicked.connect(self._onAddClicked)def _onProfileChanged(self, value: str) -> None:from app.view.components.option_cards import toProfileLabel- self.button.setText(toProfileLabel(value))+ self.profileButton.setText(toProfileLabel(value))+ self._refreshChoiceLabel()def _onPick(self, value: str) -> None:cfg.set(cfg.clientProfile, value)+ def _refreshChoiceLabel(self) -> None:+ from app.view.components.option_cards import toProfileLabel+ self.choiceLabel.setText(toProfileLabel(cfg.clientProfile.value))++ def _reload(self) -> None:+ for row in self._rowWidgets:+ self.viewLayout.removeWidget(row)+ row.deleteLater()+ self._rowWidgets.clear()+ self.viewLayout.removeWidget(self.buttonContainer)++ for i, preset in enumerate(cfg.identityPresets.value):+ row = PresetRowWidget(i, preset, self.view)+ row.editRequested.connect(self._onEditClicked)+ row.removeRequested.connect(self._onRemoveClicked)+ row.toggled.connect(self._onToggled)+ self.viewLayout.addWidget(row)+ self._rowWidgets.append(row)++ self.viewLayout.addWidget(self.buttonContainer)+ self._refreshChoiceLabel()++ def _onAddClicked(self) -> None:+ from app.view.dialogs.preset_edit import PresetEditDialog+ dialog = PresetEditDialog(self.window())+ if dialog.exec():+ presets = list(cfg.identityPresets.value)+ presets.append(dialog.preset())+ cfg.set(cfg.identityPresets, presets)+ self._reload()+ if not self.isExpand:+ self.setExpand(True)++ def _onEditClicked(self, index: int) -> None:+ presets = list(cfg.identityPresets.value)+ if index < 0 or index >= len(presets):+ return+ from app.view.dialogs.preset_edit import PresetEditDialog+ dialog = PresetEditDialog(self.window(), preset=presets[index])+ if dialog.exec():+ presets[index] = dialog.preset()+ cfg.set(cfg.identityPresets, presets)+ self._reload()++ def _onToggled(self, index: int, checked: bool) -> None:+ presets = list(cfg.identityPresets.value)+ if index < 0 or index >= len(presets):+ return+ presets[index] = {**presets[index], "isEnabled": checked}+ cfg.set(cfg.identityPresets, presets)++ def _onRemoveClicked(self, index: int) -> None:+ presets = list(cfg.identityPresets.value)+ if index < 0 or index >= len(presets):+ return+ presets.pop(index)+ cfg.set(cfg.identityPresets, presets)+ self._reload()+class DefaultHeadersSettingCard(PushSettingCard):def __init__(self, icon, title: str, content: str = "", parent=None):diff --git a/app/view/dialogs/preset_edit.py b/app/view/dialogs/preset_edit.pynew file mode 100644index 00000000..9f9d7f16--- /dev/null+++ b/app/view/dialogs/preset_edit.py@@ -0,0 +1,113 @@+from __future__ import annotations++from PySide6.QtWidgets import QHBoxLayout+from qfluentwidgets import (+ BodyLabel, DropDownPushButton, FluentIcon, LineEdit,+ MessageBoxBase, SubtitleLabel, TeachingTip, TeachingTipTailPosition,+ TransparentToolButton,+)++from app.view.components.editors import TokenLineEdit+++class PresetEditDialog(MessageBoxBase):++ def __init__(self, parent=None, *, preset: dict | None = None):+ super().__init__(parent)+ self._preset = preset+ self._profileValue = preset.get("clientProfile", "") if preset else ""++ self.titleLabel = SubtitleLabel(+ self.tr("编辑身份预设") if preset else self.tr("添加身份预设"), self+ )+ self.nameEdit = LineEdit(self)+ self.hostsEdit = TokenLineEdit(self)+ self.hostsHelpButton = TransparentToolButton(FluentIcon.QUESTION, self)+ self.hostsRow = QHBoxLayout()+ self.profileButton = DropDownPushButton(self)+ self.uaEdit = LineEdit(self)++ self._initWidget()+ self._initLayout()+ self._bind()+ self._populate()++ def _initWidget(self) -> None:+ self.widget.setMinimumWidth(480)+ self.yesButton.setText(self.tr("确定"))+ self.cancelButton.setText(self.tr("取消"))+ self.nameEdit.setPlaceholderText(self.tr("预设名称"))+ self.uaEdit.setPlaceholderText(self.tr("留空则跟随 TLS 指纹自动生成"))+ self.uaEdit.setClearButtonEnabled(True)++ from app.view.components.option_cards import buildProfileMenu+ self.profileButton.setMenu(+ buildProfileMenu(self, self._onProfilePick, includeAuto=False))++ def _initLayout(self) -> None:+ self.hostsRow.setContentsMargins(0, 0, 0, 0)+ self.hostsRow.setSpacing(4)+ self.hostsRow.addWidget(BodyLabel(self.tr("匹配 Host"), self))+ self.hostsRow.addWidget(self.hostsHelpButton)+ self.hostsRow.addStretch(1)++ self.viewLayout.setSpacing(8)+ self.viewLayout.addWidget(self.titleLabel)+ self.viewLayout.addSpacing(8)+ self.viewLayout.addWidget(BodyLabel(self.tr("名称"), self))+ self.viewLayout.addWidget(self.nameEdit)+ self.viewLayout.addLayout(self.hostsRow)+ self.viewLayout.addWidget(self.hostsEdit)+ self.viewLayout.addWidget(BodyLabel(self.tr("TLS 指纹"), self))+ self.viewLayout.addWidget(self.profileButton)+ self.viewLayout.addWidget(BodyLabel(self.tr("User-Agent"), self))+ self.viewLayout.addWidget(self.uaEdit)++ def _bind(self) -> None:+ self.hostsHelpButton.clicked.connect(self._onHostsHelpClicked)++ def _populate(self) -> None:+ self._refreshProfileLabel()+ if self._preset is None:+ return+ self.nameEdit.setText(self._preset.get("name", ""))+ self.hostsEdit.setTokens(self._preset.get("hosts", []))+ self.uaEdit.setText(self._preset.get("userAgent", ""))++ def _onHostsHelpClicked(self) -> None:+ TeachingTip.create(+ self.hostsHelpButton,+ self.tr("Host 匹配规则"),+ self.tr(+ "输入域名后按回车添加,支持两种格式:\n\n"+ "精确匹配: pcs.baidu.com\n"+ "通配符: *.pcs.baidu.com(匹配所有子域名)"+ ),+ tailPosition=TeachingTipTailPosition.BOTTOM,+ isClosable=True,+ duration=-1,+ parent=self,+ )++ def _onProfilePick(self, value: str) -> None:+ self._profileValue = value+ self._refreshProfileLabel()++ def _refreshProfileLabel(self) -> None:+ from app.view.components.option_cards import toProfileLabel+ if self._profileValue:+ self.profileButton.setText(toProfileLabel(self._profileValue))+ else:+ self.profileButton.setText(self.tr("跟随全局默认"))++ def preset(self) -> dict:+ result = {+ "name": self.nameEdit.text().strip() or self.tr("未命名预设"),+ "clientProfile": self._profileValue,+ "userAgent": self.uaEdit.text().strip(),+ "hosts": self.hostsEdit.tokens(),+ "isEnabled": True,+ }+ if self._preset is not None:+ result["isEnabled"] = self._preset.get("isEnabled", True)+ return resultdiff --git a/app/view/pages/setting_page.py b/app/view/pages/setting_page.pyindex 68d606b3..2c7d4926 100644--- a/app/view/pages/setting_page.py+++ b/app/view/pages/setting_page.py@@ -24,7 +24,7 @@ from app.view.components.setting_card_group import (CollapsibleSettingCard, CollapsibleSettingCardGroup, QWIDGETSIZE_MAX,)from app.view.components.setting_cards import (- ClientProfileSettingCard, DefaultHeadersSettingCard, LineEditSettingCard,+ DefaultHeadersSettingCard, IdentitySettingCard, LineEditSettingCard,PercentSpinBoxSettingCard, ProxySettingCard, SpinBoxSettingCard,)from app.view.components.editors import FolderPicker@@ -85,7 +85,7 @@ class SettingPage(ScrollArea):self.downloadFolderCard.hBoxLayout.addSpacing(8)self.downloadFolderCard.hBoxLayout.addWidget(self.downloadRestoreButton, 0, Qt.AlignmentFlag.AlignRight)self.downloadFolderCard.hBoxLayout.addSpacing(16)- self.clientProfileCard = ClientProfileSettingCard()+ self.clientProfileCard = IdentitySettingCard()self.generalGroup.addSettingCards([RangeSettingCard(cfg.maxTaskNum, FluentIcon.TRAIN, self.tr("最大任务数"),@@ -109,7 +109,7 @@ class SettingPage(ScrollArea):ProxySettingCard(cfg.proxyServer),self.clientProfileCard,DefaultHeadersSettingCard(FluentIcon.DICTIONARY, self.tr("默认请求头"),- self.tr("设置默认 HTTP 请求头,User-Agent 由模拟身份控制(选择原样发送时除外)")),+ self.tr("设置默认 HTTP 请求头")),])self.categoryRulesCard = CategoryRulesCard()diff --git a/features/http_pack/pack.py b/features/http_pack/pack.pyindex cc0f9cbf..d4a3f00e 100644--- a/features/http_pack/pack.py+++ b/features/http_pack/pack.py@@ -47,6 +47,7 @@ class HttpParser(TaskParser):url = options.urlheaders = dict(options.headers)clientProfile = options.clientProfile+ userAgent = options.userAgentsubworkerCount = options.subworkerCountoutputFolder = options.outputFolder@@ -64,7 +65,7 @@ class HttpParser(TaskParser):options.clientProfile or cfg.clientProfile.value,options.sourceUserAgent,)- client = buildClient(emulation=emulation)+ client = buildClient(emulation=emulation, userAgent=userAgent or None)def rangeTotal(h: dict) -> int:cr = h.get("content-range", "")@@ -195,6 +196,7 @@ class HttpParser(TaskParser):fileSize=fileSize,headers=headers,clientProfile=clientProfile,+ userAgent=userAgent,subworkerCount=subworkerCount,canUseRangeRequests=canUseRangeRequests,lastModified=lastModified,@@ -218,7 +220,7 @@ class HttpPack(FeaturePack):return [OutputFolderCard(parent, initial=task.outputFolder),HeadersEditCard(parent, initial=step.headers),- ClientProfileCard(parent, initial=step.clientProfile),+ ClientProfileCard(parent, initial=step.clientProfile, initialUserAgent=step.userAgent),SubworkerCountCard(parent, initial=step.subworkerCount),]diff --git a/features/http_pack/task.py b/features/http_pack/task.pyindex 9d628ffd..fe841b3a 100644--- a/features/http_pack/task.py+++ b/features/http_pack/task.py@@ -57,6 +57,7 @@ class HttpTaskStep(TaskStep):fileSize: int = 0headers: dict[str, str] = field(default_factory=dict)clientProfile: str = ""+ userAgent: str = ""subworkerCount: int = 8canUseRangeRequests: bool = FalselastModified: str = ""@@ -87,6 +88,8 @@ class HttpTaskStep(TaskStep):self.headers = options["headers"]if "clientProfile" in options:self.clientProfile = options["clientProfile"]+ if "userAgent" in options:+ self.userAgent = options["userAgent"]if "subworkerCount" in options:self.subworkerCount = options["subworkerCount"]@@ -242,7 +245,7 @@ class HttpTaskStep(TaskStep):if subworker.end == SpecialFileSize.UNKNOWN:while True:try:- headers = {**self.headers, "range": f"bytes={subworker.position}-", "accept-encoding": "identity"}+ headers = {**self._effectiveHeaders, "range": f"bytes={subworker.position}-", "accept-encoding": "identity"}response = await self._client.get(self.url, headers=headers)try:status = response.status.as_int()@@ -273,7 +276,7 @@ class HttpTaskStep(TaskStep):try:ftruncate(fd, 0)subworker.receivedBytes = 0- response = await self._client.get(self.url, headers=dict(self.headers))+ response = await self._client.get(self.url, headers=dict(self._effectiveHeaders))try:status = response.status.as_int()if status in PERMANENT_STATUS or response.headers.contains_key("cf-mitigated"):@@ -351,8 +354,12 @@ class HttpTaskStep(TaskStep):Path(self.outputPath).parent.mkdir(parents=True, exist_ok=True)+ self._effectiveHeaders = {**self.headers}+ if self.userAgent and not any(k.lower() == "user-agent" for k in self.headers):+ self._effectiveHeaders["user-agent"] = self.userAgent+emulation = toEmulation(self.clientProfile or cfg.clientProfile.value, "")- self._client = buildClient(emulation=emulation)+ self._client = buildClient(emulation=emulation, userAgent=self.userAgent or None)restored = Falseif self.canUseRangeRequests:diff --git a/features/m3u8_pack/pack.py b/features/m3u8_pack/pack.pyindex 0b4db528..49256813 100644--- a/features/m3u8_pack/pack.py+++ b/features/m3u8_pack/pack.py@@ -53,7 +53,8 @@ class M3U8Parser(TaskParser):options.clientProfile or cfg.clientProfile.value,options.sourceUserAgent,)- client = buildClient(emulation=emulation, headers=headers)+ client = buildClient(emulation=emulation, headers=headers,+ userAgent=options.userAgent or None)try:response = await client.get(url)response.raise_for_status()@@ -85,7 +86,7 @@ class M3U8Parser(TaskParser):variantClient = buildClient(emulation=toEmulation(options.clientProfile or cfg.clientProfile.value,options.sourceUserAgent,- ), headers=headers)+ ), headers=headers, userAgent=options.userAgent or None)try:variantResponse = await variantClient.get(variantUrl)variantResponse.raise_for_status()diff --git a/tests/test_identity_preset.py b/tests/test_identity_preset.pynew file mode 100644index 00000000..1169e3ab--- /dev/null+++ b/tests/test_identity_preset.py@@ -0,0 +1,447 @@+"""Tests for the identity preset system.++Covers: matchIdentityPreset, buildClient userAgent param, _effectiveHeaders,+featureService.parse preset injection, backward compat, toEmulation auto logic.+"""+from __future__ import annotations++import sys+from dataclasses import replace+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+++# ---------------------------------------------------------------------------+# Fixtures: mock cfg so tests don't depend on user config+# ---------------------------------------------------------------------------+[email protected](autouse=True)+def _mock_cfg(monkeypatch):+ """Provide a clean cfg with known defaults for every test."""+ from app.config.cfg import cfg+ monkeypatch.setattr(cfg.identityPresets, "value", [+ {"name": "百度网盘客户端", "clientProfile": "raw", "userAgent": "pan.baidu.com",+ "hosts": ["*.pcs.baidu.com"], "isEnabled": True},+ ])+ monkeypatch.setattr(cfg.clientProfile, "value", "auto")+ monkeypatch.setattr(cfg.defaultRequestHeaders, "value", {+ "accept-encoding": "deflate, br, gzip",+ })+++# ===========================================================================+# B. matchIdentityPreset — host matching+# ===========================================================================++class TestMatchIdentityPreset:++ def _match(self, host: str) -> dict | None:+ from app.client import matchIdentityPreset+ return matchIdentityPreset(host)++ def test_b1_exact_host_match(self, monkeypatch):+ from app.config.cfg import cfg+ monkeypatch.setattr(cfg.identityPresets, "value", [+ {"name": "exact", "clientProfile": "raw", "userAgent": "ua",+ "hosts": ["pan.baidu.com"], "isEnabled": True},+ ])+ assert self._match("pan.baidu.com") is not None+ assert self._match("pan.baidu.com")["name"] == "exact"++ def test_b2_wildcard_subdomain_match(self):+ result = self._match("d.pcs.baidu.com")+ assert result is not None+ assert result["name"] == "百度网盘客户端"++ def test_b3_wildcard_root_domain_match(self):+ result = self._match("pcs.baidu.com")+ assert result is not None+ assert result["name"] == "百度网盘客户端"++ def test_b4_no_match(self):+ assert self._match("google.com") is None++ def test_b5_disabled_preset_skipped(self, monkeypatch):+ from app.config.cfg import cfg+ monkeypatch.setattr(cfg.identityPresets, "value", [+ {"name": "disabled", "clientProfile": "raw", "userAgent": "ua",+ "hosts": ["*.example.com"], "isEnabled": False},+ ])+ assert self._match("test.example.com") is None++ def test_b6_first_match_wins(self, monkeypatch):+ from app.config.cfg import cfg+ monkeypatch.setattr(cfg.identityPresets, "value", [+ {"name": "first", "clientProfile": "raw", "userAgent": "ua1",+ "hosts": ["*.baidu.com"], "isEnabled": True},+ {"name": "second", "clientProfile": "chrome", "userAgent": "ua2",+ "hosts": ["*.baidu.com"], "isEnabled": True},+ ])+ result = self._match("d.pcs.baidu.com")+ assert result["name"] == "first"++ def test_b7_empty_hosts_not_matched(self, monkeypatch):+ from app.config.cfg import cfg+ monkeypatch.setattr(cfg.identityPresets, "value", [+ {"name": "manual-only", "clientProfile": "raw", "userAgent": "ua",+ "hosts": [], "isEnabled": True},+ ])+ assert self._match("anything.com") is None++ def test_b8_empty_hostname(self):+ assert self._match("") is None++ def test_b9_broad_wildcard(self, monkeypatch):+ from app.config.cfg import cfg+ monkeypatch.setattr(cfg.identityPresets, "value", [+ {"name": "broad", "clientProfile": "raw", "userAgent": "ua",+ "hosts": ["*.com"], "isEnabled": True},+ ])+ assert self._match("google.com") is not None+ assert self._match("baidu.com") is not None++ def test_b_missing_isEnabled_defaults_true(self, monkeypatch):+ from app.config.cfg import cfg+ monkeypatch.setattr(cfg.identityPresets, "value", [+ {"name": "old", "clientProfile": "raw", "userAgent": "ua",+ "hosts": ["*.example.com"]},+ ])+ assert self._match("test.example.com") is not None++ def test_b_deep_subdomain(self):+ result = self._match("a.b.c.pcs.baidu.com")+ assert result is not None+++# ===========================================================================+# C. buildClient userAgent parameter (mock wreq)+# ===========================================================================++class TestBuildClientUserAgent:+ """Test that buildClient correctly handles the userAgent parameter.++ Since wreq is not available in test env, we patch it.+ """++ @pytest.fixture(autouse=True)+ def _mock_wreq(self, monkeypatch):+ wreq_mock = MagicMock()+ wreq_mock.Client = MagicMock(return_value=MagicMock())+ wreq_mock.Emulation = MagicMock()+ wreq_mock.Proxy = MagicMock()++ profile_mock = MagicMock()+ wreq_mock.emulation.Platform = MagicMock()+ wreq_mock.emulation.Profile = type(profile_mock)+ wreq_mock.redirect.Policy = MagicMock()++ monkeypatch.setitem(sys.modules, "wreq", wreq_mock)+ monkeypatch.setitem(sys.modules, "wreq.emulation", wreq_mock.emulation)+ monkeypatch.setitem(sys.modules, "wreq.redirect", wreq_mock.redirect)++ if "app.client" in sys.modules:+ del sys.modules["app.client"]++ def _build(self, **kwargs):+ from app.client import buildClient+ return buildClient(**kwargs)++ def test_c9_no_headers_with_useragent(self):+ from app.client import buildClient+ import wreq+ buildClient(emulation=None, headers=None, userAgent="netdisk")+ call_kwargs = wreq.Client.call_args[1]+ assert call_kwargs.get("headers", {}).get("user-agent") == "netdisk"++ def test_c10_no_headers_no_useragent(self):+ from app.client import buildClient+ import wreq+ buildClient(emulation=None, headers=None, userAgent=None)+ call_kwargs = wreq.Client.call_args[1]+ assert "headers" not in call_kwargs or "user-agent" not in call_kwargs.get("headers", {})+++# ===========================================================================+# D. HttpTaskStep._effectiveHeaders+# ===========================================================================++class TestEffectiveHeaders:++ def test_d1_no_useragent_no_headers_ua(self):+ headers = {"cookie": "x"}+ effective = {**headers}+ user_agent = ""+ if user_agent and not any(k.lower() == "user-agent" for k in headers):+ effective["user-agent"] = user_agent+ assert "user-agent" not in effective++ def test_d2_no_useragent_headers_has_ua(self):+ headers = {"cookie": "x", "user-agent": "browser"}+ effective = {**headers}+ user_agent = ""+ if user_agent and not any(k.lower() == "user-agent" for k in headers):+ effective["user-agent"] = user_agent+ assert effective["user-agent"] == "browser"++ def test_d3_useragent_no_headers_ua(self):+ headers = {"cookie": "x"}+ effective = {**headers}+ user_agent = "netdisk"+ if user_agent and not any(k.lower() == "user-agent" for k in headers):+ effective["user-agent"] = user_agent+ assert effective["user-agent"] == "netdisk"++ def test_d4_useragent_headers_has_ua_manual_wins(self):+ headers = {"cookie": "x", "user-agent": "custom"}+ effective = {**headers}+ user_agent = "netdisk"+ if user_agent and not any(k.lower() == "user-agent" for k in headers):+ effective["user-agent"] = user_agent+ assert effective["user-agent"] == "custom"+++# ===========================================================================+# F. Preset field interactions in featureService.parse()+# ===========================================================================++class TestPresetFieldInteraction:+ """Test the inline preset matching logic from featureService.parse().++ We replicate the logic here to test without needing async/parser infra.+ """++ def _apply_preset(self, url: str, client_profile: str = "", user_agent: str = ""):+ from urllib.parse import urlparse+ from app.client import matchIdentityPreset+ from app.models.task import TaskOptions++ options = TaskOptions(url=url, clientProfile=client_profile, userAgent=user_agent)++ if not options.clientProfile:+ host = urlparse(options.url).hostname or ""+ preset = matchIdentityPreset(host)+ if preset is not None:+ kwargs = {}+ if preset["clientProfile"]:+ kwargs["clientProfile"] = preset["clientProfile"]+ if preset["userAgent"]:+ kwargs["userAgent"] = preset["userAgent"]+ if kwargs:+ options = replace(options, **kwargs)++ return options++ def test_f1_preset_sets_both_fields(self):+ options = self._apply_preset("https://d.pcs.baidu.com/file/abc")+ assert options.clientProfile == "raw"+ assert options.userAgent == "pan.baidu.com"++ def test_f2_preset_only_useragent(self, monkeypatch):+ from app.config.cfg import cfg+ monkeypatch.setattr(cfg.identityPresets, "value", [+ {"name": "ua-only", "clientProfile": "", "userAgent": "netdisk",+ "hosts": ["*.example.com"], "isEnabled": True},+ ])+ options = self._apply_preset("https://dl.example.com/file")+ assert options.clientProfile == ""+ assert options.userAgent == "netdisk"++ def test_f3_preset_only_profile(self, monkeypatch):+ from app.config.cfg import cfg+ monkeypatch.setattr(cfg.identityPresets, "value", [+ {"name": "profile-only", "clientProfile": "chrome", "userAgent": "",+ "hosts": ["*.example.com"], "isEnabled": True},+ ])+ options = self._apply_preset("https://dl.example.com/file")+ assert options.clientProfile == "chrome"+ assert options.userAgent == ""++ def test_f4_preset_empty_both_fields(self, monkeypatch):+ from app.config.cfg import cfg+ monkeypatch.setattr(cfg.identityPresets, "value", [+ {"name": "empty", "clientProfile": "", "userAgent": "",+ "hosts": ["*.example.com"], "isEnabled": True},+ ])+ options = self._apply_preset("https://dl.example.com/file")+ assert options.clientProfile == ""+ assert options.userAgent == ""++ def test_f5_explicit_clientprofile_skips_preset(self):+ options = self._apply_preset(+ "https://d.pcs.baidu.com/file/abc",+ client_profile="chrome",+ )+ assert options.clientProfile == "chrome"+ assert options.userAgent == ""++ def test_f_no_host_match(self):+ options = self._apply_preset("https://google.com/file")+ assert options.clientProfile == ""+ assert options.userAgent == ""++ def test_f_file_url_no_crash(self):+ options = self._apply_preset("file:///tmp/test.m3u8")+ assert options.clientProfile == ""+++# ===========================================================================+# G. Backward compatibility+# ===========================================================================++class TestBackwardCompat:++ def test_g1_old_step_missing_useragent(self):+ from app.models.serialization import filterFields+ from features.http_pack.task import HttpTaskStep++ old_data = {+ "stepIndex": 1,+ "url": "https://example.com/file.zip",+ "fileSize": 1024,+ "headers": {"cookie": "x"},+ "clientProfile": "auto",+ "subworkerCount": 8,+ "canUseRangeRequests": True,+ }+ filtered = filterFields(HttpTaskStep, old_data)+ step = HttpTaskStep(**filtered)+ assert step.userAgent == ""++ def test_g2_old_step_unknown_fields_dropped(self):+ from app.models.serialization import filterFields+ from features.http_pack.task import HttpTaskStep++ old_data = {+ "stepIndex": 1,+ "url": "https://example.com/file.zip",+ "unknownField": "should be dropped",+ "anotherUnknown": 42,+ }+ filtered = filterFields(HttpTaskStep, old_data)+ assert "unknownField" not in filtered+ assert "anotherUnknown" not in filtered++ def test_g_new_step_has_useragent(self):+ from features.http_pack.task import HttpTaskStep++ step = HttpTaskStep(stepIndex=1, url="https://example.com", userAgent="test")+ assert step.userAgent == "test"++ def test_g_setoptions_useragent(self):+ from features.http_pack.task import HttpTaskStep++ step = HttpTaskStep(stepIndex=1, url="https://example.com")+ step.setOptions({"userAgent": "netdisk"})+ assert step.userAgent == "netdisk"++ def test_g_setoptions_partial(self):+ from features.http_pack.task import HttpTaskStep++ step = HttpTaskStep(+ stepIndex=1, url="https://example.com",+ clientProfile="chrome", userAgent="old",+ )+ step.setOptions({"clientProfile": "raw"})+ assert step.clientProfile == "raw"+ assert step.userAgent == "old"+++# ===========================================================================+# Validator+# ===========================================================================++class TestIdentityPresetListValidator:++ def test_valid(self):+ from app.config.cfg import IdentityPresetListValidator+ v = IdentityPresetListValidator()+ data = [{"name": "test", "clientProfile": "raw", "userAgent": "ua",+ "hosts": ["*.example.com"]}]+ assert v.validate(data) is True++ def test_valid_with_isEnabled(self):+ from app.config.cfg import IdentityPresetListValidator+ v = IdentityPresetListValidator()+ data = [{"name": "test", "clientProfile": "raw", "userAgent": "ua",+ "hosts": ["*.example.com"], "isEnabled": False}]+ assert v.validate(data) is True++ def test_invalid_missing_key(self):+ from app.config.cfg import IdentityPresetListValidator+ v = IdentityPresetListValidator()+ data = [{"name": "test"}]+ assert v.validate(data) is False++ def test_invalid_hosts_not_list(self):+ from app.config.cfg import IdentityPresetListValidator+ v = IdentityPresetListValidator()+ data = [{"name": "test", "clientProfile": "raw", "userAgent": "ua",+ "hosts": "*.example.com"}]+ assert v.validate(data) is False++ def test_correct_filters_bad_entries(self):+ from app.config.cfg import IdentityPresetListValidator+ v = IdentityPresetListValidator()+ data = [+ {"name": "good", "clientProfile": "raw", "userAgent": "ua", "hosts": []},+ {"name": "bad"},+ {"name": "also-good", "clientProfile": "", "userAgent": "", "hosts": ["*.x.com"]},+ ]+ corrected = v.correct(data)+ assert len(corrected) == 2+ assert corrected[0]["name"] == "good"+ assert corrected[1]["name"] == "also-good"++ def test_empty_list_valid(self):+ from app.config.cfg import IdentityPresetListValidator+ v = IdentityPresetListValidator()+ assert v.validate([]) is True++ def test_not_list_invalid(self):+ from app.config.cfg import IdentityPresetListValidator+ v = IdentityPresetListValidator()+ assert v.validate("not a list") is False+ assert v.correct("not a list") == []+++# ===========================================================================+# TaskOptions.userAgent field+# ===========================================================================++class TestTaskOptionsUserAgent:++ def test_default_empty(self):+ from app.models.task import TaskOptions+ options = TaskOptions(url="https://example.com")+ assert options.userAgent == ""++ def test_explicit_value(self):+ from app.models.task import TaskOptions+ options = TaskOptions(url="https://example.com", userAgent="netdisk")+ assert options.userAgent == "netdisk"++ def test_from_options(self):+ from app.models.task import TaskOptions+ options = TaskOptions.fromOptions({+ "url": "https://example.com",+ "userAgent": "custom",+ })+ assert options.userAgent == "custom"++ def test_from_options_missing_useragent(self):+ from app.models.task import TaskOptions+ options = TaskOptions.fromOptions({+ "url": "https://example.com",+ })+ assert options.userAgent == ""++ def test_replace_useragent(self):+ from app.models.task import TaskOptions+ options = TaskOptions(url="https://example.com")+ modified = replace(options, userAgent="netdisk")+ assert modified.userAgent == "netdisk"+ assert options.userAgent == ""