The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor(packs): 引擎层去 PySide6,支持跨平台共享
XiaoYouChRa8adad367417
diff --git a/app/models/pack.py b/app/models/pack.pyindex a815c356..49fd63f1 100644--- a/app/models/pack.py+++ b/app/models/pack.py@@ -127,7 +127,7 @@ class BinaryRuntime:# 自描述展示信息(title 用 QT_TRANSLATE_NOOP 声明原文,展示端 translate)title: str = ""description: str = ""- icon: FluentIcon | None = None+ icon: str = "" # FluentIcon 成员名,View 侧解析isRecommended: bool = False@property@@ -268,8 +268,6 @@ class FeaturePack:proxySchemes: set[str] | None = Noneparsers: list[type[TaskParser]] = []- taskCards: dict = {}- draftCards: dict = {}parse: Callable[[TaskOptions], Awaitable[Task]] | None = NoneaddTask: Callable[[Task], None] | None = Nonesubmit: Callable[..., str] | None = None@@ -277,11 +275,11 @@ class FeaturePack:def __init__(self, services: PackServices):self._services = services- def taskCardClass(self, task: Task):- return self.taskCards.get(type(task))+ def taskCardClass(self, task: Task) -> type | None:+ return None- def draftCardClass(self, task: Task):- return self.draftCards.get(type(task))+ def draftCardClass(self, task: Task) -> type | None:+ return Nonedef optionCards(self, task: Task, parent=None) -> list[QWidget]:return []diff --git a/features/bili_pack/account.py b/features/bili_pack/account.pyindex 7e47d28f..321f62f6 100644--- a/features/bili_pack/account.py+++ b/features/bili_pack/account.py@@ -7,9 +7,8 @@ from functools import reducefrom hashlib import md5from urllib.parse import parse_qsl, urlparse-from PySide6.QtCore import QObject, Signal-from app.client import buildClient+from app.signal import Signalfrom .config import bilibiliConfigMIXIN_KEY_ENC_TAB = [@@ -49,12 +48,11 @@ def toCookie(raw: str) -> str:return "; ".join(f"{n}={parts[n]}" for n in ordered + extra)-class BilibiliAccount(QObject):+class BilibiliAccount:accountChanged = Signal()qrStateChanged = Signal(int, str)- def __init__(self, coroutineRunner, parent=None):- super().__init__(parent)+ def __init__(self, coroutineRunner):self._coroutineRunner = coroutineRunnerself._username = ""self._mid = ""diff --git a/features/bili_pack/cards.py b/features/bili_pack/cards.pyindex 147c6eea..ae8241b2 100644--- a/features/bili_pack/cards.py+++ b/features/bili_pack/cards.py@@ -20,10 +20,10 @@ from app.view.components.range_slider import RangeSliderfrom app.view.components.track_bar import TrackBar, TrackButtonfrom app.view.components.tree_view import AutoSizingTreeViewfrom app.view.dialogs.subtitle_select import SubtitleSelectDialog-from .stream import toStreamUrl-from .task import AUDIO_QUALITY_LABELS, BilibiliTask, setEpisodeTitle, setPagePart, setTimeRanges--CODEC_NAMES = {7: "H.264", 12: "H.265", 13: "AV1"}+from .task import (+ BilibiliTask, audioTiers, currentAudioTier, currentVideoTier,+ setEpisodeTitle, setPagePart, setTimeRanges, subtitleChoices, videoTiers,+)StoryboardData = namedtuple("StoryboardData", ["sheets", "timestamps", "columns", "rows"])@@ -448,46 +448,16 @@ class BilibiliDraftCard(MultiFileDraftCard):task: BilibiliTask = self._taskself._trackBar = TrackBar(self)- videoTiers = [("best", self.tr("最佳画质"))]- audioTiers = [("best", self.tr("最佳音质"))]- initialVideoKey = None- initialAudioKey = None-- page = next((p for p in task.files or [] if p._videoStreams or p._audioStreams), None)- if page:- qualityMap = dict(zip(task._acceptQualities, task._qualityLabels))-- videoTiers = []- for s in page._videoStreams:- key = f'{s["id"]}-{s["codecid"]}'- qualityName = qualityMap.get(s["id"], str(s["id"]))- codec = CODEC_NAMES.get(s["codecid"], "")- kbps = s["bandwidth"] / 1000- bitrate = f'{kbps / 1000:.1f}Mbps' if kbps >= 1000 else f'{int(kbps)}Kbps'- label = f'{qualityName} ({codec}, {bitrate})'- videoTiers.append((key, label))- if toStreamUrl(s) == page.videoUrl:- initialVideoKey = key-- if page._audioStreams:- seen = set()- audioTiers = []- for s in page._audioStreams:- if s["id"] not in seen:- seen.add(s["id"])- kbps = f'{s["bandwidth"] // 1000}Kbps'- name = AUDIO_QUALITY_LABELS.get(s["id"], str(s["id"]))- audioTiers.append((str(s["id"]), f'{name} ({kbps})'))- if toStreamUrl(s) == page.audioUrl:- initialAudioKey = str(s["id"])-- self._trackBar.videoButton.setOptions(videoTiers, selected=initialVideoKey)- self._trackBar.audioButton.setOptions(audioTiers, selected=initialAudioKey)+ video = videoTiers(task) or [("best", self.tr("最佳画质"))]+ audio = audioTiers(task) or [("best", self.tr("最佳音质"))]++ self._trackBar.videoButton.setOptions(video, selected=currentVideoTier(task) or None)+ self._trackBar.audioButton.setOptions(audio, selected=currentAudioTier(task) or None)if not task.hasAudio and len(task.files or []) <= 1:self._trackBar.audioButton.setTrackEnabled(False)self._trackBar.audioButton.setChecked(False)- self._subtitleChoices = self._buildSubtitleChoices()+ self._subtitleChoices = subtitleChoices(task)self._trackBar.subtitleButton.setTrackEnabled(bool(self._subtitleChoices))self._trackBar.coverButton.setTrackEnabled(bool(self._task.coverUrl))@@ -728,20 +698,6 @@ class BilibiliDraftCard(MultiFileDraftCard):self.nameLabel.setText(self._task.name)self._refreshFileIcon()- def _buildSubtitleChoices(self) -> list[tuple[str, str]]:- seen: set[str] = set()- choices: list[tuple[str, str]] = []- for page in self._task.files or []:- for sub in page.subtitles:- lan = sub.get("lan", "")- if lan and lan not in seen:- seen.add(lan)- label = sub.get("lan_doc", lan)- if sub.get("isAi"):- label += "(自动生成)"- choices.append((lan, label))- return choices-def _refreshButtonVisibility(self) -> None:hasMedia = self._task.isVideoEnabled or self._task.isAudioEnabledif self._selectFilesButton is not None:diff --git a/features/bili_pack/config.py b/features/bili_pack/config.pyindex cb5c39ce..29512161 100644--- a/features/bili_pack/config.py+++ b/features/bili_pack/config.py@@ -1,248 +1,22 @@from __future__ import annotations-from io import BytesIO--from PySide6.QtCore import QCoreApplication, Qt, QUrl-from PySide6.QtGui import QDesktopServices, QPixmap--from qfluentwidgets import (- BoolValidator,- BodyLabel,- CaptionLabel,- FluentIcon,- MessageBoxBase,- OptionsConfigItem,- OptionsValidator,- PixmapLabel,- PlainTextEdit,- PrimaryPushButton,- PushButton,- SettingCard,- SubtitleLabel,-)--from app.config.cfg import ConfigItem+from app.config.cfg import BoolValidator, ConfigItem, OptionsConfigItem, OptionsValidatorfrom app.models.pack import PackConfig--def _toQrPixmap(content: str, size: int = 240) -> QPixmap:- import qrcode- from qrcode.image.pure import PyPNGImage-- qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, border=2, box_size=10)- qr.add_data(content)- qr.make(fit=True)- buf = BytesIO()- qr.make_image(image_factory=PyPNGImage).save(buf)- pixmap = QPixmap()- pixmap.loadFromData(buf.getvalue(), "PNG")- return pixmap.scaled(size, size)---class ScanLoginDialog(MessageBoxBase):- def __init__(self, account, parent=None):- super().__init__(parent)- self._account = account- self._loginUrl = ""--- self.widget.setFixedSize(430, 560)- self.yesButton.hide()- self.cancelButton.setText(self.tr("关闭"))-- self.titleLabel = SubtitleLabel(self.tr("扫码登录"), self.widget)- self.descriptionLabel = CaptionLabel(- self.tr("使用哔哩哔哩手机客户端扫描下方二维码,并在手机端确认登录"),- self.widget,- )- self.qrLabel = PixmapLabel(self.widget)- self.qrLabel.setFixedSize(240, 240)- self.qrLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)- self.qrLabel.setScaledContents(True)-- self.statusLabel = BodyLabel(self.tr("正在获取二维码..."), self.widget)- self.tipLabel = CaptionLabel(- self.tr('二维码有效期约 180 秒,失效后可点击"刷新二维码"重新生成'),- self.widget,- )-- self.refreshButton = PrimaryPushButton(FluentIcon.SYNC, self.tr("刷新二维码"), self.widget)- self.openBrowserButton = PushButton(FluentIcon.LINK, self.tr("打开登录链接"), self.widget)- self.openBrowserButton.setEnabled(False)-- self._initWidget()- self._initLayout()- self._bind()- self.reloadQrCode()-- def _initWidget(self):- self.statusLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)- self.statusLabel.setWordWrap(True)- self.tipLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)- self.tipLabel.setWordWrap(True)-- def _initLayout(self):- from PySide6.QtWidgets import QHBoxLayout- buttonLayout = QHBoxLayout()- buttonLayout.setSpacing(12)- buttonLayout.addWidget(self.refreshButton)- buttonLayout.addWidget(self.openBrowserButton)-- self.viewLayout.addWidget(self.titleLabel)- self.viewLayout.addWidget(self.descriptionLabel)- self.viewLayout.addSpacing(12)- self.viewLayout.addWidget(self.qrLabel, 0, Qt.AlignmentFlag.AlignCenter)- self.viewLayout.addSpacing(8)- self.viewLayout.addWidget(self.statusLabel)- self.viewLayout.addWidget(self.tipLabel)- self.viewLayout.addSpacing(6)- self.viewLayout.addLayout(buttonLayout)-- def _bind(self):- self.refreshButton.clicked.connect(self.reloadQrCode)- self.openBrowserButton.clicked.connect(self._onOpenBrowser)- self._account.qrStateChanged.connect(self._onQrState)-- def reloadQrCode(self):- self.qrLabel.setPixmap(QPixmap())- self.qrLabel.setFixedSize(240, 240)- self.statusLabel.setText(self.tr("正在获取二维码..."))- self.openBrowserButton.setEnabled(False)- self._loginUrl = ""- self._account.startQrLogin()-- def _onQrState(self, statusCode: int, text: str):- from .account import QR_EXPIRED, QR_LOGIN_SUCCESS, QR_UNSCANNED, QR_SCANNED- if statusCode == QR_LOGIN_SUCCESS:- self.statusLabel.setText(self.tr("登录成功,正在导入 Cookie..."))- self.accept()- elif statusCode == 0:- self._loginUrl = text- self.qrLabel.setPixmap(_toQrPixmap(text))- self.qrLabel.setFixedSize(240, 240)- self.statusLabel.setText(self.tr("请使用哔哩哔哩客户端扫码"))- self.openBrowserButton.setEnabled(True)- elif statusCode == QR_UNSCANNED:- self.statusLabel.setText(self.tr("等待扫码"))- elif statusCode == QR_SCANNED:- self.statusLabel.setText(self.tr("二维码已扫码,请在手机端确认登录"))- elif statusCode == QR_EXPIRED:- self.statusLabel.setText(self.tr('二维码已失效,请点击"刷新二维码"重新生成'))- else:- self.statusLabel.setText(- QCoreApplication.translate("BilibiliErrors", text) if text else str(statusCode)- )-- def _onOpenBrowser(self):- if self._loginUrl:- QDesktopServices.openUrl(QUrl(self._loginUrl))-- def done(self, code):- self._account.cancelQrLogin()- super().done(code)---class EditCookieDialog(MessageBoxBase):- def __init__(self, parent=None, initialCookie: str = ""):- super().__init__(parent)-- self.widget.setFixedSize(420, 500)- self.yesButton.setText(self.tr("保存"))- self.cancelButton.setText(self.tr("取消"))-- self.titleLabel = SubtitleLabel(self.tr("手动导入 Cookie"), self.widget)- self.descriptionLabel = CaptionLabel(- self.tr("请粘贴浏览器导出的完整 Cookie,留空后保存可清空当前 Cookie"), self.widget,- )- self.cookieTextEdit = PlainTextEdit(self.widget)- self.cookieTextEdit.setPlaceholderText(self.tr("请在此输入用户 Cookie"))- self.cookieTextEdit.setPlainText(initialCookie or "")-- self.viewLayout.addWidget(self.titleLabel)- self.viewLayout.addWidget(self.descriptionLabel)- self.viewLayout.addWidget(self.cookieTextEdit)---class BilibiliLoginSettingCard(SettingCard):- def __init__(self, account, parent=None):- self._account = account- super().__init__(- FluentIcon.VIEW, self.tr("账号登录"),- self.tr("状态:未登录"), parent,- )- self.scanButton = PrimaryPushButton(self.tr("扫码登录"), self)- self.editButton = PushButton(self.tr("导入 Cookie"), self)- self.logoutButton = PushButton(self.tr("退出登录"), self)-- self._initLayout()- self._bind()- self.refreshLoginInfo()-- def _initLayout(self):- self.hBoxLayout.addWidget(self.scanButton, 0)- self.hBoxLayout.addSpacing(8)- self.hBoxLayout.addWidget(self.editButton, 0)- self.hBoxLayout.addSpacing(8)- self.hBoxLayout.addWidget(self.logoutButton, 0)- self.hBoxLayout.addSpacing(16)-- def _bind(self):- self.scanButton.clicked.connect(self._onScanLogin)- self.editButton.clicked.connect(self._onEditCookie)- self.logoutButton.clicked.connect(self._onLogout)- self._account.accountChanged.connect(self.refreshLoginInfo)-- def refreshLoginInfo(self):- if self._account.isLoggedIn:- uname = self._account.username or "-"- mid = self._account.mid or "-"- vip = self._account.vip or "未开通"- self.setContent(- self.tr("状态:已登录 用户名:{0} UID:{1} 会员状态:{2}").format(uname, mid, vip)- )- else:- self.setContent(self.tr("状态:未登录"))- self.scanButton.setEnabled(True)- self.editButton.setEnabled(True)- self.logoutButton.setEnabled(self._account.isLoggedIn)-- def _onScanLogin(self):- dialog = ScanLoginDialog(self._account, self.window())- dialog.exec()- dialog.deleteLater()-- def _onEditCookie(self):- from .account import toCookie- dialog = EditCookieDialog(self.window(), self._account.cookie)- if not dialog.exec():- dialog.deleteLater()- return-- newCookie = toCookie(dialog.cookieTextEdit.toPlainText())- dialog.deleteLater()- if not newCookie:- self._account.setCookie("")- return-- self._account.setCookie(newCookie)-- def _onLogout(self):- self.scanButton.setEnabled(False)- self.editButton.setEnabled(False)- self.logoutButton.setEnabled(False)- self.setContent(self.tr("正在退出登录..."))- self._account.logout()+QUALITY_VALUES = [16, 32, 64, 80, 112, 116, 120, 125, 126, 127, 128]+QUALITY_LABELS = [+ "240P", "360P", "480P", "720P", "720P60", "1080P",+ "1080P+", "1080P60", "4K", "HDR", "杜比视界",+]class BilibiliConfig(PackConfig):userCookie = ConfigItem("Bilibili", "UserCookie", "")defaultQuality = OptionsConfigItem(- "Bilibili", "DefaultQuality", 80,- OptionsValidator([16, 32, 64, 80, 112, 116, 120, 125, 126, 127, 128]),+ "Bilibili", "DefaultQuality", 80, OptionsValidator(QUALITY_VALUES),)alternativeQuality = OptionsConfigItem(- "Bilibili", "AlternativeQuality", "max",- OptionsValidator(["max", "min"]),+ "Bilibili", "AlternativeQuality", "max", OptionsValidator(["max", "min"]),)shouldIncludeHdr = ConfigItem("Bilibili", "ParseHDR", False, BoolValidator())shouldIncludeDolby = ConfigItem("Bilibili", "ParseDolby", False, BoolValidator())@@ -250,28 +24,26 @@ class BilibiliConfig(PackConfig):def settingGroups(self, parent):from qfluentwidgets import ComboBoxSettingCard, FluentIcon, SwitchSettingCardfrom app.view.components.setting_card_group import CollapsibleSettingCardGroup+ from .setting_cards import BilibiliLoginSettingCard- biliGroup = CollapsibleSettingCardGroup(self.tr("Bilibili 下载"), "bilibili", parent)- loginCard = BilibiliLoginSettingCard(self._account, biliGroup)- biliGroup.addSettingCards([- loginCard,+ group = CollapsibleSettingCardGroup(self.tr("Bilibili 下载"), "bilibili", parent)+ group.addSettingCards([+ BilibiliLoginSettingCard(self._account, group),ComboBoxSettingCard(self.defaultQuality, FluentIcon.VIDEO, self.tr("默认画质"),self.tr("选择偏好的视频画质"),- texts=["240P", "360P", "480P", "720P", "720P60", "1080P",- "1080P+", "1080P60", "4K", "HDR", "杜比视界"],- parent=biliGroup),+ texts=QUALITY_LABELS, parent=group),ComboBoxSettingCard(self.alternativeQuality, FluentIcon.SPEED_HIGH, self.tr("画质不可用时"),self.tr("当选择的画质不可用时的替代策略"),texts=[self.tr("选择最高画质"), self.tr("选择最低画质")],- parent=biliGroup),+ parent=group),SwitchSettingCard(FluentIcon.PALETTE, self.tr("HDR"),self.tr("请求 HDR 视频流(需要大会员)"),- self.shouldIncludeHdr, biliGroup),+ self.shouldIncludeHdr, group),SwitchSettingCard(FluentIcon.HEADPHONE, self.tr("杜比全景声/视界"),self.tr("请求杜比全景声和杜比视界(需要大会员)"),- self.shouldIncludeDolby, biliGroup),+ self.shouldIncludeDolby, group),])- return [biliGroup]+ return [group]bilibiliConfig = BilibiliConfig()diff --git a/features/bili_pack/manifest.toml b/features/bili_pack/manifest.tomlindex 0d2403a9..f4e78a76 100644--- a/features/bili_pack/manifest.toml+++ b/features/bili_pack/manifest.toml@@ -3,4 +3,4 @@ entry = "pack.py"class = "BilibiliPack"dependencies = ["http_pack", "ffmpeg_pack"]version = "1.1.3"-gdMinVersion = "4.2.0"+gdMinVersion = "4.3.8"diff --git a/features/bili_pack/pack.py b/features/bili_pack/pack.pyindex e86baa2c..400a742c 100644--- a/features/bili_pack/pack.py+++ b/features/bili_pack/pack.py@@ -4,10 +4,9 @@ from urllib.parse import urlparsefrom app.client import buildClientfrom app.models.pack import FeaturePack, TaskParser-from app.models.task import TaskOptions+from app.models.task import Task, TaskOptionsfrom app.platform.filesystem import toSafeFilenamefrom .account import BilibiliAccount-from .cards import BilibiliDraftCard, BilibiliTaskCardfrom .config import bilibiliConfigfrom .parse import buildPages, parseBiliUrlfrom .stream import buildSize, fetchPlayurl, toStreamUrl@@ -157,8 +156,14 @@ class BilibiliPack(FeaturePack):packId = "bili"config = bilibiliConfigparsers = [BilibiliParser]- taskCards = {BilibiliTask: BilibiliTaskCard}- draftCards = {BilibiliTask: BilibiliDraftCard}++ def taskCardClass(self, task: Task) -> type | None:+ from .cards import BilibiliTaskCard+ return BilibiliTaskCard++ def draftCardClass(self, task: Task) -> type | None:+ from .cards import BilibiliDraftCard+ return BilibiliDraftCarddef __init__(self, services):super().__init__(services)diff --git a/features/bili_pack/setting_cards.py b/features/bili_pack/setting_cards.pynew file mode 100644index 00000000..b16d8c10--- /dev/null+++ b/features/bili_pack/setting_cards.py@@ -0,0 +1,227 @@+from __future__ import annotations++from io import BytesIO++from PySide6.QtCore import QCoreApplication, Qt, QUrl+from PySide6.QtGui import QDesktopServices, QPixmap+from PySide6.QtWidgets import QHBoxLayout++from qfluentwidgets import (+ BodyLabel,+ CaptionLabel,+ FluentIcon,+ MessageBoxBase,+ PixmapLabel,+ PlainTextEdit,+ PrimaryPushButton,+ PushButton,+ SettingCard,+ SubtitleLabel,+)+++def toQrPixmap(content: str, size: int = 240) -> QPixmap:+ import qrcode+ from qrcode.image.pure import PyPNGImage++ qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, border=2, box_size=10)+ qr.add_data(content)+ qr.make(fit=True)+ buf = BytesIO()+ qr.make_image(image_factory=PyPNGImage).save(buf)+ pixmap = QPixmap()+ pixmap.loadFromData(buf.getvalue(), "PNG")+ return pixmap.scaled(size, size)+++class ScanLoginDialog(MessageBoxBase):+ def __init__(self, account, parent=None):+ super().__init__(parent)+ self._account = account+ self._loginUrl = ""++ self.widget.setFixedSize(430, 560)+ self.yesButton.hide()+ self.cancelButton.setText(self.tr("关闭"))++ self.titleLabel = SubtitleLabel(self.tr("扫码登录"), self.widget)+ self.descriptionLabel = CaptionLabel(+ self.tr("使用哔哩哔哩手机客户端扫描下方二维码,并在手机端确认登录"),+ self.widget,+ )+ self.qrLabel = PixmapLabel(self.widget)+ self.qrLabel.setFixedSize(240, 240)+ self.qrLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)+ self.qrLabel.setScaledContents(True)++ self.statusLabel = BodyLabel(self.tr("正在获取二维码..."), self.widget)+ self.tipLabel = CaptionLabel(+ self.tr('二维码有效期约 180 秒,失效后可点击"刷新二维码"重新生成'),+ self.widget,+ )++ self.refreshButton = PrimaryPushButton(FluentIcon.SYNC, self.tr("刷新二维码"), self.widget)+ self.openBrowserButton = PushButton(FluentIcon.LINK, self.tr("打开登录链接"), self.widget)+ self.openBrowserButton.setEnabled(False)++ self._initWidget()+ self._initLayout()+ self._bind()+ self.reloadQrCode()++ def _initWidget(self):+ self.statusLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)+ self.statusLabel.setWordWrap(True)+ self.tipLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)+ self.tipLabel.setWordWrap(True)++ def _initLayout(self):+ buttonLayout = QHBoxLayout()+ buttonLayout.setSpacing(12)+ buttonLayout.addWidget(self.refreshButton)+ buttonLayout.addWidget(self.openBrowserButton)++ self.viewLayout.addWidget(self.titleLabel)+ self.viewLayout.addWidget(self.descriptionLabel)+ self.viewLayout.addSpacing(12)+ self.viewLayout.addWidget(self.qrLabel, 0, Qt.AlignmentFlag.AlignCenter)+ self.viewLayout.addSpacing(8)+ self.viewLayout.addWidget(self.statusLabel)+ self.viewLayout.addWidget(self.tipLabel)+ self.viewLayout.addSpacing(6)+ self.viewLayout.addLayout(buttonLayout)++ def _bind(self):+ self.refreshButton.clicked.connect(self.reloadQrCode)+ self.openBrowserButton.clicked.connect(self._onOpenBrowser)+ self._account.qrStateChanged.connect(self._onQrState)++ def reloadQrCode(self):+ self.qrLabel.setPixmap(QPixmap())+ self.qrLabel.setFixedSize(240, 240)+ self.statusLabel.setText(self.tr("正在获取二维码..."))+ self.openBrowserButton.setEnabled(False)+ self._loginUrl = ""+ self._account.startQrLogin()++ def _onQrState(self, statusCode: int, text: str):+ from .account import QR_EXPIRED, QR_LOGIN_SUCCESS, QR_UNSCANNED, QR_SCANNED+ if statusCode == QR_LOGIN_SUCCESS:+ self.statusLabel.setText(self.tr("登录成功,正在导入 Cookie..."))+ self.accept()+ elif statusCode == 0:+ self._loginUrl = text+ self.qrLabel.setPixmap(toQrPixmap(text))+ self.qrLabel.setFixedSize(240, 240)+ self.statusLabel.setText(self.tr("请使用哔哩哔哩客户端扫码"))+ self.openBrowserButton.setEnabled(True)+ elif statusCode == QR_UNSCANNED:+ self.statusLabel.setText(self.tr("等待扫码"))+ elif statusCode == QR_SCANNED:+ self.statusLabel.setText(self.tr("二维码已扫码,请在手机端确认登录"))+ elif statusCode == QR_EXPIRED:+ self.statusLabel.setText(self.tr('二维码已失效,请点击"刷新二维码"重新生成'))+ else:+ self.statusLabel.setText(+ QCoreApplication.translate("BilibiliErrors", text) if text else str(statusCode)+ )++ def _onOpenBrowser(self):+ if self._loginUrl:+ QDesktopServices.openUrl(QUrl(self._loginUrl))++ def done(self, code):+ self._account.cancelQrLogin()+ super().done(code)+++class EditCookieDialog(MessageBoxBase):+ def __init__(self, parent=None, initialCookie: str = ""):+ super().__init__(parent)++ self.widget.setFixedSize(420, 500)+ self.yesButton.setText(self.tr("保存"))+ self.cancelButton.setText(self.tr("取消"))++ self.titleLabel = SubtitleLabel(self.tr("手动导入 Cookie"), self.widget)+ self.descriptionLabel = CaptionLabel(+ self.tr("请粘贴浏览器导出的完整 Cookie,留空后保存可清空当前 Cookie"), self.widget,+ )+ self.cookieTextEdit = PlainTextEdit(self.widget)+ self.cookieTextEdit.setPlaceholderText(self.tr("请在此输入用户 Cookie"))+ self.cookieTextEdit.setPlainText(initialCookie or "")++ self.viewLayout.addWidget(self.titleLabel)+ self.viewLayout.addWidget(self.descriptionLabel)+ self.viewLayout.addWidget(self.cookieTextEdit)+++class BilibiliLoginSettingCard(SettingCard):+ def __init__(self, account, parent=None):+ self._account = account+ super().__init__(+ FluentIcon.VIEW, self.tr("账号登录"),+ self.tr("状态:未登录"), parent,+ )+ self.scanButton = PrimaryPushButton(self.tr("扫码登录"), self)+ self.editButton = PushButton(self.tr("导入 Cookie"), self)+ self.logoutButton = PushButton(self.tr("退出登录"), self)++ self._initLayout()+ self._bind()+ self.refreshLoginInfo()++ def _initLayout(self):+ self.hBoxLayout.addWidget(self.scanButton, 0)+ self.hBoxLayout.addSpacing(8)+ self.hBoxLayout.addWidget(self.editButton, 0)+ self.hBoxLayout.addSpacing(8)+ self.hBoxLayout.addWidget(self.logoutButton, 0)+ self.hBoxLayout.addSpacing(16)++ def _bind(self):+ self.scanButton.clicked.connect(self._onScanLogin)+ self.editButton.clicked.connect(self._onEditCookie)+ self.logoutButton.clicked.connect(self._onLogout)+ self._account.accountChanged.connect(self.refreshLoginInfo)++ def refreshLoginInfo(self):+ if self._account.isLoggedIn:+ uname = self._account.username or "-"+ mid = self._account.mid or "-"+ vip = self._account.vip or "未开通"+ self.setContent(+ self.tr("状态:已登录 用户名:{0} UID:{1} 会员状态:{2}").format(uname, mid, vip)+ )+ else:+ self.setContent(self.tr("状态:未登录"))+ self.scanButton.setEnabled(True)+ self.editButton.setEnabled(True)+ self.logoutButton.setEnabled(self._account.isLoggedIn)++ def _onScanLogin(self):+ dialog = ScanLoginDialog(self._account, self.window())+ dialog.exec()+ dialog.deleteLater()++ def _onEditCookie(self):+ from .account import toCookie+ dialog = EditCookieDialog(self.window(), self._account.cookie)+ if not dialog.exec():+ dialog.deleteLater()+ return++ newCookie = toCookie(dialog.cookieTextEdit.toPlainText())+ dialog.deleteLater()+ if not newCookie:+ self._account.setCookie("")+ return++ self._account.setCookie(newCookie)++ def _onLogout(self):+ self.scanButton.setEnabled(False)+ self.editButton.setEnabled(False)+ self.logoutButton.setEnabled(False)+ self.setContent(self.tr("正在退出登录..."))+ self._account.logout()diff --git a/features/bili_pack/task.py b/features/bili_pack/task.pyindex 6352e75e..3b181044 100644--- a/features/bili_pack/task.py+++ b/features/bili_pack/task.py@@ -11,11 +11,83 @@ from loguru import loggerfrom app.models.task import Task, TaskError, TaskFile, TaskStep, TaskStatus, SpecialFileSizefrom app.platform.filesystem import toSafeFilename+from app.i18n import Nfrom http_pack.task import HttpTaskStepfrom ffmpeg_pack.task import FFmpegStepfrom .stream import buildSize, fetchPlayurl, probeSize, toStreamUrlAUDIO_QUALITY_LABELS = {30216: "64K", 30232: "132K", 30280: "192K", 30250: "杜比全景声", 30251: "Hi-Res"}+CODEC_NAMES = {7: "H.264", 12: "H.265", 13: "AV1"}+++def streamPage(task: BilibiliTask) -> BiliPage | None:+ return next((p for p in task.files or [] if p._videoStreams or p._audioStreams), None)+++def videoTiers(task: BilibiliTask) -> list[tuple[str, str]]:+ page = streamPage(task)+ if page is None:+ return []+ qualityMap = dict(zip(task._acceptQualities, task._qualityLabels))+ tiers = []+ for s in page._videoStreams:+ kbps = s["bandwidth"] / 1000+ bitrate = f"{kbps / 1000:.1f}Mbps" if kbps >= 1000 else f"{int(kbps)}Kbps"+ codec = CODEC_NAMES.get(s["codecid"], "")+ name = qualityMap.get(s["id"], str(s["id"]))+ tiers.append((f'{s["id"]}-{s["codecid"]}', f"{name} ({codec}, {bitrate})"))+ return tiers+++def audioTiers(task: BilibiliTask) -> list[tuple[str, str]]:+ page = streamPage(task)+ if page is None:+ return []+ tiers = []+ seen = set()+ for s in page._audioStreams:+ if s["id"] in seen:+ continue+ seen.add(s["id"])+ name = AUDIO_QUALITY_LABELS.get(s["id"], str(s["id"]))+ tiers.append((str(s["id"]), f'{name} ({s["bandwidth"] // 1000}Kbps)'))+ return tiers+++def currentVideoTier(task: BilibiliTask) -> str:+ page = streamPage(task)+ if page is None:+ return ""+ return next(+ (f'{s["id"]}-{s["codecid"]}'+ for s in page._videoStreams if toStreamUrl(s) == page.videoUrl),+ "",+ )+++def currentAudioTier(task: BilibiliTask) -> str:+ page = streamPage(task)+ if page is None:+ return ""+ return next(+ (str(s["id"]) for s in page._audioStreams if toStreamUrl(s) == page.audioUrl), "",+ )+++def subtitleChoices(task: BilibiliTask) -> list[tuple[str, str]]:+ seen = set()+ choices = []+ for page in task.files or []:+ for sub in page.subtitles:+ lan = sub.get("lan", "")+ if not lan or lan in seen:+ continue+ seen.add(lan)+ label = sub.get("lan_doc", lan)+ if sub.get("isAi"):+ label += N("BilibiliDraftCard", "(自动生成)")+ choices.append((lan, label))+ return choicesdef buildTimeSuffix(startTime: int, endTime: int) -> str:@@ -35,7 +107,7 @@ def parseSegmentBaseEndByte(streams: list[dict], url: str) -> int:return 4095-def pageByIndex(task, fileIndex: int):+def pageByIndex(task: BilibiliTask, fileIndex: int) -> BiliPage | None:return next((f for f in task.files or [] if f.index == fileIndex), None)@@ -64,6 +136,17 @@ def setPagePart(page: BiliPage, name: str) -> None:page.relativePath = name or f"P{page.pageNumber}"+def setFileName(task: BilibiliTask, index: int, name: str) -> None:+ page = pageByIndex(task, index)+ if page is None:+ return+ if page.episodeTitle:+ setEpisodeTitle([p for p in task.files or [] if p.bvid == page.bvid], name)+ else:+ setPagePart(page, name)+ task.update()++@dataclass(kw_only=True)class BiliPage(TaskFile):cid: int = 0diff --git a/features/bittorrent_pack/config.py b/features/bittorrent_pack/config.pyindex e91ec448..5c2197a0 100644--- a/features/bittorrent_pack/config.py+++ b/features/bittorrent_pack/config.py@@ -1,14 +1,14 @@from __future__ import annotations-from app.config.cfg import ConfigItem-from app.models.pack import PackConfig-from qfluentwidgets import (+from app.config.cfg import (BoolValidator,+ ConfigItem,OptionsConfigItem,OptionsValidator,RangeConfigItem,RangeValidator,)+from app.models.pack import PackConfigfrom .web_tracker.schema import (DEFAULT_WEB_TRACKER_SOURCES,diff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.pyindex e9e5c1a6..8fc8b824 100644--- a/features/bittorrent_pack/pack.py+++ b/features/bittorrent_pack/pack.py@@ -14,7 +14,6 @@ from app.models.pack import FeaturePack, TaskParser, FileType, UriSchemefrom app.models.task import Task, TaskOptionsfrom app.platform.filesystem import localFilePath, toSafeFilename-from .cards import BTDraftCard, BTTaskCardfrom .config import bittorrentConfigfrom .session import btSessionfrom .task import BTFile, BTTask, BTTaskStep@@ -105,8 +104,14 @@ class BitTorrentPack(FeaturePack):config = bittorrentConfigproxySchemes = {"http", "https", "socks4", "socks5"}parsers = [TorrentParser]- taskCards = {BTTask: BTTaskCard}- draftCards = {BTTask: BTDraftCard}++ def taskCardClass(self, task: Task) -> type | None:+ from .cards import BTTaskCard+ return BTTaskCard++ def draftCardClass(self, task: Task) -> type | None:+ from .cards import BTDraftCard+ return BTDraftCarddef optionCards(self, task, parent=None):from app.view.components.option_cards import OutputFolderCarddiff --git a/features/bittorrent_pack/session.py b/features/bittorrent_pack/session.pyindex 2f75713c..a38986fb 100644--- a/features/bittorrent_pack/session.py+++ b/features/bittorrent_pack/session.py@@ -11,7 +11,6 @@ from urllib.parse import urlsplitimport libtorrent as ltfrom loguru import logger-from PySide6.QtCore import QObjectfrom app.config.cfg import cfg, proxyfrom app.models.task import TaskError@@ -113,10 +112,9 @@ class ActiveTorrent:return self.seedBase-class BTSession(QObject):+class BTSession:- def __init__(self, parent=None):- super().__init__(parent)+ def __init__(self):self._session: lt.session | None = Noneself._poller: asyncio.Task | None = Noneself._active: dict[str, ActiveTorrent] = {}diff --git a/features/bittorrent_pack/web_tracker/schema.py b/features/bittorrent_pack/web_tracker/schema.pyindex 686baa64..0139d711 100644--- a/features/bittorrent_pack/web_tracker/schema.py+++ b/features/bittorrent_pack/web_tracker/schema.py@@ -1,6 +1,6 @@import json-from qfluentwidgets import ConfigSerializer, ConfigValidator+from app.config.cfg import ConfigSerializer, ConfigValidatorDEFAULT_WEB_TRACKER_SOURCES = ["https://cf.trackerslist.com/best.txt",diff --git a/features/ed2k_pack/config.py b/features/ed2k_pack/config.pyindex c6b2d060..aff0c3b3 100644--- a/features/ed2k_pack/config.py+++ b/features/ed2k_pack/config.py@@ -4,13 +4,14 @@ import platformimport sysfrom pathlib import Path-from PySide6.QtCore import QT_TRANSLATE_NOOP as N-from qfluentwidgets import ConfigItem, BoolValidator, FluentIcon, RangeConfigItem, RangeValidator+from app.config.cfg import BoolValidator, ConfigItem, RangeConfigItem, RangeValidator+from app.i18n import Nfrom app.config.paths import APP_DATA_DIRfrom app.install import FetchStep, InstallTaskfrom app.models.pack import BinaryRuntime, PackConfig-from app.platform.filesystem import toPosixPath+from app.platform.android import IS_ANDROID, nativeLibraryDir+from app.platform.filesystem import findExecutable, toPosixPathfrom app.sources import Repo, fetchLatestRelease, probeDownloadUrlfrom .task import ED2kInstallStep@@ -86,14 +87,23 @@ ed2kConfig = ED2kConfig()class ED2kRuntime(BinaryRuntime):name = "goed2kd"- canInstall = True+ canInstall = not IS_ANDROIDtitle = N("BinaryRuntime", "eD2k / eMule")description = N("BinaryRuntime", "支持电驴协议,适合下载经典资源")- icon = FluentIcon.BOOK_SHELF+ icon = "BOOK_SHELF"def installFolder(self) -> Path:return Path(ed2kConfig.installFolder.value)+ def path(self) -> str:+ if IS_ANDROID:+ nativeDir = nativeLibraryDir()+ if not nativeDir:+ return ""+ binary = Path(nativeDir) / "libgoed2kd.so"+ return str(binary) if binary.exists() else ""+ return findExecutable(self.installFolder(), "goed2kd")+async def fetchLatestVersion(self) -> str:return (await fetchLatestRelease(ED2K_REPO)).versiondiff --git a/features/ed2k_pack/pack.py b/features/ed2k_pack/pack.pyindex c25869d4..14deb956 100644--- a/features/ed2k_pack/pack.py+++ b/features/ed2k_pack/pack.py@@ -4,7 +4,6 @@ from app.models.pack import FeaturePack, TaskParser, UriSchemefrom app.models.task import Task, TaskError, TaskOptionsfrom app.platform.filesystem import toSafeFilenamefrom .config import ed2kConfig, ed2kRuntime-from .cards import ED2kTaskCardfrom .session import parseEd2kLinkfrom .task import ED2kTask, ED2kTaskStep@@ -38,7 +37,10 @@ class ED2kPack(FeaturePack):packId = "ed2k"config = ed2kConfigparsers = [ED2kParser]- taskCards = {ED2kTask: ED2kTaskCard}++ def taskCardClass(self, task: Task) -> type | None:+ from .cards import ED2kTaskCard+ return ED2kTaskCarddef uriSchemes(self) -> list[UriScheme]:return [UriScheme("ed2k", "eD2k")]diff --git a/features/ffmpeg_pack/config.py b/features/ffmpeg_pack/config.pyindex 4adf9f1b..117038a5 100644--- a/features/ffmpeg_pack/config.py+++ b/features/ffmpeg_pack/config.py@@ -5,8 +5,7 @@ import platformimport sysfrom pathlib import Path-from PySide6.QtCore import QT_TRANSLATE_NOOP as N-from qfluentwidgets import FluentIcon+from app.i18n import Nfrom app.config.cfg import ConfigItemfrom app.config.paths import APP_DATA_DIR@@ -62,7 +61,7 @@ class FFmpegRuntime(BinaryRuntime):canInstall = not IS_ANDROIDtitle = N("BinaryRuntime", "视频合并")description = N("BinaryRuntime", "哔哩哔哩、YouTube 等网站视频下载必备,合并音视频轨道为完整文件")- icon = FluentIcon.VIDEO+ icon = "VIDEO"isRecommended = Truedef installFolder(self) -> Path:diff --git a/features/ffmpeg_pack/manifest.toml b/features/ffmpeg_pack/manifest.tomlindex 5c2efb9a..f7de0804 100644--- a/features/ffmpeg_pack/manifest.toml+++ b/features/ffmpeg_pack/manifest.toml@@ -3,4 +3,4 @@ entry = "pack.py"class = "FFmpegPack"dependencies = ["http_pack"]version = "1.0.1"-gdMinVersion = "4.2.0"+gdMinVersion = "4.3.8"diff --git a/features/ftp_pack/config.py b/features/ftp_pack/config.pyindex a1a4b542..e01f6abf 100644--- a/features/ftp_pack/config.py+++ b/features/ftp_pack/config.py@@ -1,5 +1,5 @@+from app.config.cfg import ConfigItem, BoolValidatorfrom app.models.pack import PackConfig-from qfluentwidgets import ConfigItem, BoolValidatorclass FtpConfig(PackConfig):diff --git a/features/ftp_pack/manifest.toml b/features/ftp_pack/manifest.tomlindex 8912b6e8..80627dc1 100644--- a/features/ftp_pack/manifest.toml+++ b/features/ftp_pack/manifest.toml@@ -2,4 +2,4 @@entry = "pack.py"class = "FtpPack"version = "1.0.1"-gdMinVersion = "4.2.0"+gdMinVersion = "4.3.8"diff --git a/features/ftp_pack/pack.py b/features/ftp_pack/pack.pyindex 69948107..1b40dfbf 100644--- a/features/ftp_pack/pack.py+++ b/features/ftp_pack/pack.py@@ -9,7 +9,6 @@ from app.models.pack import FeaturePack, TaskParser, UriSchemefrom .config import ftpConfigfrom app.models.task import Task, TaskOptions, SpecialFileSizefrom app.platform.filesystem import toPosixPath, toSafeFilename-from .cards import FtpDraftCard, FtpTaskCardfrom .task import (FTP_DEFAULT_PORT,FtpConnectionInfo,@@ -125,8 +124,14 @@ class FtpPack(FeaturePack):config = ftpConfigproxySchemes = {"socks4", "socks5"}parsers = [FtpParser]- taskCards = {FtpTask: FtpTaskCard}- draftCards = {FtpTask: FtpDraftCard}++ def taskCardClass(self, task: Task) -> type | None:+ from .cards import FtpTaskCard+ return FtpTaskCard++ def draftCardClass(self, task: Task) -> type | None:+ from .cards import FtpDraftCard+ return FtpDraftCarddef uriSchemes(self) -> list[UriScheme]:return [UriScheme("ftp", "FTP"), UriScheme("ftps", "FTPS")]diff --git a/features/github_pack/config.py b/features/github_pack/config.pyindex 1a7405a4..fde1dad1 100644--- a/features/github_pack/config.py+++ b/features/github_pack/config.py@@ -3,9 +3,8 @@ from __future__ import annotationsfrom urllib.parse import urlparsefrom app.client import buildClient-from app.config.cfg import ConfigItem+from app.config.cfg import BoolValidator, ConfigItem, ConfigValidatorfrom app.models.pack import PackConfig-from qfluentwidgets import BoolValidator, ComboBox, ConfigValidator, FluentIcon, LineEdit, SettingCard, ToolButton, ToolTipFilterGITHUB_PROXY_SITES = ("https://gh-proxy.com",@@ -83,118 +82,6 @@ class GitHubProxySiteValidator(ConfigValidator):return site if self.validate(site) else ""-class GitHubProxySiteCard(SettingCard):- def __init__(self, submit, parent=None):- self.submit = submit- super().__init__(- FluentIcon.GLOBE, self.tr("代理站"),- self.tr("选择 GitHub 反向代理站,延迟仅供参考"), parent,- )- self._latencies: dict[str, int | None] = {s: None for s in GITHUB_PROXY_SITES}- self._isRefreshing = False- self.comboBox = ComboBox(self)- self.customSiteEdit = LineEdit(self)- self.refreshButton = ToolButton(FluentIcon.SYNC, self)-- self._initWidget()- self._initLayout()- self._bind()-- def _initWidget(self):- self.comboBox.setMinimumWidth(260)- self.customSiteEdit.setPlaceholderText("https://example.com/")- self.customSiteEdit.setClearButtonEnabled(True)- self.customSiteEdit.setMinimumWidth(220)- self.refreshButton.setToolTip(self.tr("刷新延迟"))- self.refreshButton.installEventFilter(ToolTipFilter(self.refreshButton))-- for site in GITHUB_PROXY_SITES:- self.comboBox.addItem(urlparse(site).netloc or site.rstrip("/"))- self.comboBox.addItem(self.tr("自定义"))-- currentSite = githubConfig.selectedSite.value- if currentSite == CUSTOM_SITE_KEY:- self.comboBox.setCurrentIndex(len(GITHUB_PROXY_SITES))- elif currentSite in GITHUB_PROXY_SITES:- self.comboBox.setCurrentIndex(GITHUB_PROXY_SITES.index(currentSite))- else:- self.comboBox.setCurrentIndex(0)- self.customSiteEdit.setText(githubConfig.customSite.value)- self.customSiteEdit.setVisible(currentSite == CUSTOM_SITE_KEY)-- def _initLayout(self):- self.hBoxLayout.addWidget(self.comboBox)- self.hBoxLayout.addSpacing(8)- self.hBoxLayout.addWidget(self.customSiteEdit)- self.hBoxLayout.addSpacing(8)- self.hBoxLayout.addWidget(self.refreshButton)- self.hBoxLayout.addSpacing(16)-- def _bind(self):- self.comboBox.currentIndexChanged.connect(self._onCurrentIndexChanged)- self.customSiteEdit.editingFinished.connect(self._onCustomSiteEditingFinished)- self.refreshButton.clicked.connect(self.refreshLatencies)-- def _latencyTag(self, latency: int | None) -> str:- if latency is None:- return ""- if latency == PROBE_UNAVAILABLE:- return self.tr("不可用")- if latency == PROBE_TIMEOUT:- return self.tr("超时")- return f"{latency} ms"-- def _refreshLatencyLabels(self):- for i, site in enumerate(GITHUB_PROXY_SITES):- displayName = urlparse(site).netloc or site.rstrip("/")- tag = self._latencyTag(self._latencies.get(site))- label = f"{displayName} ({tag})" if tag else displayName- self.comboBox.setItemText(i, label)-- customSite = githubConfig.customSite.value- customLatency = self._latencies.get(customSite) if customSite else None- tag = self._latencyTag(customLatency)- customLabel = f"{self.tr('自定义')} ({tag})" if tag else self.tr("自定义")- self.comboBox.setItemText(len(GITHUB_PROXY_SITES), customLabel)-- def _onCurrentIndexChanged(self, index: int):- from app.config.cfg import cfg- if index < 0:- return- if index < len(GITHUB_PROXY_SITES):- cfg.set(githubConfig.selectedSite, GITHUB_PROXY_SITES[index])- else:- cfg.set(githubConfig.selectedSite, CUSTOM_SITE_KEY)- self.customSiteEdit.setVisible(index >= len(GITHUB_PROXY_SITES))-- def _onCustomSiteEditingFinished(self):- from app.config.cfg import cfg- cfg.set(githubConfig.customSite, self.customSiteEdit.text().strip())-- def refreshLatencies(self):- if self._isRefreshing:- return- self._isRefreshing = True- self._latencies = {s: None for s in GITHUB_PROXY_SITES}- self._refreshLatencyLabels()- self.refreshButton.setEnabled(False)- self.submit(- probeProxyLatencies(),- done=self._onLatenciesDone, failed=self._onLatenciesFailed,- owner=self,- )-- def _onLatenciesDone(self, latencies: dict[str, int]):- self._isRefreshing = False- self.refreshButton.setEnabled(True)- self._latencies.update(latencies)- self._refreshLatencyLabels()-- def _onLatenciesFailed(self, error):- self._isRefreshing = False- self.refreshButton.setEnabled(True)--class GitHubConfig(PackConfig):enabled = ConfigItem("GitHub", "Enabled", False, BoolValidator())selectedSite = ConfigItem("GitHub", "SelectedSite", GITHUB_PROXY_SITES[0], GitHubProxySiteValidator())@@ -203,6 +90,7 @@ class GitHubConfig(PackConfig):def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:from qfluentwidgets import FluentIcon, SwitchSettingCardfrom app.view.components.setting_card_group import CollapsibleSettingCardGroup+ from .setting_cards import GitHubProxySiteCardgithubGroup = CollapsibleSettingCardGroup(self.tr("GitHub 加速"), "github", parent)enableCard = SwitchSettingCard(diff --git a/features/github_pack/manifest.toml b/features/github_pack/manifest.tomlindex 6f6f25c5..c5b45c8c 100644--- a/features/github_pack/manifest.toml+++ b/features/github_pack/manifest.toml@@ -3,4 +3,4 @@ entry = "pack.py"class = "GitHubPack"dependencies = ["http_pack"]version = "1.0.0"-gdMinVersion = "4.2.0"+gdMinVersion = "4.3.8"diff --git a/features/github_pack/pack.py b/features/github_pack/pack.pyindex 69c9302d..bc7b0da0 100644--- a/features/github_pack/pack.py+++ b/features/github_pack/pack.py@@ -7,7 +7,6 @@ from loguru import loggerfrom app.client import buildClientfrom app.models.pack import FeaturePack, TaskParserfrom app.models.task import Task, TaskError, TaskOptions, ResourceTaskOptions-from http_pack.cards import HttpTaskCardfrom http_pack.pack import HttpParserfrom http_pack.task import HttpTask, HttpTaskStepfrom .config import githubConfig, selectedProxySite, GITHUB_PROXY_SITES@@ -148,7 +147,10 @@ class GitHubPack(FeaturePack):packId = "github"config = githubConfigparsers = [GitHubParser]- taskCards = {HttpTask: HttpTaskCard}++ def taskCardClass(self, task: Task) -> type | None:+ from http_pack.cards import HttpTaskCard+ return HttpTaskCarddef optionCards(self, task, parent=None):from http_pack.pack import HttpPackdiff --git a/features/github_pack/setting_cards.py b/features/github_pack/setting_cards.pynew file mode 100644index 00000000..beab5704--- /dev/null+++ b/features/github_pack/setting_cards.py@@ -0,0 +1,129 @@+"""GitHub 加速的设置卡片(View)。config.py 只留配置数据。"""+from __future__ import annotations++from urllib.parse import urlparse++from qfluentwidgets import ComboBox, FluentIcon, LineEdit, SettingCard, ToolButton, ToolTipFilter++from .config import (+ CUSTOM_SITE_KEY,+ GITHUB_PROXY_SITES,+ PROBE_TIMEOUT,+ PROBE_UNAVAILABLE,+ githubConfig,+ probeProxyLatencies,+)+++class GitHubProxySiteCard(SettingCard):+ def __init__(self, submit, parent=None):+ self.submit = submit+ super().__init__(+ FluentIcon.GLOBE, self.tr("代理站"),+ self.tr("选择 GitHub 反向代理站,延迟仅供参考"), parent,+ )+ self._latencies: dict[str, int | None] = {s: None for s in GITHUB_PROXY_SITES}+ self._isRefreshing = False+ self.comboBox = ComboBox(self)+ self.customSiteEdit = LineEdit(self)+ self.refreshButton = ToolButton(FluentIcon.SYNC, self)++ self._initWidget()+ self._initLayout()+ self._bind()++ def _initWidget(self):+ self.comboBox.setMinimumWidth(260)+ self.customSiteEdit.setPlaceholderText("https://example.com/")+ self.customSiteEdit.setClearButtonEnabled(True)+ self.customSiteEdit.setMinimumWidth(220)+ self.refreshButton.setToolTip(self.tr("刷新延迟"))+ self.refreshButton.installEventFilter(ToolTipFilter(self.refreshButton))++ for site in GITHUB_PROXY_SITES:+ self.comboBox.addItem(urlparse(site).netloc or site.rstrip("/"))+ self.comboBox.addItem(self.tr("自定义"))++ currentSite = githubConfig.selectedSite.value+ if currentSite == CUSTOM_SITE_KEY:+ self.comboBox.setCurrentIndex(len(GITHUB_PROXY_SITES))+ elif currentSite in GITHUB_PROXY_SITES:+ self.comboBox.setCurrentIndex(GITHUB_PROXY_SITES.index(currentSite))+ else:+ self.comboBox.setCurrentIndex(0)+ self.customSiteEdit.setText(githubConfig.customSite.value)+ self.customSiteEdit.setVisible(currentSite == CUSTOM_SITE_KEY)++ def _initLayout(self):+ self.hBoxLayout.addWidget(self.comboBox)+ self.hBoxLayout.addSpacing(8)+ self.hBoxLayout.addWidget(self.customSiteEdit)+ self.hBoxLayout.addSpacing(8)+ self.hBoxLayout.addWidget(self.refreshButton)+ self.hBoxLayout.addSpacing(16)++ def _bind(self):+ self.comboBox.currentIndexChanged.connect(self._onCurrentIndexChanged)+ self.customSiteEdit.editingFinished.connect(self._onCustomSiteEditingFinished)+ self.refreshButton.clicked.connect(self.refreshLatencies)++ def _latencyTag(self, latency: int | None) -> str:+ if latency is None:+ return ""+ if latency == PROBE_UNAVAILABLE:+ return self.tr("不可用")+ if latency == PROBE_TIMEOUT:+ return self.tr("超时")+ return f"{latency} ms"++ def _refreshLatencyLabels(self):+ for i, site in enumerate(GITHUB_PROXY_SITES):+ displayName = urlparse(site).netloc or site.rstrip("/")+ tag = self._latencyTag(self._latencies.get(site))+ label = f"{displayName} ({tag})" if tag else displayName+ self.comboBox.setItemText(i, label)++ customSite = githubConfig.customSite.value+ customLatency = self._latencies.get(customSite) if customSite else None+ tag = self._latencyTag(customLatency)+ customLabel = f"{self.tr('自定义')} ({tag})" if tag else self.tr("自定义")+ self.comboBox.setItemText(len(GITHUB_PROXY_SITES), customLabel)++ def _onCurrentIndexChanged(self, index: int):+ from app.config.cfg import cfg+ if index < 0:+ return+ if index < len(GITHUB_PROXY_SITES):+ cfg.set(githubConfig.selectedSite, GITHUB_PROXY_SITES[index])+ else:+ cfg.set(githubConfig.selectedSite, CUSTOM_SITE_KEY)+ self.customSiteEdit.setVisible(index >= len(GITHUB_PROXY_SITES))++ def _onCustomSiteEditingFinished(self):+ from app.config.cfg import cfg+ cfg.set(githubConfig.customSite, self.customSiteEdit.text().strip())++ def refreshLatencies(self):+ if self._isRefreshing:+ return+ self._isRefreshing = True+ self._latencies = {s: None for s in GITHUB_PROXY_SITES}+ self._refreshLatencyLabels()+ self.refreshButton.setEnabled(False)+ self.submit(+ probeProxyLatencies(),+ done=self._onLatenciesDone, failed=self._onLatenciesFailed,+ owner=self,+ )++ def _onLatenciesDone(self, latencies: dict[str, int]):+ self._isRefreshing = False+ self.refreshButton.setEnabled(True)+ self._latencies.update(latencies)+ self._refreshLatencyLabels()++ def _onLatenciesFailed(self, error):+ self._isRefreshing = False+ self.refreshButton.setEnabled(True)++diff --git a/features/http_pack/manifest.toml b/features/http_pack/manifest.tomlindex 48a28ef8..d82be254 100644--- a/features/http_pack/manifest.toml+++ b/features/http_pack/manifest.toml@@ -3,4 +3,4 @@ entry = "pack.py"class = "HttpPack"dependencies = []version = "1.0.1"-gdMinVersion = "4.2.0"+gdMinVersion = "4.3.8"diff --git a/features/http_pack/pack.py b/features/http_pack/pack.pyindex 817ea911..40af227c 100644--- a/features/http_pack/pack.py+++ b/features/http_pack/pack.py@@ -16,7 +16,6 @@ from app.models.task import (Task, TaskOptions, ResourceTaskOptions, SpecialFileSize,)from app.platform.filesystem import toSafeFilename-from .cards import HttpTaskCardfrom .task import HttpTask, HttpTaskStep@@ -211,7 +210,10 @@ class HttpParser(TaskParser):class HttpPack(FeaturePack):packId = "http"parsers = [HttpParser]- taskCards = {HttpTask: HttpTaskCard}++ def taskCardClass(self, task: Task) -> type | None:+ from .cards import HttpTaskCard+ return HttpTaskCarddef optionCards(self, task, parent=None):from app.view.components.option_cards import (diff --git a/features/huggingface_pack/config.py b/features/huggingface_pack/config.pyindex 0f1c7af4..9d929284 100644--- a/features/huggingface_pack/config.py+++ b/features/huggingface_pack/config.py@@ -3,12 +3,9 @@ from __future__ import annotationsfrom urllib.parse import urlparsefrom app.client import buildClient-from app.config.cfg import ConfigItem+from app.config.cfg import BoolValidator, ConfigItem, ConfigValidatorfrom app.models.pack import PackConfig-from qfluentwidgets import (- BoolValidator, ComboBox, ConfigValidator, FluentIcon, HyperlinkButton,- LineEdit, PasswordLineEdit, SettingCard, ToolButton, ToolTipFilter,-)+HF_PROXY_SITES = ("https://hf-mirror.com",@@ -82,144 +79,6 @@ class HuggingFaceProxySiteValidator(ConfigValidator):return site if self.validate(site) else ""-class HuggingFaceProxySiteCard(SettingCard):- def __init__(self, submit, parent=None):- self.submit = submit- super().__init__(- FluentIcon.GLOBE, self.tr("镜像站"),- self.tr("选择 HuggingFace 镜像站,延迟仅供参考"), parent,- )- self._latencies: dict[str, int | None] = {s: None for s in HF_PROXY_SITES}- self._isRefreshing = False- self.comboBox = ComboBox(self)- self.customSiteEdit = LineEdit(self)- self.refreshButton = ToolButton(FluentIcon.SYNC, self)-- self._initWidget()- self._initLayout()- self._bind()-- def _initWidget(self) -> None:- self.comboBox.setMinimumWidth(260)- self.customSiteEdit.setPlaceholderText("https://example.com/")- self.customSiteEdit.setClearButtonEnabled(True)- self.customSiteEdit.setMinimumWidth(220)- self.refreshButton.setToolTip(self.tr("刷新延迟"))- self.refreshButton.installEventFilter(ToolTipFilter(self.refreshButton))-- for site in HF_PROXY_SITES:- self.comboBox.addItem(urlparse(site).netloc or site.rstrip("/"))- self.comboBox.addItem(self.tr("自定义"))-- currentSite = huggingFaceConfig.selectedSite.value- if currentSite == CUSTOM_SITE_KEY:- self.comboBox.setCurrentIndex(len(HF_PROXY_SITES))- elif currentSite in HF_PROXY_SITES:- self.comboBox.setCurrentIndex(HF_PROXY_SITES.index(currentSite))- else:- self.comboBox.setCurrentIndex(0)- self.customSiteEdit.setText(huggingFaceConfig.customSite.value)- self.customSiteEdit.setVisible(currentSite == CUSTOM_SITE_KEY)-- def _initLayout(self) -> None:- self.hBoxLayout.addWidget(self.comboBox)- self.hBoxLayout.addSpacing(8)- self.hBoxLayout.addWidget(self.customSiteEdit)- self.hBoxLayout.addSpacing(8)- self.hBoxLayout.addWidget(self.refreshButton)- self.hBoxLayout.addSpacing(16)-- def _bind(self) -> None:- self.comboBox.currentIndexChanged.connect(self._onCurrentIndexChanged)- self.customSiteEdit.editingFinished.connect(self._onCustomSiteEditingFinished)- self.refreshButton.clicked.connect(self.refreshLatencies)-- def _refreshLatencyLabels(self) -> None:- for i, site in enumerate(HF_PROXY_SITES):- displayName = urlparse(site).netloc or site.rstrip("/")- latency = self._latencies.get(site)- if latency is None:- label = displayName- elif latency < 0:- label = f"{displayName} ({self.tr('超时')})"- else:- label = f"{displayName} ({latency} ms)"- self.comboBox.setItemText(i, label)-- customSite = huggingFaceConfig.customSite.value- customLatency = self._latencies.get(customSite) if customSite else None- if customLatency is None:- customLabel = self.tr("自定义")- elif customLatency < 0:- customLabel = f"{self.tr('自定义')} ({self.tr('超时')})"- else:- customLabel = f"{self.tr('自定义')} ({customLatency} ms)"- self.comboBox.setItemText(len(HF_PROXY_SITES), customLabel)-- def _onCurrentIndexChanged(self, index: int) -> None:- from app.config.cfg import cfg- if index < 0:- return- if index < len(HF_PROXY_SITES):- cfg.set(huggingFaceConfig.selectedSite, HF_PROXY_SITES[index])- else:- cfg.set(huggingFaceConfig.selectedSite, CUSTOM_SITE_KEY)- self.customSiteEdit.setVisible(index >= len(HF_PROXY_SITES))-- def _onCustomSiteEditingFinished(self) -> None:- from app.config.cfg import cfg- cfg.set(huggingFaceConfig.customSite, self.customSiteEdit.text().strip())-- def refreshLatencies(self) -> None:- if self._isRefreshing:- return- self._isRefreshing = True- self._latencies = {s: None for s in HF_PROXY_SITES}- self._refreshLatencyLabels()- self.refreshButton.setEnabled(False)- self.submit(- probeProxyLatencies(),- done=self._onLatenciesDone, failed=self._onLatenciesFailed,- owner=self,- )-- def _onLatenciesDone(self, latencies: dict[str, int]) -> None:- self._isRefreshing = False- self.refreshButton.setEnabled(True)- self._latencies.update(latencies)- self._refreshLatencyLabels()-- def _onLatenciesFailed(self, error) -> None:- self._isRefreshing = False- self.refreshButton.setEnabled(True)---class HuggingFaceTokenCard(SettingCard):- def __init__(self, parent=None):- super().__init__(- FluentIcon.FINGERPRINT, self.tr("Access Token"),- self.tr("用于下载需要授权的模型(如 Llama、Mistral)"), parent,- )- self.tokenEdit = PasswordLineEdit(self)- self.tokenEdit.setPlaceholderText("hf_xxxxxxxxxxxx")- self.tokenEdit.setMinimumWidth(240)- self.tokenEdit.setText(huggingFaceConfig.accessToken.value)- self.openTokenPageButton = HyperlinkButton(self)- self.openTokenPageButton.setText(self.tr("获取 Token"))- self.openTokenPageButton.setUrl(TOKEN_URL)-- self.hBoxLayout.addWidget(self.tokenEdit)- self.hBoxLayout.addSpacing(8)- self.hBoxLayout.addWidget(self.openTokenPageButton)- self.hBoxLayout.addSpacing(16)-- self.tokenEdit.editingFinished.connect(self._onTokenEdited)-- def _onTokenEdited(self) -> None:- from app.config.cfg import cfg- cfg.set(huggingFaceConfig.accessToken, self.tokenEdit.text().strip())--class HuggingFaceConfig(PackConfig):isEnabled = ConfigItem("HuggingFace", "Enabled", True, BoolValidator())selectedSite = ConfigItem("HuggingFace", "SelectedSite", HF_PROXY_SITES[0], HuggingFaceProxySiteValidator())@@ -229,6 +88,7 @@ class HuggingFaceConfig(PackConfig):def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:from qfluentwidgets import FluentIcon, SwitchSettingCardfrom app.view.components.setting_card_group import CollapsibleSettingCardGroup+ from .setting_cards import HuggingFaceProxySiteCard, HuggingFaceTokenCardgroup = CollapsibleSettingCardGroup(self.tr("HuggingFace"), "huggingface", parent)group.addSettingCards([diff --git a/features/huggingface_pack/manifest.toml b/features/huggingface_pack/manifest.tomlindex eae94f2d..0cc64967 100644--- a/features/huggingface_pack/manifest.toml+++ b/features/huggingface_pack/manifest.toml@@ -3,4 +3,4 @@ entry = "pack.py"class = "HuggingFacePack"dependencies = ["http_pack"]version = "1.0.1"-gdMinVersion = "4.2.0"+gdMinVersion = "4.3.8"diff --git a/features/huggingface_pack/pack.py b/features/huggingface_pack/pack.pyindex 06ad843b..7e6c3a85 100644--- a/features/huggingface_pack/pack.py+++ b/features/huggingface_pack/pack.py@@ -8,7 +8,6 @@ from app.client import buildClientfrom app.models.pack import FeaturePack, TaskParserfrom app.models.task import Task, TaskFile, TaskOptionsfrom app.platform.filesystem import toSafeFilename-from .cards import HuggingFaceDraftCard, HuggingFaceTaskCardfrom .config import accessToken, huggingFaceConfig, selectedProxySitefrom .task import HuggingFaceFile, HuggingFaceStep, HuggingFaceTask@@ -198,8 +197,14 @@ class HuggingFacePack(FeaturePack):packId = "huggingface"config = huggingFaceConfigparsers = [HuggingFaceParser]- taskCards = {HuggingFaceTask: HuggingFaceTaskCard}- draftCards = {HuggingFaceTask: HuggingFaceDraftCard}++ def taskCardClass(self, task: Task) -> type | None:+ from .cards import HuggingFaceTaskCard+ return HuggingFaceTaskCard++ def draftCardClass(self, task: Task) -> type | None:+ from .cards import HuggingFaceDraftCard+ return HuggingFaceDraftCarddef optionCards(self, task, parent=None):from app.view.components.option_cards import OutputFolderCarddiff --git a/features/huggingface_pack/setting_cards.py b/features/huggingface_pack/setting_cards.pynew file mode 100644index 00000000..b086ffa8--- /dev/null+++ b/features/huggingface_pack/setting_cards.py@@ -0,0 +1,157 @@+"""HuggingFace 加速的设置卡片(View)。config.py 只留配置数据。"""+from __future__ import annotations++from urllib.parse import urlparse++from qfluentwidgets import (+ ComboBox, FluentIcon, HyperlinkButton, LineEdit, PasswordLineEdit,+ SettingCard, ToolButton, ToolTipFilter,+)++from .config import (+ CUSTOM_SITE_KEY,+ HF_PROXY_SITES,+ TOKEN_URL,+ huggingFaceConfig,+ probeProxyLatencies,+)+++class HuggingFaceProxySiteCard(SettingCard):+ def __init__(self, submit, parent=None):+ self.submit = submit+ super().__init__(+ FluentIcon.GLOBE, self.tr("镜像站"),+ self.tr("选择 HuggingFace 镜像站,延迟仅供参考"), parent,+ )+ self._latencies: dict[str, int | None] = {s: None for s in HF_PROXY_SITES}+ self._isRefreshing = False+ self.comboBox = ComboBox(self)+ self.customSiteEdit = LineEdit(self)+ self.refreshButton = ToolButton(FluentIcon.SYNC, self)++ self._initWidget()+ self._initLayout()+ self._bind()++ def _initWidget(self) -> None:+ self.comboBox.setMinimumWidth(260)+ self.customSiteEdit.setPlaceholderText("https://example.com/")+ self.customSiteEdit.setClearButtonEnabled(True)+ self.customSiteEdit.setMinimumWidth(220)+ self.refreshButton.setToolTip(self.tr("刷新延迟"))+ self.refreshButton.installEventFilter(ToolTipFilter(self.refreshButton))++ for site in HF_PROXY_SITES:+ self.comboBox.addItem(urlparse(site).netloc or site.rstrip("/"))+ self.comboBox.addItem(self.tr("自定义"))++ currentSite = huggingFaceConfig.selectedSite.value+ if currentSite == CUSTOM_SITE_KEY:+ self.comboBox.setCurrentIndex(len(HF_PROXY_SITES))+ elif currentSite in HF_PROXY_SITES:+ self.comboBox.setCurrentIndex(HF_PROXY_SITES.index(currentSite))+ else:+ self.comboBox.setCurrentIndex(0)+ self.customSiteEdit.setText(huggingFaceConfig.customSite.value)+ self.customSiteEdit.setVisible(currentSite == CUSTOM_SITE_KEY)++ def _initLayout(self) -> None:+ self.hBoxLayout.addWidget(self.comboBox)+ self.hBoxLayout.addSpacing(8)+ self.hBoxLayout.addWidget(self.customSiteEdit)+ self.hBoxLayout.addSpacing(8)+ self.hBoxLayout.addWidget(self.refreshButton)+ self.hBoxLayout.addSpacing(16)++ def _bind(self) -> None:+ self.comboBox.currentIndexChanged.connect(self._onCurrentIndexChanged)+ self.customSiteEdit.editingFinished.connect(self._onCustomSiteEditingFinished)+ self.refreshButton.clicked.connect(self.refreshLatencies)++ def _refreshLatencyLabels(self) -> None:+ for i, site in enumerate(HF_PROXY_SITES):+ displayName = urlparse(site).netloc or site.rstrip("/")+ latency = self._latencies.get(site)+ if latency is None:+ label = displayName+ elif latency < 0:+ label = f"{displayName} ({self.tr('超时')})"+ else:+ label = f"{displayName} ({latency} ms)"+ self.comboBox.setItemText(i, label)++ customSite = huggingFaceConfig.customSite.value+ customLatency = self._latencies.get(customSite) if customSite else None+ if customLatency is None:+ customLabel = self.tr("自定义")+ elif customLatency < 0:+ customLabel = f"{self.tr('自定义')} ({self.tr('超时')})"+ else:+ customLabel = f"{self.tr('自定义')} ({customLatency} ms)"+ self.comboBox.setItemText(len(HF_PROXY_SITES), customLabel)++ def _onCurrentIndexChanged(self, index: int) -> None:+ from app.config.cfg import cfg+ if index < 0:+ return+ if index < len(HF_PROXY_SITES):+ cfg.set(huggingFaceConfig.selectedSite, HF_PROXY_SITES[index])+ else:+ cfg.set(huggingFaceConfig.selectedSite, CUSTOM_SITE_KEY)+ self.customSiteEdit.setVisible(index >= len(HF_PROXY_SITES))++ def _onCustomSiteEditingFinished(self) -> None:+ from app.config.cfg import cfg+ cfg.set(huggingFaceConfig.customSite, self.customSiteEdit.text().strip())++ def refreshLatencies(self) -> None:+ if self._isRefreshing:+ return+ self._isRefreshing = True+ self._latencies = {s: None for s in HF_PROXY_SITES}+ self._refreshLatencyLabels()+ self.refreshButton.setEnabled(False)+ self.submit(+ probeProxyLatencies(),+ done=self._onLatenciesDone, failed=self._onLatenciesFailed,+ owner=self,+ )++ def _onLatenciesDone(self, latencies: dict[str, int]) -> None:+ self._isRefreshing = False+ self.refreshButton.setEnabled(True)+ self._latencies.update(latencies)+ self._refreshLatencyLabels()++ def _onLatenciesFailed(self, error) -> None:+ self._isRefreshing = False+ self.refreshButton.setEnabled(True)+++class HuggingFaceTokenCard(SettingCard):+ def __init__(self, parent=None):+ super().__init__(+ FluentIcon.FINGERPRINT, self.tr("Access Token"),+ self.tr("用于下载需要授权的模型(如 Llama、Mistral)"), parent,+ )+ self.tokenEdit = PasswordLineEdit(self)+ self.tokenEdit.setPlaceholderText("hf_xxxxxxxxxxxx")+ self.tokenEdit.setMinimumWidth(240)+ self.tokenEdit.setText(huggingFaceConfig.accessToken.value)+ self.openTokenPageButton = HyperlinkButton(self)+ self.openTokenPageButton.setText(self.tr("获取 Token"))+ self.openTokenPageButton.setUrl(TOKEN_URL)++ self.hBoxLayout.addWidget(self.tokenEdit)+ self.hBoxLayout.addSpacing(8)+ self.hBoxLayout.addWidget(self.openTokenPageButton)+ self.hBoxLayout.addSpacing(16)++ self.tokenEdit.editingFinished.connect(self._onTokenEdited)++ def _onTokenEdited(self) -> None:+ from app.config.cfg import cfg+ cfg.set(huggingFaceConfig.accessToken, self.tokenEdit.text().strip())++diff --git a/features/m3u8_pack/config.py b/features/m3u8_pack/config.pyindex 2fa2da7e..d356a0fc 100644--- a/features/m3u8_pack/config.py+++ b/features/m3u8_pack/config.py@@ -4,17 +4,16 @@ import platformimport sysfrom pathlib import Path-from PySide6.QtCore import QT_TRANSLATE_NOOP as N-from qfluentwidgets import (+from app.config.cfg import (BoolValidator,ConfigItem,- FluentIcon,FolderValidator,OptionsConfigItem,OptionsValidator,RangeConfigItem,RangeValidator,)+from app.i18n import Nfrom app.config.paths import APP_DATA_DIRfrom app.install import createInstallTask@@ -147,7 +146,7 @@ class M3U8Runtime(BinaryRuntime):canInstall = not IS_ANDROIDtitle = N("BinaryRuntime", "M3U8 / 直播下载")description = N("BinaryRuntime", "支持 HLS、DASH 等流媒体协议,可录制直播流")- icon = FluentIcon.MEDIA+ icon = "MEDIA"isRecommended = Truedef installFolder(self) -> Path:diff --git a/features/m3u8_pack/manifest.toml b/features/m3u8_pack/manifest.tomlindex 16e79c67..ca1d8c4f 100644--- a/features/m3u8_pack/manifest.toml+++ b/features/m3u8_pack/manifest.toml@@ -3,4 +3,4 @@ entry = "pack.py"class = "M3U8Pack"dependencies = ["http_pack", "ffmpeg_pack"]version = "1.0.2"-gdMinVersion = "4.2.0"+gdMinVersion = "4.3.8"diff --git a/features/m3u8_pack/pack.py b/features/m3u8_pack/pack.pyindex a030d5db..ae313ee8 100644--- a/features/m3u8_pack/pack.py+++ b/features/m3u8_pack/pack.py@@ -17,7 +17,6 @@ from app.i18n import Nfrom app.models.pack import FeaturePack, TaskParser, FileTypefrom app.models.task import Task, TaskOptionsfrom app.platform.filesystem import localFilePath, toSafeFilename-from .cards import M3U8DraftCard, M3U8TaskCardfrom .config import m3u8Config, m3u8Runtimefrom .task import M3U8Task, M3U8TaskStep@@ -249,14 +248,17 @@ class M3U8Parser(TaskParser):class M3U8Pack(FeaturePack):packId = "m3u8"parsers = [M3U8Parser]- taskCards = {M3U8Task: M3U8TaskCard}- draftCards = {M3U8Task: M3U8DraftCard}- def taskCardClass(self, task):+ def taskCardClass(self, task: Task) -> type | None:if getattr(task, "isLive", False):from .cards import M3U8LiveTaskCardreturn M3U8LiveTaskCard- return super().taskCardClass(task)+ from .cards import M3U8TaskCard+ return M3U8TaskCard++ def draftCardClass(self, task: Task) -> type | None:+ from .cards import M3U8DraftCard+ return M3U8DraftCarddef __init__(self, services):self.config = m3u8Configdiff --git a/features/yt_dlp_pack/config.py b/features/yt_dlp_pack/config.pyindex a2961b1b..8e3a8da9 100644--- a/features/yt_dlp_pack/config.py+++ b/features/yt_dlp_pack/config.py@@ -5,12 +5,8 @@ import platformimport sysfrom pathlib import Path-from PySide6.QtCore import QCoreApplication, QT_TRANSLATE_NOOP as N, Qt-from PySide6.QtWidgets import QHBoxLayout, QWidget-from qfluentwidgets import (- BoolValidator, CaptionLabel, ConfigItem, FluentIcon, FolderValidator,- PushButton, SettingCard, ToolButton, ToolTipFilter,-)+from app.config.cfg import BoolValidator, ConfigItem, FolderValidator+from app.i18n import Nfrom app.config.paths import APP_DATA_DIRfrom app.models.pack import BinaryRuntime, PackConfig, VersionInfo@@ -99,6 +95,7 @@ class YtDlpConfig(PackConfig):installFolderCard.pathChanged.connect(runtimeCard._onInstallFolderChanged)cards.insert(0, installFolderCard)+ from .setting_cards import CookieSettingCardcards.append(CookieSettingCard(group))cards.extend([@@ -138,7 +135,7 @@ class YouTubeRuntime(BinaryRuntime):canInstall = Truetitle = N("BinaryRuntime", "YouTube 下载")description = N("BinaryRuntime", "支持 YouTube、Twitter 等数百个视频网站")- icon = FluentIcon.GLOBE+ icon = "GLOBE"isRecommended = Truedef installFolder(self) -> Path:@@ -292,88 +289,4 @@ def _qjsAssetName() -> str:return f"qjs-linux-{arch}"-class CookieSettingCard(SettingCard):-- def __init__(self, parent=None):- super().__init__(- FluentIcon.CERTIFICATE,- QCoreApplication.translate("YtDlpConfig", "YouTube Cookie"),- self._statusText(),- parent,- )- self._importButton = PushButton(- QCoreApplication.translate("YtDlpConfig", "导入"),- self,- )- self._clearButton = ToolButton(FluentIcon.DELETE, self)- self._clearButton.setToolTip(- QCoreApplication.translate("YtDlpConfig", "清除 Cookie")- )- self._clearButton.installEventFilter(ToolTipFilter(self._clearButton))- self._clearButton.setVisible(hasCookieFile())-- buttonLayout = QHBoxLayout()- buttonLayout.setContentsMargins(0, 0, 0, 0)- buttonLayout.setSpacing(8)- buttonLayout.addWidget(self._importButton)- buttonLayout.addWidget(self._clearButton)- self.hBoxLayout.addLayout(buttonLayout)- self.hBoxLayout.addSpacing(16)-- self._importButton.clicked.connect(self._onImportClicked)- self._clearButton.clicked.connect(self._onClearClicked)-- def _statusText(self) -> str:- if hasCookieFile():- return QCoreApplication.translate("YtDlpConfig", "已导入")- return QCoreApplication.translate(- "YtDlpConfig", "下载需要登录的内容时需要 Cookie,推荐通过浏览器扩展自动导入"- )-- def showEvent(self, event) -> None:- super().showEvent(event)- self._refresh()-- def _refresh(self) -> None:- self.setContent(self._statusText())- self._clearButton.setVisible(hasCookieFile())-- def _onImportClicked(self) -> None:- from qfluentwidgets import MessageBoxBase, SubtitleLabel, PlainTextEdit-- dialog = MessageBoxBase(self.window())- dialog.widget.setMinimumWidth(500)- dialog.viewLayout.addWidget(SubtitleLabel(- QCoreApplication.translate("YtDlpConfig", "导入 YouTube Cookie"),- dialog,- ))-- label = CaptionLabel(- QCoreApplication.translate(- "YtDlpConfig",- "安装浏览器扩展后,下载 YouTube 视频时会自动携带登录信息,无需手动操作。\n"- "如需手动导入:打开 YouTube 并登录,按 F12 打开开发者工具,在 Network 标签中"- "找到任意请求,复制其 Cookie 请求头的值并粘贴到下方。",- ),- dialog,- )- label.setWordWrap(True)- dialog.viewLayout.addWidget(label)-- editor = PlainTextEdit(dialog)- editor.setPlaceholderText("SID=xxx; HSID=xxx; ...")- editor.setMinimumHeight(120)- dialog.viewLayout.addWidget(editor)-- if dialog.exec():- text = editor.toPlainText().strip()- if text:- saveCookies(text)- self._refresh()-- def _onClearClicked(self) -> None:- clearCookies()- self._refresh()--youTubeRuntime = YouTubeRuntime()diff --git a/features/yt_dlp_pack/pack.py b/features/yt_dlp_pack/pack.pyindex c9d59969..7b5b2670 100644--- a/features/yt_dlp_pack/pack.py+++ b/features/yt_dlp_pack/pack.py@@ -7,7 +7,6 @@ from app.models.task import Task, TaskOptions, SpecialFileSizefrom app.platform.filesystem import toSafeFilenamefrom loguru import logger-from .cards import YtDlpDraftCard, YtDlpTaskCardfrom .config import ytDlpConfig, youTubeRuntimefrom .task import YouTubeTask, buildStepGroup@@ -62,8 +61,14 @@ class YouTubeParser(TaskParser):class YouTubePack(FeaturePack):packId = "ytdlp"parsers = [YouTubeParser]- taskCards = {YouTubeTask: YtDlpTaskCard}- draftCards = {YouTubeTask: YtDlpDraftCard}++ def taskCardClass(self, task: Task) -> type | None:+ from .cards import YtDlpTaskCard+ return YtDlpTaskCard++ def draftCardClass(self, task: Task) -> type | None:+ from .cards import YtDlpDraftCard+ return YtDlpDraftCarddef __init__(self, services):self.config = ytDlpConfigdiff --git a/features/yt_dlp_pack/setting_cards.py b/features/yt_dlp_pack/setting_cards.pynew file mode 100644index 00000000..3d5ccd0d--- /dev/null+++ b/features/yt_dlp_pack/setting_cards.py@@ -0,0 +1,94 @@+"""yt-dlp 的设置卡片(View)。config.py 只留配置数据。"""+from __future__ import annotations++from PySide6.QtCore import QCoreApplication, Qt+from PySide6.QtWidgets import QHBoxLayout+from qfluentwidgets import (+ CaptionLabel, FluentIcon, PushButton, SettingCard, ToolButton, ToolTipFilter,+)++from .config import clearCookies, hasCookieFile, saveCookies+++class CookieSettingCard(SettingCard):++ def __init__(self, parent=None):+ super().__init__(+ FluentIcon.CERTIFICATE,+ QCoreApplication.translate("YtDlpConfig", "YouTube Cookie"),+ self._statusText(),+ parent,+ )+ self._importButton = PushButton(+ QCoreApplication.translate("YtDlpConfig", "导入"),+ self,+ )+ self._clearButton = ToolButton(FluentIcon.DELETE, self)+ self._clearButton.setToolTip(+ QCoreApplication.translate("YtDlpConfig", "清除 Cookie")+ )+ self._clearButton.installEventFilter(ToolTipFilter(self._clearButton))+ self._clearButton.setVisible(hasCookieFile())++ buttonLayout = QHBoxLayout()+ buttonLayout.setContentsMargins(0, 0, 0, 0)+ buttonLayout.setSpacing(8)+ buttonLayout.addWidget(self._importButton)+ buttonLayout.addWidget(self._clearButton)+ self.hBoxLayout.addLayout(buttonLayout)+ self.hBoxLayout.addSpacing(16)++ self._importButton.clicked.connect(self._onImportClicked)+ self._clearButton.clicked.connect(self._onClearClicked)++ def _statusText(self) -> str:+ if hasCookieFile():+ return QCoreApplication.translate("YtDlpConfig", "已导入")+ return QCoreApplication.translate(+ "YtDlpConfig", "下载需要登录的内容时需要 Cookie,推荐通过浏览器扩展自动导入"+ )++ def showEvent(self, event) -> None:+ super().showEvent(event)+ self._refresh()++ def _refresh(self) -> None:+ self.setContent(self._statusText())+ self._clearButton.setVisible(hasCookieFile())++ def _onImportClicked(self) -> None:+ from qfluentwidgets import MessageBoxBase, SubtitleLabel, PlainTextEdit++ dialog = MessageBoxBase(self.window())+ dialog.widget.setMinimumWidth(500)+ dialog.viewLayout.addWidget(SubtitleLabel(+ QCoreApplication.translate("YtDlpConfig", "导入 YouTube Cookie"),+ dialog,+ ))++ label = CaptionLabel(+ QCoreApplication.translate(+ "YtDlpConfig",+ "安装浏览器扩展后,下载 YouTube 视频时会自动携带登录信息,无需手动操作。\n"+ "如需手动导入:打开 YouTube 并登录,按 F12 打开开发者工具,在 Network 标签中"+ "找到任意请求,复制其 Cookie 请求头的值并粘贴到下方。",+ ),+ dialog,+ )+ label.setWordWrap(True)+ dialog.viewLayout.addWidget(label)++ editor = PlainTextEdit(dialog)+ editor.setPlaceholderText("SID=xxx; HSID=xxx; ...")+ editor.setMinimumHeight(120)+ dialog.viewLayout.addWidget(editor)++ if dialog.exec():+ text = editor.toPlainText().strip()+ if text:+ saveCookies(text)+ self._refresh()++ def _onClearClicked(self) -> None:+ clearCookies()+ self._refresh()