The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(packs): 重构功能包系统
XiaoYouChRd65b373ea681
diff --git a/features/bili_pack/account.py b/features/bili_pack/account.pynew file mode 100644index 00000000..67299c72--- /dev/null+++ b/features/bili_pack/account.py@@ -0,0 +1,316 @@+from __future__ import annotations++import asyncio+import time+import urllib.parse+from functools import reduce+from hashlib import md5+from urllib.parse import parse_qsl, urlparse++from PySide6.QtCore import QObject, Signal++from app.client import buildClient+from .config import bilibiliConfig++MIXIN_KEY_ENC_TAB = [+ 46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49,+ 33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40,+ 61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57, 62, 11,+ 36, 20, 34, 44, 52,+]++QR_GENERATE_API = "https://passport.bilibili.com/x/passport-login/web/qrcode/generate"+QR_POLL_API = "https://passport.bilibili.com/x/passport-login/web/qrcode/poll"+LOGIN_INFO_API = "https://api.bilibili.com/x/web-interface/nav"+LOGOUT_API = "https://passport.bilibili.com/login/exit/v2"+QR_POLL_INTERVAL = 2.0+QR_UNSCANNED = 86101+QR_SCANNED = 86090+QR_EXPIRED = 86038+QR_LOGIN_SUCCESS = 1++COOKIE_ORDER = ("SESSDATA", "bili_jct", "DedeUserID", "DedeUserID__ckMd5", "sid")+++def toCookie(raw: str) -> str:+ parts: dict[str, str] = {}+ for part in raw.replace("\r", ";").replace("\n", ";").split(";"):+ part = part.strip()+ if not part or "=" not in part:+ continue+ name, value = part.split("=", 1)+ name, value = name.strip(), value.strip()+ if name and value:+ parts[name] = value+ if not parts:+ return ""+ ordered = [n for n in COOKIE_ORDER if n in parts]+ extra = [n for n in parts if n not in COOKIE_ORDER]+ return "; ".join(f"{n}={parts[n]}" for n in ordered + extra)+++class BilibiliAccount(QObject):+ accountChanged = Signal()+ qrStateChanged = Signal(int, str)++ def __init__(self, parent=None):+ super().__init__(parent)+ self._username = ""+ self._mid = ""+ self._vip = ""+ self._mixinKey = ""+ self._qrWorkId = ""++ @property+ def cookie(self) -> str:+ return bilibiliConfig.userCookie.value++ @property+ def isLoggedIn(self) -> bool:+ return bool(self.cookie)++ @property+ def username(self) -> str:+ return self._username++ @property+ def mid(self) -> str:+ return self._mid++ @property+ def vip(self) -> str:+ return self._vip++ def _updateWbiKeys(self, data: dict) -> None:+ wbiImg = data.get("wbi_img") or {}+ imgUrl = str(wbiImg.get("img_url") or "")+ subUrl = str(wbiImg.get("sub_url") or "")+ imgKey = imgUrl.rsplit("/", 1)[-1].split(".")[0] if imgUrl else ""+ subKey = subUrl.rsplit("/", 1)[-1].split(".")[0] if subUrl else ""+ if imgKey and subKey:+ orig = imgKey + subKey+ self._mixinKey = reduce(lambda s, i: s + orig[i], MIXIN_KEY_ENC_TAB, "")[:32]++ def signParams(self, params: dict) -> dict:+ if not self._mixinKey:+ return params+ params["wts"] = round(time.time())+ params = dict(sorted(params.items()))+ params = {k: "".join(c for c in str(v) if c not in "!'()*") for k, v in params.items()}+ query = urllib.parse.urlencode(params)+ params["w_rid"] = md5((query + self._mixinKey).encode()).hexdigest()+ return params++ # ── QR login (wreq via coroutineRunner) ──++ def startQrLogin(self):+ from app.services.coroutine_runner import coroutineRunner+ self.cancelQrLogin()+ self._qrWorkId = coroutineRunner.submit(+ self._pollQrLogin(), done=self._onQrLoginDone, failed=self._onQrLoginFailed,+ )++ def cancelQrLogin(self):+ if self._qrWorkId:+ from app.services.coroutine_runner import coroutineRunner+ coroutineRunner.cancel(self._qrWorkId)+ self._qrWorkId = ""++ async def _pollQrLogin(self) -> str:+ from app.services.coroutine_runner import coroutineRunner++ client = buildClient()+ try:+ response = await client.get(QR_GENERATE_API)+ response.raise_for_status()+ payload = await response.json()+ if payload.get("code") not in {None, 0}:+ raise ValueError(payload.get("message") or "获取二维码失败")++ data = payload.get("data") or {}+ loginUrl = str(data.get("url") or "").strip()+ qrCodeKey = str(data.get("qrcode_key") or "").strip()+ if not loginUrl or not qrCodeKey:+ raise ValueError("二维码接口返回了不完整的数据")++ coroutineRunner.post(self.qrStateChanged.emit, 0, loginUrl)++ while True:+ await asyncio.sleep(QR_POLL_INTERVAL)++ response = await client.get(QR_POLL_API, query={"qrcode_key": qrCodeKey})+ response.raise_for_status()+ payload = await response.json()+ data = payload.get("data") or {}+ statusCode = int(data.get("code", -1))+ statusMessage = str(data.get("message") or "")++ if statusCode in {QR_UNSCANNED, QR_SCANNED}:+ coroutineRunner.post(self.qrStateChanged.emit, statusCode, statusMessage)+ continue++ if statusCode == QR_EXPIRED:+ coroutineRunner.post(self.qrStateChanged.emit, QR_EXPIRED, "")+ return ""++ if statusCode == 0:+ successUrl = str(data.get("url") or "")+ items: dict[str, str] = {}+ for name, value in parse_qsl(urlparse(successUrl).query, keep_blank_values=False):+ if name in COOKIE_ORDER and value:+ items[name] = value+ if items:+ return toCookie("; ".join(f"{k}={v}" for k, v in items.items()))++ return ""+ finally:+ client.close()++ def _onQrLoginDone(self, cookie: str):+ self._qrWorkId = ""+ if cookie:+ self.setCookie(cookie)+ self.fetchAccountInfo()+ self.qrStateChanged.emit(QR_LOGIN_SUCCESS, "")++ def _onQrLoginFailed(self, error: str):+ self._qrWorkId = ""+ self.qrStateChanged.emit(-1, error)++ # ── cookie / logout / account info (wreq via coroutineRunner) ──++ def setCookie(self, cookie: str):+ from app.config.cfg import cfg+ from app.services.coroutine_runner import coroutineRunner++ cookie = toCookie(cookie)+ oldCookie = self.cookie+ if oldCookie and oldCookie != cookie:+ def onDone(_):+ cfg.set(bilibiliConfig.userCookie, cookie)+ self.accountChanged.emit()+ coroutineRunner.submit(self._logout(), done=onDone, failed=onDone)+ else:+ cfg.set(bilibiliConfig.userCookie, cookie)+ self.accountChanged.emit()++ def logout(self):+ from app.services.coroutine_runner import coroutineRunner+ coroutineRunner.submit(self._logout(), done=self._onLogoutDone, failed=self._onLogoutFailed)++ def fetchAccountInfo(self):+ from app.services.coroutine_runner import coroutineRunner+ coroutineRunner.submit(self._fetchAccountInfo(), done=self._onAccountInfoDone)++ async def fetchWbiKeys(self) -> None:+ if self._mixinKey:+ return+ client = buildClient()+ try:+ response = await client.get(LOGIN_INFO_API)+ response.raise_for_status()+ payload = await response.json()+ self._updateWbiKeys(payload.get("data") or {})+ finally:+ client.close()++ async def _logout(self) -> bool:+ cookie = self.cookie+ parts: dict[str, str] = {}+ for part in cookie.split(";"):+ part = part.strip()+ if "=" in part:+ name, value = part.split("=", 1)+ parts[name.strip()] = value.strip()++ required = ("DedeUserID", "bili_jct", "SESSDATA")+ if any(not parts.get(n) for n in required):+ return True++ client = buildClient(headers={+ "cookie": cookie,+ "origin": "https://www.bilibili.com",+ "referer": "https://www.bilibili.com/",+ })+ try:+ response = await client.post(LOGOUT_API, form={+ "biliCSRF": parts["bili_jct"],+ "gourl": "https://www.bilibili.com/",+ })+ response.raise_for_status()+ contentType = (response.headers.get("content-type") or b"").decode().lower()+ if "application/json" not in contentType:+ return True++ payload = await response.json()+ if payload.get("code") == 0 and payload.get("status") is True:+ return True++ raise ValueError(payload.get("message") or "退出登录失败")+ finally:+ client.close()++ async def _fetchAccountInfo(self) -> dict:+ cookie = self.cookie+ if not cookie:+ return {"isLoggedIn": False, "uname": ""}++ client = buildClient(headers={"cookie": cookie})+ try:+ response = await client.get(LOGIN_INFO_API)+ response.raise_for_status()+ payload = await response.json()+ data = payload.get("data") or {}++ if payload.get("code") == -101 or not data.get("isLogin"):+ return {"isLoggedIn": False, "uname": ""}++ if payload.get("code") not in {None, 0}:+ raise ValueError(payload.get("message") or "获取登录信息失败")++ vipPayload = data.get("vip") or {}+ vipStatus = int(data.get("vipStatus") or vipPayload.get("status") or 0)+ if vipStatus != 1:+ vipText = "未开通"+ else:+ vipLabel = ((vipPayload.get("label") or {}).get("text")+ or (data.get("vip_label") or {}).get("text") or "").strip()+ if vipLabel:+ vipText = vipLabel+ else:+ vipType = int(data.get("vipType") or vipPayload.get("type") or 0)+ vipText = {1: "月度大会员", 2: "年度大会员"}.get(vipType, "大会员")++ return {+ "isLoggedIn": True,+ "uname": str(data.get("uname") or "").strip(),+ "mid": str(data.get("mid") or ""),+ "vip": vipText,+ "wbiData": data,+ }+ finally:+ client.close()++ def _onLogoutDone(self, shouldClear: bool):+ if shouldClear:+ from app.config.cfg import cfg+ cfg.set(bilibiliConfig.userCookie, "")+ self._username = ""+ self._mid = ""+ self._vip = ""+ self.accountChanged.emit()++ def _onLogoutFailed(self, error: str):+ self.accountChanged.emit()++ def _onAccountInfoDone(self, result: dict):+ self._username = result.get("uname", "")+ self._mid = result.get("mid", "")+ self._vip = result.get("vip", "")+ wbiData = result.get("wbiData")+ if wbiData:+ self._updateWbiKeys(wbiData)+ self.accountChanged.emit()+++bilibiliAccount = BilibiliAccount()diff --git a/features/bili_pack/cards.py b/features/bili_pack/cards.pynew file mode 100644index 00000000..5eae2b24--- /dev/null+++ b/features/bili_pack/cards.py@@ -0,0 +1,174 @@+from __future__ import annotations++from PySide6.QtCore import Qt+from PySide6.QtGui import QStandardItem, QStandardItemModel+from PySide6.QtWidgets import QAbstractItemView, QHBoxLayout, QHeaderView+from qfluentwidgets import (+ BodyLabel, ComboBox, FluentIcon, MessageBoxBase,+ PrimaryPushButton, PushButton, SubtitleLabel,+ ToolTipFilter, TransparentToolButton,+)++from app.format import toReadableSize+from app.view.cards.draft_cards import UniversalDraftCard+from app.view.components.tree_view import AutoSizingTreeView+from .task import BilibiliTask, DownloadMode++MODE_LABELS = ("视频", "音频", "封面")+++class BilibiliDraftCard(UniversalDraftCard):++ def _initWidget(self) -> None:+ super()._initWidget()+ self._modeCombo = ComboBox(self)+ self._modeCombo.setMinimumWidth(80)+ for label in MODE_LABELS:+ self._modeCombo.addItem(self.tr(label))+ self._modeCombo.setCurrentIndex(self.task.mode.value)++ self._selectPagesButton = TransparentToolButton(FluentIcon.LIBRARY, self)+ self._selectPagesButton.installEventFilter(ToolTipFilter(self._selectPagesButton))+ self._selectPagesButton.setToolTip(self.tr("选择分P"))+ self._refreshPageButtonVisibility()++ def _initLayout(self) -> None:+ super()._initLayout()+ self.layout().addWidget(self._modeCombo)+ self.layout().addWidget(self._selectPagesButton)++ def _bind(self) -> None:+ super()._bind()+ self._modeCombo.currentIndexChanged.connect(self._onModeChanged)+ self._selectPagesButton.clicked.connect(self._onSelectPagesClicked)++ def _onModeChanged(self, index: int) -> None:+ task: BilibiliTask = self._task+ task.setMode(DownloadMode(index))+ self._refreshSummary()++ def _onSelectPagesClicked(self) -> None:+ task: BilibiliTask = self._task+ dialog = PageSelectDialog(task, self.window())+ if dialog.exec():+ selected = dialog.selectedPageNumbers()+ if selected:+ task.setPageSelection(selected)+ self._refreshSummary()++ def _refreshSummary(self) -> None:+ self.sizeLabel.setText(toReadableSize(self._task.fileSize))+ self.nameLabel.setText(self._task.name)+ self._refreshPageButtonVisibility()++ def _refreshPageButtonVisibility(self) -> None:+ task: BilibiliTask = self._task+ visible = task.mode != DownloadMode.COVER and len(task.pages) > 1+ self._selectPagesButton.setVisible(visible)+++class PageSelectDialog(MessageBoxBase):++ def __init__(self, task: BilibiliTask, parent=None):+ super().__init__(parent)+ self._pages = task.pages++ self.titleLabel = SubtitleLabel(self.tr("选择分P"), self)+ self.summaryLabel = BodyLabel("", self)++ self.selectAllButton = PrimaryPushButton(self.tr("全选"), self)+ self.clearButton = PushButton(self.tr("全不选"), self)+ self.invertButton = PushButton(self.tr("反选"), self)++ self.treeView = AutoSizingTreeView(self, minimumVisibleRows=3, maximumVisibleRows=16)+ self.treeModel = QStandardItemModel(self.treeView)++ self._initWidget()+ self._initLayout()+ self._bind()+ self._refreshSummary()++ def _initWidget(self) -> None:+ self.widget.setMinimumWidth(500)+ self.yesButton.setText(self.tr("确定"))+ self.cancelButton.setText(self.tr("取消"))++ self.treeView.setRootIsDecorated(False)+ self.treeView.setUniformRowHeights(True)+ self.treeView.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)++ self.treeModel.setHorizontalHeaderLabels([self.tr("分P"), self.tr("大小")])+ self.treeView.setModel(self.treeModel)+ self.treeView.header().setStretchLastSection(False)+ self.treeView.header().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)+ self.treeView.header().setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)++ for page in self._pages:+ pageNumber = page["pageNumber"]+ pagePart = page.get("pagePart", "").strip()+ videoSize = page.get("videoSize", 0)+ audioSize = page.get("audioSize", 0)+ totalSize = videoSize + audioSize++ label = f"P{pageNumber}"+ if pagePart:+ label += f": {pagePart}"++ nameItem = QStandardItem(label)+ nameItem.setCheckable(True)+ nameItem.setCheckState(Qt.CheckState.Checked if page.get("selected", True) else Qt.CheckState.Unchecked)+ nameItem.setData(pageNumber, Qt.ItemDataRole.UserRole)++ sizeItem = QStandardItem(toReadableSize(totalSize) if totalSize > 0 else "")+ sizeItem.setEditable(False)++ self.treeModel.appendRow([nameItem, sizeItem])++ def _initLayout(self) -> None:+ actionsLayout = QHBoxLayout()+ actionsLayout.setContentsMargins(0, 0, 0, 0)+ actionsLayout.setSpacing(8)+ actionsLayout.addWidget(self.selectAllButton)+ actionsLayout.addWidget(self.clearButton)+ actionsLayout.addWidget(self.invertButton)+ actionsLayout.addStretch(1)+ actionsLayout.addWidget(self.summaryLabel)++ self.viewLayout.addWidget(self.titleLabel)+ self.viewLayout.addSpacing(8)+ self.viewLayout.addWidget(self.treeView)+ self.viewLayout.addSpacing(4)+ self.viewLayout.addLayout(actionsLayout)++ def _bind(self) -> None:+ self.selectAllButton.clicked.connect(lambda: self._setAll(True))+ self.clearButton.clicked.connect(lambda: self._setAll(False))+ self.invertButton.clicked.connect(self._onInvert)+ self.treeModel.itemChanged.connect(lambda _: self._refreshSummary())++ def _setAll(self, checked: bool) -> None:+ state = Qt.CheckState.Checked if checked else Qt.CheckState.Unchecked+ for row in range(self.treeModel.rowCount()):+ self.treeModel.item(row, 0).setCheckState(state)++ def _onInvert(self) -> None:+ for row in range(self.treeModel.rowCount()):+ item = self.treeModel.item(row, 0)+ item.setCheckState(+ Qt.CheckState.Unchecked if item.checkState() == Qt.CheckState.Checked else Qt.CheckState.Checked+ )++ def _refreshSummary(self) -> None:+ count = sum(+ 1 for row in range(self.treeModel.rowCount())+ if self.treeModel.item(row, 0).checkState() == Qt.CheckState.Checked+ )+ self.summaryLabel.setText(self.tr("{0}/{1} 个分P").format(count, self.treeModel.rowCount()))+ self.yesButton.setEnabled(count > 0)++ def selectedPageNumbers(self) -> set[int]:+ return {+ self.treeModel.item(row, 0).data(Qt.ItemDataRole.UserRole)+ for row in range(self.treeModel.rowCount())+ if self.treeModel.item(row, 0).checkState() == Qt.CheckState.Checked+ }diff --git a/features/bili_pack/config.py b/features/bili_pack/config.pyindex 58712202..fb3960cb 100644--- a/features/bili_pack/config.py+++ b/features/bili_pack/config.py@@ -1,99 +1,50 @@+from __future__ import annotations+from io import BytesIO-from typing import TYPE_CHECKING-import qrcodefrom PySide6.QtCore import Qt, QUrlfrom PySide6.QtGui import QDesktopServices, QPixmap-from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget+from qfluentwidgets import (- MessageBoxBase,- SubtitleLabel,- PlainTextEdit,- ConfigValidator,- OptionsConfigItem,- OptionsValidator,BoolValidator,- ConfigItem,- ComboBoxSettingCard,- SettingCard,- FluentIcon,- SwitchSettingCard,BodyLabel,CaptionLabel,- PushButton,- PrimaryPushButton,+ FluentIcon,+ MessageBoxBase,+ OptionsConfigItem,+ OptionsValidator,PixmapLabel,+ PlainTextEdit,+ PrimaryPushButton,+ PushButton,+ SettingCard,+ SubtitleLabel,)-from qrcode.image.pure import PyPNGImage--from app.bases.models import PackConfig-from app.services.core_service import coreService-from app.supports.config import cfg-from app.view.components.setting_card_group import CollapsibleSettingCardGroup-from .login import (- _QR_UNSCANNED,- _QR_SCANNED,- _QR_EXPIRED,- _toCookie,- requestQrCode,- pollQrLogin,- fetchLoginInfo,- logout,-)--if TYPE_CHECKING:- from app.view.pages.setting_page import SettingPage+from app.config.cfg import ConfigItem+from app.models.pack import PackConfig-def _createQrPixmap(content: str, size: int = 240) -> QPixmap:- qrCode = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, border=2, box_size=10)- qrCode.add_data(content)- qrCode.make(fit=True)- image = qrCode.make_image(image_factory=PyPNGImage, fill_color="black", back_color="white")- buffer = BytesIO()- image.save(buffer)+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(buffer.getvalue(), "PNG")+ pixmap.loadFromData(buf.getvalue(), "PNG")return pixmap.scaled(size, size)-class EditCookieDialog(MessageBoxBase):- def __init__(self, parent=None, initialCookie: str = ""):- super().__init__(parent=parent)- self.setClosableOnMaskClicked(True)-- 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 ScanLoginDialog(MessageBoxBase):def __init__(self, parent=None):- super().__init__(parent=parent)-- self.cookie = ""- self._qrCodeKey = ""+ super().__init__(parent)self._loginUrl = ""- self._generation = 0- self._generating = False- self._closed = False- self.setClosableOnMaskClicked(True)+self.widget.setFixedSize(430, 560)self.yesButton.hide()self.cancelButton.setText(self.tr("关闭"))@@ -103,383 +54,226 @@ class ScanLoginDialog(MessageBoxBase):self.tr("使用哔哩哔哩手机客户端扫描下方二维码,并在手机端确认登录"),self.widget,)- self.qrPixmapLabel = PixmapLabel(self.widget)- self.qrPixmapLabel.setFixedSize(240, 240)- self.qrPixmapLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)- self.qrPixmapLabel.setScaledContents(True)+ 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.statusLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)- self.statusLabel.setWordWrap(True)-self.tipLabel = CaptionLabel(self.tr('二维码有效期约 180 秒,失效后可点击"刷新二维码"重新生成'),self.widget,)- self.tipLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)- self.tipLabel.setWordWrap(True)-- self.buttonContainer = QVBoxLayout()- self.buttonContainer.setContentsMargins(0, 0, 0, 0)- self.buttonContainer.setSpacing(10)-- self.actionLayout = QHBoxLayout()- self.actionLayout.setContentsMargins(0, 0, 0, 0)- self.actionLayout.setSpacing(12)self.refreshButton = PrimaryPushButton(FluentIcon.SYNC, self.tr("刷新二维码"), self.widget)self.openBrowserButton = PushButton(FluentIcon.LINK, self.tr("打开登录链接"), self.widget)self.openBrowserButton.setEnabled(False)- self.actionLayout.addWidget(self.refreshButton)- self.actionLayout.addWidget(self.openBrowserButton)- self.buttonContainer.addLayout(self.actionLayout)+ 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.qrPixmapLabel, 0, Qt.AlignmentFlag.AlignCenter)+ 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(self.buttonContainer)+ self.viewLayout.addLayout(buttonLayout)+ def _bind(self):+ from .account import bilibiliAccountself.refreshButton.clicked.connect(self.reloadQrCode)- self.openBrowserButton.clicked.connect(self._openLoginUrl)-- self.reloadQrCode()-- def done(self, code):- self._closed = True- super().done(code)+ self.openBrowserButton.clicked.connect(self._onOpenBrowser)+ bilibiliAccount.qrStateChanged.connect(self._onQrState)def reloadQrCode(self):- if self._closed or self._generating:- return-- self._generation += 1- self._generating = True- self.cookie = ""- self._qrCodeKey = ""- self._loginUrl = ""- self.openBrowserButton.setEnabled(False)- self.qrPixmapLabel.setPixmap(QPixmap())+ from .account import bilibiliAccount+ self.qrLabel.setPixmap(QPixmap())+ self.qrLabel.setFixedSize(240, 240)self.statusLabel.setText(self.tr("正在获取二维码..."))+ self.openBrowserButton.setEnabled(False)+ self._loginUrl = ""+ bilibiliAccount.startQrLogin()- generation = self._generation- coreService.runCoroutine(- requestQrCode(),- lambda result, error: self._onQrCodeGenerated(generation, result, error),- )-- def _onQrCodeGenerated(self, generation: int, result: dict | None, error: str | None):- if self._closed or generation != self._generation:- return-- self._generating = False- self.refreshButton.setEnabled(True)-- if error:- self.statusLabel.setText(self.tr(f"二维码获取失败:{error}"))- return-- self._loginUrl = str((result or {}).get("url") or "").strip()- self._qrCodeKey = str((result or {}).get("qrcode_key") or "").strip()- if not self._loginUrl or not self._qrCodeKey:- self.statusLabel.setText(self.tr("二维码获取失败:接口未返回有效的登录地址"))- return-- try:- self.qrPixmapLabel.setPixmap(_createQrPixmap(self._loginUrl))- except Exception as e:- self.statusLabel.setText(self.tr(f"二维码生成失败:{e}"))- raise-- self.openBrowserButton.setEnabled(True)- self.statusLabel.setText(self.tr("等待扫码并在手机端确认登录"))- generation = self._generation- coreService.runCoroutine(- pollQrLogin(- self._qrCodeKey,- lambda statusCode, statusMessage: self._onLoginPollingStatus(generation, statusCode, statusMessage),- lambda: self._closed or generation != self._generation,- ),- lambda result, error: self._onLoginPolled(generation, result, error),- )-- def _onLoginPollingStatus(self, generation: int, statusCode: int, statusMessage: str):- if self._closed or generation != self._generation:- return-- if statusCode == _QR_UNSCANNED:+ 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("等待扫码"))- return-- if statusCode == _QR_SCANNED:+ elif statusCode == QR_SCANNED:self.statusLabel.setText(self.tr("二维码已扫码,请在手机端确认登录"))- return-- if statusMessage:- self.statusLabel.setText(statusMessage)-- def _onLoginPolled(self, generation: int, result: dict | None, error: str | None):- if self._closed or generation != self._generation:- return-- if error:- self.statusLabel.setText(self.tr('轮询扫码状态失败,请点击"刷新二维码"重试'))- return-- payload = result or {}- statusCode = int(payload.get("code", -1))- statusMessage = str(payload.get("message") or "").strip()-- if statusCode == -1:- return-- if statusCode == _QR_EXPIRED:+ elif statusCode == QR_EXPIRED:self.statusLabel.setText(self.tr('二维码已失效,请点击"刷新二维码"重新生成'))- return-- if statusCode == 0:- self.cookie = str(payload.get("cookie") or "")- if not self.cookie:- self.statusLabel.setText(self.tr("登录成功,但未能提取到有效 Cookie"))- return-- self.statusLabel.setText(self.tr("登录成功,正在导入 Cookie..."))- self.accept()- return-- self.statusLabel.setText(self.tr(statusMessage or f"未知扫码状态:{statusCode}"))+ else:+ self.statusLabel.setText(text or str(statusCode))- def _openLoginUrl(self):+ def _onOpenBrowser(self):if self._loginUrl:QDesktopServices.openUrl(QUrl(self._loginUrl))+ def done(self, code):+ from .account import bilibiliAccount+ bilibiliAccount.cancelQrLogin()+ super().done(code)-class BilibiliLoginSettingCard(SettingCard):- def __init__(self, userCookieItem: ConfigItem, parent=None):- super().__init__(- FluentIcon.VIEW,- self.tr("账号登录"),- "状态:未登录 用户名:- UID:- 会员状态:未开通",- parent,- )- self.userCookieItem = userCookieItem- self._infoGeneration = 0- self._statusText = "未登录"- self._uname = "-"- self._mid = "-"- self._vipText = "未开通"-- self.operationWidget = QWidget(self)- self.operationLayout = QHBoxLayout(self.operationWidget)- self.operationLayout.setContentsMargins(0, 0, 0, 0)- self.operationLayout.setSpacing(8)-- self.scanLoginButton = PrimaryPushButton(self.tr("扫码登录"), self.operationWidget)- self.editCookieButton = PushButton(self.tr("手动设置 Cookie"), self.operationWidget)- self.logoutButton = PushButton(self.tr("退出登录"), self.operationWidget)-- self.operationLayout.addWidget(self.scanLoginButton)- self.operationLayout.addWidget(self.editCookieButton)- self.operationLayout.addWidget(self.logoutButton)-- self.hBoxLayout.addWidget(self.operationWidget, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)- self.hBoxLayout.addSpacing(16)- self.scanLoginButton.clicked.connect(self._onScanLogin)- self.editCookieButton.clicked.connect(self._onEditCookie)- self.logoutButton.clicked.connect(self._onLogout)+class EditCookieDialog(MessageBoxBase):+ def __init__(self, parent=None, initialCookie: str = ""):+ super().__init__(parent)- self._syncButtonsEnabled()- self.refreshLoginInfo()+ self.widget.setFixedSize(420, 500)+ self.yesButton.setText(self.tr("保存"))+ self.cancelButton.setText(self.tr("取消"))- def _renderAccountInfo(self):- self.setContent(- f"状态:{self._statusText} "- f"用户名:{self._uname} "- f"UID:{self._mid} "- f"会员状态:{self._vipText}"+ 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 "")- def _syncButtonsEnabled(self, busy: bool = False):- self.scanLoginButton.setEnabled(not busy)- self.editCookieButton.setEnabled(not busy)- self.logoutButton.setEnabled(not busy and bool(self.userCookieItem.value))-- def _setAccountInfo(self, status: str, uname: str | None = None, mid: str | None = None, vip: str | None = None):- self._statusText = status- if uname is not None:- self._uname = uname- if mid is not None:- self._mid = mid- if vip is not None:- self._vipText = vip- self._renderAccountInfo()+ self.viewLayout.addWidget(self.titleLabel)+ self.viewLayout.addWidget(self.descriptionLabel)+ self.viewLayout.addWidget(self.cookieTextEdit)- def refreshLoginInfo(self):- cookie = self.userCookieItem.value- self._syncButtonsEnabled()- if not cookie:- self._setAccountInfo("未登录", "-", "-", "未开通")- return- self._setAccountInfo("正在获取账号信息...", "-", "-", "-")- self._infoGeneration += 1- generation = self._infoGeneration- coreService.runCoroutine(- fetchLoginInfo(cookie),- lambda result, error: self._onLoginInfoLoaded(generation, result, error),+class BilibiliLoginSettingCard(SettingCard):+ def __init__(self, parent=None):+ 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)- def _onLoginInfoLoaded(self, generation: int, result: dict | None, error: str | None):- if generation != self._infoGeneration:- return-- self._syncButtonsEnabled()- if error:- self._setAccountInfo("账号信息获取失败", "-", "-", "-")- return+ self._initLayout()+ self._bind()+ self.refreshLoginInfo()- payload = result or {}- self._setAccountInfo(- str(payload.get("status") or "未登录"),- str(payload.get("uname") or "-"),- str(payload.get("mid") or "-"),- str(payload.get("vip") or "未开通"),- )+ 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 _updateCookie(self, newCookie: str):- normalizedCookie = _toCookie(newCookie)- if not normalizedCookie:- cfg.set(self.userCookieItem, "")- self.refreshLoginInfo()- return+ def _bind(self):+ from .account import bilibiliAccount+ self.scanButton.clicked.connect(self._onScanLogin)+ self.editButton.clicked.connect(self._onEditCookie)+ self.logoutButton.clicked.connect(self._onLogout)+ bilibiliAccount.accountChanged.connect(self.refreshLoginInfo)- currentCookie = self.userCookieItem.value- self._syncButtonsEnabled(True)- if currentCookie and currentCookie != normalizedCookie:- self._setAccountInfo("正在退出旧账号并导入新账号...", "-", "-", "-")- coreService.runCoroutine(- logout(currentCookie),- lambda _result, _error: self._onCookieUpdated(normalizedCookie),+ def refreshLoginInfo(self):+ from .account import bilibiliAccount+ if bilibiliAccount.isLoggedIn:+ uname = bilibiliAccount.username or "-"+ mid = bilibiliAccount.mid or "-"+ vip = bilibiliAccount.vip or "未开通"+ self.setContent(+ self.tr("状态:已登录 用户名:{0} UID:{1} 会员状态:{2}").format(uname, mid, vip))else:- self._onCookieUpdated(normalizedCookie)-- def _onCookieUpdated(self, cookie: str):- cfg.set(self.userCookieItem, cookie)- self.refreshLoginInfo()+ self.setContent(self.tr("状态:未登录"))+ self.scanButton.setEnabled(True)+ self.editButton.setEnabled(True)+ self.logoutButton.setEnabled(bilibiliAccount.isLoggedIn)def _onScanLogin(self):dialog = ScanLoginDialog(self.window())- if dialog.exec():- self._updateCookie(dialog.cookie)+ dialog.exec()+ dialog.deleteLater()def _onEditCookie(self):- dialog = EditCookieDialog(self.window(), self.userCookieItem.value)- try:- if dialog.exec():- self._updateCookie(dialog.cookieTextEdit.toPlainText())- finally:+ from .account import bilibiliAccount, toCookie+ dialog = EditCookieDialog(self.window(), bilibiliAccount.cookie)+ if not dialog.exec():dialog.deleteLater()-- def _onLogout(self):- cookie = self.userCookieItem.value- if not cookie:- self.refreshLoginInfo()return- self._syncButtonsEnabled(True)- self._setAccountInfo("正在退出登录...")- coreService.runCoroutine(logout(cookie), self._onLoggedOut)-- def _onLoggedOut(self, result: dict | None, error: str | None):- if error:- self._syncButtonsEnabled()- self._setAccountInfo("退出登录失败")+ newCookie = toCookie(dialog.cookieTextEdit.toPlainText())+ dialog.deleteLater()+ if not newCookie:+ bilibiliAccount.setCookie("")return- payload = result or {}- if payload.get("clear_local"):- cfg.set(self.userCookieItem, "")- self.refreshLoginInfo()---class CookieValidator(ConfigValidator):- def validate(self, value) -> bool:- return isinstance(value, str)+ bilibiliAccount.setCookie(newCookie)- def correct(self, value) -> str:- if not isinstance(value, str):- return ""- return _toCookie(value)+ def _onLogout(self):+ from .account import bilibiliAccount+ self.scanButton.setEnabled(False)+ self.editButton.setEnabled(False)+ self.logoutButton.setEnabled(False)+ self.setContent(self.tr("正在退出登录..."))+ bilibiliAccount.logout()class BilibiliConfig(PackConfig):+ userCookie = ConfigItem("Bilibili", "UserCookie", "")defaultQuality = OptionsConfigItem(- "Download",- "DefaultQuality",- 16,- OptionsValidator([127, 120, 116, 112, 80, 74, 64, 32, 16]),+ "Bilibili", "DefaultQuality", 80,+ OptionsValidator([16, 32, 64, 80, 112, 116, 120, 125, 126, 127, 128]),)- alternativeQuality = OptionsConfigItem("Download", "AlternativeQuality", "max", OptionsValidator(["max", "min"]))- parseHDR = ConfigItem("Download", "ParseHDR", False, BoolValidator())- parseDolby = ConfigItem("Download", "ParseDolby", False, BoolValidator())- userCookie = ConfigItem("Download", "UserCookie", "", CookieValidator())-- def setupSettings(self, settingPage: "SettingPage"):- self.parseBilibiliGroup = CollapsibleSettingCardGroup(self.tr("哔哩哔哩视频下载"), "bili", settingPage.container)-- self.defaultQualityCard = ComboBoxSettingCard(- self.defaultQuality,- FluentIcon.VIDEO,- self.tr("默认清晰度"),- self.tr("下载视频时默认的清晰度"),- ["8K", "4K", "1080P60", "1080P+", "1080P", "720P60", "720P", "480P", "360P"],- self.parseBilibiliGroup,- )-- self.alternativeQualityCard = ComboBoxSettingCard(- self.alternativeQuality,- FluentIcon.VIDEO,- self.tr("备选清晰度"),- self.tr("下载视频时备选的清晰度"),- [self.tr("可以下载的最高画质"), self.tr("可以下载的最低画质")],- self.parseBilibiliGroup,- )-- self.parseHDRCard = SwitchSettingCard(- FluentIcon.VIDEO,- self.tr("HDR"),- self.tr("下载 HDR 视频"),- self.parseHDR,- self.parseBilibiliGroup,- )-- self.parseDolbyCard = SwitchSettingCard(- FluentIcon.VIDEO,- self.tr("杜比视界"),- self.tr("下载杜比视界视频"),- self.parseDolby,- self.parseBilibiliGroup,- )-- self.loginCard = BilibiliLoginSettingCard(- self.userCookie,- self.parseBilibiliGroup,- )-- self.parseBilibiliGroup.addSettingCard(self.defaultQualityCard)- self.parseBilibiliGroup.addSettingCard(self.alternativeQualityCard)- self.parseBilibiliGroup.addSettingCard(self.parseHDRCard)- self.parseBilibiliGroup.addSettingCard(self.parseDolbyCard)- self.parseBilibiliGroup.addSettingCard(self.loginCard)-- settingPage.addSettingGroup(self.parseBilibiliGroup)+ alternativeQuality = OptionsConfigItem(+ "Bilibili", "AlternativeQuality", "max",+ OptionsValidator(["max", "min"]),+ )+ shouldIncludeHdr = ConfigItem("Bilibili", "ParseHDR", False, BoolValidator())+ shouldIncludeDolby = ConfigItem("Bilibili", "ParseDolby", False, BoolValidator())++ def settingGroups(self, parent):+ from qfluentwidgets import ComboBoxSettingCard, FluentIcon, SwitchSettingCard+ from app.view.components.setting_card_group import CollapsibleSettingCardGroup++ biliGroup = CollapsibleSettingCardGroup(self.tr("Bilibili 下载"), "bilibili", parent)+ loginCard = BilibiliLoginSettingCard(biliGroup)+ biliGroup.addSettingCards([+ loginCard,+ ComboBoxSettingCard(self.defaultQuality, FluentIcon.VIDEO, self.tr("默认画质"),+ self.tr("选择偏好的视频画质"),+ texts=["240P", "360P", "480P", "720P", "720P60", "1080P",+ "1080P+", "1080P60", "4K", "HDR", "杜比视界"],+ parent=biliGroup),+ ComboBoxSettingCard(self.alternativeQuality, FluentIcon.SPEED_HIGH, self.tr("画质不可用时"),+ self.tr("当选择的画质不可用时的替代策略"),+ texts=[self.tr("选择最高画质"), self.tr("选择最低画质")],+ parent=biliGroup),+ SwitchSettingCard(FluentIcon.PALETTE, self.tr("HDR"),+ self.tr("请求 HDR 视频流(需要大会员)"),+ self.shouldIncludeHdr, biliGroup),+ SwitchSettingCard(FluentIcon.HEADPHONE, self.tr("杜比全景声/视界"),+ self.tr("请求杜比全景声和杜比视界(需要大会员)"),+ self.shouldIncludeDolby, biliGroup),+ ])+ return [biliGroup]bilibiliConfig = BilibiliConfig()diff --git a/features/bili_pack/login.py b/features/bili_pack/login.pydeleted file mode 100644index c19e13f8..00000000--- a/features/bili_pack/login.py+++ /dev/null@@ -1,266 +0,0 @@-import asyncio-from urllib.parse import parse_qsl, urlparse--import niquests--from app.supports.config import activeUserAgent, cfg-from app.supports.utils import getProxies--_QR_GENERATE_API = "https://passport.bilibili.com/x/passport-login/web/qrcode/generate"-_QR_POLL_API = "https://passport.bilibili.com/x/passport-login/web/qrcode/poll"-_LOGIN_INFO_API = "https://api.bilibili.com/x/web-interface/nav"-_LOGOUT_API = "https://passport.bilibili.com/login/exit/v2"-_QR_POLL_INTERVAL_MS = 2000-_QR_UNSCANNED = 86101-_QR_SCANNED = 86090-_QR_EXPIRED = 86038-_COOKIE_ORDER = (- "SESSDATA",- "bili_jct",- "DedeUserID",- "DedeUserID__ckMd5",- "sid",-)---def _toCookie(raw: str) -> str:- parts: dict[str, str] = {}- if not isinstance(raw, str):- return ""-- for part in raw.replace("\r", ";").replace("\n", ";").split(";"):- part = part.strip()- if not part or "=" not in part:- continue- name, value = part.split("=", 1)- name = name.strip()- value = value.strip()- if name and value:- parts[name] = value-- if not parts:- return ""-- ordered = [name for name in _COOKIE_ORDER if name in parts]- extra = [name for name in parts if name not in _COOKIE_ORDER]- return "; ".join(f"{name}={parts[name]}" for name in ordered + extra)---def _headers(cookie: str = "", origin: bool = False) -> dict[str, str]:- headers = {- "accept": "application/json, text/plain, */*",- "accept-language": "zh-CN,zh;q=0.9",- "user-agent": activeUserAgent(),- }- if cookie:- headers["cookie"] = cookie- if origin:- headers["origin"] = "https://www.bilibili.com"- headers["referer"] = "https://www.bilibili.com/"- return headers---def _extractCookie(response, successUrl: str) -> str:- items = {str(k): str(v) for k, v in response.cookies.items() if k and v}- if not any(name in items for name in _COOKIE_ORDER):- for name, value in parse_qsl(urlparse(successUrl).query, keep_blank_values=False):- if name in _COOKIE_ORDER and value:- items[name] = value-- if not items:- return ""- return _toCookie("; ".join(f"{k}={v}" for k, v in items.items()))---async def requestQrCode() -> dict[str, str]:- async with niquests.AsyncSession(- headers=_headers(),- timeout=30,- happy_eyeballs=True,- ) as client:- client.trust_env = False- response = await client.get(- _QR_GENERATE_API,- proxies=getProxies(),- verify=cfg.SSLVerify.value,- allow_redirects=True,- )- response.raise_for_status()- payload = response.json()-- if payload.get("code") not in {None, 0}:- raise ValueError(payload.get("message") or "获取二维码失败")-- data = payload.get("data") or {}- loginUrl = str(data.get("url") or "").strip()- qrCodeKey = str(data.get("qrcode_key") or "").strip()- if not loginUrl or not qrCodeKey:- raise ValueError("二维码接口返回了不完整的数据")-- return {- "url": loginUrl,- "qrcode_key": qrCodeKey,- }---async def pollQrLogin(- qrCodeKey: str,- statusCallback=None,- shouldStop=None,-) -> dict[str, str | int]:- from app.services.core_service import coreService-- async with niquests.AsyncSession(- headers=_headers(),- timeout=30,- happy_eyeballs=True,- ) as client:- client.trust_env = False-- while True:- if shouldStop is not None and shouldStop():- return {"code": -1, "message": "cancelled", "url": "", "cookie": ""}-- response = await client.get(- _QR_POLL_API,- params={"qrcode_key": qrCodeKey},- proxies=getProxies(),- verify=cfg.SSLVerify.value,- allow_redirects=True,- )- response.raise_for_status()- payload = response.json()- data = payload.get("data") or {}- cookieString = _extractCookie(response, str(data.get("url") or "")) if data.get("code") == 0 else ""-- if payload.get("code") not in {None, 0}:- raise ValueError(payload.get("message") or "轮询扫码状态失败")-- statusCode = int(data.get("code", -1))- statusMessage = str(data.get("message") or "").strip()- result = {- "code": statusCode,- "message": statusMessage,- "url": str(data.get("url") or "").strip(),- "cookie": cookieString,- }-- if statusCode in {_QR_UNSCANNED, _QR_SCANNED}:- coreService._executeCallback(statusCallback, statusCode, statusMessage)- await asyncio.sleep(_QR_POLL_INTERVAL_MS / 1000)- continue-- return result---async def fetchLoginInfo(cookie: str) -> dict[str, str | bool]:- if not cookie:- return {- "logged_in": False,- "status": "未登录",- "uname": "-",- "mid": "-",- "vip": "未开通",- }-- async with niquests.AsyncSession(- headers=_headers(cookie),- timeout=30,- happy_eyeballs=True,- ) as client:- client.trust_env = False- response = await client.get(- _LOGIN_INFO_API,- proxies=getProxies(),- verify=cfg.SSLVerify.value,- allow_redirects=True,- )- response.raise_for_status()- payload = response.json()-- data = payload.get("data") or {}- if payload.get("code") == -101 or not data.get("isLogin"):- return {- "logged_in": False,- "status": "未登录",- "uname": "-",- "mid": "-",- "vip": "未开通",- }-- if payload.get("code") not in {None, 0}:- raise ValueError(payload.get("message") or "获取登录信息失败")-- vipPayload = data.get("vip") or {}- vipStatus = int(data.get("vipStatus") or vipPayload.get("status") or 0)- if vipStatus != 1:- vipText = "未开通"- else:- vipLabel = ((vipPayload.get("label") or {}).get("text") or (data.get("vip_label") or {}).get("text") or "").strip()- if vipLabel:- vipText = vipLabel- else:- vipType = int(data.get("vipType") or vipPayload.get("type") or 0)- vipText = {1: "月度大会员", 2: "年度大会员"}.get(vipType, "大会员")-- return {- "logged_in": True,- "status": "已登录",- "uname": str(data.get("uname") or "-").strip() or "-",- "mid": str(data.get("mid") or "-"),- "vip": vipText,- }---async def logout(cookie: str) -> dict[str, str | bool]:- parts: dict[str, str] = {}- for part in cookie.split(";"):- part = part.strip()- if "=" in part:- name, value = part.split("=", 1)- parts[name.strip()] = value.strip()-- requiredCookies = ("DedeUserID", "bili_jct", "SESSDATA")- missingCookies = [name for name in requiredCookies if not parts.get(name)]- if missingCookies:- return {- "remote_logout": False,- "clear_local": True,- "message": f"Cookie 缺少 {', '.join(missingCookies)},已清除本地登录状态",- }-- async with niquests.AsyncSession(- headers=_headers(cookie, origin=True),- timeout=30,- happy_eyeballs=True,- ) as client:- client.trust_env = False- response = await client.post(- _LOGOUT_API,- data={- "biliCSRF": parts["bili_jct"],- "gourl": "https://www.bilibili.com/",- },- proxies=getProxies(),- verify=cfg.SSLVerify.value,- allow_redirects=True,- )- response.raise_for_status()- contentType = str(response.headers.get("content-type") or "").lower()- if "application/json" not in contentType:- return {- "remote_logout": False,- "clear_local": True,- "message": "当前 Cookie 可能已失效,已清除本地登录状态",- }-- payload = response.json()-- if payload.get("code") == 0 and payload.get("status") is True:- return {- "remote_logout": True,- "clear_local": True,- "message": "已退出登录",- }-- raise ValueError(payload.get("message") or "退出登录失败")diff --git a/features/bili_pack/pack.py b/features/bili_pack/pack.pyindex b785be75..8155c651 100644--- a/features/bili_pack/pack.py+++ b/features/bili_pack/pack.py@@ -1,219 +1,89 @@+from __future__ import annotations+import re-from pathlib import Path+import urllib.parsefrom urllib.parse import parse_qs, urlparse-import niquests--from app.bases.interfaces import FeaturePack-from app.bases.models import Task-from app.supports.config import cfg-from app.supports.utils import getProxies, toSafeFilename+from app.client import buildClient, toEmulation+from app.config.cfg import cfg+from app.models.pack import FeaturePack, TaskParser+from app.models.task import TaskOptions+from app.platform.filesystem import toSafeFilename+from .account import bilibiliAccountfrom .config import bilibiliConfig-from .task import BilibiliVideoStage, BilibiliAudioStage, BilibiliMergeStage---def _normalizeBilibiliReferer(referer: str) -> str:- parsedUrl = urlparse(referer)- if (parsedUrl.hostname or "").lower() != "bilibili.com":- return referer- return parsedUrl._replace(netloc="www.bilibili.com").geturl()---def _buildBilibiliHeaders(referer: str) -> dict[str, str]:- headers = {- "accept-encoding": "deflate, br, gzip",- "accept-language": "zh-CN,zh;q=0.9",- "sec-fetch-dest": "document",- "sec-fetch-mode": "navigate",- "sec-fetch-site": "none",- "sec-fetch-user": "?1",- "upgrade-insecure-requests": "1",- "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 Edg/144.0.0.0",- "referer": _normalizeBilibiliReferer(referer),- }-- userCookie = bilibiliConfig.userCookie.value- if userCookie:- headers["cookie"] = userCookie-- return headers---def _parseVideoIdAndPages(url: str) -> tuple[str, list[int] | None]:- parsedUrl = urlparse(url)- host = (parsedUrl.hostname or "").lower()- if not (host == "bilibili.com" or host.endswith(".bilibili.com")):- raise ValueError("Invalid Bilibili video URL")-- matchResult = re.match(r"/video/(BV[a-zA-Z0-9]+|av\d+)", parsedUrl.path)- if not matchResult:- raise ValueError("Invalid Bilibili video URL")-- pageParam = parse_qs(parsedUrl.query).get("p", [""])[0].strip()- pageRange = None if not pageParam else _parsePageParam(pageParam)- return matchResult.group(1), pageRange---def _parsePageParam(pageParam: str) -> list[int]:- values: list[int] = []- if "," in pageParam:- for part in pageParam.split(","):- values.extend(_parsePageParam(part.strip()))- return values-- if "-" in pageParam:- start, end = map(int, pageParam.split("-", 1))- if start > end:- start, end = end, start- return list(range(start, end + 1))-- return [int(pageParam)]---def _buildViewApiUrl(videoId: str) -> str:- if videoId.startswith("av"):- return f"https://api.bilibili.com/x/web-interface/view?avid={videoId[2:]}"- return f"https://api.bilibili.com/x/web-interface/view?bvid={videoId}"---def _buildPlayApiUrl(videoId: str, cid: int, fnval: int, qn: int) -> str:- if videoId.startswith("av"):- return f"https://api.bilibili.com/x/player/wbi/playurl?avid={videoId[2:]}&cid={cid}&qn={qn}&fnval={fnval}&fourk=1"- return f"https://api.bilibili.com/x/player/wbi/playurl?bvid={videoId}&cid={cid}&qn={qn}&fnval={fnval}&fourk=1"---def _resolveRequestedFnval(videoQuality: int) -> int:- fnval = 16- if bilibiliConfig.parseHDR.value:- fnval |= 64- if bilibiliConfig.parseDolby.value:- fnval |= 256- fnval |= 512- if videoQuality == 128:- fnval |= 1024- if videoQuality == 120:- fnval |= 128- return fnval---def _buildPageSuffix(pageNumber: int, pagePart: str, baseTitle: str, totalSelected: int) -> str:- if totalSelected <= 1:- return ""- suffix = f" - P{pageNumber}"- if pagePart and pagePart != baseTitle:- suffix += f" {pagePart}"- return suffix---def _pickVideoStream(pageData: dict, requestedQuality: int) -> dict:- dash = pageData.get("dash") or {}- videoOptions = dash.get("video") or []- if not videoOptions:- raise ValueError("Bilibili 返回结果中不存在 DASH 视频流")-- acceptQuality = list(pageData.get("accept_quality") or [])- quality = requestedQuality- if acceptQuality and quality not in acceptQuality:- if bilibiliConfig.alternativeQuality.value == "max":- quality = max(acceptQuality)- else:- quality = min(acceptQuality)-- for option in videoOptions:- if option.get("id") != quality:- continue- if _getStreamUrl(option):- return option-- for option in videoOptions:- if _getStreamUrl(option):- return option-- raise ValueError("未找到可用的视频流")-+from .task import BilibiliTask-def _pickAudioStream(pageData: dict) -> dict:- dash = pageData.get("dash") or {}- audioOptions = dash.get("audio") or []- if not audioOptions:- raise ValueError("Bilibili 返回结果中不存在 DASH 音频流")- for option in audioOptions:- if _getStreamUrl(option):- return option-- raise ValueError("未找到可用的音频流")---def _getStreamUrl(stream: dict) -> str:- url = stream.get("baseUrl") or stream.get("base_url")- if isinstance(url, str) and url:- return url-- backup = stream.get("backupUrl") or stream.get("backup_url") or []- if isinstance(backup, list):- for item in backup:- if isinstance(item, str) and item:- return item-- return ""---async def _getFileSizeWithClient(url: str, headers: dict, proxies: dict, client: niquests.AsyncSession) -> int:- requestHeaders = headers.copy()- requestHeaders["range"] = "bytes=0-0"-- response = await client.get(- url,- headers=requestHeaders,- proxies=proxies,- verify=cfg.SSLVerify.value,- allow_redirects=True,- stream=True,- )- try:- response.raise_for_status()- head = {k.lower(): v for k, v in response.headers.items()}-- if response.status_code == 206 and "content-range" in head:- _left, _char, right = head["content-range"].rpartition("/")- if right != "*":- return int(right)-- raise ValueError("音视频流不支持范围请求,当前实现无法下载")- finally:- await response.close()---class BilibiliPack(FeaturePack):- packId = "bili"+class BilibiliParser(TaskParser):priority = 50- config = bilibiliConfig- def matches(self, url: str) -> bool:- hostname = (urlparse(url).hostname or "").lower()+ def match(self, options: TaskOptions) -> bool:+ hostname = (urlparse(options.url).hostname or "").lower()return hostname == "bilibili.com" or hostname.endswith(".bilibili.com")- async def parse(self, payload: dict) -> Task:- url: str = payload["url"]- proxies: dict = payload.get("proxies", getProxies())- blockNum: int = payload.get("preBlockNum", cfg.preBlockNum.value)- path: Path = payload.get("path", Path(cfg.downloadFolder.value))-- headers = _buildBilibiliHeaders(url)- async with niquests.AsyncSession(headers=headers, timeout=60, happy_eyeballs=True) as client:- client.trust_env = False-- videoId, selectedPages = _parseVideoIdAndPages(url)+ async def parse(self, options: TaskOptions) -> Task:+ url = options.url+ subworkerCount = options.subworkerCount+ outputFolder = options.outputFolder++ await bilibiliAccount.fetchWbiKeys()++ parsed = urlparse(url)+ referer = parsed._replace(netloc="www.bilibili.com").geturl() if (+ (parsed.hostname or "").lower() != "bilibili.com"+ ) else url++ apiHeaders = {}+ cookie = bilibiliAccount.cookie+ if cookie:+ apiHeaders["cookie"] = cookie++ downloadHeaders = {+ **dict(options.headers),+ "referer": referer,+ }+ if cookie:+ downloadHeaders["cookie"] = cookie++ emulation = toEmulation(+ options.clientProfile or cfg.clientProfile.value,+ options.sourceUserAgent,+ )+ client = buildClient(emulation=None, headers=apiHeaders)++ try:+ videoIdMatch = re.match(r"/video/(BV[a-zA-Z0-9]+|av\d+)", parsed.path)+ if not videoIdMatch:+ raise ValueError("不是有效的 Bilibili 视频链接")+ videoId = videoIdMatch.group(1)++ pageParam = parse_qs(parsed.query).get("p", [""])[0].strip()+ selectedPages: list[int] | None = None+ if pageParam:+ selectedPages = []+ for part in pageParam.split(","):+ part = part.strip()+ if "-" in part:+ start, end = map(int, part.split("-", 1))+ if start > end:+ start, end = end, start+ selectedPages.extend(range(start, end + 1))+ else:+ selectedPages.append(int(part))++ viewApiUrl = (+ f"https://api.bilibili.com/x/web-interface/view?avid={videoId[2:]}"+ if videoId.startswith("av")+ else f"https://api.bilibili.com/x/web-interface/view?bvid={videoId}"+ )- response = await client.get(_buildViewApiUrl(videoId), proxies=proxies, allow_redirects=True)+ response = await client.get(viewApiUrl)response.raise_for_status()- videoPayload = response.json()-- if videoPayload.get("code") not in {None, 0}:- raise ValueError(videoPayload.get("message") or "获取 Bilibili 视频信息失败")+ viewPayload = await response.json()+ if viewPayload.get("code") not in {None, 0}:+ raise ValueError(viewPayload.get("message") or "获取 Bilibili 视频信息失败")- viewData = videoPayload.get("data") or {}+ viewData = viewPayload.get("data") or {}pages = list(viewData.get("pages") or [])if not pages:raise ValueError("未获取到视频分P信息")@@ -226,47 +96,58 @@ class BilibiliPack(FeaturePack):videoTitle = str(viewData.get("title", "")).strip() or "bilibili_video"requestedQuality = bilibiliConfig.defaultQuality.value- totalSize = 0+ baseName = toSafeFilename(videoTitle, fallback="bilibili_video")+ taskName = f"{baseName}.mp4"++ fnval = 16+ if bilibiliConfig.shouldIncludeHdr.value:+ fnval |= 64+ if bilibiliConfig.shouldIncludeDolby.value:+ fnval |= 256 | 512+ if requestedQuality == 128:+ fnval |= 1024+ if requestedQuality == 120:+ fnval |= 128- baseTitle = toSafeFilename(videoTitle, fallback="bilibili_video")- if len(selectedPages) == 1:- page = pages[selectedPages[0] - 1]- pagePart = str(page.get("part", "")).strip()- suffix = _buildPageSuffix(selectedPages[0], pagePart, baseTitle, len(selectedPages))- title = f"{baseTitle}{suffix}.mp4"- else:- title = f"{baseTitle}.mp4"+ totalSize = 0+ parsedPages = []- resolvedPages = []- for index, pageNumber in enumerate(selectedPages):+ for pageNumber in range(1, len(pages) + 1):page = pages[pageNumber - 1]pagePart = str(page.get("part", "")).strip()cid = int(page["cid"])- playResponse = await client.get(- _buildPlayApiUrl(videoId, cid, _resolveRequestedFnval(requestedQuality), requestedQuality),- proxies=proxies,- allow_redirects=True,- )- playResponse.raise_for_status()- playPayload = playResponse.json()-+ playParams = {"cid": cid, "qn": requestedQuality, "fnval": fnval, "fourk": 1}+ if videoId.startswith("av"):+ playParams["avid"] = videoId[2:]+ else:+ playParams["bvid"] = videoId+ playParams = bilibiliAccount.signParams(playParams)+ playApiUrl = f"https://api.bilibili.com/x/player/wbi/playurl?{urllib.parse.urlencode(playParams)}"++ response = await client.get(playApiUrl)+ response.raise_for_status()+ playPayload = await response.json()if playPayload.get("code") not in {None, 0}:raise ValueError(playPayload.get("message") or "获取 Bilibili 音视频流失败")pageData = playPayload.get("data") or {}- videoStream = _pickVideoStream(pageData, requestedQuality)- audioStream = _pickAudioStream(pageData)- videoUrl = _getStreamUrl(videoStream)- audioUrl = _getStreamUrl(audioStream)+ videoUrl = self._selectStream(+ pageData.get("dash", {}).get("video") or [],+ requestedQuality,+ list(pageData.get("accept_quality") or []),+ )+ audioUrl = self._selectStream(+ pageData.get("dash", {}).get("audio") or [],+ )if not videoUrl or not audioUrl:raise ValueError("未能解析出完整的音视频下载链接")- videoSize = await _getFileSizeWithClient(videoUrl, headers, proxies, client)- audioSize = await _getFileSizeWithClient(audioUrl, headers, proxies, client)+ videoSize = await self._fetchSize(client, videoUrl, downloadHeaders)+ audioSize = await self._fetchSize(client, audioUrl, downloadHeaders)totalSize += videoSize + audioSize- resolvedPages.append({+ parsedPages.append({"pageNumber": pageNumber,"pagePart": pagePart,"videoUrl": videoUrl,@@ -275,47 +156,104 @@ class BilibiliPack(FeaturePack):"audioSize": audioSize,})- task = Task(- title=title,+ coverUrl = str(viewData.get("pic") or "").strip()+ if coverUrl.startswith("http://"):+ coverUrl = "https://" + coverUrl[7:]++ coverSize = 0+ if coverUrl:+ try:+ headResponse = await client.head(coverUrl)+ cl = headResponse.headers.get("content-length")+ if cl:+ coverSize = int(cl.decode() if isinstance(cl, bytes) else cl)+ except Exception:+ pass++ for info in parsedPages:+ info["headers"] = dict(downloadHeaders)+ info["subworkerCount"] = subworkerCount+ info["selected"] = info["pageNumber"] in selectedPages++ task = BilibiliTask(+ name=taskName,url=url,- packId=self.packId,fileSize=totalSize,- path=path,+ outputFolder=outputFolder,+ coverUrl=coverUrl,+ coverSize=coverSize,+ pages=parsedPages,+ _baseName=baseName,)-- for index, pageInfo in enumerate(resolvedPages):- pageSuffix = _buildPageSuffix(- pageInfo["pageNumber"],- pageInfo["pagePart"],- baseTitle,- len(selectedPages),- )- stageBase = index * 3-- task.addStage(BilibiliVideoStage(- stageIndex=stageBase + 1,- url=pageInfo["videoUrl"],- fileSize=pageInfo["videoSize"],- headers=headers.copy(),- proxies=proxies,- blockNum=blockNum,- pageIndex=index,- pageSuffix=pageSuffix,- ))- task.addStage(BilibiliAudioStage(- stageIndex=stageBase + 2,- url=pageInfo["audioUrl"],- fileSize=pageInfo["audioSize"],- headers=headers.copy(),- proxies=proxies,- blockNum=blockNum,- pageIndex=index,- pageSuffix=pageSuffix,- ))- task.addStage(BilibiliMergeStage(- stageIndex=stageBase + 3,- pageIndex=index,- pageSuffix=pageSuffix,- ))+ task._rebuildSteps()return task+ finally:+ client.close()++ def _selectStream(+ self,+ streams: list[dict],+ quality: int | None = None,+ acceptQuality: list[int] | None = None,+ ) -> str:+ if not streams:+ raise ValueError("Bilibili 返回结果中不存在可用的媒体流")++ def streamUrl(s: dict) -> str:+ url = s.get("baseUrl") or s.get("base_url")+ if isinstance(url, str) and url:+ return url+ backup = s.get("backupUrl") or s.get("backup_url") or []+ if isinstance(backup, list):+ for item in backup:+ if isinstance(item, str) and item:+ return item+ return ""++ if quality is not None and acceptQuality:+ targetQuality = quality+ if targetQuality not in acceptQuality:+ targetQuality = max(acceptQuality) if bilibiliConfig.alternativeQuality.value == "max" else min(acceptQuality)+ for s in streams:+ if s.get("id") == targetQuality and streamUrl(s):+ return streamUrl(s)++ for s in streams:+ url = streamUrl(s)+ if url:+ return url++ raise ValueError("未找到可用的媒体流")++ async def _fetchSize(self, client, url: str, headers: dict) -> int:+ response = await client.get(url, headers={**headers, "range": "bytes=0-0"})+ try:+ response.raise_for_status()+ head = {k.decode().lower(): v.decode() for k, v in response.headers}+ if response.status.as_int() == 206 and "content-range" in head:+ _, _, total = head["content-range"].rpartition("/")+ if total != "*":+ return int(total)+ raise ValueError("音视频流不支持范围请求,当前实现无法下载")+ finally:+ response.close()+++class BilibiliPack(FeaturePack):+ packId = "bili"+ config = bilibiliConfig++ def parsers(self):+ return [BilibiliParser()]++ def draftCard(self, task, parent=None):+ from .cards import BilibiliDraftCard+ return BilibiliDraftCard(task, parent)++ def optionCards(self, task, parent=None):+ from app.view.components.option_cards import OutputFolderCard+ return [OutputFolderCard(parent, initial=task.outputFolder)]++ def start(self):+ bilibiliAccount.fetchAccountInfo()diff --git a/features/bili_pack/task.py b/features/bili_pack/task.pyindex 48b7263e..5b017029 100644--- a/features/bili_pack/task.py+++ b/features/bili_pack/task.py@@ -1,58 +1,196 @@-from dataclasses import dataclass+from __future__ import annotations++from dataclasses import dataclass, field+from enum import IntEnumfrom pathlib import Path-from typing import TYPE_CHECKING-if TYPE_CHECKING:- from features.ffmpeg_pack.task import FFmpegStage- from features.http_pack.task import HttpTaskStage-else:- from ffmpeg_pack.task import FFmpegStage- from http_pack.task import HttpTaskStage+from app.models.task import Task+from app.platform.filesystem import toSafeFilename+from http_pack.task import HttpTaskStep+from ffmpeg_pack.task import FFmpegStep+++class DownloadMode(IntEnum):+ VIDEO = 0+ AUDIO = 1+ COVER = 2+++@dataclass(kw_only=True, eq=False)+class BilibiliTask(Task):+ packId: str = "bili"+ canEdit = True+ coverUrl: str = ""+ coverSize: int = 0+ mode: DownloadMode = DownloadMode.VIDEO+ pages: list[dict] = field(default_factory=list)+ _baseName: str = ""++ def setMode(self, mode: DownloadMode) -> None:+ self.mode = mode+ self._rebuildSteps()++ def setPageSelection(self, selectedPageNumbers: set[int]) -> None:+ for page in self.pages:+ page["selected"] = page["pageNumber"] in selectedPageNumbers+ self._rebuildSteps()++ @property+ def selectedPages(self) -> list[dict]:+ return [p for p in self.pages if p.get("selected", True)]++ def deduplicateFilename(self) -> None:+ if len(self.selectedPages) <= 1:+ super().deduplicateFilename()+ return++ folder = self.outputFolder+ def anyOutputExists() -> bool:+ for step in self.steps:+ outputFile = getattr(step, "outputFile", "")+ if not outputFile:+ continue+ path = Path(outputFile)+ if path.exists() or Path(f"{outputFile}.ghd").exists():+ return True+ return False-def _bilibiliStem(taskTitle: str, pageSuffix: str) -> str:- baseTitle = taskTitle[:-4] if taskTitle.lower().endswith(".mp4") else taskTitle- return f"{baseTitle}{pageSuffix}" if pageSuffix else baseTitle+ if not anyOutputExists():+ return++ stem = self._baseName+ suffixes = "".join(Path(self.name).suffixes)+ index = 1+ while True:+ self._baseName = f"{stem}({index})"+ self.name = toSafeFilename(f"{self._baseName}{suffixes}", fallback=self.name)+ self._rebuildSteps()+ if not anyOutputExists():+ break+ index += 1++ def _rebuildSteps(self) -> None:+ self.steps.clear()+ selected = self.selectedPages++ if self.mode == DownloadMode.COVER:+ self.name = toSafeFilename(f"{self._baseName}.jpg", fallback="cover.jpg")+ self.fileSize = self.coverSize+ self.addStep(HttpTaskStep(+ stepIndex=1,+ url=self.coverUrl,+ fileSize=self.coverSize,+ headers={},+ canUseRangeRequests=self.coverSize > 0,+ subworkerCount=1,+ ))+ return++ if self.mode == DownloadMode.AUDIO:+ suffix = ".m4a" if len(selected) <= 1 else ".m4a"+ self.name = toSafeFilename(f"{self._baseName}{suffix}", fallback=f"audio{suffix}")+ self.fileSize = sum(p["audioSize"] for p in selected)+ for i, info in enumerate(selected):+ pageSuffix = self._pageSuffix(info)+ self.addStep(BilibiliAudioStep(+ stepIndex=i + 1,+ url=info["audioUrl"],+ fileSize=info["audioSize"],+ headers=dict(info.get("headers") or {}),+ subworkerCount=info.get("subworkerCount", 8),+ canUseRangeRequests=True,+ pageIndex=i,+ pageSuffix=pageSuffix,+ ))+ return++ # VIDEO mode+ self.name = toSafeFilename(f"{self._baseName}.mp4", fallback="video.mp4")+ self.fileSize = sum(p["videoSize"] + p["audioSize"] for p in selected)+ for i, info in enumerate(selected):+ pageSuffix = self._pageSuffix(info)+ stepBase = i * 3+ self.addStep(BilibiliVideoStep(+ stepIndex=stepBase + 1,+ url=info["videoUrl"],+ fileSize=info["videoSize"],+ headers=dict(info.get("headers") or {}),+ subworkerCount=info.get("subworkerCount", 8),+ canUseRangeRequests=True,+ pageIndex=i,+ pageSuffix=pageSuffix,+ ))+ self.addStep(BilibiliAudioStep(+ stepIndex=stepBase + 2,+ url=info["audioUrl"],+ fileSize=info["audioSize"],+ headers=dict(info.get("headers") or {}),+ subworkerCount=info.get("subworkerCount", 8),+ canUseRangeRequests=True,+ pageIndex=i,+ pageSuffix=pageSuffix,+ ))+ self.addStep(BilibiliMergeStep(+ stepIndex=stepBase + 3,+ pageIndex=i,+ pageSuffix=pageSuffix,+ ))++ def _pageSuffix(self, pageInfo: dict) -> str:+ selected = self.selectedPages+ if len(selected) <= 1:+ return ""+ suffix = f" - P{pageInfo['pageNumber']}"+ part = pageInfo.get("pagePart", "").strip()+ if part and part != self._baseName:+ suffix += f" {part}"+ return suffix+++def pageStem(taskName: str, pageSuffix: str) -> str:+ for ext in (".mp4", ".m4a", ".jpg"):+ if taskName.lower().endswith(ext):+ taskName = taskName[:-len(ext)]+ break+ return f"{taskName}{pageSuffix}" if pageSuffix else taskName@dataclass(kw_only=True)-class BilibiliVideoStage(HttpTaskStage):+class BilibiliVideoStep(HttpTaskStep):pageIndex: int = 0pageSuffix: str = ""@property- def outputFile(self) -> str:- stem = _bilibiliStem(self.task.title, self.pageSuffix)- return str(Path(self.task.path) / f"{stem}.video.m4s")+ def outputPath(self) -> str:+ return str(self.task.outputFolder / f"{pageStem(self.task.name, self.pageSuffix)}.video.m4s")@dataclass(kw_only=True)-class BilibiliAudioStage(HttpTaskStage):+class BilibiliAudioStep(HttpTaskStep):pageIndex: int = 0pageSuffix: str = ""@property- def outputFile(self) -> str:- stem = _bilibiliStem(self.task.title, self.pageSuffix)- return str(Path(self.task.path) / f"{stem}.audio.m4s")+ def outputPath(self) -> str:+ stem = pageStem(self.task.name, self.pageSuffix)+ ext = ".m4a" if self.task.mode == DownloadMode.AUDIO else ".audio.m4s"+ return str(self.task.outputFolder / f"{stem}{ext}")@dataclass(kw_only=True)-class BilibiliMergeStage(FFmpegStage):+class BilibiliMergeStep(FFmpegStep):pageIndex: int = 0pageSuffix: str = ""@property- def outputFile(self) -> Path:- stem = _bilibiliStem(self.task.title, self.pageSuffix)- return Path(self.task.path) / f"{stem}.mp4"+ def outputFile(self) -> str:+ return str(self.task.outputFolder / f"{pageStem(self.task.name, self.pageSuffix)}.mp4")@property- def videoPath(self) -> Path:- stem = _bilibiliStem(self.task.title, self.pageSuffix)- return Path(self.task.path) / f"{stem}.video.m4s"+ def _videoPath(self) -> Path:+ return self.task.outputFolder / f"{pageStem(self.task.name, self.pageSuffix)}.video.m4s"@property- def audioPath(self) -> Path:- stem = _bilibiliStem(self.task.title, self.pageSuffix)- return Path(self.task.path) / f"{stem}.audio.m4s"+ def _audioPath(self) -> Path:+ return self.task.outputFolder / f"{pageStem(self.task.name, self.pageSuffix)}.audio.m4s"diff --git a/features/bittorrent_pack/cards.py b/features/bittorrent_pack/cards.pyindex 55d9b830..f84c9766 100644--- a/features/bittorrent_pack/cards.py+++ b/features/bittorrent_pack/cards.py@@ -1,31 +1,17 @@-from pathlib import Path--from PySide6.QtCore import Qt-from PySide6.QtWidgets import (- QHBoxLayout,- QVBoxLayout,- QWidget,- QFileIconProvider,-)-from qfluentwidgets import (- BodyLabel,- CaptionLabel,- FluentIcon,- IconWidget,- PrimaryPushButton,- StrongBodyLabel,- ToolButton,-)--from app.bases.models import TaskStatus-from app.supports.utils import toReadableSize, toReadableTime-from app.view.components.cards import ResultCard, UniversalTaskCard-from app.view.components.dialogs import FileSelectDialog-from app.view.components.labels import IconBodyLabel-from .task import BTFile, BTTask---def _openFileSelection(task: BTTask, parent) -> set[int] | None:++from PySide6.QtWidgets import QFileIconProvider+from qfluentwidgets import FluentIcon, ToolButton++from app.format import toReadableSize, toReadableTime+from app.models.task import TaskStatus+from app.view.cards.draft_cards import UniversalDraftCard+from app.view.cards.task_cards import UniversalTaskCard+from app.view.dialogs.file_select import FileSelectDialog+from .session import btSession+from .task import BTTask+++def openFileSelection(task: BTTask, parent) -> set[int] | None:dialog = TorrentFileSelectDialog(task, parent)try:if not dialog.exec():@@ -38,161 +24,94 @@ def _openFileSelection(task: BTTask, parent) -> set[int] | None:class TorrentFileSelectDialog(FileSelectDialog):- def __init__(self, task: BTTask, parent=None):- super().__init__(task, parent)- self.task: BTTask = task+ def _fileDisplayPath(self, file) -> str:+ return self._task.toRelativePath(file)- def _fileDisplayPath(self, file: BTFile) -> str:- return self.task.mapPath(file)- def _fileTypePath(self, file: BTFile) -> str:- return file.path+class BTDraftCard(UniversalDraftCard):--class BitTorrentResultCard(ResultCard):- def __init__(self, task: BTTask, parent: QWidget = None):- super().__init__(task, parent)- # instant widget- self.iconLabel = IconWidget(self)- self.titleLabel = StrongBodyLabel(self.task.title, self)- self.sourceLabel = CaptionLabel(self._sourceText(), self)- self.summaryLabel = BodyLabel("", self)- self.selectFilesButton = PrimaryPushButton(self.tr("选择文件"), self)- # instant layout- self.mainLayout = QHBoxLayout(self)- self.textLayout = QVBoxLayout()-- self._initWidget()- self._initLayout()- self._bind()- self._refreshSummary()- self._renderCategoryButton()+ @property+ def task(self) -> BTTask:+ return self._taskdef _initWidget(self):- self.setFixedHeight(45)- self.iconLabel.setFixedSize(20, 20)+ super()._initWidget()icon = QFileIconProvider.IconType.File if self.task.isSingleFile else QFileIconProvider.IconType.Folder- self.iconLabel.setIcon(QFileIconProvider().icon(icon))+ self.iconLabel.setImage(QFileIconProvider().icon(icon).pixmap(16, 16))+ self.iconLabel.setFixedSize(16, 16)+ self._selectFilesButton = None+ if len(self.task.files) > 1:+ from qfluentwidgets import ToolTipFilter+ from qfluentwidgets import TransparentToolButton+ self._selectFilesButton = TransparentToolButton(FluentIcon.LIBRARY, self)+ self._selectFilesButton.setFixedSize(28, 28)+ self._selectFilesButton.setToolTip(self.tr("选择文件"))+ self._selectFilesButton.installEventFilter(ToolTipFilter(self._selectFilesButton))def _initLayout(self):- self.mainLayout.setContentsMargins(10, 6, 10, 6)- self.mainLayout.setSpacing(12)- self.textLayout.setContentsMargins(0, 0, 0, 0)- self.textLayout.setSpacing(2)- self.textLayout.addWidget(self.titleLabel)- self.textLayout.addWidget(self.sourceLabel)- self.mainLayout.addWidget(self.iconLabel, 0, Qt.AlignmentFlag.AlignCenter)- self.mainLayout.addLayout(self.textLayout)- self.mainLayout.addStretch(1)- self.mainLayout.addWidget(self.summaryLabel)- self.mainLayout.addSpacing(12)- self.mainLayout.addWidget(self.categoryButton)- self.mainLayout.addWidget(self.selectFilesButton)+ super()._initLayout()+ if self._selectFilesButton is not None:+ self.layout().addWidget(self._selectFilesButton)def _bind(self):- self.selectFilesButton.clicked.connect(self._onSelectFilesClicked)-- def _sourceText(self) -> str:- typeText = "Magnet" if self.task.sourceType == "magnet" else "Torrent"- trackerCount = len(self.task.trackers)- if trackerCount > 0:- return self.tr("{0} · {1} 个 Tracker").format(typeText, trackerCount)- return typeText+ super()._bind()+ if self._selectFilesButton is not None:+ self._selectFilesButton.clicked.connect(self._onSelectFilesClicked)def _refreshSummary(self):- self.summaryLabel.setText(+ self.sizeLabel.setText(self.tr("{0}/{1} 个文件 · {2}").format(self.task.countSelected,- self.task.countAll,+ len(self.task.files),toReadableSize(self.task.fileSize),))def _onSelectFilesClicked(self):- if _openFileSelection(self.task, self.window()) is not None:+ if openFileSelection(self.task, self.window()) is not None:self._refreshSummary()- def getTask(self) -> BTTask:- return self.task-class BTTaskCard(UniversalTaskCard):def __init__(self, task: BTTask, parent=None):super().__init__(task, parent)- self.task: BTTask = task- self.speedLabel.setIcon(FluentIcon.DOWNLOAD)- self.uploadRateLabel = IconBodyLabel("", FluentIcon.SHARE, self)- self.infoLayout.insertWidget(self.infoLayout.indexOf(self.leftTimeLabel), self.uploadRateLabel)- self.metaInfoLabel = IconBodyLabel("", FluentIcon.INFO, self)- self.infoLayout.insertWidget(self.infoLayout.indexOf(self.infoLabel), self.metaInfoLabel)self.selectFilesButton = ToolButton(FluentIcon.LIBRARY, self)- self.hBoxLayout.insertWidget(self.hBoxLayout.indexOf(self.verifyHashButton), self.selectFilesButton)+ self.hBoxLayout.insertWidget(+ self.hBoxLayout.indexOf(self.verifyHashButton),+ self.selectFilesButton,+ )self.selectFilesButton.clicked.connect(self._onSelectFilesClicked)- self._refreshInfoLayout()-- def _metaText(self) -> str:- parts: list[str] = []- if self.task.stateText and self.task.stateText not in {"下载中", "做种中"}:- parts.append(self.task.stateText)- if self.task.isSeeding and self.task.shareRatioPercent > 0:- parts.append(self.tr("分享率 {0:.2f}%").format(self.task.shareRatioPercent))- if self.task.isSeeding and self.task.seedingTimeSeconds > 0:- parts.append(self.tr("做种 {0}").format(toReadableTime(self.task.seedingTimeSeconds)))- if self.task.peerCount or self.task.seedCount:- parts.append(- self.tr("Peers {0} / Seeds {1}").format(- self.task.peerCount,- self.task.seedCount,- )- )- return " · ".join(parts)-- def _refreshInfoLayout(self):- if self.task.status == TaskStatus.RUNNING:- self.speedLabel.setText(f"{toReadableSize(self.task.downloadRate)}/s")- self.uploadRateLabel.setText(f"{toReadableSize(self.task.uploadRate)}/s")- if self.task.isSeeding:- self.leftTimeLabel.hide()- elif self.task.fileSize > 0 and self.task.downloadRate > 0:- remainingBytes = self.task.fileSize - self.task.stage.receivedBytes- self.leftTimeLabel.setText(toReadableTime(int(remainingBytes / self.task.downloadRate)))- self.leftTimeLabel.show()- else:- self.leftTimeLabel.setText("--")- self.leftTimeLabel.show()- metaText = self._metaText()- self.metaInfoLabel.setText(metaText)- self.metaInfoLabel.setVisible(bool(metaText))+ btSession.seedingUpdated.connect(self._onSeedingUpdated)++ def _refreshTransferInfo(self):+ task = self.task+ if task.status == TaskStatus.RUNNING:+ self.speedLabel.setText(f"{toReadableSize(task.downloadRate)}/s")+ if task.fileSize > 0 and task.downloadRate > 0 and not task.isSeeding:+ remaining = task.fileSize - task.step.receivedBytes+ self.etaLabel.setText(toReadableTime(int(remaining / task.downloadRate)))self.speedLabel.show()- self.uploadRateLabel.show()- self.progressLabel.show()- self.infoLabel.hide()- return+ elif task.status == TaskStatus.COMPLETED and task.isSeeding:+ parts = [f"↑ {toReadableSize(task.uploadRate)}/s"]+ parts.append(self.tr("分享率 {0}").format(f"{task.shareRatioPercent:.1f}%"))+ if task.peerCount > 0:+ parts.append(self.tr("{0} peers").format(task.peerCount))+ self.statusLabel.setText(self.tr("做种中") + " " + " ".join(parts))- self.uploadRateLabel.hide()- self.metaInfoLabel.hide()+ def _onSeedingUpdated(self):+ if self.task.status == TaskStatus.COMPLETED and self.task.isSeeding:+ self._refreshTransferInfo()def _onSelectFilesClicked(self):- previousSelected = {file.index for file in self.task.files if file.selected}- selectedIndexes = _openFileSelection(self.task, self.window())+ previousSelected = {f.index for f in self.task.files if f.selected}+ selectedIndexes = openFileSelection(self.task, self.window())if selectedIndexes is None:return-- self._refreshInfoLayout()- if self.task.status == TaskStatus.COMPLETED and selectedIndexes - previousSelected and self.task.reopen():- self.resumeTask()+ self._refreshTransferInfo()def refresh(self):super().refresh()- self._refreshInfoLayout()- self.progressBar.setVisible(self.task.status != TaskStatus.COMPLETED and not self.task.isSeeding)- self.verifyHashButton.setVisible(- self.task.isSingleFile- and self.task.status == TaskStatus.COMPLETED- and Path(self.task.outputFolder).is_file()+ self._refreshTransferInfo()+ self.selectFilesButton.setEnabled(+ self.task.status != TaskStatus.COMPLETED or any(not f.selected for f in self.task.files))- self.selectFilesButton.setEnabled(self.task.status != TaskStatus.COMPLETED or self.task.hasUnselected)-- def onTaskFinished(self):- super().onTaskFinished()- self._refreshInfoLayout()diff --git a/features/bittorrent_pack/config.py b/features/bittorrent_pack/config.pyindex 32059320..146f2efa 100644--- a/features/bittorrent_pack/config.py+++ b/features/bittorrent_pack/config.py@@ -1,246 +1,111 @@-import sys-from typing import TYPE_CHECKING+from __future__ import annotations+from app.config.cfg import ConfigItem+from app.models.pack import PackConfigfrom qfluentwidgets import (BoolValidator,- ComboBoxSettingCard,- ConfigItem,- FluentIcon,OptionsConfigItem,OptionsValidator,RangeConfigItem,- RangeSettingCard,RangeValidator,- SwitchSettingCard,)-from app.bases.models import PackConfig-from app.supports.config import StringListValidator-from app.view.components.setting_card_group import CollapsibleSettingCardGroup-from app.view.components.setting_cards import SpinBoxSettingCardfrom .web_tracker.schema import (DEFAULT_WEB_TRACKER_SOURCE,SourceCacheSerializer,SourceCacheValidator,)-if TYPE_CHECKING:- from app.view.pages.setting_page import SettingPage++class StringListValidator:+ def validate(self, value) -> bool:+ return isinstance(value, list) and all(isinstance(i, str) for i in value)++ def correct(self, value) -> list:+ if not isinstance(value, list):+ return []+ return [i for i in value if isinstance(i, str)]class BitTorrentConfig(PackConfig):+ enableDht = ConfigItem("BitTorrent", "EnableDHT", True, BoolValidator())+ enableLsd = ConfigItem("BitTorrent", "EnableLSD", True, BoolValidator())+ enableWebTrackers = ConfigItem("BitTorrent", "EnableWebTrackers", True, BoolValidator())+ autoRefreshWebTrackers = ConfigItem("BitTorrent", "AutoRefreshWebTrackers", True, BoolValidator())+ saveMagnetFile = ConfigItem("BitTorrent", "SaveMagnetTorrentFile", False, BoolValidator())+ seedingRatioLimit = RangeConfigItem("BitTorrent", "SeedRatioLimitPercent", 0, RangeValidator(0, 10000))+ seedingTimeLimit = RangeConfigItem("BitTorrent", "SeedTimeLimitMinutes", 0, RangeValidator(0, 43200))+ maxConnections = RangeConfigItem("BitTorrent", "ConnectionsLimit", 500, RangeValidator(20, 2000))+ maxUploadSpeed = RangeConfigItem("BitTorrent", "UploadRateLimit", 0, RangeValidator(0, 1024 * 1024 * 100))listenPort = RangeConfigItem("BitTorrent", "ListenPort", 0, RangeValidator(0, 65535))metadataTimeout = RangeConfigItem("BitTorrent", "MetadataTimeout", 30, RangeValidator(5, 300))- connectionsLimit = RangeConfigItem("BitTorrent", "ConnectionsLimit", 500, RangeValidator(20, 2000))- downloadRateLimit = RangeConfigItem(- "BitTorrent",- "DownloadRateLimit",- 0,- RangeValidator(0, 1024 * 1024 * 100),- )- uploadRateLimit = RangeConfigItem(- "BitTorrent",- "UploadRateLimit",- 0,- RangeValidator(0, 1024 * 1024 * 100),+ enableSequentialDownload = ConfigItem("BitTorrent", "SequentialDownload", False, BoolValidator())+ storageMode = OptionsConfigItem(+ "BitTorrent", "StorageMode", "sparse", OptionsValidator(["sparse", "allocate"]),)- sequentialDownload = ConfigItem("BitTorrent", "SequentialDownload", False, BoolValidator())- enableDHT = ConfigItem("BitTorrent", "EnableDHT", True, BoolValidator())- enableLSD = ConfigItem("BitTorrent", "EnableLSD", True, BoolValidator())- enableUPnP = ConfigItem("BitTorrent", "EnableUPnP", True, BoolValidator())- enableNATPMP = ConfigItem("BitTorrent", "EnableNATPMP", True, BoolValidator())- seedRatioLimitPercent = RangeConfigItem("BitTorrent", "SeedRatioLimitPercent", 0, RangeValidator(0, 10000))- seedTimeLimitMinutes = RangeConfigItem("BitTorrent", "SeedTimeLimitMinutes", 0, RangeValidator(0, 43200))- saveMagnetTorrentFile = ConfigItem("BitTorrent", "SaveMagnetTorrentFile", False, BoolValidator())- enableWebTrackers = ConfigItem("BitTorrent", "EnableWebTrackers", True, BoolValidator())- autoRefreshWebTrackers = ConfigItem("BitTorrent", "AutoRefreshWebTrackers", True, BoolValidator())associateFileTypes = ConfigItem("BitTorrent", "AssociateFileTypes", False, BoolValidator())webTrackerSources = ConfigItem(- "BitTorrent",- "WebTrackerSources",- [DEFAULT_WEB_TRACKER_SOURCE],- StringListValidator(),+ "BitTorrent", "WebTrackerSources", [DEFAULT_WEB_TRACKER_SOURCE], StringListValidator(),)webTrackerSourceCache = ConfigItem(- "BitTorrent",- "WebTrackerSourceCache",- {},- SourceCacheValidator(),- SourceCacheSerializer(),+ "BitTorrent", "WebTrackerSourceCache", {}, SourceCacheValidator(), SourceCacheSerializer(),)webTrackerCustomList = ConfigItem("BitTorrent", "WebTrackerCustomList", "")- storageMode = OptionsConfigItem(- "BitTorrent",- "StorageMode",- "sparse",- OptionsValidator(["sparse", "allocate"]),- )- def setupSettings(self, settingPage: "SettingPage"):+ def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:+ import sys+ from qfluentwidgets import ComboBoxSettingCard, FluentIcon, RangeSettingCard, SwitchSettingCard+ from app.view.components.setting_card_group import CollapsibleSettingCardGroup+ from app.view.components.setting_cards import SpinBoxSettingCardfrom .web_tracker.card import WebTrackerCard- self.bittorrentGroup = CollapsibleSettingCardGroup(self.tr("BitTorrent 下载"), "bittorrent", settingPage.container)- # macOS 的文件关联在构建时烘进 Info.plist, 运行时开关无意义, 不创建也不显示+ btGroup = CollapsibleSettingCardGroup(self.tr("BitTorrent 下载"), "bittorrent", parent)++ cards = []if sys.platform != "darwin":- self.associateCard = SwitchSettingCard(- FluentIcon.LINK,- self.tr("关联 .torrent 文件"),+ cards.append(SwitchSettingCard(+ FluentIcon.LINK, self.tr("关联 .torrent 文件"),self.tr("把 .torrent 文件的打开方式设为 Ghost Downloader"),- self.associateFileTypes,- self.bittorrentGroup,- )- self.bittorrentGroup.addSettingCard(self.associateCard)- self.listenPortCard = SpinBoxSettingCard(- FluentIcon.GLOBE,- self.tr("监听端口"),- self.tr("0 表示交给系统自动分配可用端口"),- "",- self.listenPort,- self.bittorrentGroup,- 1,- )- self.metadataTimeoutCard = SpinBoxSettingCard(- FluentIcon.HISTORY,- self.tr("元数据超时"),- self.tr("解析 magnet 链接时等待元数据的最长时间"),- " s",- self.metadataTimeout,- self.bittorrentGroup,- 5,- )- self.connectionsLimitCard = RangeSettingCard(- self.connectionsLimit,- FluentIcon.PEOPLE,- self.tr("连接数上限"),- self.tr("单个 BT 任务对应 session 的最大连接数"),- self.bittorrentGroup,- )- self.downloadRateLimitCard = SpinBoxSettingCard(- FluentIcon.DOWNLOAD,- self.tr("下载限速"),- self.tr("0 表示不限速,单位为 session 级别的 KB/s"),- " KB/s",- self.downloadRateLimit,- self.bittorrentGroup,- 256,- 1 / 1024,- )- self.uploadRateLimitCard = SpinBoxSettingCard(- FluentIcon.SHARE,- self.tr("上传限速"),- self.tr("0 表示不限速,单位为 session 级别的 KB/s"),- " KB/s",- self.uploadRateLimit,- self.bittorrentGroup,- 64,- 1 / 1024,- )- self.seedRatioLimitCard = SpinBoxSettingCard(- FluentIcon.SHARE,- self.tr("自动暂停做种分享率"),- self.tr("下载完成后继续做种;0 表示不按分享率自动暂停,100% 表示分享率 1.0"),- " %",- self.seedRatioLimitPercent,- self.bittorrentGroup,- 50,- )- self.seedTimeLimitCard = SpinBoxSettingCard(- FluentIcon.STOP_WATCH,- self.tr("自动暂停做种时长"),- self.tr("下载完成后继续做种;0 表示不按做种时长自动暂停"),- " min",- self.seedTimeLimitMinutes,- self.bittorrentGroup,- 10,- )- self.storageModeCard = ComboBoxSettingCard(- self.storageMode,- FluentIcon.SAVE,- self.tr("文件分配模式"),- self.tr("稀疏分配更省磁盘写入,预分配更容易提前暴露空间不足"),- texts=[self.tr("稀疏分配"), self.tr("预分配")],- parent=self.bittorrentGroup,- )- self.saveMagnetTorrentFileCard = SwitchSettingCard(- FluentIcon.SAVE,- self.tr("保存 Magnet 种子文件"),- self.tr("下载 magnet 链接时,在下载目录额外保存解析得到的 .torrent 文件"),- self.saveMagnetTorrentFile,- self.bittorrentGroup,- )- self.sequentialDownloadCard = SwitchSettingCard(- FluentIcon.LIBRARY,- self.tr("顺序下载"),- self.tr("按文件顺序下载内容,适合边下边看但通常会影响整体效率"),- self.sequentialDownload,- self.bittorrentGroup,- )- self.enableDHTCard = SwitchSettingCard(- FluentIcon.GLOBE,- self.tr("启用 DHT"),- self.tr("允许通过 DHT 网络发现 peers"),- self.enableDHT,- self.bittorrentGroup,- )- self.enableLSDCard = SwitchSettingCard(- FluentIcon.HOME,- self.tr("启用 LSD"),- self.tr("在局域网中广播并发现同一 torrent 的 peers"),- self.enableLSD,- self.bittorrentGroup,- )- self.enableUPnPCard = SwitchSettingCard(- FluentIcon.GLOBE,- self.tr("启用 UPnP"),- self.tr("允许自动尝试映射路由器端口"),- self.enableUPnP,- self.bittorrentGroup,- )- self.enableNATPMPCard = SwitchSettingCard(- FluentIcon.GLOBE,- self.tr("启用 NAT-PMP"),- self.tr("允许自动尝试通过 NAT-PMP 映射端口"),- self.enableNATPMP,- self.bittorrentGroup,- )- self.enableWebTrackersCard = SwitchSettingCard(- FluentIcon.LINK,- self.tr("启用 Web Tracker"),- self.tr("把配置好的额外 Trackers 合并到新建 BT 任务中"),- self.enableWebTrackers,- self.bittorrentGroup,- )- self.autoRefreshWebTrackersCard = SwitchSettingCard(- FluentIcon.SYNC,- self.tr("新建任务时刷新 Web Tracker"),- self.tr("创建新的 BT 任务时,先从源地址拉取最新 Tracker;失败时回退到缓存"),- self.autoRefreshWebTrackers,- self.bittorrentGroup,- )- self.webTrackerCard = WebTrackerCard(self.bittorrentGroup)-- for card in (- self.listenPortCard,- self.metadataTimeoutCard,- self.connectionsLimitCard,- self.downloadRateLimitCard,- self.uploadRateLimitCard,- self.seedRatioLimitCard,- self.seedTimeLimitCard,- self.storageModeCard,- self.saveMagnetTorrentFileCard,- self.sequentialDownloadCard,- self.enableDHTCard,- self.enableLSDCard,- self.enableUPnPCard,- self.enableNATPMPCard,- self.enableWebTrackersCard,- self.autoRefreshWebTrackersCard,- self.webTrackerCard,- ):- self.bittorrentGroup.addSettingCard(card)-- settingPage.addSettingGroup(self.bittorrentGroup)+ self.associateFileTypes, btGroup,+ ))+ cards += [+ SpinBoxSettingCard(FluentIcon.GLOBE, self.tr("监听端口"),+ self.tr("0 表示交给系统自动分配可用端口"), "", self.listenPort, btGroup, 1),+ SpinBoxSettingCard(FluentIcon.HISTORY, self.tr("元数据超时"),+ self.tr("解析 magnet 链接时等待元数据的最长时间"), " s", self.metadataTimeout, btGroup, 5),+ RangeSettingCard(self.maxConnections, FluentIcon.PEOPLE, self.tr("连接数上限"),+ self.tr("单个 BT 任务对应 session 的最大连接数"), btGroup),+ SpinBoxSettingCard(FluentIcon.SHARE, self.tr("上传限速"),+ self.tr("0 表示不限速,单位为 session 级别的 KB/s"), " KB/s",+ self.maxUploadSpeed, btGroup, 64, 1 / 1024),+ SpinBoxSettingCard(FluentIcon.SHARE, self.tr("自动暂停做种分享率"),+ self.tr("0 表示不按分享率自动暂停,100% 表示分享率 1.0"), " %",+ self.seedingRatioLimit, btGroup, 50),+ SpinBoxSettingCard(FluentIcon.STOP_WATCH, self.tr("自动暂停做种时长"),+ self.tr("0 表示不按做种时长自动暂停"), " min",+ self.seedingTimeLimit, btGroup, 10),+ ComboBoxSettingCard(self.storageMode, FluentIcon.SAVE, self.tr("文件分配模式"),+ self.tr("稀疏分配更省磁盘写入,预分配更容易提前暴露空间不足"),+ texts=[self.tr("稀疏分配"), self.tr("预分配")], parent=btGroup),+ SwitchSettingCard(FluentIcon.SAVE, self.tr("保存 Magnet 种子文件"),+ self.tr("下载 magnet 链接时额外保存 .torrent 文件"), self.saveMagnetFile, btGroup),+ SwitchSettingCard(FluentIcon.LIBRARY, self.tr("顺序下载"),+ self.tr("按文件顺序下载,适合边下边看但通常会影响整体效率"),+ self.enableSequentialDownload, btGroup),+ SwitchSettingCard(FluentIcon.GLOBE, self.tr("启用 DHT"),+ self.tr("允许通过 DHT 网络发现 peers"), self.enableDht, btGroup),+ SwitchSettingCard(FluentIcon.HOME, self.tr("启用 LSD"),+ self.tr("在局域网中广播并发现同一 torrent 的 peers"), self.enableLsd, btGroup),+ SwitchSettingCard(FluentIcon.LINK, self.tr("启用 Web Tracker"),+ self.tr("把配置好的额外 Trackers 合并到新建 BT 任务中"),+ self.enableWebTrackers, btGroup),+ SwitchSettingCard(FluentIcon.SYNC, self.tr("新建任务时刷新 Web Tracker"),+ self.tr("创建新的 BT 任务时先从源地址拉取最新 Tracker"),+ self.autoRefreshWebTrackers, btGroup),+ WebTrackerCard(btGroup),+ ]+ btGroup.addSettingCards(cards)+ return [btGroup]bittorrentConfig = BitTorrentConfig()diff --git a/features/bittorrent_pack/loaders.py b/features/bittorrent_pack/loaders.pydeleted file mode 100644index c812eec6..00000000--- a/features/bittorrent_pack/loaders.py+++ /dev/null@@ -1,154 +0,0 @@-import asyncio-from base64 import b64encode-from pathlib import Path, PurePosixPath-from typing import cast-from urllib.parse import unquote, urlparse-from urllib.request import url2pathname--import libtorrent as lt-import niquests-from loguru import logger--from app.bases.models import TaskStage-from app.supports.config import cfg, defaultHeaders-from app.supports.utils import getProxies, splitCookies, toSafeFilename-from .config import bittorrentConfig-from .session import btSessionService-from .task import BTFile, BTTask-from .trackers import mergeTrackers-from .web_tracker.service import webTrackerService---def loadLocalTorrent(source: str) -> Path | None:- text = str(source).strip()- if not text:- return None-- parsed = urlparse(text)- if parsed.scheme.lower() == "file":- location = f"//{parsed.netloc}{parsed.path}" if parsed.netloc else parsed.path- path = Path(url2pathname(unquote(location))).expanduser()- return path if path.suffix.lower() == ".torrent" else None-- if "://" in text or parsed.scheme.lower() == "magnet":- return None-- path = Path(text).expanduser()- return path if path.suffix.lower() == ".torrent" else None---async def _loadFromFile(source: str) -> tuple[bytes, lt.torrent_info]:- torrentPath = loadLocalTorrent(source)- if torrentPath is None:- raise ValueError("不是有效的本地 .torrent 文件路径")- torrentBytes = await asyncio.to_thread(torrentPath.resolve().read_bytes)- return torrentBytes, lt.torrent_info(torrentBytes)---async def _loadFromUrl(payload: dict) -> tuple[bytes, lt.torrent_info]:- url = str(payload["url"]).strip()- headers = payload.get("headers") or defaultHeaders()- proxies = payload.get("proxies", getProxies())- requestHeaders, requestCookies = splitCookies(- headers if isinstance(headers, dict) else defaultHeaders()- )-- async with niquests.AsyncSession(timeout=30, happy_eyeballs=True) as client:- client.trust_env = False- response = await client.get(- url,- headers=requestHeaders,- cookies=requestCookies,- proxies=proxies,- verify=cfg.SSLVerify.value,- allow_redirects=True,- )- response.raise_for_status()- torrentBytes = cast(bytes, response.content)-- return torrentBytes, lt.torrent_info(torrentBytes)---async def _loadFromMagnet(- payload: dict,- webTrackers: list[str],-) -> tuple[bytes, lt.torrent_info, list[str]]:- url = str(payload["url"]).strip()- return await btSessionService.resolveMetadata(url, webTrackers)---def _buildTask(- ti: lt.torrent_info,- *,- payload: dict,- sourceType: str,- sourceUrl: str,- torrentBytes: bytes,- trackers: list[str],-) -> BTTask:- files = ti.files()- entries: list[BTFile] = [- BTFile(- index=index,- path=files.file_path(index),- size=files.file_size(index),- )- for index in range(ti.num_files())- if not (files.file_flags(index) & lt.file_storage.flag_pad_file)- ]-- if not entries:- raise ValueError("该种子中没有可下载的普通文件")-- rootName = toSafeFilename(PurePosixPath(entries[0].path).parts[0], fallback="torrent")- title = toSafeFilename(Path(entries[0].path).name, fallback="torrent") if len(entries) == 1 else rootName-- return BTTask(- title=title,- url=sourceUrl,- fileSize=sum(entry.size for entry in entries),- path=Path(payload.get("path", cfg.downloadFolder.value)),- stages=[TaskStage(stageIndex=1)],- sourceType=sourceType,- torrentData=b64encode(torrentBytes).decode(),- trackers=trackers,- files=entries,- )---async def resolve(payload: dict) -> BTTask:- url = str(payload["url"]).strip()-- if bittorrentConfig.enableWebTrackers.value:- if bittorrentConfig.autoRefreshWebTrackers.value:- try:- await webTrackerService.refresh()- except Exception as e:- logger.opt(exception=e).warning("刷新 Web Tracker 失败,使用缓存 {}", repr(e))- webTrackers = webTrackerService.mergedTrackers()- else:- webTrackers = []-- # Fixes https://github.com/XiaoYouChR/Ghost-Downloader-3/issues/448- localTorrentPath = loadLocalTorrent(url)- if localTorrentPath is not None:- torrentBytes, ti = await _loadFromFile(url)- trackers = mergeTrackers(ti, webTrackers)- sourceType, sourceUrl = "torrent", str(localTorrentPath.resolve())- elif urlparse(url).scheme.lower() == "magnet":- torrentBytes, ti, trackers = await _loadFromMagnet(payload, webTrackers)- sourceType, sourceUrl = "magnet", url- else:- torrentBytes, ti = await _loadFromUrl(payload)- trackers = mergeTrackers(ti, webTrackers)- sourceType, sourceUrl = "torrent", url-- return await asyncio.to_thread(- _buildTask,- ti,- payload=payload,- sourceType=sourceType,- sourceUrl=sourceUrl,- torrentBytes=torrentBytes,- trackers=trackers,- )diff --git a/features/bittorrent_pack/metadata.py b/features/bittorrent_pack/metadata.pynew file mode 100644index 00000000..afab7be0--- /dev/null+++ b/features/bittorrent_pack/metadata.py@@ -0,0 +1,58 @@+from __future__ import annotations++import asyncio+from pathlib import Path+from tempfile import gettempdir++import libtorrent as lt++from .config import bittorrentConfig+++async def fetchTorrentBytes(magnetUri: str, webTrackers: list[str]) -> bytes:+ from .session import btSession+ btSession.open()+ session = btSession.session()++ params = lt.parse_magnet_uri(magnetUri)+ params.trackers = list(dict.fromkeys(t for g in (params.trackers, webTrackers) for t in g if t))+ tempDir = Path(gettempdir()) / "ghost_downloader_bt_metadata"+ tempDir.mkdir(parents=True, exist_ok=True)+ params.save_path = str(tempDir)+ params.storage_mode = lt.storage_mode_t.storage_mode_sparse+ params.flags |= lt.torrent_flags.default_dont_download | lt.torrent_flags.update_subscribe++ infoHash = params.info_hashes.v1 if params.ti is None else params.ti.info_hashes().v1+ if session.find_torrent(infoHash).is_valid():+ raise RuntimeError("该种子已在下载中")+ handle = session.add_torrent(params)++ handle.force_reannounce(0, -1, lt.reannounce_flags_t.ignore_min_interval)+ if bittorrentConfig.enableDht.value:+ handle.force_dht_announce()++ waiter: asyncio.Future[lt.torrent_info] = asyncio.get_running_loop().create_future()++ def onAlert(alert):+ if not hasattr(alert, "handle") or alert.handle != handle:+ return+ if isinstance(alert, lt.metadata_received_alert):+ ti = handle.torrent_file()+ if ti is not None and ti.is_valid() and not waiter.done():+ waiter.set_result(ti)+ elif isinstance(alert, (lt.metadata_failed_alert, lt.torrent_error_alert)):+ if not waiter.done():+ waiter.set_exception(RuntimeError(alert.message()))++ btSession.alertReceived.connect(onAlert)+ try:+ torrentInfo = await asyncio.wait_for(waiter, timeout=bittorrentConfig.metadataTimeout.value)+ return lt.bencode(lt.create_torrent(torrentInfo).generate())+ except asyncio.TimeoutError:+ raise TimeoutError("等待 magnet 元数据超时")+ finally:+ btSession.alertReceived.disconnect(onAlert)+ try:+ session.remove_torrent(handle)+ except Exception:+ passdiff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.pyindex 29112e51..6faa9121 100644--- a/features/bittorrent_pack/pack.py+++ b/features/bittorrent_pack/pack.py@@ -1,86 +1,144 @@+from __future__ import annotations++import asyncio+from base64 import b64encode+from pathlib import Path, PurePosixPathfrom urllib.parse import urlparse+import libtorrent as ltfrom loguru import logger-from app.bases.interfaces import FeaturePack, FileType-from app.bases.models import Task-from app.services.core_service import coreService-from app.supports import file_association-from .cards import BitTorrentResultCard, BTTaskCard-from .config import bittorrentConfig-from .loaders import loadLocalTorrent, resolve as _btResolve-from .session import btSessionService-from .web_tracker.service import webTrackerService-+from app.client import buildClient, toEmulation+from app.config.cfg import cfg+from app.models.pack import FeaturePack, TaskParser, FileType+from app.models.task import Task, TaskOptions, TaskStep+from app.platform.filesystem import localFilePath, toSafeFilename-def _isTorrentUrl(url: str) -> bool:- if loadLocalTorrent(url) is not None:- return True-- parsedUrl = urlparse(url)- scheme = parsedUrl.scheme.lower()- if scheme == "magnet":- return "xt=urn:btih:" in url.lower()- if scheme not in {"http", "https"}:- return False- return parsedUrl.path.lower().endswith(".torrent")+from .config import bittorrentConfig+from .session import btSession+from .task import BTFile, BTTask+from .web_tracker.service import trackerService-class BitTorrentPack(FeaturePack):- packId = "bt"+class TorrentParser(TaskParser):priority = 85- config = bittorrentConfig-- def setup(self, mainWindow):- if bittorrentConfig.associateFileTypes.value:- file_association.register(self.fileTypes())- bittorrentConfig.associateFileTypes.valueChanged.connect(self._onAssociationToggled)- if webTrackerService.mergedTrackers():- return+ def match(self, options: TaskOptions) -> bool:+ url = options.url.strip()+ if urlparse(url).scheme.lower() == "magnet":+ return True+ return localFilePath(url, {".torrent"}) is not None or url.lower().endswith(".torrent")++ async def parse(self, options: TaskOptions) -> Task:+ url = options.url.strip()+ outputFolder = options.outputFolder++ if bittorrentConfig.enableWebTrackers.value:+ if bittorrentConfig.autoRefreshWebTrackers.value:+ try:+ await trackerService.refresh()+ except Exception as e:+ logger.opt(exception=e).warning("刷新 Web Tracker 失败,使用缓存")+ webTrackers = trackerService.mergedTrackers()+ else:+ webTrackers = []- coreService.runCoroutine(webTrackerService.refresh(), self._onTrackersLoaded)+ localPath = localFilePath(url, {".torrent"})+ if localPath is not None:+ torrentBytes = await asyncio.to_thread(localPath.resolve().read_bytes)+ sourceType, sourceUrl = "torrent", str(localPath.resolve())- def shutdown(self):- btSessionService.shutdown()+ elif urlparse(url).scheme.lower() == "magnet":+ from .metadata import fetchTorrentBytes+ magnetTrackers = list(lt.parse_magnet_uri(url).trackers)+ torrentBytes = await fetchTorrentBytes(url, webTrackers)+ sourceType, sourceUrl = "magnet", url- def _onAssociationToggled(self, enabled: bool):- if enabled:- file_association.register(self.fileTypes())else:- file_association.unregister(self.fileTypes())+ emulation = toEmulation(+ options.clientProfile or cfg.clientProfile.value,+ options.sourceUserAgent,+ )+ client = buildClient(emulation=emulation, headers=dict(options.headers))+ try:+ response = await client.get(url)+ response.raise_for_status()+ torrentBytes = response.content+ finally:+ client.close()+ sourceType, sourceUrl = "torrent", url++ ti = lt.torrent_info(torrentBytes)+ torrentTrackers = [str(t.url).strip() for t in ti.trackers()]+ allSources = (magnetTrackers, torrentTrackers, webTrackers) if sourceType == "magnet" else (torrentTrackers, webTrackers)+ trackers = list(dict.fromkeys(t for g in allSources for t in g if t))++ fileStorage = ti.files()+ entries: list[BTFile] = [+ BTFile(+ index=i,+ relativePath=fileStorage.file_path(i),+ size=fileStorage.file_size(i),+ )+ for i in range(ti.num_files())+ if not (fileStorage.file_flags(i) & lt.file_storage.flag_pad_file)+ ]++ if not entries:+ raise ValueError("该种子中没有可下载的普通文件")++ rootName = toSafeFilename(PurePosixPath(entries[0].relativePath).parts[0], fallback="torrent")+ name = toSafeFilename(Path(entries[0].relativePath).name, fallback="torrent") if len(entries) == 1 else rootName++ task = BTTask(+ name=name,+ url=sourceUrl,+ fileSize=sum(e.size for e in entries),+ outputFolder=outputFolder,+ steps=[TaskStep(stepIndex=1)],+ sourceType=sourceType,+ torrentData=b64encode(torrentBytes).decode(),+ trackers=trackers,+ files=entries,+ )+ return task- def matches(self, url: str) -> bool:- return _isTorrentUrl(url)- async def parse(self, payload: dict) -> Task:- return await _btResolve(payload)+class BitTorrentPack(FeaturePack):+ packId = "bt"+ config = bittorrentConfig+ proxySchemes = {"socks5"}++ def parsers(self):+ return [TorrentParser()]def taskCard(self, task, parent=None):+ from .cards import BTTaskCardreturn BTTaskCard(task, parent)- def resultCard(self, task, parent=None):- return BitTorrentResultCard(task, parent)+ def draftCard(self, task, parent=None):+ from .cards import BTDraftCard+ return BTDraftCard(task, parent)++ def optionCards(self, task, parent=None):+ from app.view.components.option_cards import OutputFolderCard+ return [OutputFolderCard(parent, initial=task.outputFolder)]def fileTypes(self):return [FileType(extensions=(".torrent",),- displayName=self.tr("种子文件"),+ displayName=self.tr("BitTorrent 种子文件"),mimeType="application/x-bittorrent",icon="torrent",- )+ ),]- def _onTrackersLoaded(self, result, error: str | None):- if error:- logger.warning("初始化 Web Tracker 失败: {}", error)- return-- success, total = result- logger.info(- "已自动初始化 {} 条 Web Tracker (成功 {}/{} 个源)",- len(webTrackerService.mergedTrackers()),- success,- total,- )+ def start(self):+ from app.services.coroutine_runner import coroutineRunner+ from app.services.task_service import taskService+ coroutineRunner.submit(btSession.resumeAllSeeding(taskService.tasks))++ def stop(self):+ from app.services.coroutine_runner import coroutineRunner+ coroutineRunner.submit(btSession.close())diff --git a/features/bittorrent_pack/session.py b/features/bittorrent_pack/session.pyindex d5a66c49..934ac6e0 100644--- a/features/bittorrent_pack/session.py+++ b/features/bittorrent_pack/session.py@@ -1,199 +1,184 @@+from __future__ import annotations+import asynciofrom base64 import b64decode, b64encode-from dataclasses import dataclass, field-from pathlib import Path-from tempfile import gettempdir+from typing import TYPE_CHECKINGfrom urllib.parse import urlsplit-import libtorrent as ltfrom loguru import logger+from PySide6.QtCore import QObject, Signal-from app.services.core_service import coreService-from app.supports.config import VERSION, cfg-from app.supports.utils import getProxies-from .config import bittorrentConfig-from .task import BTTask-from .trackers import mergeTrackers--USER_AGENT = f"GhostDownloader/{VERSION} libtorrent/{lt.__version__}"--_STATE_TEXT = {- "checking_files": "校验已有文件",- "checking_resume_data": "检查续传状态",- "downloading_metadata": "获取元数据",- "downloading": "下载中",- "finished": "下载完成",- "seeding": "做种中",- "allocating": "分配文件中",- "queued_for_checking": "等待校验",-}--_ERROR_ALERTS = (- lt.file_error_alert,- lt.metadata_failed_alert,- lt.torrent_error_alert,- lt.hash_failed_alert,-)+from app.config.cfg import cfg, proxy+from .config import bittorrentConfig-@dataclass(eq=False)-class _ActiveTorrent:- task: BTTask- handle: lt.torrent_handle- done: asyncio.Future- resumeWaiter: asyncio.Future | None = None- appliedSelectionVersion: int = -1- _seedBase: int = field(init=False)- _seedStart: int | None = field(default=None, init=False)-- def __post_init__(self) -> None:- self._seedBase = self.task.seedingTimeSeconds+if TYPE_CHECKING:+ import libtorrent as lt+ from .task import BTTask- def seedingElapsed(self, isSeeding: bool, sessionSeconds: int) -> int:- if isSeeding:- if self._seedStart is None:- self._seedStart = sessionSeconds- return self._seedBase + max(0, sessionSeconds - self._seedStart)- if self._seedStart is not None:- self._seedBase += max(0, sessionSeconds - self._seedStart)- self._seedStart = None- return self._seedBase+class BTSession(QObject):+ alertReceived = Signal(object)+ seedingUpdated = Signal()-class BTSessionService:- def __init__(self) -> None:+ def __init__(self, parent=None):+ super().__init__(parent)self._session: lt.session | None = None- self._poller: asyncio.Task | None = None- self._active: dict[str, _ActiveTorrent] = {}- self._pendingMetadata: list[tuple[lt.torrent_handle, asyncio.Future]] = []- self._bind()-- def _bind(self) -> None:+ self._supervisor = None+ self._seedingTasks: dict[str, tuple[BTTask, lt.torrent_handle]] = {}+ self._resumeWaiters: dict[str, asyncio.Future] = {}for item in (- bittorrentConfig.downloadRateLimit,- bittorrentConfig.uploadRateLimit,- bittorrentConfig.connectionsLimit,- cfg.enableSpeedLimitation,+ bittorrentConfig.maxUploadSpeed,+ bittorrentConfig.maxConnections,+ cfg.isSpeedLimitEnabled,cfg.speedLimitation,):- item.valueChanged.connect(self._onLimitsChanged)-- async def lease(self, task: BTTask) -> None:- if task.countSelected <= 0:- raise RuntimeError("至少需要选择一个文件")+ item.valueChanged.connect(self._onLimitChanged)+ cfg.proxyServer.valueChanged.connect(self._onProxyChanged)- self._prepareTarget(task)- self._saveMagnetFile(task)- self._open()+ def open(self):+ if self._session is not None:+ import libtorrent as lt+ settings = self._proxySettings()+ self._session.apply_settings(+ settings or {"proxy_type": lt.proxy_type_t.none}+ )+ return+ import libtorrent as lt+ from app.config.constants import VERSION+ self._session = lt.session({+ "user_agent": f"GhostDownloader/{VERSION} libtorrent/{lt.__version__}",+ "listen_interfaces": f"0.0.0.0:{bittorrentConfig.listenPort.value}",+ "connections_limit": bittorrentConfig.maxConnections.value,+ "download_rate_limit": self._downloadLimit(),+ "upload_rate_limit": int(bittorrentConfig.maxUploadSpeed.value),+ "enable_dht": bittorrentConfig.enableDht.value,+ "enable_lsd": bittorrentConfig.enableLsd.value,+ "announce_to_all_trackers": True,+ "announce_to_all_tiers": True,+ "alert_mask": lt.alert.category_t.all_categories,+ **self._proxySettings(),+ })+ self._supervisor = asyncio.get_running_loop().create_task(self._supervise())- handle = self._addTorrent(task)- handle.resume()- self._announce(handle)+ async def close(self):+ for taskId in list(self._seedingTasks):+ await self._removeSeedingTorrent(taskId)+ if self._supervisor is not None:+ self._supervisor.cancel()+ try:+ await self._supervisor+ except asyncio.CancelledError:+ pass+ self._supervisor = None+ self._session = None- active = _ActiveTorrent(task, handle, asyncio.get_running_loop().create_future())- self._active[task.taskId] = active- try:- await active.done- finally:- await asyncio.shield(self._removeTorrent(active))+ def session(self):+ return self._session- async def resolveMetadata(- self, magnetUri: str, webTrackers: list[str]- ) -> tuple[bytes, lt.torrent_info, list[str]]:- self._open()+ # -- seeding lifecycle --- params = lt.parse_magnet_uri(magnetUri)- params.trackers = mergeTrackers(params.trackers, webTrackers)- tempDir = Path(gettempdir()) / "ghost_downloader_bt_metadata"- tempDir.mkdir(parents=True, exist_ok=True)- params.save_path = str(tempDir)- params.storage_mode = lt.storage_mode_t.storage_mode_sparse- params.flags |= lt.torrent_flags.default_dont_download | lt.torrent_flags.update_subscribe+ def registerSeeding(self, task: BTTask, handle: lt.torrent_handle) -> None:+ task.shouldSeed = True+ task.isSeeding = True+ self._seedingTasks[task.taskId] = (task, handle)- handle = self._addToSession(params)- self._announce(handle)+ def stopSeeding(self, task: BTTask) -> None:+ if task.taskId not in self._seedingTasks:+ return+ task.shouldSeed = False+ task.isSeeding = False+ task.uploadRate = 0+ task.stateText = ""+ from app.services.coroutine_runner import coroutineRunner+ coroutineRunner.submit(self._removeSeedingTorrent(task.taskId))++ def startSeeding(self, task: BTTask) -> None:+ if task.taskId in self._seedingTasks:+ return+ if not task.resumeData or self._session is None:+ return+ import libtorrent as lt+ try:+ params = lt.read_resume_data(b64decode(task.resumeData))+ params.save_path = str(task.outputFolder)+ params.flags |= lt.torrent_flags.upload_mode+ handle = self._session.add_torrent(params)+ except Exception as e:+ logger.opt(exception=e).warning("恢复做种失败 {}", task.name)+ return+ task.shouldSeed = True+ task.isSeeding = True+ self._seedingTasks[task.taskId] = (task, handle)++ async def resumeAllSeeding(self, tasks) -> None:+ from app.models.task import TaskStatus+ from .task import BTTask+ for task in tasks:+ if isinstance(task, BTTask) and task.status == TaskStatus.COMPLETED and task.shouldSeed and task.resumeData:+ self.open()+ self.startSeeding(task)++ async def _removeSeedingTorrent(self, taskId: str) -> None:+ entry = self._seedingTasks.pop(taskId, None)+ if entry is None:+ return+ task, handle = entry+ await self._saveSeedingResume(task, handle)+ try:+ self._session.remove_torrent(handle)+ except Exception:+ pass+ async def _saveSeedingResume(self, task: BTTask, handle: lt.torrent_handle) -> None:+ import libtorrent as lt+ try:+ handle.save_resume_data(+ lt.save_resume_flags_t.flush_disk_cache | lt.save_resume_flags_t.save_info_dict+ )+ except Exception:+ returnwaiter = asyncio.get_running_loop().create_future()- self._pendingMetadata.append((handle, waiter))+ self._resumeWaiters[task.taskId] = waitertry:- torrentInfo = await asyncio.wait_for(waiter, timeout=bittorrentConfig.metadataTimeout.value)- torrentBytes = lt.bencode(lt.create_torrent(torrentInfo).generate())+ await asyncio.wait_for(waiter, timeout=10)except asyncio.TimeoutError:- raise TimeoutError("等待 magnet 元数据超时")+ passfinally:- self._pendingMetadata.remove((handle, waiter))- try:- self._session.remove_torrent(handle)- except Exception:- pass+ self._resumeWaiters.pop(task.taskId, None)- return torrentBytes, torrentInfo, params.trackers.copy()+ # -- config change handlers --- def shutdown(self) -> None:+ def _onLimitChanged(self, _value=None):if self._session is None:return- try:- coreService.runBlocking(self._shutdown(), timeout=15)- except Exception as e:- logger.opt(exception=e).warning("BitTorrent session 关闭异常")-- async def _shutdown(self) -> None:- actives = list(self._active.values())- if actives:- await asyncio.gather(- *(self._saveResume(active) for active in actives),- return_exceptions=True,- )-- if self._poller is not None:- self._poller.cancel()- try:- await self._poller- except asyncio.CancelledError:- pass- self._poller = None-- session, self._session = self._session, None- if session is not None:- for active in actives:- try:- session.remove_torrent(active.handle)- except Exception:- pass- self._active.clear()+ self._session.apply_settings({+ "download_rate_limit": self._downloadLimit(),+ "upload_rate_limit": int(bittorrentConfig.maxUploadSpeed.value),+ "connections_limit": bittorrentConfig.maxConnections.value,+ })- def _open(self) -> None:+ def _onProxyChanged(self, _value=None):if self._session is None:- self._session = lt.session(self._sessionSettings())- if self._poller is None or self._poller.done():- self._poller = asyncio.get_running_loop().create_task(self._pollLoop())+ return+ import libtorrent as lt+ settings = self._proxySettings()+ self._session.apply_settings(+ settings or {"proxy_type": lt.proxy_type_t.none}+ )- def _sessionSettings(self) -> dict:- settings = {- "user_agent": USER_AGENT,- "listen_interfaces": f"0.0.0.0:{bittorrentConfig.listenPort.value}",- "connections_limit": bittorrentConfig.connectionsLimit.value,- "download_rate_limit": self._downloadLimit(),- "upload_rate_limit": bittorrentConfig.uploadRateLimit.value,- "enable_dht": bittorrentConfig.enableDHT.value,- "enable_lsd": bittorrentConfig.enableLSD.value,- "enable_upnp": bittorrentConfig.enableUPnP.value,- "enable_natpmp": bittorrentConfig.enableNATPMP.value,- "announce_to_all_trackers": True,- "announce_to_all_tiers": True,- "alert_mask": lt.alert.category_t.all_categories,- }- settings.update(self._proxySettings(getProxies()))- return settings+ def _downloadLimit(self) -> int:+ if not cfg.isSpeedLimitEnabled.value:+ return 0+ return int(cfg.speedLimitation.value)- def _proxySettings(self, proxies: dict | None) -> dict:- if not proxies:- return {}- proxyUrl = str(proxies.get("https") or proxies.get("http") or "").strip()- if not proxyUrl:+ def _proxySettings(self) -> dict:+ url = proxy()+ if not url:return {}- parsed = urlsplit(proxyUrl)- if parsed.scheme.lower() != "socks5" or not parsed.hostname or not parsed.port:+ parsed = urlsplit(url)+ import libtorrent as lt+ if parsed.scheme.lower() not in {"socks5", "socks5h"} or not parsed.hostname or not parsed.port:return {}hasCredentials = bool(parsed.username or parsed.password)return {@@ -208,260 +193,70 @@ class BTSessionService:"force_proxy": False,}- def _onLimitsChanged(self, _=None) -> None:- if self._session is None:- return- self._session.apply_settings({- "download_rate_limit": self._downloadLimit(),- "upload_rate_limit": bittorrentConfig.uploadRateLimit.value,- "connections_limit": bittorrentConfig.connectionsLimit.value,- })-- def _downloadLimit(self) -> int:- btLimit = bittorrentConfig.downloadRateLimit.value- if not cfg.enableSpeedLimitation.value:- return btLimit- globalLimit = cfg.speedLimitation.value- if btLimit <= 0:- return globalLimit- return min(btLimit, globalLimit)-- def _addTorrent(self, task: BTTask) -> lt.torrent_handle:- params = None- if task.resumeData:- try:- params = lt.read_resume_data(b64decode(task.resumeData))- except Exception as e:- logger.opt(exception=e).warning("读取 BitTorrent resume 数据失败,改用种子元数据 {}", task.title)+ # -- supervise loop --- if params is None:- params = lt.add_torrent_params()- params.ti = lt.torrent_info(b64decode(task.torrentData))- params.flags |= lt.torrent_flags.update_subscribe-- params.save_path = str(task.path)- params.storage_mode = (- lt.storage_mode_t.storage_mode_allocate- if bittorrentConfig.storageMode.value == "allocate"- else lt.storage_mode_t.storage_mode_sparse- )- params.file_priorities = task.priorities()- if bittorrentConfig.sequentialDownload.value:- params.flags |= lt.torrent_flags.sequential_download- else:- params.flags &= ~lt.torrent_flags.sequential_download- if task.trackers:- params.trackers = task.trackers.copy()-- handle = self._addToSession(params)- for file in task.files:- mappedPath = task.mapPath(file)- if mappedPath != file.path:- handle.rename_file(file.index, mappedPath)- return handle-- def _addToSession(self, params: lt.add_torrent_params) -> lt.torrent_handle:- infoHash = params.ti.info_hashes().v1 if params.ti is not None else params.info_hashes.v1- if self._session.find_torrent(infoHash).is_valid():- raise RuntimeError("该种子已在下载中")- return self._session.add_torrent(params)-- def _announce(self, handle: lt.torrent_handle) -> None:- handle.force_reannounce(0, -1, lt.reannounce_flags_t.ignore_min_interval)- if bittorrentConfig.enableDHT.value:- handle.force_dht_announce()+ async def _supervise(self):+ while self._session is not None:+ for alert in self._session.pop_alerts():+ if not self._routeSeedingAlert(alert):+ self.alertReceived.emit(alert)+ self._refreshSeedingTasks()+ await asyncio.sleep(1)- def _prepareTarget(self, task: BTTask) -> None:- target = Path(task.outputFolder)- if target.exists():- return- target.parent.mkdir(parents=True, exist_ok=True)- target.touch() if task.isSingleFile else target.mkdir()+ def _routeSeedingAlert(self, alert) -> bool:+ import libtorrent as lt+ if not hasattr(alert, "handle"):+ return False+ for taskId, (task, handle) in self._seedingTasks.items():+ if alert.handle != handle:+ continue+ if isinstance(alert, lt.save_resume_data_alert):+ task.resumeData = b64encode(lt.write_resume_data_buf(alert.params)).decode()+ waiter = self._resumeWaiters.get(taskId)+ if waiter is not None and not waiter.done():+ waiter.set_result(True)+ elif isinstance(alert, lt.save_resume_data_failed_alert):+ task.resumeData = ""+ waiter = self._resumeWaiters.get(taskId)+ if waiter is not None and not waiter.done():+ waiter.set_result(False)+ return True+ return False- def _saveMagnetFile(self, task: BTTask) -> None:- if task.sourceType != "magnet" or not bittorrentConfig.saveMagnetTorrentFile.value:+ def _refreshSeedingTasks(self) -> None:+ if not self._seedingTasks:return- try:- task.magnetTorrentPath.write_bytes(b64decode(task.torrentData))- except Exception as e:- logger.opt(exception=e).warning("保存 magnet 种子文件失败 {}", task.title)-- async def _removeTorrent(self, active: _ActiveTorrent) -> None:- await self._saveResume(active)- self._active.pop(active.task.taskId, None)- if self._session is not None:+ for taskId in list(self._seedingTasks):+ task, handle = self._seedingTasks[taskId]try:- self._session.remove_torrent(active.handle)+ status = handle.status()+ task.isSeeding = status.is_seeding+ task.uploadRate = status.upload_rate+ task.peerCount = status.num_peers+ task.seedCount = status.num_seeds+ task.stateText = "做种中" if status.is_seeding else ""+ downloaded = status.all_time_download or status.total_wanted_done or status.total_done+ task.shareRatioPercent = (status.all_time_upload / downloaded * 100) if downloaded > 0 else 0.0+ sessionSeconds = int(status.seeding_duration.total_seconds())+ task.seedingTimeSeconds = max(task.seedingTimeSeconds, sessionSeconds)+ if self._isSeedingLimitReached(task):+ logger.info("{} 自动暂停做种: 分享率 {:.2f}%, 做种时间 {}s",+ task.name, task.shareRatioPercent, task.seedingTimeSeconds)+ self.stopSeeding(task)except Exception:pass+ self.seedingUpdated.emit()- async def _saveResume(self, active: _ActiveTorrent) -> None:- if self._session is None:- active.task.resumeData = ""- return-- try:- active.handle.save_resume_data(- lt.save_resume_flags_t.flush_disk_cache | lt.save_resume_flags_t.save_info_dict- )- except Exception as e:- logger.opt(exception=e).warning("保存 BitTorrent resume 数据失败 {}", active.task.title)- active.task.resumeData = ""- return-- active.resumeWaiter = asyncio.get_running_loop().create_future()- try:- await asyncio.wait_for(active.resumeWaiter, timeout=10)- except asyncio.TimeoutError:- logger.warning("等待 BitTorrent resume 数据超时 {}", active.task.title)- active.task.resumeData = ""- finally:- active.resumeWaiter = None-- def _onResumeData(self, handle: lt.torrent_handle, resumeData: str) -> None:- active = self._activeOf(handle)- if active is None or active.resumeWaiter is None or active.resumeWaiter.done():- return- active.task.resumeData = resumeData- active.resumeWaiter.set_result(bool(resumeData))-- async def _pollLoop(self) -> None:- while self._session is not None:- try:- for alert in self._session.pop_alerts():- self._handleAlert(alert)- for active in list(self._active.values()):- self._updateTask(active)- except Exception as e:- logger.opt(exception=e).error("BitTorrent 轮询循环异常")- await asyncio.sleep(1)-- def _updateTask(self, active: _ActiveTorrent) -> None:- task = active.task- status = active.handle.status()- wasSeeding = task.isSeeding-- task.stateText = _STATE_TEXT.get(status.state.name, status.state.name)- task.peerCount = status.num_peers- task.seedCount = status.num_seeds- task.isSeeding = status.is_seeding- task.downloadRate = status.download_rate- task.uploadRate = status.upload_rate- cfg.globalSpeed += status.download_rate- task._updateSlot()-- downloaded = status.all_time_download or status.total_wanted_done or status.total_done- task.shareRatioPercent = (status.all_time_upload / downloaded * 100) if downloaded > 0 else 0.0- task.seedingTimeSeconds = active.seedingElapsed(- task.isSeeding, int(status.seeding_duration.total_seconds())- )-- self._updateStage(task, status)- task.updateProgress(active.handle.file_progress())-- if active.appliedSelectionVersion != task.fileSelectionVersion:- active.handle.prioritize_files(task.priorities())- active.appliedSelectionVersion = task.fileSelectionVersion-- if wasSeeding != task.isSeeding:- coreService.rebalance()-- if self._seedingLimitReached(task) and not active.done.done():- active.done.set_result(None)-- def _updateStage(self, task: BTTask, status: lt.torrent_status) -> None:- task.stage.speed = status.download_rate- task.stage.receivedBytes = status.total_wanted_done- if status.total_wanted > 0:- task.fileSize = status.total_wanted- task.stage.progress = status.total_wanted_done / status.total_wanted * 100- elif task.fileSize > 0:- task.stage.progress = task.stage.receivedBytes / task.fileSize * 100- else:- task.stage.progress = 0-- def _seedingLimitReached(self, task: BTTask) -> bool:+ def _isSeedingLimitReached(self, task: BTTask) -> bool:if not task.isSeeding:return False-- ratioLimit = bittorrentConfig.seedRatioLimitPercent.value+ ratioLimit = bittorrentConfig.seedingRatioLimit.valueif ratioLimit > 0 and task.shareRatioPercent >= ratioLimit:- logger.info(- "{} 自动暂停做种: 分享率达到 {:.2f}% / {}%",- task.title, task.shareRatioPercent, ratioLimit,- )return True-- timeLimitMinutes = bittorrentConfig.seedTimeLimitMinutes.value+ timeLimitMinutes = bittorrentConfig.seedingTimeLimit.valueif timeLimitMinutes > 0 and task.seedingTimeSeconds >= timeLimitMinutes * 60:- logger.info(- "{} 自动暂停做种: 做种时间达到 {} / {} 分钟",- task.title, round(task.seedingTimeSeconds / 60), timeLimitMinutes,- )return True-return False- def _handleAlert(self, alert: lt.alert) -> None:- if isinstance(alert, lt.metadata_received_alert):- self._onMetadata(alert)- return-- if isinstance(alert, lt.save_resume_data_alert):- self._onResumeData(alert.handle, b64encode(lt.write_resume_data_buf(alert.params)).decode())- return-- if isinstance(alert, lt.save_resume_data_failed_alert):- logger.warning("保存 BitTorrent resume 数据失败: {}", alert.message())- self._onResumeData(alert.handle, "")- return-- if isinstance(alert, lt.file_completed_alert):- active = self._activeOf(alert.handle)- if active is not None:- for file in active.task.files:- if file.index == alert.index:- file.completed = True- file.downloadedBytes = file.size- break- return-- if isinstance(alert, lt.fastresume_rejected_alert):- active = self._activeOf(alert.handle)- if active is not None:- active.task.resumeData = ""- logger.warning("BitTorrent fastresume 被拒绝: {}", alert.message())- return-- if isinstance(alert, _ERROR_ALERTS):- self._failTorrent(alert)-- def _onMetadata(self, alert: lt.metadata_received_alert) -> None:- for handle, waiter in self._pendingMetadata:- if handle == alert.handle and not waiter.done():- torrentInfo = handle.torrent_file()- if torrentInfo is not None and torrentInfo.is_valid():- waiter.set_result(torrentInfo)- else:- waiter.set_exception(RuntimeError("magnet 元数据无效"))- return-- def _failTorrent(self, alert: lt.alert) -> None:- active = self._activeOf(alert.handle)- if active is not None:- if not active.done.done():- active.done.set_exception(RuntimeError(alert.message()))- return- for handle, waiter in self._pendingMetadata:- if handle == alert.handle and not waiter.done():- waiter.set_exception(RuntimeError(alert.message()))- return-- def _activeOf(self, handle: lt.torrent_handle) -> _ActiveTorrent | None:- for active in self._active.values():- if active.handle == handle:- return active- return None--btSessionService = BTSessionService()+btSession = BTSession()diff --git a/features/bittorrent_pack/task.py b/features/bittorrent_pack/task.pyindex 14d68b22..efb23adb 100644--- a/features/bittorrent_pack/task.py+++ b/features/bittorrent_pack/task.py@@ -1,35 +1,56 @@+from __future__ import annotations+import asyncio+from base64 import b64decode, b64encode+from contextlib import suppressfrom dataclasses import dataclass, fieldfrom pathlib import Path, PurePosixPath+import libtorrent as ltfrom loguru import logger-from app.bases.models import Task, TaskStage, TaskStatus-from app.supports.utils import removePath, toSafeFilename+from app.models.task import Task, TaskStep, TaskFile, TaskStatus+from app.platform.filesystem import deletePath, toPosixPath+from app.services.speed_meter import speedMeter+from .config import bittorrentConfig++STATE_TEXT = {+ "checking_files": "校验已有文件",+ "checking_resume_data": "检查续传状态",+ "downloading_metadata": "获取元数据",+ "downloading": "下载中",+ "finished": "下载完成",+ "seeding": "做种中",+ "allocating": "分配文件中",+ "queued_for_checking": "等待校验",+}+ERROR_ALERTS = (+ lt.file_error_alert,+ lt.metadata_failed_alert,+ lt.torrent_error_alert,+ lt.hash_failed_alert,+)-@dataclass-class BTFile:- index: int- path: str- size: int- selected: bool = True++@dataclass(kw_only=True)+class BTFile(TaskFile):priority: int = 4- downloadedBytes: int = 0- completed: bool = Falsedef __post_init__(self):- self.path = str(PurePosixPath(str(self.path).replace("\\", "/")))+ self.relativePath = toPosixPath(self.relativePath)@dataclass(kw_only=True, eq=False)class BTTask(Task):packId: str = "bt"- sourceType: str- torrentData: str+ canEdit = True+ fileType = BTFile+ sourceType: str = "torrent"+ torrentData: str = ""resumeData: str = ""trackers: list[str] = field(default_factory=list)- files: list[BTFile] = field(default_factory=list)+ shouldSeed: bool = TrueshareRatioPercent: float = 0seedingTimeSeconds: int = 0isSeeding: bool = False@@ -40,149 +61,291 @@ class BTTask(Task):uploadRate: int = 0def __post_init__(self):- self.files = [- item if isinstance(item, BTFile) else BTFile(**item)- for item in self.files- ]- self.fileSelectionVersion = 0- self.title = toSafeFilename(self.title, fallback="torrent")+ if self.files:+ self.files = [+ item if isinstance(item, BTFile) else BTFile(**item)+ for item in self.files+ ]+ self._fileSelectionVersion = 0super().__post_init__()- self.fileSize = sum(file.size for file in self.files if file.selected)- self._updateSlot()+ self.fileSize = sum(f.size for f in self.files if f.selected)@property- def stage(self) -> TaskStage:- return self.stages[0]+ def step(self) -> TaskStep:+ return self.steps[0]@propertydef magnetTorrentPath(self) -> Path | None:if self.sourceType != "magnet":return None- return self.path / f"{self.title}.torrent"+ return self.outputFolder / f"{self.name}.torrent"@propertydef countSelected(self) -> int:- return sum(1 for file in self.files if file.selected)-- @property- def countAll(self) -> int:- return len(self.files)+ return sum(1 for f in self.files if f.selected)@propertydef isSingleFile(self) -> bool:return len(self.files) == 1- @property- def hasUnselected(self) -> bool:- return not all(file.selected for file in self.files)-- def mapPath(self, file: BTFile) -> str:+ def toRelativePath(self, file: BTFile) -> str:if self.isSingleFile:- return self.title- return str(PurePosixPath(self.title, *PurePosixPath(file.path).parts[1:]))+ return self.name+ return toPosixPath(Path(self.name, *PurePosixPath(file.relativePath).parts[1:]))def priorities(self) -> list[int]:- return [file.priority if file.selected else 0 for file in self.files]+ return [f.priority if f.selected else 0 for f in self.files]def setSelection(self, selectedIndexes: set[int]):if not selectedIndexes:raise ValueError("至少需要选择一个文件")-changed = False- for file in self.files:- selected = file.index in selectedIndexes+ for f in self.files:+ selected = f.index in selectedIndexespriority = 4 if selected else 0- if file.selected != selected or file.priority != priority:+ if f.selected != selected or f.priority != priority:changed = True- file.selected = selected- file.priority = priority+ f.selected = selected+ f.priority = priorityif not selected:- file.downloadedBytes = 0- file.completed = False-+ f.downloadedBytes = 0+ f.completed = Falseif not changed:return+ self._fileSelectionVersion += 1+ self.fileSize = sum(f.size for f in self.files if f.selected)- self.fileSelectionVersion += 1- self.fileSize = sum(file.size for file in self.files if file.selected)-- def cleanup(self):- super().cleanup()+ def deleteFiles(self):+ super().deleteFiles()if self.magnetTorrentPath is not None:- removePath(self.magnetTorrentPath)-- def reopen(self) -> bool:- if self.stage.status != TaskStatus.COMPLETED:- return False-- if not any(file.selected and not file.completed for file in self.files):- return False-- self.isSeeding = False- self._updateSlot()- self.stateText = "已添加新的下载文件"- self.stage.setStatus(TaskStatus.PAUSED)- self.stage.receivedBytes = sum(file.downloadedBytes for file in self.files if file.selected)- if self.fileSize > 0:- self.stage.progress = self.stage.receivedBytes / self.fileSize * 100- else:- self.stage.progress = 0- return True-- def updateProgress(self, fileBytes: list[int]):- for file in self.files:- if not file.selected:- file.downloadedBytes = 0- file.completed = False- continue- downloaded = fileBytes[file.index] if file.index < len(fileBytes) else 0- file.downloadedBytes = downloaded- file.completed = file.size > 0 and downloaded >= file.size+ deletePath(self.magnetTorrentPath)def reset(self) -> TaskStatus:result = super().reset()self.resumeData = ""+ self.shouldSeed = Trueself.shareRatioPercent = 0self.seedingTimeSeconds = 0self.isSeeding = False- self._updateSlot()self.stateText = ""self.peerCount = 0self.seedCount = 0self.downloadRate = 0self.uploadRate = 0- for file in self.files:- file.downloadedBytes = 0- file.completed = False+ for f in self.files:+ f.downloadedBytes = 0+ f.completed = Falsereturn result- def _updateSlot(self):- self.usesSlot = not self.isSeeding+ def _addTorrent(self, session: lt.session) -> lt.torrent_handle:+ params = None+ if self.resumeData:+ try:+ params = lt.read_resume_data(b64decode(self.resumeData))+ except Exception as e:+ logger.opt(exception=e).warning("读取 BitTorrent resume 数据失败 {}", self.name)++ if params is None:+ params = lt.add_torrent_params()+ params.ti = lt.torrent_info(b64decode(self.torrentData))+ params.flags |= lt.torrent_flags.update_subscribe++ params.save_path = str(self.outputFolder)+ params.storage_mode = (+ lt.storage_mode_t.storage_mode_allocate+ if bittorrentConfig.storageMode.value == "allocate"+ else lt.storage_mode_t.storage_mode_sparse+ )+ params.file_priorities = self.priorities()+ if bittorrentConfig.enableSequentialDownload.value:+ params.flags |= lt.torrent_flags.sequential_download+ else:+ params.flags &= ~lt.torrent_flags.sequential_download+ if self.trackers:+ params.trackers = self.trackers.copy()++ hashes = params.ti.info_hashes() if params.ti is not None else params.info_hashes+ for existing in session.get_torrents():+ eh = existing.info_hashes()+ if (hashes.has_v1() and eh.has_v1() and hashes.v1 == eh.v1) or \+ (hashes.has_v2() and eh.has_v2() and hashes.v2 == eh.v2):+ raise RuntimeError("该种子已在下载中")++ handle = session.add_torrent(params)++ for f in self.files:+ mapped = self.toRelativePath(f)+ if mapped != f.relativePath:+ handle.rename_file(f.index, mapped)++ return handleasync def run(self):- from .session import btSessionService+ from .session import btSession++ try:+ if self.countSelected <= 0:+ raise RuntimeError("至少需要选择一个文件")++ target = Path(self.outputPath)+ if not target.exists():+ target.parent.mkdir(parents=True, exist_ok=True)+ target.touch() if self.isSingleFile else target.mkdir()++ if self.sourceType == "magnet" and bittorrentConfig.saveMagnetFile.value:+ try:+ self.magnetTorrentPath.write_bytes(b64decode(self.torrentData))+ except Exception as e:+ logger.opt(exception=e).warning("保存 magnet 种子文件失败 {}", self.name)++ btSession.open()++ session = btSession.session()+ handle = self._addTorrent(session)+ except Exception as e:+ self.step.setError(e)+ raise++ handle.resume()+ handle.force_reannounce(0, -1, lt.reannounce_flags_t.ignore_min_interval)+ if bittorrentConfig.enableDht.value:+ handle.force_dht_announce()++ self._handle = handle+ self._downloadDone = asyncio.get_running_loop().create_future()+ self._resumeWaiter: asyncio.Future | None = None+ self._appliedSelectionVersion = -1+ completed = False++ btSession.alertReceived.connect(self._onAlert)+ supervisor = asyncio.create_task(self._supervise())try:- await btSessionService.lease(self)+ await self._downloadDone+ completed = True+ self.step.setStatus(TaskStatus.COMPLETED)+ self.step.progress = 100+ self.step.speed = 0+ self.downloadRate = 0+ btSession.registerSeeding(self, handle)except asyncio.CancelledError:- self.stateText = "已暂停做种" if self.isSeeding else "已暂停下载"+ self.stateText = "已暂停下载"self.isSeeding = False- self._updateSlot()- self.stage.setStatus(TaskStatus.PAUSED)- logger.info("{} 停止下载", self.title)+ self.step.setStatus(TaskStatus.PAUSED)raiseexcept Exception as e:- if not self.stage.error:- self.stage.setError(e)- logger.opt(exception=e).error("{} 下载失败", self.title)+ self.step.setError(e)raise- else:- self.isSeeding = False- self._updateSlot()- self.stateText = "已自动暂停做种"- self.stage.setStatus(TaskStatus.COMPLETED)- self.stage.progress = 100- self.stage.speed = 0-- def __hash__(self):- return hash(self.taskId)+ finally:+ btSession.alertReceived.disconnect(self._onAlert)+ supervisor.cancel()+ with suppress(asyncio.CancelledError):+ await supervisor+ if not completed:+ await asyncio.shield(self._removeTorrent(session, handle))++ async def _removeTorrent(self, session, handle):+ await self._saveResume()+ try:+ session.remove_torrent(handle)+ except Exception:+ pass++ async def _supervise(self):+ while True:+ try:+ status = self._handle.status()++ self.stateText = STATE_TEXT.get(status.state.name, status.state.name)+ self.peerCount = status.num_peers+ self.seedCount = status.num_seeds+ self.isSeeding = status.is_seeding+ self.downloadRate = status.download_rate+ self.uploadRate = status.upload_rate+ speedMeter.addSpeed(status.download_rate)++ downloaded = status.all_time_download or status.total_wanted_done or status.total_done+ self.shareRatioPercent = (status.all_time_upload / downloaded * 100) if downloaded > 0 else 0.0++ self.step.speed = status.download_rate+ self.step.receivedBytes = status.total_wanted_done+ if status.total_wanted > 0:+ self.fileSize = status.total_wanted+ self.step.progress = status.total_wanted_done / status.total_wanted * 100+ elif self.fileSize > 0:+ self.step.progress = self.step.receivedBytes / self.fileSize * 100+ else:+ self.step.progress = 0++ fileBytes = self._handle.file_progress()+ for f in self.files:+ if not f.selected:+ f.downloadedBytes = 0+ f.completed = False+ continue+ dl = fileBytes[f.index] if f.index < len(fileBytes) else 0+ f.downloadedBytes = dl+ f.completed = f.size > 0 and dl >= f.size++ if self._appliedSelectionVersion != self._fileSelectionVersion:+ self._handle.prioritize_files(self.priorities())+ self._appliedSelectionVersion = self._fileSelectionVersion++ if status.is_seeding and not self._downloadDone.done():+ self._downloadDone.set_result(None)++ except Exception as e:+ logger.opt(exception=e).error("BitTorrent 监控异常")+ await asyncio.sleep(1)++ def _onAlert(self, alert):+ if not hasattr(alert, "handle") or alert.handle != self._handle:+ return++ if isinstance(alert, lt.save_resume_data_alert):+ data = b64encode(lt.write_resume_data_buf(alert.params)).decode()+ self.resumeData = data+ if self._resumeWaiter is not None and not self._resumeWaiter.done():+ self._resumeWaiter.set_result(True)+ return++ if isinstance(alert, lt.save_resume_data_failed_alert):+ self.resumeData = ""+ if self._resumeWaiter is not None and not self._resumeWaiter.done():+ self._resumeWaiter.set_result(False)+ return++ if isinstance(alert, lt.file_completed_alert):+ for f in self.files:+ if f.index == alert.index:+ f.completed = True+ f.downloadedBytes = f.size+ break+ return++ if isinstance(alert, lt.fastresume_rejected_alert):+ self.resumeData = ""+ return++ if isinstance(alert, ERROR_ALERTS):+ if not self._downloadDone.done():+ self._downloadDone.set_exception(RuntimeError(alert.message()))++ async def _saveResume(self):+ try:+ self._handle.save_resume_data(+ lt.save_resume_flags_t.flush_disk_cache | lt.save_resume_flags_t.save_info_dict+ )+ except Exception as e:+ logger.opt(exception=e).warning("保存 BitTorrent resume 数据失败 {}", self.name)+ self.resumeData = ""+ return++ self._resumeWaiter = asyncio.get_running_loop().create_future()+ try:+ await asyncio.wait_for(self._resumeWaiter, timeout=10)+ except asyncio.TimeoutError:+ logger.warning("等待 BitTorrent resume 数据超时 {}", self.name)+ self.resumeData = ""+ finally:+ self._resumeWaiter = Nonediff --git a/features/bittorrent_pack/trackers.py b/features/bittorrent_pack/trackers.pydeleted file mode 100644index d249b0f6..00000000--- a/features/bittorrent_pack/trackers.py+++ /dev/null@@ -1,63 +0,0 @@-from collections.abc import Iterable-from urllib.parse import urlsplit--import libtorrent as lt-import niquests--from app.supports.config import cfg, defaultHeaders-from app.supports.utils import getProxies--_TRACKER_SCHEMES = {"http", "https", "udp", "ws", "wss"}---def toTrackers(source: str) -> str:- value = source.strip()- if not value:- return ""- parsed = urlsplit(value)- if parsed.scheme not in {"http", "https"} or not parsed.netloc:- return ""- return value---def parseTrackerText(text: str) -> list[str]:- return list(dict.fromkeys(- tracker for tracker in text.split()- if (parsed := urlsplit(tracker)).scheme.lower() in _TRACKER_SCHEMES and parsed.netloc- ))---def mergeTrackers(*groups: "lt.torrent_info | Iterable[str]") -> list[str]:- def _iter(group):- if isinstance(group, lt.torrent_info):- return (str(tracker.url).strip() for tracker in group.trackers())- return group-- return list(dict.fromkeys(- tracker- for group in groups- for tracker in _iter(group)- if tracker- ))---async def fetchWebTrackers(sourceUrl: str) -> list[str]:- normalizedSource = toTrackers(sourceUrl)- if not normalizedSource:- raise ValueError("Web Tracker 源地址无效")-- async with niquests.AsyncSession(headers=defaultHeaders(), timeout=30, happy_eyeballs=True) as client:- client.trust_env = False- response = await client.get(- normalizedSource,- proxies=getProxies(),- verify=cfg.SSLVerify.value,- allow_redirects=True,- )- response.raise_for_status()- trackers = parseTrackerText(response.text)-- if not trackers:- raise ValueError("Web Tracker 源没有返回有效的 Tracker")-- return trackersdiff --git a/features/bittorrent_pack/web_tracker/card.py b/features/bittorrent_pack/web_tracker/card.pyindex d4792a85..6d5a5a88 100644--- a/features/bittorrent_pack/web_tracker/card.py+++ b/features/bittorrent_pack/web_tracker/card.py@@ -7,66 +7,55 @@ from qfluentwidgets import (ToolTipFilter,)-from app.services.core_service import coreService-from .dialog import WebTrackerDialog-from .service import webTrackerService+from app.services.coroutine_runner import coroutineRunner+from ..config import bittorrentConfig+from .service import trackerServiceclass WebTrackerCard(SettingCard):-def __init__(self, parent=None):- super().__init__(- FluentIcon.GLOBE,- self.tr("Web Tracker"),- "",- parent,- )- # instant widget+ super().__init__(FluentIcon.GLOBE, self.tr("Web Tracker"), "", parent)self.manageButton = PrimaryPushButton(self.tr("管理"), self)self.refreshButton = ToolButton(FluentIcon.SYNC, self)-self._stateToolTip: StateToolTip | None = Noneself._initWidget()self._initLayout()self._bind()- def refreshContent(self) -> None:- sourceCount = len(webTrackerService.sourceUrls())- cachedTotal = len(webTrackerService.mergedTrackers())- self.setContent(- self.tr("{0} 个源 · 共 {1} 条缓存").format(sourceCount, cachedTotal)- )-- def _initWidget(self) -> None:+ def _initWidget(self):self.refreshButton.setToolTip(self.tr("刷新缓存"))self.refreshButton.installEventFilter(ToolTipFilter(self.refreshButton))self.refreshContent()- def _initLayout(self) -> None:+ def _initLayout(self):self.hBoxLayout.addWidget(self.manageButton, 0)self.hBoxLayout.addSpacing(8)self.hBoxLayout.addWidget(self.refreshButton, 0)self.hBoxLayout.addSpacing(16)- def _bind(self) -> None:+ def _bind(self):self.manageButton.clicked.connect(self._onManageClicked)- self.refreshButton.clicked.connect(self._refresh)- webTrackerService.trackersChanged.connect(self.refreshContent)+ self.refreshButton.clicked.connect(self._onRefreshClicked)++ def refreshContent(self):+ sourceCount = len(list(bittorrentConfig.webTrackerSources.value))+ cachedTotal = len(trackerService.mergedTrackers())+ self.setContent(self.tr("{0} 个源 · 共 {1} 条缓存").format(sourceCount, cachedTotal))- def _onManageClicked(self) -> None:+ def _onManageClicked(self):+ from .dialog import WebTrackerDialogdialog = WebTrackerDialog(self.window())try:if dialog.exec():- self._refresh()+ self._onRefreshClicked()finally:dialog.deleteLater()- def _refresh(self) -> None:- urls = webTrackerService.sourceUrls()+ def _onRefreshClicked(self):+ urls = list(bittorrentConfig.webTrackerSources.value)if not urls:return-self.refreshButton.setEnabled(False)self._stateToolTip = StateToolTip(self.tr("正在刷新 Web Tracker"),@@ -75,22 +64,30 @@ class WebTrackerCard(SettingCard):)self._stateToolTip.move(self._stateToolTip.getSuitablePos())self._stateToolTip.show()- coreService.runCoroutine(webTrackerService.refresh(), self._onRefreshFinished)- def _onRefreshFinished(self, result, error: str | None) -> None:+ coroutineRunner.submit(+ trackerService.refresh(),+ done=self._onRefreshDone, failed=self._onRefreshFailed,+ owner=self,+ )++ def _onRefreshDone(self, result):self.refreshButton.setEnabled(True)if self._stateToolTip is None:return+ success, total = result+ cachedTotal = len(trackerService.mergedTrackers())+ self._stateToolTip.setContent(+ self.tr("已刷新 {0}/{1} 个源,共 {2} 条 Tracker").format(success, total, cachedTotal)+ )+ self._stateToolTip.setState(True)+ self._stateToolTip = None+ self.refreshContent()- if error:- self._stateToolTip.setContent(self.tr("刷新失败: {0}").format(error))- else:- success, total = result- cachedTotal = len(webTrackerService.mergedTrackers())- self._stateToolTip.setContent(- self.tr("已刷新 {0}/{1} 个源,共 {2} 条 Tracker").format(- success, total, cachedTotal- )- )+ def _onRefreshFailed(self, error):+ self.refreshButton.setEnabled(True)+ if self._stateToolTip is None:+ return+ self._stateToolTip.setContent(self.tr("刷新失败: {0}").format(str(error)))self._stateToolTip.setState(True)self._stateToolTip = Nonediff --git a/features/bittorrent_pack/web_tracker/dialog.py b/features/bittorrent_pack/web_tracker/dialog.pyindex 9cabc938..70325873 100644--- a/features/bittorrent_pack/web_tracker/dialog.py+++ b/features/bittorrent_pack/web_tracker/dialog.py@@ -1,3 +1,5 @@+from urllib.parse import urlsplit+from PySide6.QtCore import Signalfrom PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QWidgetfrom qfluentwidgets import (@@ -6,13 +8,18 @@ from qfluentwidgets import (InfoBar,LineEdit,MessageBoxBase,- TransparentToolButton, SubtitleLabel, PrimaryPushButton,+ PrimaryPushButton,+ SubtitleLabel,+ TransparentToolButton,)+from app.config.cfg import cfgfrom app.view.components.editors import AutoSizingEdit+from ..config import bittorrentConfigfrom .schema import DEFAULT_WEB_TRACKER_SOURCE-from .service import webTrackerService-from ..trackers import parseTrackerText, toTrackers+++TRACKER_SCHEMES = {"http", "https", "udp", "ws", "wss"}class WebTrackerSourceCard(QWidget):@@ -20,79 +27,78 @@ class WebTrackerSourceCard(QWidget):def __init__(self, url: str = "", cachedCount: int | None = None, parent=None):super().__init__(parent)- # instant widgetself.urlEdit = LineEdit(self)self.statusLabel = BodyLabel(self)self.deleteButton = TransparentToolButton(FluentIcon.CLOSE, self)- # instant layoutself.hBoxLayout = QHBoxLayout(self)self._initWidget(url, cachedCount)self._initLayout()self._bind()+ @propertydef url(self) -> str:- return toTrackers(self.urlEdit.text())-- def setCachedCount(self, count: int | None) -> None:+ value = self.urlEdit.text().strip()+ if not value:+ return ""+ parsed = urlsplit(value)+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:+ return ""+ return value++ def setCachedCount(self, count: int | None):if count is None:self.statusLabel.setText(self.tr("未拉取"))else:self.statusLabel.setText(self.tr("{0} 条").format(count))- def _initWidget(self, url: str, cachedCount: int | None) -> None:+ def _initWidget(self, url: str, cachedCount: int | None):self.urlEdit.setText(url)self.urlEdit.setPlaceholderText(DEFAULT_WEB_TRACKER_SOURCE)self.setCachedCount(cachedCount)- def _initLayout(self) -> None:+ def _initLayout(self):self.hBoxLayout.setContentsMargins(0, 0, 0, 0)self.hBoxLayout.setSpacing(8)self.hBoxLayout.addWidget(self.urlEdit, 1)self.hBoxLayout.addWidget(self.statusLabel)self.hBoxLayout.addWidget(self.deleteButton)- def _bind(self) -> None:- self.urlEdit.editingFinished.connect(self._onUrlEditingFinished)- self.deleteButton.clicked.connect(self._onDeleteClicked)-- def _onUrlEditingFinished(self) -> None:- normalized = self.url()- self.setCachedCount(webTrackerService.cachedCount(normalized) if normalized else None)-- def _onDeleteClicked(self) -> None:- self.removed.emit(self)+ def _bind(self):+ self.deleteButton.clicked.connect(lambda: self.removed.emit(self))class WebTrackerDialog(MessageBoxBase):-def __init__(self, parent=None):super().__init__(parent)- # instant widgetself.sourceHeaderLabel = SubtitleLabel(self.tr("Tracker 源"), self.widget)- self.addSourceButton = PrimaryPushButton(FluentIcon.ADD, "添加", self.widget)+ self.addSourceButton = PrimaryPushButton(FluentIcon.ADD, self.tr("添加"), self.widget)self.sourceContainer = QWidget(self.widget)self.customLabel = SubtitleLabel(self.tr("自定义 Tracker"), self.widget)self.customEdit = AutoSizingEdit(self.widget)- # instant layoutself.sourceHeaderLayout = QHBoxLayout()self.sourceLayout = QVBoxLayout(self.sourceContainer)- self._sourceRows: list[WebTrackerSourceCard] = []+ self._sourceCards: list[WebTrackerSourceCard] = []self._initWidget()self._initLayout()self._bind()- def _initWidget(self) -> None:+ def _initWidget(self):self.widget.setMinimumWidth(720)self.yesButton.setText(self.tr("保存并刷新"))self.cancelButton.setText(self.tr("取消"))- self.customEdit.setPlaceholderText("每行一个 tracker URL,不会被源刷新覆盖")- self.customEdit.setPlainText("\n".join(webTrackerService.customTrackers()))- for url in webTrackerService.sourceUrls():- self._addSourceRow(url)-- def _initLayout(self) -> None:+ customText = bittorrentConfig.webTrackerCustomList.value+ customTrackers = [+ t for t in customText.split()+ if urlsplit(t).scheme.lower() in TRACKER_SCHEMES and urlsplit(t).netloc+ ]+ self.customEdit.setPlaceholderText(self.tr("每行一个 tracker URL,不会被源刷新覆盖"))+ self.customEdit.setPlainText("\n".join(customTrackers))+ for url in list(bittorrentConfig.webTrackerSources.value):+ self._addSourceCard(url)++ def _initLayout(self):self.sourceHeaderLayout.setContentsMargins(0, 0, 0, 0)self.sourceHeaderLayout.addWidget(self.sourceHeaderLabel)self.sourceHeaderLayout.addStretch(1)@@ -107,39 +113,42 @@ class WebTrackerDialog(MessageBoxBase):self.viewLayout.addWidget(self.customLabel)self.viewLayout.addWidget(self.customEdit)- def _bind(self) -> None:- self.addSourceButton.clicked.connect(self._onAddSourceClicked)+ def _bind(self):+ self.addSourceButton.clicked.connect(lambda: self._addSourceCard())def validate(self) -> bool:urls: list[str] = []- for row in self._sourceRows:- normalized = row.url()+ for card in self._sourceCards:+ normalized = card.urlif not normalized:InfoBar.error(self.tr("源地址无效"),self.tr("请输入有效的 HTTP/HTTPS 地址"),parent=self,)- row.urlEdit.setFocus()+ card.urlEdit.setFocus()return Falseurls.append(normalized)uniqueUrls = list(dict.fromkeys(urls))- webTrackerService.setSourceUrls(uniqueUrls)- webTrackerService.setCustomTrackers(parseTrackerText(self.customEdit.toPlainText()))- return True+ cfg.set(bittorrentConfig.webTrackerSources, uniqueUrls)- def _addSourceRow(self, url: str = "") -> None:- cachedCount = webTrackerService.cachedCount(url) if url else None- row = WebTrackerSourceCard(url, cachedCount, self.sourceContainer)- row.removed.connect(self._onSourceRemoved)- self.sourceLayout.addWidget(row)- self._sourceRows.append(row)-- def _onAddSourceClicked(self) -> None:- self._addSourceRow()+ customTrackers = [+ t for t in self.customEdit.toPlainText().split()+ if urlsplit(t).scheme.lower() in TRACKER_SCHEMES and urlsplit(t).netloc+ ]+ cfg.set(bittorrentConfig.webTrackerCustomList, "\n".join(customTrackers))+ return True- def _onSourceRemoved(self, row: WebTrackerSourceCard) -> None:- self._sourceRows.remove(row)- self.sourceLayout.removeWidget(row)- row.deleteLater()+ def _addSourceCard(self, url: str = ""):+ cache = dict(bittorrentConfig.webTrackerSourceCache.value)+ cachedCount = len(cache[url]) if url in cache else None+ card = WebTrackerSourceCard(url, cachedCount, self.sourceContainer)+ card.removed.connect(self._onSourceRemoved)+ self.sourceLayout.addWidget(card)+ self._sourceCards.append(card)++ def _onSourceRemoved(self, card: WebTrackerSourceCard):+ self._sourceCards.remove(card)+ self.sourceLayout.removeWidget(card)+ card.deleteLater()diff --git a/features/bittorrent_pack/web_tracker/schema.py b/features/bittorrent_pack/web_tracker/schema.pyindex 0a6c30b5..2532e6c4 100644--- a/features/bittorrent_pack/web_tracker/schema.py+++ b/features/bittorrent_pack/web_tracker/schema.py@@ -1,6 +1,6 @@-from orjson import dumps, loads-from qfluentwidgets import ConfigSerializer, ConfigValidator+import json+from qfluentwidgets import ConfigSerializer, ConfigValidatorDEFAULT_WEB_TRACKER_SOURCE = "https://cf.trackerslist.com/best.txt"@@ -9,12 +9,11 @@ class SourceCacheValidator(ConfigValidator):def validate(self, value) -> bool:if not isinstance(value, dict):return False- for url, trackers in value.items():- if not isinstance(url, str) or not isinstance(trackers, list):- return False- if not all(isinstance(tracker, str) for tracker in trackers):- return False- return True+ return all(+ isinstance(url, str) and isinstance(trackers, list)+ and all(isinstance(t, str) for t in trackers)+ for url, trackers in value.items()+ )def correct(self, value) -> dict:return value if self.validate(value) else {}@@ -22,11 +21,11 @@ class SourceCacheValidator(ConfigValidator):class SourceCacheSerializer(ConfigSerializer):def serialize(self, value: dict[str, list[str]]) -> str:- return dumps(value).decode("utf-8")+ return json.dumps(value, ensure_ascii=False)def deserialize(self, value: str) -> dict[str, list[str]]:try:- result = loads(value)+ result = json.loads(value)except (ValueError, TypeError):return {}if not isinstance(result, dict):diff --git a/features/bittorrent_pack/web_tracker/service.py b/features/bittorrent_pack/web_tracker/service.pyindex 862e938d..ecd248c3 100644--- a/features/bittorrent_pack/web_tracker/service.py+++ b/features/bittorrent_pack/web_tracker/service.py@@ -1,59 +1,62 @@+from __future__ import annotations+import asyncio+from urllib.parse import urlsplit-from PySide6.QtCore import QObject, Signal+from app.client import buildClient+from app.config.cfg import cfg-from app.supports.config import cfgfrom ..config import bittorrentConfig-from ..trackers import (- fetchWebTrackers,- mergeTrackers,- parseTrackerText,-)---class WebTrackerService(QObject):- trackersChanged = Signal()-- def sourceUrls(self) -> list[str]:- return list(bittorrentConfig.webTrackerSources.value)- def customTrackers(self) -> list[str]:- return parseTrackerText(bittorrentConfig.webTrackerCustomList.value)+TRACKER_SCHEMES = {"http", "https", "udp", "ws", "wss"}- def cachedCount(self, url: str) -> int | None:- cache = self._sourceCache()- if url not in cache:- return None- return len(cache[url])+class TrackerService:def mergedTrackers(self) -> list[str]:- cache = self._sourceCache()- return mergeTrackers(*cache.values(), self.customTrackers())-- def setSourceUrls(self, urls: list[str]) -> None:- cfg.set(bittorrentConfig.webTrackerSources, urls)- cache = self._sourceCache()- prunedCache = {url: trackers for url, trackers in cache.items() if url in urls}- if prunedCache != cache:- cfg.set(bittorrentConfig.webTrackerSourceCache, prunedCache)- self.trackersChanged.emit()-- def setCustomTrackers(self, trackers: list[str]) -> None:- cfg.set(bittorrentConfig.webTrackerCustomList, "\n".join(trackers))- self.trackersChanged.emit()+ cache = dict(bittorrentConfig.webTrackerSourceCache.value)+ customText = bittorrentConfig.webTrackerCustomList.value+ customTrackers = [+ t for t in customText.split()+ if (p := urlsplit(t)).scheme.lower() in TRACKER_SCHEMES and p.netloc+ ]+ return list(dict.fromkeys(+ tracker+ for source in (*cache.values(), customTrackers)+ for tracker in source+ if tracker+ ))async def refresh(self) -> tuple[int, int]:- urls = self.sourceUrls()+ urls = list(bittorrentConfig.webTrackerSources.value)if not urls:- self.trackersChanged.emit()return 0, 0+ async def fetchOne(sourceUrl: str) -> list[str]:+ normalized = sourceUrl.strip()+ parsed = urlsplit(normalized)+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:+ raise ValueError("Web Tracker 源地址无效")+ client = buildClient()+ try:+ response = await client.get(normalized)+ response.raise_for_status()+ text = await response.text()+ finally:+ client.close()+ trackers = [+ t for t in text.split()+ if (p := urlsplit(t)).scheme.lower() in TRACKER_SCHEMES and p.netloc+ ]+ if not trackers:+ raise ValueError("Web Tracker 源没有返回有效的 Tracker")+ return trackers+results = await asyncio.gather(- *(fetchWebTrackers(url) for url in urls),+ *(fetchOne(url) for url in urls),return_exceptions=True,)- oldCache = self._sourceCache()+ oldCache = dict(bittorrentConfig.webTrackerSourceCache.value)newCache: dict[str, list[str]] = {}successCount = 0for url, result in zip(urls, results):@@ -65,11 +68,7 @@ class WebTrackerService(QObject):successCount += 1cfg.set(bittorrentConfig.webTrackerSourceCache, newCache)- self.trackersChanged.emit()return successCount, len(urls)- def _sourceCache(self) -> dict[str, list[str]]:- return dict(bittorrentConfig.webTrackerSourceCache.value)--webTrackerService = WebTrackerService()+trackerService = TrackerService()diff --git a/features/disk_pack/pack.py b/features/disk_pack/pack.pyindex 871de128..96de8ad5 100644--- a/features/disk_pack/pack.py+++ b/features/disk_pack/pack.py@@ -1,68 +1,102 @@-from pathlib import Path+from __future__ import annotations-from app.bases.interfaces import FeaturePack-from app.supports.config import defaultHeaders-from app.supports.utils import getProxies, toPosixPath-from .task import ExtractStage, InstallStage, InstallTask+from pathlib import PurePosixPath+from urllib.parse import urlparse++from app.models.pack import FeaturePack, TaskParser+from app.models.task import BinaryInstallOptions, Task, TaskOptions+from app.platform.filesystem import toPosixPath+from .task import BinaryInstallStep, ChecksumStep, ExtractStep, InstallStep, InstallTask++ARCHIVE_SUFFIXES = (".zip", ".tar.gz")+++def isArchive(name: str) -> bool:+ lower = name.lower()+ return any(lower.endswith(suffix) for suffix in ARCHIVE_SUFFIXES)+++def assetNameFromUrl(url: str) -> str:+ return PurePosixPath(urlparse(url).path).name+++class InstallParser(TaskParser):+ priority = 55++ def match(self, options: TaskOptions) -> bool:+ return isinstance(options, BinaryInstallOptions)++ async def parse(self, options: BinaryInstallOptions) -> Task:+ from app.services.feature_service import featureService++ installFolder = options.outputFolder+ assetName = assetNameFromUrl(options.url)++ download = await featureService.parse(+ TaskOptions(url=options.url, outputFolder=installFolder)+ )+ downloadStep = download.steps[0]++ archive = isArchive(assetName)+ if archive:+ targetPath = toPosixPath(installFolder / assetName)+ else:+ binaryName = options.executableNames[0] if options.executableNames else assetName+ targetPath = toPosixPath(installFolder / binaryName)+ downloadStep.outputFile = targetPath++ task = InstallTask(+ name=options.name or assetName,+ url=options.url,+ packId="disk",+ fileSize=download.fileSize,+ outputFolder=installFolder,+ installFolder=str(installFolder),+ )+ stepIndex = 1+ downloadStep.stepIndex = stepIndex+ task.addStep(downloadStep)+ stepIndex += 1++ if options.sha256Url:+ checksumDownload = await featureService.parse(+ TaskOptions(url=options.sha256Url, outputFolder=installFolder)+ )+ checksumStep = checksumDownload.steps[0]+ sha256Path = toPosixPath(installFolder / assetNameFromUrl(options.sha256Url))+ checksumStep.outputFile = sha256Path+ checksumStep.stepIndex = stepIndex+ task.addStep(checksumStep)+ stepIndex += 1+ task.addStep(ChecksumStep(+ stepIndex=stepIndex, targetFile=targetPath, sha256File=sha256Path,+ ))+ stepIndex += 1++ if archive:+ extractFolder = toPosixPath(installFolder / ".extracting")+ task.addStep(ExtractStep(+ stepIndex=stepIndex,+ archivePath=targetPath,+ outputFolder=extractFolder,+ archiveSize=download.fileSize,+ ))+ stepIndex += 1+ task.addStep(InstallStep(+ stepIndex=stepIndex,+ sourceFolder=extractFolder,+ installFolder=toPosixPath(installFolder),+ archivePath=targetPath,+ executableNames=list(options.executableNames),+ ))+ else:+ task.addStep(BinaryInstallStep(stepIndex=stepIndex, binaryPath=targetPath))++ return taskclass DiskPack(FeaturePack):packId = "disk"--async def buildToolInstallTask(- *,- packId: str,- title: str,- downloadUrl: str,- fallbackAssetName: str,- fallbackSize: int,- installFolder: Path,- executableNames: list[str],- headers: dict[str, str] | None = None,-) -> InstallTask:- from app.services.feature_service import featureService-- downloadPayload = {- "url": downloadUrl,- "headers": (headers or defaultHeaders()).copy(),- "proxies": getProxies(),- "path": installFolder,- }- downloadTask = await featureService.parse(downloadPayload)- if not downloadTask.stages:- raise RuntimeError(f"解析 {fallbackAssetName} 下载链接后未获取到下载阶段")-- downloadStage = downloadTask.stages[0]- archiveSize = downloadTask.fileSize if downloadTask.fileSize > 0 else fallbackSize- assetName = downloadTask.title or fallbackAssetName- archivePath = toPosixPath(installFolder / assetName)-- downloadStage.stageIndex = 1- downloadStage.outputFile = archivePath-- task = InstallTask(- title=title,- url=downloadTask.url,- packId=packId,- fileSize=archiveSize,- path=installFolder,- usesSlot=False,- installFolder=str(installFolder),- )- extractDir = toPosixPath(installFolder / ".extracting")- task.addStage(downloadStage)- task.addStage(ExtractStage(- stageIndex=2,- archivePath=archivePath,- outputFolder=extractDir,- archiveSize=archiveSize,- ))- task.addStage(InstallStage(- stageIndex=3,- sourceDir=extractDir,- installFolder=toPosixPath(installFolder),- archivePath=archivePath,- executableNames=executableNames,- ))- return task+ def parsers(self):+ return [InstallParser()]diff --git a/features/disk_pack/task.py b/features/disk_pack/task.pyindex 4d2e0481..4dbbc8bc 100644--- a/features/disk_pack/task.py+++ b/features/disk_pack/task.py@@ -1,4 +1,8 @@+from __future__ import annotations+import asyncio+from asyncio import CancelledError+import hashlibimport shutilimport sysimport tarfile@@ -7,174 +11,153 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom time import perf_counter-from app.bases.interfaces import Worker-from app.bases.models import Task, TaskStage, TaskStatus-from app.supports.utils import removePath+from app.models.task import Task, TaskStep, TaskStatus+from app.platform.filesystem import deletePath++CHUNK_SIZE = 1 << 20+++# Disabled: our own HTTP client doesn't set com.apple.quarantine, so for one-click+# install this is a no-op. Kept (commented) in case a future install source is+# quarantined (e.g. a user-supplied, browser-downloaded archive). To re-enable,+# uncomment this plus the two call sites below and restore `import os` / suppress.+# def removeQuarantine(path: Path) -> None:+# if sys.platform != "darwin":+# return+# with suppress(OSError):+# os.removexattr(str(path), "com.apple.quarantine")@dataclass(kw_only=True, eq=False)class InstallTask(Task):+ hasOutputFile = FalseinstallFolder: str = ""- def cleanup(self):- # 装好的工具产物散在 installFolder 各处, 不能只删 archive — 整个目录端掉+ @property+ def canPause(self) -> bool:+ return False++ def deleteFiles(self):if self.installFolder:- removePath(Path(self.installFolder))+ deletePath(Path(self.installFolder))return- super().cleanup()---_CHUNK_SIZE = 1 << 20+ super().deleteFiles()@dataclass(kw_only=True)-class ExtractStage(TaskStage):- workerType: type = field(init=False, repr=False)- canPause: bool = field(init=False, default=False)+class ExtractStep(TaskStep):+ canPause = FalsearchivePath: stroutputFolder: strarchiveSize: int = 0--async def _extractZip(archive: Path, outputFolder: Path, stage: ExtractStage):- with zipfile.ZipFile(archive) as zf:- files = [info for info in zf.infolist() if not info.is_dir()]- totalSize = sum(info.file_size for info in files)- stage.task.fileSize = max(stage.archiveSize + totalSize, stage.archiveSize)-- safeRoot = outputFolder.resolve()- extractedBytes = speedBytes = 0- speedTime = perf_counter()- for info in files:- # 防 zip-slip:archive 里若含 "../" 路径会让文件落到 outputFolder 之外- memberPath = (outputFolder / info.filename).resolve()- if safeRoot not in {memberPath, *memberPath.parents}:- raise RuntimeError(f"压缩包包含非法路径: {info.filename}")- memberPath.parent.mkdir(parents=True, exist_ok=True)- with zf.open(info, "r") as source, open(memberPath, "wb") as target:- while chunk := source.read(_CHUNK_SIZE):- target.write(chunk)- extractedBytes += len(chunk)- stage.receivedBytes = extractedBytes- if totalSize > 0:- stage.progress = min(99.5, extractedBytes / totalSize * 100)- now = perf_counter()- if now - speedTime >= 0.5:- stage.speed = int((extractedBytes - speedBytes) / (now - speedTime))- speedBytes, speedTime = extractedBytes, now- await asyncio.sleep(0)---async def _extractTar(archive: Path, outputFolder: Path, stage: ExtractStage):- with tarfile.open(archive, "r:*") as tf:- files = [m for m in tf.getmembers() if m.isfile()]- totalSize = sum(m.size for m in files)- stage.task.fileSize = max(stage.archiveSize + totalSize, stage.archiveSize)-- safeRoot = outputFolder.resolve()- extractedBytes = speedBytes = 0- speedTime = perf_counter()- for member in files:- # 防 tar-slip:archive 里若含 "../" 路径会让文件落到 outputFolder 之外- memberPath = (outputFolder / member.name).resolve()- if safeRoot not in {memberPath, *memberPath.parents}:- raise RuntimeError(f"压缩包包含非法路径: {member.name}")- memberPath.parent.mkdir(parents=True, exist_ok=True)- source = tf.extractfile(member)- if source is None:- continue- with source, open(memberPath, "wb") as target:- while chunk := source.read(_CHUNK_SIZE):- target.write(chunk)- extractedBytes += len(chunk)- stage.receivedBytes = extractedBytes- if totalSize > 0:- stage.progress = min(99.5, extractedBytes / totalSize * 100)- now = perf_counter()- if now - speedTime >= 0.5:- stage.speed = int((extractedBytes - speedBytes) / (now - speedTime))- speedBytes, speedTime = extractedBytes, now- await asyncio.sleep(0)---class ExtractWorker(Worker):- def __init__(self, stage: ExtractStage):- super().__init__(stage)- self.stage = stage-- async def run(self):- archive = Path(self.stage.archivePath)- if not archive.is_file():- raise FileNotFoundError(f"未找到安装包: {archive}")-- outputFolder = Path(self.stage.outputFolder)-+ async def _extractZip(self, archive: Path, outputFolder: Path):+ with zipfile.ZipFile(archive) as zf:+ files = [info for info in zf.infolist() if not info.is_dir()]+ totalSize = sum(info.file_size for info in files)+ self.task.fileSize = max(self.archiveSize + totalSize, self.archiveSize)++ safeRoot = outputFolder.resolve()+ extractedBytes = speedBytes = 0+ speedTime = perf_counter()+ for info in files:+ memberPath = (outputFolder / info.filename).resolve()+ if safeRoot not in {memberPath, *memberPath.parents}:+ raise RuntimeError(f"压缩包包含非法路径: {info.filename}")+ memberPath.parent.mkdir(parents=True, exist_ok=True)+ with zf.open(info, "r") as source, open(memberPath, "wb") as target:+ while chunk := source.read(CHUNK_SIZE):+ target.write(chunk)+ extractedBytes += len(chunk)+ self.receivedBytes = extractedBytes+ if totalSize > 0:+ self.progress = min(99.5, extractedBytes / totalSize * 100)+ now = perf_counter()+ if now - speedTime >= 0.5:+ self.speed = int((extractedBytes - speedBytes) / (now - speedTime))+ speedBytes, speedTime = extractedBytes, now+ await asyncio.sleep(0)++ async def _extractTar(self, archive: Path, outputFolder: Path):+ with tarfile.open(archive, "r:*") as tf:+ files = [m for m in tf.getmembers() if m.isfile()]+ totalSize = sum(m.size for m in files)+ self.task.fileSize = max(self.archiveSize + totalSize, self.archiveSize)++ safeRoot = outputFolder.resolve()+ extractedBytes = speedBytes = 0+ speedTime = perf_counter()+ for member in files:+ memberPath = (outputFolder / member.name).resolve()+ if safeRoot not in {memberPath, *memberPath.parents}:+ raise RuntimeError(f"压缩包包含非法路径: {member.name}")+ memberPath.parent.mkdir(parents=True, exist_ok=True)+ source = tf.extractfile(member)+ if source is None:+ continue+ with source, open(memberPath, "wb") as target:+ while chunk := source.read(CHUNK_SIZE):+ target.write(chunk)+ extractedBytes += len(chunk)+ self.receivedBytes = extractedBytes+ if totalSize > 0:+ self.progress = min(99.5, extractedBytes / totalSize * 100)+ now = perf_counter()+ if now - speedTime >= 0.5:+ self.speed = int((extractedBytes - speedBytes) / (now - speedTime))+ speedBytes, speedTime = extractedBytes, now+ await asyncio.sleep(0)++ async def run(self) -> None:try:- self.stage.progress = 0- self.stage.speed = 0- self.stage.receivedBytes = 0-+ archive = Path(self.archivePath)+ if not archive.is_file():+ raise FileNotFoundError(f"未找到安装包: {archive}")++ outputFolder = Path(self.outputFolder)+ self.progress = 0+ self.speed = 0+ self.receivedBytes = 0outputFolder.mkdir(parents=True, exist_ok=True)lowered = archive.name.lower()if lowered.endswith(".tar.gz"):- await _extractTar(archive, outputFolder, self.stage)+ await self._extractTar(archive, outputFolder)elif lowered.endswith(".zip"):- await _extractZip(archive, outputFolder, self.stage)+ await self._extractZip(archive, outputFolder)else:raise RuntimeError(f"不支持的压缩包格式: {archive.name}")- self.stage.setStatus(TaskStatus.COMPLETED)- except asyncio.CancelledError:- self.stage.setStatus(TaskStatus.PAUSED)+ self.setStatus(TaskStatus.COMPLETED)+ except CancelledError:+ self.setStatus(TaskStatus.PAUSED)raiseexcept Exception as e:- self.stage.setError(e)+ self.setError(e)raise-ExtractStage.workerType = ExtractWorker--@dataclass(kw_only=True)-class InstallStage(TaskStage):- workerType: type = field(init=False, repr=False)- canPause: bool = field(init=False, default=False)+class InstallStep(TaskStep):+ canPause = False- sourceDir: str+ sourceFolder: strinstallFolder: strarchivePath: str = ""- cleanup: bool = True+ shouldDeleteSource: bool = TrueexecutableNames: list[str] = field(default_factory=list)--def _executablePath(root: Path, name: str) -> Path:- for candidate in (root / "bin" / name, root / name):- if candidate.is_file():- return candidate- found = next((c for c in root.rglob(name) if c.is_file()), None)- if found is None:- raise RuntimeError(f"安装包解压完成,但未找到可执行文件: {name}")- return found---class InstallWorker(Worker):- def __init__(self, stage: InstallStage):- super().__init__(stage)- self.stage = stage-- async def run(self):- sourceDir = Path(self.stage.sourceDir)- installDir = Path(self.stage.installFolder)- archive = Path(self.stage.archivePath) if self.stage.archivePath else None+ async def run(self) -> None:+ sourceFolder = Path(self.sourceFolder)+ installFolder = Path(self.installFolder)+ archive = Path(self.archivePath) if self.archivePath else Nonetry:- # archive 和 sourceDir 都可能位于 installDir 内,清空时必须保留- preserve = {sourceDir.name}- if archive is not None and archive.parent == installDir:+ preserve = {sourceFolder.name}+ if archive is not None and archive.parent == installFolder:preserve.add(archive.name)- for child in installDir.iterdir():+ for child in installFolder.iterdir():if child.name in preserve:continueif child.is_dir() and not child.is_symlink():@@ -182,34 +165,83 @@ class InstallWorker(Worker):else:child.unlink(missing_ok=True)- # archive 常把内容包在一个顶层版本目录里(如 ffmpeg-7.0/),跳过它直接移内层- children = list(sourceDir.iterdir())- contentRoot = children[0] if len(children) == 1 and children[0].is_dir() else sourceDir+ children = list(sourceFolder.iterdir())+ contentRoot = children[0] if len(children) == 1 and children[0].is_dir() else sourceFolderfor child in list(contentRoot.iterdir()):- shutil.move(str(child), str(installDir / child.name))-- executables: dict[str, Path] = {- name: _executablePath(installDir, name)- for name in self.stage.executableNames- }- if sys.platform != "win32":- for path in executables.values():- path.chmod(path.stat().st_mode | 0o755)-- if self.stage.cleanup and archive is not None and archive.exists():+ shutil.move(str(child), str(installFolder / child.name))++ for name in self.executableNames:+ executable = None+ for candidate in (installFolder / "bin" / name, installFolder / name):+ if candidate.is_file():+ executable = candidate+ break+ if executable is None:+ executable = next((c for c in installFolder.rglob(name) if c.is_file()), None)+ if executable is None:+ raise RuntimeError(f"安装包解压完成,但未找到可执行文件: {name}")+ if sys.platform != "win32":+ executable.chmod(executable.stat().st_mode | 0o755)+ # removeQuarantine(executable) # disabled — see removeQuarantine note++ if self.shouldDeleteSource and archive is not None and archive.exists():archive.unlink()- self.stage.setStatus(TaskStatus.COMPLETED)- except asyncio.CancelledError:- self.stage.setStatus(TaskStatus.PAUSED)- raise+ self.setStatus(TaskStatus.COMPLETED)except Exception as e:- self.stage.setError(e)+ self.setError(e)raisefinally:- if self.stage.cleanup and sourceDir.exists():- shutil.rmtree(sourceDir, ignore_errors=True)+ if self.shouldDeleteSource and sourceFolder.exists():+ shutil.rmtree(sourceFolder, ignore_errors=True)+++@dataclass(kw_only=True)+class ChecksumStep(TaskStep):+ canPause = False++ targetFile: str+ sha256File: str++ async def run(self) -> None:+ try:+ text = Path(self.sha256File).read_text(encoding="utf-8", errors="ignore").strip()+ expected = text.split()[0].lower() if text else ""+ if not expected:+ raise RuntimeError(f"未能从校验文件读取 SHA256: {self.sha256File}")+ actual = await asyncio.to_thread(self._sha256, Path(self.targetFile))+ if expected != actual:+ raise RuntimeError(f"SHA256 校验失败: 期望 {expected}, 实际 {actual}")+ deletePath(Path(self.sha256File))+ self.setStatus(TaskStatus.COMPLETED)+ except Exception as e:+ self.setError(e)+ raise++ def _sha256(self, path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as file:+ for chunk in iter(lambda: file.read(CHUNK_SIZE), b""):+ digest.update(chunk)+ return digest.hexdigest().lower()+++@dataclass(kw_only=True)+class BinaryInstallStep(TaskStep):+ canPause = False+ binaryPath: str-InstallStage.workerType = InstallWorker+ async def run(self) -> None:+ try:+ path = Path(self.binaryPath)+ if not path.is_file():+ raise FileNotFoundError(f"未找到已下载的可执行文件: {path}")+ if sys.platform != "win32":+ path.chmod(path.stat().st_mode | 0o755)+ # removeQuarantine(path) # disabled — see removeQuarantine note+ self.setStatus(TaskStatus.COMPLETED)+ except Exception as e:+ self.setError(e)+ raisediff --git a/features/ed2k_pack/config.py b/features/ed2k_pack/config.pynew file mode 100644index 00000000..674800b4--- /dev/null+++ b/features/ed2k_pack/config.py@@ -0,0 +1,130 @@+from __future__ import annotations++import platform+import sys+from pathlib import Path++from app.config.cfg import cfg+from app.config.paths import APP_DATA_DIR+from app.models.pack import BinaryRuntime, PackConfig+from app.platform.filesystem import findExecutable, toPosixPath+from qfluentwidgets import ConfigItem, BoolValidator, RangeConfigItem, RangeValidator++RELEASE_API = "https://api.github.com/repos/XiaoYouChR/Python-eD2k/releases/latest"+RELEASE_HEADERS = {"accept": "application/vnd.github+json"}+++class ED2kConfig(PackConfig):+ installFolder = ConfigItem("ED2k", "InstallFolder", f"{APP_DATA_DIR}/goed2kd")+ enableDht = ConfigItem("ED2k", "EnableDHT", True, BoolValidator())+ enableUpnp = ConfigItem("ED2k", "EnableUPnP", True, BoolValidator())+ listenPort = RangeConfigItem("ED2k", "ListenPort", 0, RangeValidator(0, 65535))+ serverMetSource = ConfigItem("ED2k", "ServerMetSource", "")+ nodesDatSource = ConfigItem("ED2k", "NodesDatSource", "")++ def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:+ from qfluentwidgets import FluentIcon, SwitchSettingCard+ from app.view.components.setting_card_group import CollapsibleSettingCardGroup+ from app.view.components.setting_cards import SelectFolderSettingCard, RuntimeCard, SpinBoxSettingCard++ group = CollapsibleSettingCardGroup(self.tr("eD2k 下载"), "ed2k", parent)+ installFolderCard = SelectFolderSettingCard(+ ed2kConfig.installFolder, f"{APP_DATA_DIR}/goed2kd",+ self.tr("goed2kd 安装目录"),+ group,+ )+ runtimeCard = RuntimeCard(ed2kRuntime, group)++ installFolderCard.pathChanged.connect(runtimeCard._onInstallFolderChanged)+ group.addSettingCards([+ installFolderCard,+ runtimeCard,+ SwitchSettingCard(+ FluentIcon.WIFI, self.tr("启用 DHT"),+ self.tr("通过分布式哈希表查找节点,关闭后仅使用 eD2k 服务器"),+ self.enableDht, group,+ ),+ SwitchSettingCard(+ FluentIcon.GLOBE, self.tr("启用 UPnP"),+ self.tr("自动配置路由器端口转发"),+ self.enableUpnp, group,+ ),+ SpinBoxSettingCard(+ FluentIcon.LINK, self.tr("监听端口"),+ self.tr("0 表示交给系统自动分配可用端口"), "",+ self.listenPort, group, 1,+ ),+ ])+ runtimeCard.refreshStatus()+ return [group]+++ed2kConfig = ED2kConfig()+++class ED2kRuntime(BinaryRuntime):+ name = "goed2kd"+ canInstall = True++ def path(self) -> str:+ return findExecutable(Path(ed2kConfig.installFolder.value), "goed2kd")++ async def installTask(self):+ from app.client import buildClient+ from app.update import Release+ from http_pack.task import HttpTaskStep+ from disk_pack.task import InstallTask+ from .task import ED2kInstallStep++ client = buildClient(headers=RELEASE_HEADERS)+ try:+ response = await client.get(RELEASE_API)+ response.raise_for_status()+ release = Release.fromResponse(await response.json())+ finally:+ client.close()++ assetName = _assetName()+ asset = next((a for a in release.assets if a.name == assetName), None)+ if asset is None:+ raise RuntimeError(f"未找到适配当前平台的 goed2kd: {assetName}")+ if not asset.downloadUrl or asset.size <= 0:+ raise RuntimeError("GitHub Release 返回了不完整的安装包信息")++ installFolder = Path(ed2kConfig.installFolder.value)+ binaryName = "goed2kd.exe" if sys.platform == "win32" else "goed2kd"+ binaryPath = toPosixPath(installFolder / binaryName)++ task = InstallTask(+ name=f"goed2kd 安装 ({assetName})",+ url=asset.downloadUrl,+ packId="ed2k",+ fileSize=asset.size,+ outputFolder=installFolder,+ installFolder=str(installFolder),+ )+ task.addStep(HttpTaskStep(+ stepIndex=1,+ url=asset.downloadUrl,+ fileSize=asset.size,+ headers=dict(cfg.defaultRequestHeaders.value),+ subworkerCount=cfg.preBlockNum.value,+ canUseRangeRequests=True,+ outputFile=binaryPath,+ ))+ task.addStep(ED2kInstallStep(stepIndex=2, binaryPath=binaryPath))+ return task+++def _assetName() -> str:+ machine = platform.machine().lower()+ arch = "arm64" if machine in {"arm64", "aarch64"} else "amd64"+ if sys.platform == "win32":+ return f"goed2kd-windows-{arch}.exe"+ elif sys.platform == "darwin":+ return f"goed2kd-darwin-{arch}"+ else:+ return f"goed2kd-linux-{arch}"+++ed2kRuntime = ED2kRuntime()diff --git a/features/ed2k_pack/manifest.toml b/features/ed2k_pack/manifest.tomlnew file mode 100644index 00000000..86e7c35b--- /dev/null+++ b/features/ed2k_pack/manifest.toml@@ -0,0 +1,3 @@+[pack]+entry = "pack.py"+dependencies = ["disk_pack"]diff --git a/features/ed2k_pack/pack.py b/features/ed2k_pack/pack.pynew file mode 100644index 00000000..4f6a28f5--- /dev/null+++ b/features/ed2k_pack/pack.py@@ -0,0 +1,43 @@+from __future__ import annotations++from app.models.pack import FeaturePack, TaskParser+from app.models.task import Task, TaskOptions+from app.platform.filesystem import toSafeFilename+from .config import ed2kConfig+from .task import ED2kTask, ED2kTaskStep, parseEd2kLink+++class ED2kParser(TaskParser):+ priority = 45++ def match(self, options: TaskOptions) -> bool:+ return options.url.strip().lower().startswith("ed2k://")++ async def parse(self, options: TaskOptions) -> Task:+ link = options.url.strip()+ name, fileSize, _ = parseEd2kLink(link)+ name = toSafeFilename(name, fallback="ed2k_download")++ task = ED2kTask(+ name=name,+ url=link,+ fileSize=fileSize,+ outputFolder=options.outputFolder,+ )+ task.addStep(ED2kTaskStep(stepIndex=1))+ return task+++class ED2kPack(FeaturePack):+ packId = "ed2k"+ config = ed2kConfig++ def parsers(self):+ return [ED2kParser()]++ def stop(self):+ from .session import ed2kSession+ if ed2kSession._client is None:+ return+ from app.services.coroutine_runner import coroutineRunner+ coroutineRunner.submit(ed2kSession.close())diff --git a/features/ed2k_pack/python_ed2k/__init__.py b/features/ed2k_pack/python_ed2k/__init__.pynew file mode 100644index 00000000..738568e5--- /dev/null+++ b/features/ed2k_pack/python_ed2k/__init__.py@@ -0,0 +1,15 @@+from .client import Client+from .errors import EngineExited, Error, ErrorCode, ProtocolError+from .models import Settings, Snapshot, Transfer, TransferState++__all__ = [+ "Client",+ "EngineExited",+ "Error",+ "ErrorCode",+ "ProtocolError",+ "Settings",+ "Snapshot",+ "Transfer",+ "TransferState",+]diff --git a/features/ed2k_pack/python_ed2k/client.py b/features/ed2k_pack/python_ed2k/client.pynew file mode 100644index 00000000..6e162e9b--- /dev/null+++ b/features/ed2k_pack/python_ed2k/client.py@@ -0,0 +1,291 @@+import asyncio+import json+from collections import deque+from collections.abc import AsyncIterator, Mapping+from pathlib import Path+from typing import Any++from .errors import EngineExited, Error, ErrorCode, ProtocolError+from .models import Settings, Snapshot, Transfer, TransferState+++RPC_VERSION = 1+STREAM_LIMIT = 4 * 1024 * 1024+++class Client:+ def __init__(self, executable: Path, dataDir: Path) -> None:+ self._executable = executable+ self._dataDir = dataDir+ self._loop: asyncio.AbstractEventLoop | None = None+ self._process: asyncio.subprocess.Process | None = None+ self._writeLock: asyncio.Lock | None = None+ self._pending: dict[int, asyncio.Future[Any]] = {}+ self._tasks: set[asyncio.Task[None]] = set()+ self._nextId = 1+ self._stderr: deque[str] = deque(maxlen=20)+ self._closing = False+ self._stopped = True+ self._latest: Snapshot | None = None+ self._snapshotVersion = 0+ self._snapshotCondition = asyncio.Condition()+ self._exitError: Error | None = None++ async def start(self, settings: Settings = Settings()) -> Snapshot:+ loop = asyncio.get_running_loop()+ if self._loop is None:+ self._loop = loop+ elif self._loop is not loop:+ raise Error(ErrorCode.INVALID_REQUEST, "Client is bound to another event loop")+ if self._process is not None and self._process.returncode is None:+ raise Error(ErrorCode.INVALID_REQUEST, "Client is already running")++ self._writeLock = asyncio.Lock()+ self._stderr.clear()+ self._closing = False+ self._latest = None+ self._exitError = None+ try:+ process = await asyncio.create_subprocess_exec(+ self._executable,+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ limit=STREAM_LIMIT,+ )+ except OSError as error:+ raise Error(ErrorCode.INVALID_REQUEST, f"cannot start goed2kd: {error}") from error+ self._process = process+ self._stopped = False+ for coroutine in (+ self._readStdout(process),+ self._readStderr(process),+ self._watchProcess(process),+ ):+ task = asyncio.create_task(coroutine)+ self._tasks.add(task)+ task.add_done_callback(self._tasks.discard)++ try:+ current = _toSnapshot(+ await self._request(+ "start",+ {+ "dataDir": str(self._dataDir),+ "settings": _toSettings(settings),+ },+ )+ )+ except Exception:+ await self.terminate()+ raise+ await self._publish(current)+ return current++ async def snapshot(self) -> Snapshot:+ current = _toSnapshot(await self._request("snapshot"))+ await self._publish(current)+ return current++ async def snapshots(self) -> AsyncIterator[Snapshot]:+ version = -1+ while True:+ async with self._snapshotCondition:+ await self._snapshotCondition.wait_for(+ lambda: self._snapshotVersion != version+ or self._exitError is not None+ or self._stopped+ )+ if self._exitError is not None:+ raise self._exitError+ if self._stopped and self._snapshotVersion == version:+ return+ current = self._latest+ version = self._snapshotVersion+ if current is not None:+ yield current++ async def addLink(self, link: str, outputDir: Path) -> Transfer:+ return _toTransfer(+ await self._request("addLink", {"link": link, "outputDir": str(outputDir)})+ )++ async def pause(self, hash: str) -> Transfer:+ return _toTransfer(await self._request("pause", {"hash": hash}))++ async def resume(self, hash: str) -> Transfer:+ return _toTransfer(await self._request("resume", {"hash": hash}))++ async def remove(self, hash: str, deleteFile: bool = False) -> None:+ await self._request("remove", {"hash": hash, "deleteFile": deleteFile})++ async def close(self) -> None:+ process = self._process+ if process is None or process.returncode is not None:+ return+ self._closing = True+ await self._request("close")+ await process.wait()+ await self._setStopped(process)+ if self._process is process:+ self._process = None++ async def terminate(self) -> None:+ if self._loop is not None and self._loop is not asyncio.get_running_loop():+ raise Error(ErrorCode.INVALID_REQUEST, "Client is bound to another event loop")+ process = self._process+ if process is None or process.returncode is not None:+ return+ self._closing = True+ try:+ process.kill()+ except ProcessLookupError:+ pass+ await process.wait()+ await self._setStopped(process)+ if self._process is process:+ self._process = None++ async def _request(self, method: str, params: Mapping[str, Any] | None = None) -> Any:+ if self._loop is not asyncio.get_running_loop():+ raise Error(ErrorCode.INVALID_REQUEST, "Client is bound to another event loop")+ process = self._process+ if process is None or process.returncode is not None or process.stdin is None:+ if self._exitError is not None:+ raise self._exitError+ raise Error(ErrorCode.NOT_RUNNING, "Client is not running")+ if self._writeLock is None:+ raise Error(ErrorCode.NOT_RUNNING, "Client is not running")++ requestId = self._nextId+ self._nextId += 1+ future = asyncio.get_running_loop().create_future()+ self._pending[requestId] = future+ request = {+ "version": RPC_VERSION,+ "id": requestId,+ "method": method,+ "params": params or {},+ }+ try:+ try:+ async with self._writeLock:+ process.stdin.write(+ json.dumps(request, separators=(",", ":")).encode() + b"\n"+ )+ await process.stdin.drain()+ except (BrokenPipeError, ConnectionResetError) as error:+ returnCode = process.returncode if process.returncode is not None else -1+ raise EngineExited(returnCode, tuple(self._stderr)) from error+ return await future+ finally:+ self._pending.pop(requestId, None)++ async def _readStdout(self, process: asyncio.subprocess.Process) -> None:+ if process.stdout is None:+ return+ while line := await process.stdout.readline():+ try:+ response = json.loads(line)+ if response.get("version") != RPC_VERSION:+ raise ProtocolError("goed2kd returned an unsupported RPC version")+ if response.get("method") == "snapshot" and "id" not in response:+ await self._publish(_toSnapshot(response["params"]))+ continue+ requestId = response["id"]+ future = self._pending.get(requestId)+ if future is None or future.done():+ continue+ if failure := response.get("error"):+ code = ErrorCode(failure["code"])+ future.set_exception(Error(code, failure["message"]))+ else:+ future.set_result(response.get("result"))+ except (KeyError, TypeError, ValueError, json.JSONDecodeError, ProtocolError) as error:+ protocolError = (+ error+ if isinstance(error, ProtocolError)+ else ProtocolError(f"invalid goed2kd response: {error}")+ )+ if self._process is process:+ self._exitError = protocolError+ self._failPending(protocolError)+ try:+ process.kill()+ except ProcessLookupError:+ pass+ return++ async def _readStderr(self, process: asyncio.subprocess.Process) -> None:+ if process.stderr is None:+ return+ while line := await process.stderr.readline():+ if self._process is process:+ self._stderr.append(line.decode(errors="replace").rstrip())++ async def _watchProcess(self, process: asyncio.subprocess.Process) -> None:+ returnCode = await process.wait()+ await self._setStopped(process, EngineExited(returnCode, tuple(self._stderr)))++ async def _setStopped(+ self, process: asyncio.subprocess.Process, error: EngineExited | None = None+ ) -> None:+ if self._process is not process:+ return+ if error is not None:+ self._failPending(error)+ if not self._closing and self._exitError is None:+ self._exitError = error+ self._stopped = True+ async with self._snapshotCondition:+ self._snapshotCondition.notify_all()++ def _failPending(self, error: Error) -> None:+ for future in self._pending.values():+ if not future.done():+ future.set_exception(error)++ async def _publish(self, snapshot: Snapshot) -> None:+ async with self._snapshotCondition:+ self._latest = snapshot+ self._snapshotVersion += 1+ self._snapshotCondition.notify_all()+++def _toSnapshot(value: Any) -> Snapshot:+ try:+ return Snapshot(transfers=tuple(_toTransfer(transfer) for transfer in value["transfers"]))+ except (KeyError, TypeError, ValueError) as error:+ raise ProtocolError(f"invalid snapshot: {error}") from error+++def _toSettings(settings: Settings) -> dict[str, Any]:+ return {+ "servers": settings.servers,+ "serverMetSource": settings.serverMetSource or "",+ "dhtNodes": settings.dhtNodes,+ "nodesDatSource": settings.nodesDatSource or "",+ "listenPort": settings.listenPort,+ "udpPort": settings.udpPort,+ "enableDht": settings.enableDht,+ "enableUpnp": settings.enableUpnp,+ "reconnectToServer": settings.reconnectToServer,+ }+++def _toTransfer(value: Any) -> Transfer:+ try:+ return Transfer(+ hash=value["hash"],+ name=value["name"],+ path=Path(value["path"]),+ size=value["size"],+ state=TransferState(value["state"]),+ done=value["done"],+ received=value["received"],+ downloadRate=value["downloadRate"],+ uploadRate=value["uploadRate"],+ peers=value["peers"],+ )+ except (KeyError, TypeError, ValueError) as error:+ raise ProtocolError(f"invalid transfer: {error}") from errordiff --git a/features/ed2k_pack/python_ed2k/errors.py b/features/ed2k_pack/python_ed2k/errors.pynew file mode 100644index 00000000..edb3f797--- /dev/null+++ b/features/ed2k_pack/python_ed2k/errors.py@@ -0,0 +1,33 @@+from enum import StrEnum+++class ErrorCode(StrEnum):+ INTERNAL = "INTERNAL"+ INVALID_LINK = "INVALID_LINK"+ INVALID_REQUEST = "INVALID_REQUEST"+ NOT_RUNNING = "NOT_RUNNING"+ OUTPUT_EXISTS = "OUTPUT_EXISTS"+ TRANSFER_EXISTS = "TRANSFER_EXISTS"+ TRANSFER_NOT_FOUND = "TRANSFER_NOT_FOUND"+++class Error(Exception):+ def __init__(self, code: ErrorCode, message: str) -> None:+ super().__init__(message)+ self.code = code+ self.message = message+++class EngineExited(Error):+ def __init__(self, returnCode: int, stderr: tuple[str, ...]) -> None:+ message = f"goed2kd exited with code {returnCode}"+ if stderr:+ message = f"{message}: {stderr[-1]}"+ super().__init__(ErrorCode.NOT_RUNNING, message)+ self.returnCode = returnCode+ self.stderr = stderr+++class ProtocolError(Error):+ def __init__(self, message: str) -> None:+ super().__init__(ErrorCode.INVALID_REQUEST, message)diff --git a/features/ed2k_pack/python_ed2k/models.py b/features/ed2k_pack/python_ed2k/models.pynew file mode 100644index 00000000..b329293f--- /dev/null+++ b/features/ed2k_pack/python_ed2k/models.py@@ -0,0 +1,43 @@+from dataclasses import dataclass+from enum import StrEnum+from pathlib import Path+++class TransferState(StrEnum):+ LOADING_RESUME_DATA = "LOADING_RESUME_DATA"+ DOWNLOADING = "DOWNLOADING"+ PAUSED = "PAUSED"+ VERIFYING = "VERIFYING"+ FINISHED = "FINISHED"+++@dataclass(frozen=True, slots=True)+class Settings:+ servers: tuple[str, ...] = ()+ serverMetSource: str | None = None+ dhtNodes: tuple[str, ...] = ()+ nodesDatSource: str | None = None+ listenPort: int = 0+ udpPort: int = 0+ enableDht: bool = True+ enableUpnp: bool = True+ reconnectToServer: bool = True+++@dataclass(frozen=True, slots=True)+class Transfer:+ hash: str+ name: str+ path: Path+ size: int+ state: TransferState+ done: int+ received: int+ downloadRate: int+ uploadRate: int+ peers: int+++@dataclass(frozen=True, slots=True)+class Snapshot:+ transfers: tuple[Transfer, ...]diff --git a/features/ed2k_pack/session.py b/features/ed2k_pack/session.pynew file mode 100644index 00000000..269f6e83--- /dev/null+++ b/features/ed2k_pack/session.py@@ -0,0 +1,52 @@+from __future__ import annotations++from pathlib import Path++from loguru import logger++from app.config.paths import APP_DATA_DIR+from .config import ed2kConfig, ed2kRuntime+from .python_ed2k import Client, Settings+++class ED2kSession:++ def __init__(self):+ self._client: Client | None = None++ def client(self) -> Client:+ if self._client is None:+ raise RuntimeError("ED2kSession 未启动")+ return self._client++ async def open(self) -> None:+ if self._client is not None:+ return+ path = ed2kRuntime.path()+ if not path:+ raise RuntimeError("未找到 goed2kd,请先在设置中安装")+ client = Client(Path(path), Path(APP_DATA_DIR) / "ed2k_data")+ try:+ await client.start(Settings(+ enableDht=ed2kConfig.enableDht.value,+ enableUpnp=ed2kConfig.enableUpnp.value,+ listenPort=ed2kConfig.listenPort.value,+ serverMetSource=ed2kConfig.serverMetSource.value or None,+ nodesDatSource=ed2kConfig.nodesDatSource.value or None,+ ))+ except Exception:+ await client.terminate()+ raise+ self._client = client++ async def close(self) -> None:+ if self._client is None:+ return+ try:+ await self._client.close()+ except Exception as e:+ logger.opt(exception=e).warning("关闭 goed2kd 失败")+ self._client = None+++ed2kSession = ED2kSession()diff --git a/features/ed2k_pack/task.py b/features/ed2k_pack/task.pynew file mode 100644index 00000000..54251c69--- /dev/null+++ b/features/ed2k_pack/task.py@@ -0,0 +1,121 @@+from __future__ import annotations++import asyncio+import sys+from dataclasses import dataclass+from pathlib import Path+from urllib.parse import unquote++from loguru import logger++from app.models.task import Task, TaskStep, TaskStatus+from app.services.speed_meter import speedMeter+++@dataclass(kw_only=True, eq=False)+class ED2kTask(Task):+ packId: str = "ed2k"+ fileHash: str = ""++ async def run(self):+ from .python_ed2k import TransferState+ from .python_ed2k.errors import ErrorCode, Error+ from .session import ed2kSession++ try:+ await ed2kSession.open()+ client = ed2kSession.client()++ if self.fileHash:+ await client.resume(self.fileHash)+ else:+ try:+ transfer = await client.addLink(self.url, self.outputFolder)+ except Error as e:+ if e.code != ErrorCode.TRANSFER_EXISTS:+ raise+ _, _, linkHash = parseEd2kLink(self.url)+ await client.remove(linkHash, deleteFile=False)+ transfer = await client.addLink(self.url, self.outputFolder)+ self.fileHash = transfer.hash+ self.name = transfer.name or self.name++ async for snapshot in client.snapshots():+ for t in snapshot.transfers:+ if t.hash != self.fileHash:+ continue+ step = self.step+ step.receivedBytes = t.received+ step.speed = t.downloadRate+ speedMeter.addSpeed(t.downloadRate)+ if t.size > 0:+ self.fileSize = t.size+ step.progress = min(99.9, t.received / t.size * 100)+ if t.state == TransferState.FINISHED:+ step.setStatus(TaskStatus.COMPLETED)+ await client.pause(self.fileHash)+ return+ break+ except asyncio.CancelledError:+ if self.fileHash:+ try:+ await ed2kSession.client().pause(self.fileHash)+ except Exception as e:+ logger.opt(exception=e).warning("暂停 eD2k 传输失败")+ raise+ except Exception as e:+ self.step.setError(e)+ raise++ @property+ def step(self) -> TaskStep:+ return self.steps[0]++ def reset(self) -> TaskStatus:+ self.fileHash = ""+ return super().reset()++ def deleteFiles(self):+ if self.fileHash:+ from app.services.coroutine_runner import coroutineRunner+ from .session import ed2kSession+ try:+ coroutineRunner.submit(ed2kSession.client().remove(self.fileHash, deleteFile=True))+ except Exception:+ pass+ super().deleteFiles()+++@dataclass(kw_only=True)+class ED2kTaskStep(TaskStep):+ pass+++@dataclass(kw_only=True)+class ED2kInstallStep(TaskStep):+ canPause = False+ binaryPath: str = ""++ async def run(self) -> None:+ path = Path(self.binaryPath)+ if not path.is_file():+ raise FileNotFoundError(f"未找到已下载的 goed2kd: {path}")+ if sys.platform != "win32":+ path.chmod(path.stat().st_mode | 0o755)+ self.setStatus(TaskStatus.COMPLETED)+++def parseEd2kLink(link: str) -> tuple[str, int, str]:+ link = link.strip()+ if not link.lower().startswith("ed2k://"):+ raise ValueError("不是有效的 eD2k 链接")+ parts = link.strip("/").split("|")+ if len(parts) < 5 or parts[1].lower() != "file":+ raise ValueError("不支持的 eD2k 链接格式")+ name = unquote(parts[2])+ try:+ size = int(parts[3])+ except ValueError:+ size = 0+ fileHash = parts[4] if len(parts) > 4 else ""+ return name, size, fileHashdiff --git a/features/ffmpeg_pack/config.py b/features/ffmpeg_pack/config.pyindex 692eacd7..9508e18d 100644--- a/features/ffmpeg_pack/config.py+++ b/features/ffmpeg_pack/config.py@@ -1,198 +1,113 @@+from __future__ import annotations+import asyncio-import shutil+import platformimport sysfrom pathlib import Path-from typing import TYPE_CHECKING--from PySide6.QtCore import Qt, QUrl-from PySide6.QtGui import QDesktopServices-from PySide6.QtWidgets import QApplication-from qfluentwidgets import (- ConfigItem,- FluentIcon,- FolderValidator,- InfoBar,- InfoBarPosition,- PrimaryPushButton,- SettingCard,- ToolButton,-)--from app.bases.models import PackConfig-from app.services.core_service import coreService-from app.supports.android import IS_ANDROID, nativeLibraryDir-from app.supports.paths import APP_DATA_DIR-from app.supports.utils import findExecutable, toPosixPath-from app.view.components.setting_card_group import CollapsibleSettingCardGroup-from app.view.components.setting_cards import InstallFolderCard--if TYPE_CHECKING:- from app.view.pages.setting_page import SettingPage- from app.view.windows.main_window import MainWindow---def _linuxInstallCommand() -> str:- """检测可用包管理器;都没命中时 fallback 到 apt 命令文本(让用户自行替换)。"""- candidates = (- ("apt", "sudo apt install ffmpeg"),- ("dnf", "sudo dnf install ffmpeg"),- ("pacman", "sudo pacman -S ffmpeg"),- ("zypper", "sudo zypper install ffmpeg"),- ("apk", "sudo apk add ffmpeg"),- )- return next((cmd for pm, cmd in candidates if shutil.which(pm)), candidates[0][1])---def ffmpegPaths() -> tuple[str, str]:- if IS_ANDROID:- nativeDir = nativeLibraryDir()- if not nativeDir:- return ("", "")- ffmpeg, ffprobe = Path(nativeDir) / "libffmpeg.so", Path(nativeDir) / "libffprobe.so"- return (- str(ffmpeg) if ffmpeg.exists() else "",- str(ffprobe) if ffprobe.exists() else "",- )- installFolder = Path(ffmpegConfig.installFolder.value)- return (- findExecutable(installFolder, "ffmpeg", "bin"),- findExecutable(installFolder, "ffprobe", "bin"),- )---async def probeFFmpegRuntime() -> dict[str, str]:- ffmpegPath, ffprobePath = ffmpegPaths()- runtimeInfo = {- "ffmpegPath": ffmpegPath,- "ffprobePath": ffprobePath,- "version": "",- "installPath": "",- }- if not ffmpegPath or not ffprobePath:- return runtimeInfo-- process = await asyncio.create_subprocess_exec(- ffmpegPath,- "-version",- stdin=asyncio.subprocess.DEVNULL,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.DEVNULL,- )- stdout, _ = await process.communicate()- if process.returncode != 0:- return runtimeInfo-- lines = stdout.decode("utf-8", errors="ignore").splitlines()- versionLine = lines[0].strip() if lines else ""- version = versionLine.removeprefix("ffmpeg version ").split(" Copyright", 1)[0].strip()- runtimeInfo["version"] = version or versionLine- binPath = Path(ffmpegPath)- installRoot = binPath.parent.parent if binPath.parent.name.lower() == "bin" else binPath.parent- runtimeInfo["installPath"] = toPosixPath(installRoot)- return runtimeInfo---class FFmpegRuntimeCard(SettingCard):- def __init__(self, parent=None):- super().__init__(FluentIcon.INFO, self.tr("当前 FFmpeg"), self.tr("正在检测 FFmpeg 运行时..."), parent)- self.installButton = PrimaryPushButton(self)- self.refreshButton = ToolButton(FluentIcon.SYNC, self)-- self._initWidget()- self._initLayout()- self._bind()-- def _initWidget(self):- if IS_ANDROID:- self.installButton.hide()- self._installAction = lambda: None- elif sys.platform == "win32":- self.installButton.setText(self.tr("一键安装"))- self._installAction = self._downloadFFmpeg- elif sys.platform == "darwin" and not shutil.which("brew"):- self.installButton.setText(self.tr("打开 brew.sh"))- self._installAction = lambda: QDesktopServices.openUrl(QUrl("https://brew.sh"))- else:- command = "brew install ffmpeg" if sys.platform == "darwin" else _linuxInstallCommand()- self.installButton.setText(self.tr("复制安装命令"))- self._installAction = lambda: self._copyCommand(command)-- def _initLayout(self):- self.hBoxLayout.addWidget(self.installButton, 0, Qt.AlignmentFlag.AlignRight)- self.hBoxLayout.addSpacing(8)- self.hBoxLayout.addWidget(self.refreshButton, 0, Qt.AlignmentFlag.AlignRight)- self.hBoxLayout.addSpacing(16)-- def _bind(self):- self.installButton.clicked.connect(self._installAction)- self.refreshButton.clicked.connect(self.refreshStatus)-- def refreshStatus(self):- self.refreshButton.setEnabled(False)- self.setContent(self.tr("正在检测 FFmpeg 运行时..."))- coreService.runCoroutine(probeFFmpegRuntime(), self._onRuntimeLoaded)-- def _onRuntimeLoaded(self, result, error: str | None):- self.refreshButton.setEnabled(True)- if error:- self.setContent(self.tr("检测 FFmpeg 运行时失败"))- return-- runtimeInfo = result or {}- ffmpegPath = runtimeInfo.get("ffmpegPath", "")- ffprobePath = runtimeInfo.get("ffprobePath", "")- if ffmpegPath and ffprobePath:- version = runtimeInfo.get("version", "")- installPath = runtimeInfo.get("installPath", "")- self.setContent(self.tr("版本: {0}\n安装路径: {1}").format(version or self.tr("未知"), installPath or ffmpegPath))- else:- self.setContent(self.tr("未检测到可用的 ffmpeg 和 ffprobe"))-- def _downloadFFmpeg(self):- from .pack import createInstallTask- self.installButton.setEnabled(False)- self.installButton.setText(self.tr("准备中..."))- coreService.runCoroutine(createInstallTask(), self._onInstallTaskCreated)-- def _copyCommand(self, command: str):- QApplication.clipboard().setText(command)- InfoBar.success(- self.tr("已复制安装命令"), command,- duration=2000, position=InfoBarPosition.BOTTOM_RIGHT, parent=self.window(),- )- def _onInstallTaskCreated(self, result, error: str | None):- self.installButton.setEnabled(True)- self.installButton.setText(self.tr("一键安装"))+from app.config.cfg import ConfigItem+from app.config.paths import APP_DATA_DIR+from app.models.pack import BinaryRuntime, PackConfig+from app.models.task import Task+from app.platform.android import IS_ANDROID, nativeLibraryDir+from app.platform.filesystem import findExecutable+- mainWindow: "MainWindow" = self.window()- if error or result is None:- InfoBar.error(self.tr("安装 FFmpeg 失败"), error or self.tr("无法创建安装任务"), duration=-1, parent=mainWindow)- return- mainWindow.addTask(result)+RELEASE_BASE = "https://github.com/XiaoYouChR/Ghost-Downloader-FFmpeg"+++def ffmpegAssetTarget() -> str:+ machine = platform.machine().lower()+ isArm = machine in {"arm64", "aarch64"}+ if sys.platform == "win32":+ return "winarm64" if isArm else "win64"+ if sys.platform == "darwin":+ return "macos-arm64" if isArm else "macos-x64"+ if sys.platform == "linux":+ return "linux-arm64" if isArm else "linux-x64"+ raise RuntimeError(f"当前平台暂不支持一键安装 FFmpeg: {sys.platform}")class FFmpegConfig(PackConfig):- installFolder = ConfigItem("FFmpeg", "InstallFolder", f"{APP_DATA_DIR}/FFmpeg", FolderValidator())+ installFolder = ConfigItem("FFmpeg", "InstallFolder", f"{APP_DATA_DIR}/FFmpeg")- def setupSettings(self, settingPage: "SettingPage"):- self.ffmpegGroup = CollapsibleSettingCardGroup(self.tr("FFmpeg"), "ffmpeg", settingPage.container)- self.installFolderCard = InstallFolderCard(- ffmpegConfig.installFolder,- f"{APP_DATA_DIR}/FFmpeg",+ def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:+ from app.view.components.setting_card_group import CollapsibleSettingCardGroup+ from app.view.components.setting_cards import RuntimeCard, SelectFolderSettingCard++ ffmpegGroup = CollapsibleSettingCardGroup(self.tr("FFmpeg"), "ffmpeg", parent)+ installFolderCard = SelectFolderSettingCard(+ ffmpegConfig.installFolder, f"{APP_DATA_DIR}/FFmpeg",self.tr("FFmpeg 安装目录"),- self.tr("选择 FFmpeg 安装目录"),- self.ffmpegGroup,+ ffmpegGroup,)- self.runtimeCard = FFmpegRuntimeCard(self.ffmpegGroup)+ runtimeCard = RuntimeCard(ffmpegRuntime, ffmpegGroup)- self.installFolderCard.pathChanged.connect(lambda _: self.runtimeCard.refreshStatus())+ installFolderCard.pathChanged.connect(runtimeCard._onInstallFolderChanged)+ ffmpegGroup.addSettingCards([installFolderCard, runtimeCard])+ runtimeCard.refreshStatus()+ return [ffmpegGroup]- self.ffmpegGroup.addSettingCard(self.installFolderCard)- self.ffmpegGroup.addSettingCard(self.runtimeCard)- settingPage.addSettingGroup(self.ffmpegGroup)- self.runtimeCard.refreshStatus()+ffmpegConfig = FFmpegConfig()-ffmpegConfig = FFmpegConfig()+class FFmpegRuntime(BinaryRuntime):+ name = "FFmpeg"+ canInstall = not IS_ANDROID++ def path(self) -> str:+ if IS_ANDROID:+ nativeDir = nativeLibraryDir()+ if not nativeDir:+ return ""+ binary = Path(nativeDir) / "libffmpeg.so"+ return str(binary) if binary.exists() else ""+ return findExecutable(Path(ffmpegConfig.installFolder.value), "ffmpeg", "bin")++ def ffprobePath(self) -> str:+ if IS_ANDROID:+ nativeDir = nativeLibraryDir()+ if not nativeDir:+ return ""+ binary = Path(nativeDir) / "libffprobe.so"+ return str(binary) if binary.exists() else ""+ return findExecutable(Path(ffmpegConfig.installFolder.value), "ffprobe", "bin")++ async def probeVersion(self) -> str:+ path = self.path()+ if not path:+ return ""+ process = await asyncio.create_subprocess_exec(+ path, "-version",+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.DEVNULL,+ )+ stdout, _ = await process.communicate()+ if process.returncode != 0:+ return ""+ line = stdout.decode("utf-8", errors="ignore").splitlines()[0].strip()+ return line.removeprefix("ffmpeg version ").split(" Copyright", 1)[0].strip() or line++ async def installTask(self) -> Task:+ from app.services.feature_service import featureService+ from app.models.task import BinaryInstallOptions++ target = ffmpegAssetTarget()+ extension = "zip" if sys.platform == "win32" else "tar.gz"+ url = f"{RELEASE_BASE}/releases/latest/download/ffmpeg-{target}.{extension}"+ executableNames = (+ ("ffmpeg.exe", "ffprobe.exe") if sys.platform == "win32"+ else ("ffmpeg", "ffprobe")+ )+ return await featureService.parse(BinaryInstallOptions(+ url=url,+ outputFolder=Path(ffmpegConfig.installFolder.value),+ name=f"FFmpeg 安装 ({target})",+ executableNames=executableNames,+ sha256Url=f"{url}.sha256",+ ))+++ffmpegRuntime = FFmpegRuntime()diff --git a/features/ffmpeg_pack/pack.py b/features/ffmpeg_pack/pack.pyindex c4a39101..98aca88f 100644--- a/features/ffmpeg_pack/pack.py+++ b/features/ffmpeg_pack/pack.py@@ -1,218 +1,79 @@-import asyncio-import platform-import sys+from __future__ import annotations+from pathlib import Path-from typing import Any, TYPE_CHECKINGfrom urllib.parse import urlparse-import niquests--from app.bases.interfaces import FeaturePack-from app.bases.models import Task, SpecialFileSize-from app.supports.config import activeUserAgent, cfg-from app.supports.utils import getProxies, toExecutable, toSafeFilename-from .config import ffmpegConfig, ffmpegPaths-from app.view.components.cards import UniversalTaskCard-from .task import FFmpegResourceStage, FFmpegStage--if TYPE_CHECKING:- from features.disk_pack.pack import buildToolInstallTask- from features.http_pack.task import HttpTaskStage-else:- from disk_pack.pack import buildToolInstallTask- from http_pack.task import HttpTaskStage---FFMPEG_MERGE_URL = "gd3+ffmpeg://merge"--_FFMPEG_RELEASE_API = "https://api.github.com/repos/BtbN/FFmpeg-Builds/releases/latest"-_FFMPEG_HEADERS = {- "accept": "application/vnd.github+json",- "user-agent": activeUserAgent(),-}-+from app.models.pack import FeaturePack, TaskParser+from app.models.task import MergeTaskOptions, Task, TaskOptions+from app.platform.filesystem import toSafeFilename+from .config import ffmpegConfig, ffmpegRuntime+from .task import FFmpegResourceStep, FFmpegStep-def _resourceExtension(name: str, url: str) -> str:- target = name or urlparse(url).path- return Path(target).suffix.lstrip(".").lower()+class MergeParser(TaskParser):+ priority = 60-def _windowsTarget() -> tuple[str, str]:- if sys.platform != "win32":- raise RuntimeError("一键安装 FFmpeg 仅支持 Windows 平台")+ def match(self, options: TaskOptions) -> bool:+ return isinstance(options, MergeTaskOptions)- machine = platform.machine().lower()- if machine in {"amd64", "x86_64"}:- return "win64", "x64"- if machine in {"arm64", "aarch64"}:- return "winarm64", "arm64"- raise RuntimeError(f"不支持的 Windows 架构: {platform.machine()}")+ async def parse(self, options: TaskOptions) -> Task:+ assert isinstance(options, MergeTaskOptions)+ if not ffmpegRuntime.path() or not ffmpegRuntime.ffprobePath():+ raise RuntimeError("未找到可用的 ffmpeg 和 ffprobe,请先在设置中安装或配置 FFmpeg")-def _bestAsset(assets: list[dict[str, Any]], target: str) -> dict[str, Any]:- candidates: list[tuple[int, dict[str, Any]]] = []- for asset in assets:- lowerName = asset["name"].lower()- if target not in lowerName or not lowerName.endswith(".zip") or "shared" in lowerName:- continue+ from app.services.feature_service import featureService- score = 0- if "master-latest" in lowerName:- score += 100- if "-gpl" in lowerName:- score += 10- if "-latest-" in lowerName:- score += 5- candidates.append((score, asset))+ videoTask = await featureService.parse(options.video)+ audioTask = await featureService.parse(options.audio)- if not candidates:- raise RuntimeError(f"未找到适用于当前平台的 FFmpeg 安装包: {target}")- return max(candidates, key=lambda item: item[0])[1]+ videoStep = videoTask.steps[0]+ audioStep = audioTask.steps[0]+ videoExt = Path(videoTask.name or urlparse(videoStep.url).path).suffix.lstrip(".").lower()+ audioExt = Path(audioTask.name or urlparse(audioStep.url).path).suffix.lstrip(".").lower()+ rawName = options.video.name or videoTask.name+ stem = toSafeFilename(rawName, fallback="merged-media")+ name = stem if stem.lower().endswith(".mp4") else f"{stem}.mp4"-async def _fetchLatestRelease(target: str) -> dict[str, Any]:- async with niquests.AsyncSession(headers=_FFMPEG_HEADERS, timeout=30, happy_eyeballs=True) as client:- client.trust_env = False- response = await client.get(- _FFMPEG_RELEASE_API,- proxies=getProxies(),- verify=cfg.SSLVerify.value,- allow_redirects=True,+ task = Task(+ name=name,+ url=videoStep.url,+ packId="ffmpeg",+ fileSize=max(0, videoTask.fileSize) + max(0, audioTask.fileSize),+ outputFolder=options.outputFolder,)- response.raise_for_status()- payload = response.json()-- assets = payload.get("assets")- if not isinstance(assets, list):- raise RuntimeError("GitHub Release 返回了无效的 assets 数据")-- asset = _bestAsset(assets, target)- downloadUrl = asset["browser_download_url"].strip()- assetName = asset["name"].strip()- size = asset["size"]- if not downloadUrl or not assetName or size <= 0:- raise RuntimeError("GitHub Release 返回了不完整的 FFmpeg 安装包信息")-- return {- "name": assetName,- "url": downloadUrl,- "size": size,- }---async def _resourceDownloadTask(item: dict[str, Any], payload: dict[str, Any], path: Path) -> Task:- from app.services.feature_service import featureService-- url = item["url"].strip()- if not url.startswith(("http://", "https://")):- raise RuntimeError("在线合并暂不支持 blob 或非 HTTP 资源")-- resourceTask = await featureService.parse({- "url": url,- "filename": (item.get("filename") or "").strip(),- "headers": item.get("headers") or {},- "fileSize": item.get("fileSize") or SpecialFileSize.UNKNOWN,- "supportsRange": bool(item.get("supportsRange")),- "proxies": payload.get("proxies", getProxies()),- "path": path,- "preBlockNum": payload.get("preBlockNum", cfg.preBlockNum.value),- })- if not resourceTask.stages:- raise RuntimeError("解析在线合并源文件失败")- return resourceTask---async def createMergeTask(payload: dict[str, Any]) -> Task:- ffmpeg, ffprobe = ffmpegPaths()- if not ffmpeg or not ffprobe:- raise RuntimeError("未找到可用的 ffmpeg 和 ffprobe,请先在设置中安装或配置 FFmpeg")-- resources = payload.get("resources") or []- if len(resources) != 2:- raise RuntimeError("在线合并暂时只支持 2 个 HTTP 音视频资源")-- path = Path(payload.get("path", cfg.downloadFolder.value))- videoTask, audioTask = await asyncio.gather(- _resourceDownloadTask(resources[0], payload, path),- _resourceDownloadTask(resources[1], payload, path),- )-- rawTitle = (- (payload.get("outputTitle") or "").strip()- or (resources[0].get("pageTitle") or "").strip()- )- baseTitle = toSafeFilename(rawTitle, fallback="merged-media")- outputTitle = baseTitle if baseTitle.lower().endswith(".mp4") else f"{baseTitle}.mp4"-- videoSource: HttpTaskStage = videoTask.stages[0]- audioSource: HttpTaskStage = audioTask.stages[0]- videoExt = _resourceExtension(videoTask.title, videoSource.url)- audioExt = _resourceExtension(audioTask.title, audioSource.url)-- videoStage = _toResourceStage(videoSource, role="video", extension=videoExt, stageIndex=1)- audioStage = _toResourceStage(audioSource, role="audio", extension=audioExt, stageIndex=2)- mergeStage = FFmpegStage(- stageIndex=3,- videoExtension=videoExt,- audioExtension=audioExt,- )-- task = Task(- title=outputTitle,- url=videoStage.url,- packId="ffmpeg",- fileSize=max(0, videoTask.fileSize) + max(0, audioTask.fileSize),- path=path,- )- task.addStage(videoStage)- task.addStage(audioStage)- task.addStage(mergeStage)- return task---def _toResourceStage(- httpStage: "HttpTaskStage", *, role: str, extension: str, stageIndex: int,-) -> FFmpegResourceStage:- return FFmpegResourceStage(- stageIndex=stageIndex,- url=httpStage.url,- fileSize=httpStage.fileSize,- headers=httpStage.headers,- proxies=httpStage.proxies,- blockNum=httpStage.blockNum,- supportsRange=httpStage.supportsRange,- role=role,- extension=extension,- )---async def createInstallTask() -> Task:- target, archLabel = _windowsTarget()- assetInfo = await _fetchLatestRelease(target)- return await buildToolInstallTask(- packId="ffmpeg",- title=f"FFmpeg 安装 ({archLabel})",- downloadUrl=assetInfo["url"],- fallbackAssetName=assetInfo["name"],- fallbackSize=assetInfo["size"],- installFolder=Path(ffmpegConfig.installFolder.value),- executableNames=[toExecutable("ffmpeg"), toExecutable("ffprobe")],- headers=_FFMPEG_HEADERS,- )+ task.addStep(FFmpegResourceStep(+ stepIndex=1,+ url=videoStep.url,+ fileSize=videoStep.fileSize,+ headers=videoStep.headers,+ subworkerCount=videoStep.subworkerCount,+ canUseRangeRequests=videoStep.canUseRangeRequests,+ role="video",+ extension=videoExt,+ ))+ task.addStep(FFmpegResourceStep(+ stepIndex=2,+ url=audioStep.url,+ fileSize=audioStep.fileSize,+ headers=audioStep.headers,+ subworkerCount=audioStep.subworkerCount,+ canUseRangeRequests=audioStep.canUseRangeRequests,+ role="audio",+ extension=audioExt,+ ))+ task.addStep(FFmpegStep(+ stepIndex=3,+ videoExtension=videoExt,+ audioExtension=audioExt,+ ))+ return taskclass FFmpegPack(FeaturePack):packId = "ffmpeg"config = ffmpegConfig- def matches(self, url: str) -> bool:- return url.strip() == FFMPEG_MERGE_URL-- async def parse(self, payload: dict) -> Task:- return await createMergeTask(payload)-- def taskCard(self, task, parent=None):- from disk_pack.task import InstallTask- if isinstance(task, InstallTask):- return UniversalTaskCard(task, parent)- return super().taskCard(task, parent)+ def parsers(self):+ return [MergeParser()]diff --git a/features/ffmpeg_pack/task.py b/features/ffmpeg_pack/task.pyindex 7b2d7a0c..f9989b38 100644--- a/features/ffmpeg_pack/task.py+++ b/features/ffmpeg_pack/task.py@@ -1,165 +1,143 @@+from __future__ import annotations+import asynciofrom contextlib import suppress-from dataclasses import dataclass, field+from dataclasses import dataclassfrom pathlib import Path-from typing import TYPE_CHECKINGfrom loguru import logger-from app.bases.interfaces import Worker-from app.bases.models import TaskStage, TaskStatus-from .config import ffmpegPaths--if TYPE_CHECKING:- from features.http_pack.task import HttpTaskStage-else:- from http_pack.task import HttpTaskStage+from app.models.task import TaskStep, TaskStatus+from app.platform.filesystem import deletePath+from http_pack.task import HttpTaskStep+from .config import ffmpegRuntime-def _baseTitle(taskTitle: str) -> str:- return taskTitle[:-4] if taskTitle.lower().endswith(".mp4") else taskTitle+def mediaStem(task) -> str:+ name = task.name+ return name.rsplit(".", 1)[0] if "." in name else name@dataclass(kw_only=True)-class FFmpegResourceStage(HttpTaskStage):- # role ∈ {"video", "audio"}:合并任务里两路源各自的角色,落盘文件名带这个中缀- role: str = "video"+class FFmpegResourceStep(HttpTaskStep):+ role: str = ""extension: str = ""@property- def outputFile(self) -> str:+ def outputPath(self) -> str:suffix = f".{self.extension}" if self.extension else ""- return str(Path(self.task.path) / f"{_baseTitle(self.task.title)}.{self.role}{suffix}")---def _parseDuration(value: str) -> float:- try:- return max(0.0, float(value))- except ValueError:- return 0.0---async def _probeDuration(ffprobe: str, path: Path) -> float:- process = await asyncio.create_subprocess_exec(- ffprobe,- "-v", "error",- "-show_entries", "format=duration",- "-of", "default=noprint_wrappers=1:nokey=1",- path,- stdin=asyncio.subprocess.DEVNULL,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- )- stdout, stderr = await process.communicate()-- if process.returncode != 0:- message = stderr.decode("utf-8", errors="ignore").strip()- logger.warning("ffprobe 获取时长失败: {}, {}", path, message or process.returncode)- return 0.0-- return _parseDuration(stdout.decode("utf-8", errors="ignore").strip())+ return str(self.task.outputFolder / f"{mediaStem(self.task)}.{self.role}{suffix}")@dataclass(kw_only=True)-class FFmpegStage(TaskStage):- workerType: type = field(init=False, repr=False)- canPause: bool = field(init=False, default=False)+class FFmpegStep(TaskStep):+ canPause = FalsevideoExtension: str = ""audioExtension: str = ""- cleanupSource: bool = True+ shouldDeleteSource: bool = True@property- def outputFile(self) -> Path:- return Path(self.task.path) / f"{_baseTitle(self.task.title)}.mp4"+ def outputFile(self) -> str:+ return str(self.task.outputFolder / f"{mediaStem(self.task)}.mp4")@property- def videoPath(self) -> Path:+ def _videoPath(self) -> Path:suffix = f".{self.videoExtension}" if self.videoExtension else ""- return Path(self.task.path) / f"{_baseTitle(self.task.title)}.video{suffix}"+ return self.task.outputFolder / f"{mediaStem(self.task)}.video{suffix}"@property- def audioPath(self) -> Path:+ def _audioPath(self) -> Path:suffix = f".{self.audioExtension}" if self.audioExtension else ""- return Path(self.task.path) / f"{_baseTitle(self.task.title)}.audio{suffix}"+ return self.task.outputFolder / f"{mediaStem(self.task)}.audio{suffix}"+ async def run(self) -> None:-class FFmpegWorker(Worker):- def __init__(self, stage: FFmpegStage):- super().__init__(stage)- self.stage = stage+ ffmpegPath = ffmpegRuntime.path()+ ffprobePath = ffmpegRuntime.ffprobePath()+ if not ffmpegPath or not ffprobePath:+ raise RuntimeError("未找到可用的 ffmpeg 和 ffprobe,请先在设置中安装或配置 FFmpeg")- async def _readProgress(self, stream: asyncio.StreamReader, totalDuration: float):- while True:- rawLine = await stream.readline()- if not rawLine:- break+ Path(self.outputFile).parent.mkdir(parents=True, exist_ok=True)- line = rawLine.decode("utf-8", errors="ignore").strip()- if not line:- continue+ totalDuration = await self._probeDuration(ffprobePath, self._videoPath)- if line.startswith("out_time_us=") and totalDuration > 0:- currentDuration = _parseDuration(line.removeprefix("out_time_us=")) / 1_000_000- if currentDuration <= 0:- continue- self.stage.progress = min(99.5, max(0.0, currentDuration / totalDuration * 100))- elif line == "progress=end":- self.stage.progress = 100-- async def run(self):- ffmpeg, ffprobe = ffmpegPaths()- if not ffmpeg or not ffprobe:- raise RuntimeError("未找到可用的 ffmpeg 和 ffprobe,请先在设置中安装或配置 FFmpeg")+ process = await asyncio.create_subprocess_exec(+ ffmpegPath,+ "-y", "-v", "error", "-nostats", "-progress", "pipe:1",+ "-i", str(self._videoPath),+ "-i", str(self._audioPath),+ "-c", "copy",+ self.outputFile,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ progressTask = asyncio.create_task(self._readProgress(process.stdout, totalDuration))- self.stage.outputFile.parent.mkdir(parents=True, exist_ok=True)-- process = None- progressTask = Nonetry:- totalDuration = await _probeDuration(ffprobe, self.stage.videoPath)- process = await asyncio.create_subprocess_exec(- ffmpeg,- "-y", "-v", "error", "-nostats", "-progress", "pipe:1",- "-i", self.stage.videoPath,- "-i", self.stage.audioPath,- "-c", "copy",- self.stage.outputFile,- stdin=asyncio.subprocess.DEVNULL,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- )- progressTask = asyncio.create_task(self._readProgress(process.stdout, totalDuration))-await process.wait()await progressTask+if process.returncode != 0:- stderrOutput = (await process.stderr.read()).decode("utf-8", errors="ignore").strip()- suffix = f", {stderrOutput}" if stderrOutput else ""+ stderr = (await process.stderr.read()).decode("utf-8", errors="ignore").strip()+ suffix = f", {stderr}" if stderr else ""raise RuntimeError(f"ffmpeg 退出码异常: {process.returncode}{suffix}")- self.stage.setStatus(TaskStatus.COMPLETED)- if self.stage.cleanupSource:- # 同时清理 HttpWorker 写下的 .ghd 临时元数据文件- for path in (self.stage.videoPath, self.stage.audioPath):- for target in (path, path.with_name(f"{path.name}.ghd")):- try:- target.unlink(missing_ok=True)- except OSError as e:- logger.opt(exception=e).warning("failed to cleanup temporary file {}", target)+ self.setStatus(TaskStatus.COMPLETED)++ if self.shouldDeleteSource:+ for path in (self._videoPath, self._audioPath):+ deletePath(path)+ deletePath(Path(f"{path}.ghd"))except asyncio.CancelledError:- self.stage.setStatus(TaskStatus.PAUSED)- if process is not None and process.returncode is None:+ self.setStatus(TaskStatus.PAUSED)+ if process.returncode is None:process.kill()await process.wait()- if progressTask is not None and not progressTask.done():+ if not progressTask.done():progressTask.cancel()with suppress(asyncio.CancelledError):await progressTaskraiseexcept Exception as e:- self.stage.setError(e)+ self.setError(e)raise--FFmpegStage.workerType = FFmpegWorker+ async def _readProgress(self, stream: asyncio.StreamReader, totalDuration: float):+ while True:+ rawLine = await stream.readline()+ if not rawLine:+ break+ line = rawLine.decode("utf-8", errors="ignore").strip()+ if not line:+ continue+ if line.startswith("out_time_us=") and totalDuration > 0:+ try:+ currentSeconds = max(0.0, float(line.removeprefix("out_time_us="))) / 1_000_000+ except ValueError:+ continue+ if currentSeconds > 0:+ self.progress = min(99.5, max(0.0, currentSeconds / totalDuration * 100))+ elif line == "progress=end":+ self.progress = 100++ async def _probeDuration(self, ffprobePath: str, videoPath: Path) -> float:+ process = await asyncio.create_subprocess_exec(+ ffprobePath,+ "-v", "error",+ "-show_entries", "format=duration",+ "-of", "default=noprint_wrappers=1:nokey=1",+ str(videoPath),+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ stdout, stderr = await process.communicate()+ if process.returncode != 0:+ logger.warning("ffprobe 获取时长失败: {}", videoPath)+ return 0.0+ try:+ return max(0.0, float(stdout.decode("utf-8", errors="ignore").strip()))+ except ValueError:+ return 0.0diff --git a/features/ftp_pack/cards.py b/features/ftp_pack/cards.pyindex b07b0261..5192b894 100644--- a/features/ftp_pack/cards.py+++ b/features/ftp_pack/cards.py@@ -1,32 +1,16 @@-from pathlib import Path--from PySide6.QtCore import QFileInfo, Qt-from PySide6.QtWidgets import (- QFileIconProvider,- QHBoxLayout,- QVBoxLayout,- QWidget,-)-from qfluentwidgets import (- BodyLabel,- CaptionLabel,- FluentIcon,- IconWidget,- LineEdit,- PrimaryPushButton,- ToolButton,-)--from app.bases.models import TaskStatus-from app.supports.utils import toReadableSize, toReadableTime, openFile, openFolder-from app.view.components.cards import ResultCard, UniversalTaskCard-from app.view.components.dialogs import FileSelectDialog-from app.view.components.labels import EditableLabel++from qfluentwidgets import FluentIcon, ToolButton++from app.format import toReadableSize+from app.models.task import TaskStatus+from app.view.cards.draft_cards import UniversalDraftCard+from app.view.cards.task_cards import UniversalTaskCard+from app.view.dialogs.file_select import FileSelectDialogfrom .task import FtpTask-def _openFileSelection(task: FtpTask, parent) -> set[int] | None:- dialog = FtpFileSelectDialog(task, parent)+def openFileSelection(task: FtpTask, parent) -> set[int] | None:+ dialog = FileSelectDialog(task, parent)try:if not dialog.exec():return None@@ -37,213 +21,71 @@ def _openFileSelection(task: FtpTask, parent) -> set[int] | None:dialog.deleteLater()-class FtpFileSelectDialog(FileSelectDialog):- def __init__(self, task: FtpTask, parent=None):- super().__init__(task, parent)- self.task: FtpTask = task-- def _fileDisplayPath(self, file) -> str:- return file.relativePath+class FtpDraftCard(UniversalDraftCard):--class FtpResultCard(ResultCard):- def __init__(self, task: FtpTask, parent: QWidget = None):- super().__init__(task, parent)-- self.mainLayout = QHBoxLayout(self)- self.textLayout = QVBoxLayout()- self.iconLabel = IconWidget(self)- self.titleLabel = EditableLabel(self.task.title, self, onEdit=self._enterEditMode)- self.titleEdit = LineEdit(self)- self.sourceLabel = CaptionLabel(self._sourceText(), self)- self.summaryLabel = BodyLabel("", self)- self.selectFilesButton = PrimaryPushButton(self.tr("选择文件"), self)-- self._initWidget()- self._initLayout()- self._refreshSummary()- self._renderCategoryButton()+ @property+ def task(self) -> FtpTask:+ return self._taskdef _initWidget(self):- self.setFixedHeight(50)- icon = (- QFileIconProvider().icon(QFileIconProvider.IconType.Folder)- if self.task.isDirectory- else QFileIconProvider().icon(QFileInfo(self.task.outputFolder))- )- self.iconLabel.setIcon(icon)- self.iconLabel.setFixedSize(20, 20)- self.titleEdit.setText(self.task.title)- self.titleEdit.editingFinished.connect(self._onEditingFinished)- self.titleEdit.hide()- self.selectFilesButton.setVisible(self.task.countAll > 1)- self.selectFilesButton.clicked.connect(self._onSelectFilesClicked)+ super()._initWidget()+ self._selectFilesButton = None+ if self.task.files and len(self.task.files) > 1:+ from qfluentwidgets import ToolTipFilter+ from qfluentwidgets import TransparentToolButton+ self._selectFilesButton = TransparentToolButton(FluentIcon.LIBRARY, self)+ self._selectFilesButton.setFixedSize(28, 28)+ self._selectFilesButton.setToolTip(self.tr("选择文件"))+ self._selectFilesButton.installEventFilter(ToolTipFilter(self._selectFilesButton))+ self._refreshSummary()def _initLayout(self):- self.mainLayout.setContentsMargins(10, 6, 10, 6)- self.mainLayout.setSpacing(12)- self.textLayout.setContentsMargins(0, 0, 0, 0)- self.textLayout.setSpacing(2)- self.textLayout.addWidget(self.titleLabel)- self.textLayout.addWidget(self.titleEdit)- self.textLayout.addWidget(self.sourceLabel)- self.mainLayout.addWidget(self.iconLabel, 0, Qt.AlignmentFlag.AlignCenter)- self.mainLayout.addLayout(self.textLayout, 1)- self.mainLayout.addWidget(self.summaryLabel)- self.mainLayout.addSpacing(12)- self.mainLayout.addWidget(self.categoryButton)- self.mainLayout.addWidget(self.selectFilesButton)-- def _enterEditMode(self):- self.titleLabel.hide()- self.titleEdit.show()- self.titleEdit.setFocus()- self.titleEdit.selectAll()-- def _onEditingFinished(self):- newTitle = self.titleEdit.text().strip()- if newTitle and newTitle != self.task.title:- self.task.setTitle(newTitle)- self.titleLabel.setText(self.task.title)- self.titleEdit.setText(self.task.title)-- self.titleEdit.hide()- self.titleLabel.show()- self.titleLabel.setFocus()-- def _sourceText(self) -> str:- sourceType = self.tr("FTP 目录") if self.task.isDirectory else self.tr("FTP 文件")- return self.tr("{0} · {1}").format(- sourceType,- self.task.connectionInfo.host,- )+ super()._initLayout()+ if self._selectFilesButton is not None:+ self.layout().addWidget(self._selectFilesButton)++ def _bind(self):+ super()._bind()+ if self._selectFilesButton is not None:+ self._selectFilesButton.clicked.connect(self._onSelectFilesClicked)def _refreshSummary(self):- if self.task.countAll > 1 or self.task.isDirectory:- self.summaryLabel.setText(- self.tr("{0}/{1} 个文件 · {2}").format(- self.task.countSelected,- self.task.countAll,- toReadableSize(self.task.fileSize),- )- )+ if not self.task.files or len(self.task.files) <= 1:+ self.sizeLabel.setText(toReadableSize(self.task.fileSize))return-- self.summaryLabel.setText(toReadableSize(self.task.fileSize))+ self.sizeLabel.setText(+ self.tr("{0}/{1} 个文件 · {2}").format(+ self.task.countSelected,+ len(self.task.files),+ toReadableSize(self.task.fileSize),+ )+ )def _onSelectFilesClicked(self):- if _openFileSelection(self.task, self.window()) is not None:+ if openFileSelection(self.task, self.window()) is not None:self._refreshSummary()- def getTask(self) -> FtpTask:- return self.task--class FtpTaskCard(UniversalTaskCard):def __init__(self, task: FtpTask, parent=None):super().__init__(task, parent)- self.task = taskself.selectFilesButton = ToolButton(FluentIcon.LIBRARY, self)self.hBoxLayout.insertWidget(self.hBoxLayout.indexOf(self.verifyHashButton),self.selectFilesButton,)self.selectFilesButton.clicked.connect(self._onSelectFilesClicked)- self.openFileButton.clicked.disconnect()- self.openFolderButton.clicked.disconnect()- self.openFileButton.clicked.connect(self._openPrimaryTarget)- self.openFolderButton.clicked.connect(self._openTaskFolder)- self._refreshIconLabel()-- def _refreshIconLabel(self):- if self.task.isDirectory:- icon = QFileIconProvider().icon(QFileIconProvider.IconType.Folder)- else:- icon = QFileIconProvider().icon(QFileInfo(self.task.outputFolder))- self.iconLabel.setPixmap(icon.pixmap(48, 48))- self.iconLabel.setFixedSize(48, 48)-- def _selectedStageStats(self) -> tuple[int, int]:- receivedBytes = 0- speed = 0- for stage in self.task.selectedStages:- receivedBytes += stage.receivedBytes- speed += stage.speed- return receivedBytes, speed-- def _openPrimaryTarget(self):- openFile(self.task.outputFolder)-- def _openTaskFolder(self):- target = Path(self.task.outputFolder)- if target.exists():- openFolder(str(target))- return- openFolder(str(target.parent))- def statusInfoText(self) -> str | None:- if self.task.status == TaskStatus.PAUSED:- return super().statusInfoText()-- if self.task.status in {TaskStatus.WAITING, TaskStatus.COMPLETED}:- if self.task.countAll > 1 or self.task.isDirectory:- return self.tr("{0}/{1} 个文件").format(- self.task.countSelected,- self.task.countAll,- )-- return super().statusInfoText()-- def _renderTaskState(self):- super()._renderTaskState()-- receivedBytes, speed = self._selectedStageStats()- if self.task.fileSize > 0:- self.progressBar.setValue(receivedBytes / self.task.fileSize * 100)- self.progressLabel.setText(- f"{toReadableSize(receivedBytes)}/{toReadableSize(self.task.fileSize)}"- )- else:- self.progressLabel.setText(f"{toReadableSize(receivedBytes)}/--")+ def refresh(self):+ super().refresh()+ hasMultipleFiles = self.task.files and len(self.task.files) > 1+ self.selectFilesButton.setVisible(hasMultipleFiles)+ self.selectFilesButton.setEnabled(self.task.status != TaskStatus.RUNNING)- if self.task.status == TaskStatus.RUNNING:- self.speedLabel.setText(f"{toReadableSize(speed)}/s")- if self.task.fileSize > 0 and speed > 0:- remaining = max(0, self.task.fileSize - receivedBytes)- self.leftTimeLabel.setText(toReadableTime(int(remaining / speed)))- elif self.task.fileSize > 0:- self.leftTimeLabel.setText("--")+ if self.task.status in {TaskStatus.WAITING, TaskStatus.COMPLETED} and hasMultipleFiles:+ selected = sum(1 for f in self.task.files if f.selected)+ self.statusLabel.setText(self.tr("{0}/{1} 个文件").format(selected, len(self.task.files)))def _onSelectFilesClicked(self):if self.task.status == TaskStatus.RUNNING:return-- previousSelected = {- file.index for file in self.task.files if file.selected- }- selectedIndexes = _openFileSelection(self.task, self.window())- if selectedIndexes is None:- return-- if (- self.task.status == TaskStatus.COMPLETED- and selectedIndexes - previousSelected- and self.task.reopen()- ):- self.resumeTask()- return-- self.cardStatus = self.task.status- self._renderTaskState()-- def refresh(self):- super().refresh()- self.verifyHashButton.setVisible(- not self.task.isDirectory- and self.task.countSelected == 1- and self.task.status == TaskStatus.COMPLETED- and Path(self.task.outputFolder).is_file()- )- self.selectFilesButton.setVisible(self.task.countAll > 1)- self.selectFilesButton.setEnabled(self.task.status != TaskStatus.RUNNING)-+ openFileSelection(self.task, self.window())diff --git a/features/ftp_pack/pack.py b/features/ftp_pack/pack.pyindex 337c36a6..2581737d 100644--- a/features/ftp_pack/pack.py+++ b/features/ftp_pack/pack.py@@ -1,23 +1,144 @@-from urllib.parse import urlparse+from __future__ import annotations-from app.bases.interfaces import FeaturePack-from app.bases.models import Task-from .cards import FtpResultCard, FtpTaskCard-from .task import resolve as _ftpResolve+from pathlib import PurePosixPath+from urllib.parse import unquote, urlparse+from loguru import logger-class FtpPack(FeaturePack):- packId = "ftp"+from app.models.pack import FeaturePack, TaskParser+from app.models.task import Task, TaskOptions, SpecialFileSize+from app.platform.filesystem import toPosixPath, toSafeFilename+from .task import (+ FTP_DEFAULT_PORT,+ FtpConnectionInfo,+ FtpFile,+ FtpStep,+ FtpTask,+)+++class FtpParser(TaskParser):priority = 95- def matches(self, url: str) -> bool:- return urlparse(url).scheme.lower() in {"ftp", "ftps"}+ def match(self, options: TaskOptions) -> bool:+ return urlparse(options.url).scheme.lower() in {"ftp", "ftps"}++ async def parse(self, options: TaskOptions) -> Task:+ url = options.url.strip()+ parsed = urlparse(url)+ scheme = parsed.scheme.lower()++ sourcePath = PurePosixPath(unquote(parsed.path or "/"))+ connectionInfo = FtpConnectionInfo(+ scheme=scheme,+ host=parsed.hostname or "",+ port=parsed.port or FTP_DEFAULT_PORT,+ username=unquote(parsed.username or "anonymous"),+ password=unquote(parsed.password or "anon@"),+ sourcePath=str(sourcePath),+ hasPort=parsed.port is not None,+ )++ client = await connectionInfo.connect()+ try:+ sourceInfo = await client.stat(sourcePath)+ sourceType = sourceInfo["type"]+ if sourceType not in {"file", "dir"}:+ raise ValueError("当前 FTP 路径既不是普通文件,也不是目录")++ try:+ await client.command("TYPE I", "200")+ await client.command("REST 1", "350")+ canUseRangeRequests = True+ except Exception as e:+ logger.info("FTP 服务器不支持 REST 断点续传: {}", repr(e))+ canUseRangeRequests = False++ files: list[FtpFile] = []+ if sourceType == "file":+ files.append(FtpFile(+ index=0,+ remotePath=str(sourcePath),+ relativePath=sourcePath.name or "ftp_file",+ size=max(int(sourceInfo.get("size") or 0), 0) or SpecialFileSize.UNKNOWN,+ ))+ else:+ entries = [item async for item in client.list(sourcePath, recursive=True)]+ index = 0+ for remotePath, info in entries:+ if info["type"] != "file":+ continue+ relPath = (+ str(remotePath.relative_to(sourcePath))+ if sourcePath in remotePath.parents+ else remotePath.name+ )+ files.append(FtpFile(+ index=index,+ remotePath=str(remotePath),+ relativePath=relPath,+ size=max(int(info.get("size") or 0), 0) or SpecialFileSize.UNKNOWN,+ ))+ index += 1- async def parse(self, payload: dict) -> Task:- return await _ftpResolve(payload)+ if not files:+ raise ValueError("该 FTP 目录中没有可下载的普通文件")++ name = toSafeFilename(+ sourcePath.name or connectionInfo.host,+ fallback="ftp_download",+ )++ steps = []+ for file in files:+ steps.append(FtpStep(+ stepIndex=len(steps) + 1,+ fileIndex=file.index,+ remotePath=file.remotePath,+ fileSize=file.size,+ canUseRangeRequests=canUseRangeRequests,+ subworkerCount=options.subworkerCount,+ ))++ task = FtpTask(+ name=name,+ url=url,+ fileSize=sum(f.size for f in files),+ outputFolder=options.outputFolder,+ steps=steps,+ connectionInfo=connectionInfo,+ sourceType=sourceType,+ files=files,+ )+ return task+ finally:+ try:+ await client.quit()+ except Exception:+ client.close()+++class FtpPack(FeaturePack):+ packId = "ftp"+ proxySchemes = {"socks4", "socks5"}++ def parsers(self):+ return [FtpParser()]def taskCard(self, task, parent=None):+ from .cards import FtpTaskCardreturn FtpTaskCard(task, parent)- def resultCard(self, task, parent=None):- return FtpResultCard(task, parent)+ def draftCard(self, task, parent=None):+ from .cards import FtpDraftCard+ return FtpDraftCard(task, parent)++ def optionCards(self, task, parent=None):+ from app.view.components.option_cards import OutputFolderCard, SubworkerCountCard+ step = task.steps[0] if task.steps else None+ if step is None:+ return []+ return [+ OutputFolderCard(parent, initial=task.outputFolder),+ SubworkerCountCard(parent, initial=step.subworkerCount),+ ]diff --git a/features/ftp_pack/task.py b/features/ftp_pack/task.pyindex 25cd0cec..b1b6920e 100644--- a/features/ftp_pack/task.py+++ b/features/ftp_pack/task.py@@ -1,3 +1,5 @@+from __future__ import annotations+import asyncioimport osimport ssl@@ -6,351 +8,298 @@ from contextlib import suppressfrom dataclasses import dataclass, fieldfrom pathlib import Path, PurePosixPathfrom struct import pack, unpack-from typing import Anyfrom urllib.parse import unquote, urlparseimport aioftpfrom loguru import logger-from app.bases.interfaces import Worker-from app.bases.models import SpecialFileSize, Task, TaskStage, TaskStatus-from app.supports.config import cfg-from app.supports.sysio import ftruncate, pwrite-from app.supports.utils import getProxies, removePath, toSafeFilename+from app.config.cfg import cfg+from app.models.task import Task, TaskStep, TaskFile, TaskStatus, SpecialFileSize+from app.platform.filesystem import deletePath, toPosixPath+from app.platform.sysio import ftruncate, pwrite+from app.services.speed_meter import speedMeterFTP_CONNECTION_TIMEOUT = 15FTP_SOCKET_TIMEOUT = 30FTP_PATH_TIMEOUT = 30-FTP_CHUNK_SIZE = 65536FTP_RETRY_DELAY = 5FTP_DEFAULT_PORT = 21FTPS_DEFAULT_PORT = 990-def _parseSize(value) -> int:- size = int(value or 0)- return size if size > 0 else SpecialFileSize.UNKNOWN--def _buildArgs(proxies: dict | None) -> dict[str, Any]:- kwargs: dict[str, Any] = {- "connection_timeout": FTP_CONNECTION_TIMEOUT,- "socket_timeout": FTP_SOCKET_TIMEOUT,- "path_timeout": FTP_PATH_TIMEOUT,- }+@dataclass+class FtpConnectionInfo:+ scheme: str+ host: str+ port: int+ username: str+ password: str+ sourcePath: str+ hasPort: bool = False++ async def connect(self) -> aioftp.Client:+ from app.config.cfg import proxy++ scheme = self.scheme.lower()+ if scheme != "ftps":+ attempts = [(self.port, "plain")]+ elif not self.hasPort:+ attempts = [(FTP_DEFAULT_PORT, "explicit"), (FTPS_DEFAULT_PORT, "implicit")]+ elif self.port == FTPS_DEFAULT_PORT:+ attempts = [(self.port, "implicit")]+ else:+ attempts = [(self.port, "explicit"), (self.port, "implicit")]- proxyUrl = ""- if isinstance(proxies, dict):- for key in ("ftp", "https", "http"):- value = str(proxies.get(key) or "").strip()- if value:- proxyUrl = value- break- if not proxyUrl:- return kwargs-- parsedProxy = urlparse(proxyUrl)- if parsedProxy.scheme not in {"socks4", "socks5"}:- raise ValueError("FTP/FTPS 下载目前仅支持 SOCKS4/SOCKS5 代理或直连")- if not parsedProxy.hostname or not parsedProxy.port:- raise ValueError("代理配置无效")-- kwargs.update(- {- "socks_host": parsedProxy.hostname,- "socks_port": parsedProxy.port,- "socks_version": 4 if parsedProxy.scheme == "socks4" else 5,+ kwargs = {+ "connection_timeout": FTP_CONNECTION_TIMEOUT,+ "socket_timeout": FTP_SOCKET_TIMEOUT,+ "path_timeout": FTP_PATH_TIMEOUT,}- )- if parsedProxy.username:- kwargs["username"] = unquote(parsedProxy.username)- if parsedProxy.password:- kwargs["password"] = unquote(parsedProxy.password)- return kwargs++ url = proxy()+ if url:+ parsed = urlparse(url)+ if parsed.scheme in {"socks4", "socks5", "socks5h"} and parsed.hostname and parsed.port:+ kwargs.update({+ "socks_host": parsed.hostname,+ "socks_port": parsed.port,+ "socks_version": 4 if parsed.scheme == "socks4" else 5,+ })+ if parsed.username:+ kwargs["username"] = unquote(parsed.username)+ if parsed.password:+ kwargs["password"] = unquote(parsed.password)++ lastError: Exception | None = None+ for index, (port, mode) in enumerate(attempts):+ client = aioftp.Client(+ **kwargs,+ ssl=ssl.create_default_context() if mode == "implicit" else None,+ )+ try:+ await client.connect(self.host, port)+ if mode == "explicit":+ await client.upgrade_to_tls()+ await client.login(self.username, self.password)+ return client+ except Exception as e:+ client.close()+ lastError = e+ if index < len(attempts) - 1:+ logger.info(+ "{}://{}:{} 使用 {} TLS 连接失败,尝试下一种模式: {}",+ scheme, self.host, port, mode, repr(e),+ )++ raise lastError or RuntimeError("无法建立 FTP 连接")@dataclass-class FtpConnectionInfo:- host: str- scheme: str = "ftp"- port: int = FTP_DEFAULT_PORT- username: str = "anonymous"- password: str = "anon@"- sourcePath: str = "/"- portSpecified: bool = False--# 选了不一定下载, 故拆成 FtpFile 和 FtpStage-@dataclass-class FtpFile:+class FtpSubworker:index: int+ start: int+ end: int+ receivedBytes: int = 0++ @property+ def position(self) -> int:+ return self.start + self.receivedBytes+++@dataclass(kw_only=True)+class FtpFile(TaskFile):remotePath: str- relativePath: str- size: int- selected: bool = True- downloadedBytes: int = 0- completed: bool = Falsedef __post_init__(self):- self.remotePath = str(PurePosixPath(self.remotePath))- self.relativePath = str(PurePosixPath(self.relativePath))+ self.remotePath = toPosixPath(self.remotePath)+ self.relativePath = toPosixPath(self.relativePath)@dataclass(kw_only=True)-class FtpStage(TaskStage):+class FtpStep(TaskStep):fileIndex: intremotePath: str- fileSize: int- outputFile: str- supportsRange: bool = field(default=True)- accelerated: bool = field(default=False)+ fileSize: int = 0+ canUseRangeRequests: bool = False+ isAccelerated: bool = False+ subworkerCount: int = 8+ def __post_init__(self):+ self.canPause = self.canUseRangeRequests++ @property+ def outputPath(self) -> str:+ task: FtpTask = self.task+ if self.fileIndex >= 0 and task.files and task.isFolder:+ for file in task.files:+ if file.index == self.fileIndex:+ return toPosixPath(task.outputFolder / task.name / file.relativePath)+ return toPosixPath(task.outputFolder / task.name)++ def setOptions(self, options: dict) -> None:+ if "subworkerCount" in options:+ self.subworkerCount = options["subworkerCount"]def setStatus(self, status: TaskStatus, sync: bool = True):if status == TaskStatus.COMPLETED:self.receivedBytes = self.fileSizesuper().setStatus(status, sync=sync)+ @classmethod+ def fromFile(cls, file: TaskFile, task: Task) -> FtpStep:+ ftpFile: FtpFile = file+ return cls(+ stepIndex=file.index + 1,+ fileIndex=file.index,+ remotePath=ftpFile.remotePath,+ fileSize=file.size,+ canUseRangeRequests=True,+ subworkerCount=cfg.preBlockNum.value,+ )-@dataclass(kw_only=True, eq=False)-class FtpTask(Task):- packId: str = field(default="ftp")- connectionInfo: FtpConnectionInfo | dict[str, Any]- sourceType: str = field(default="file")- files: list[FtpFile | dict[str, Any]] = field(default_factory=list)- proxies: dict | None = field(default_factory=getProxies)- blockNum: int = field(default_factory=lambda: cfg.preBlockNum.value)-- def __post_init__(self):- if isinstance(self.connectionInfo, dict):- self.connectionInfo = FtpConnectionInfo(**self.connectionInfo)- self.files = [- item if isinstance(item, FtpFile) else FtpFile(**item)- for item in self.files- ]- self._filesByIndex = {file.index: file for file in self.files}- self.title = toSafeFilename(self.title, fallback="ftp_download")- super().__post_init__()- self._recalculateSelection()- self._syncFiles()- self.updateStagePaths()-- @property- def countAll(self) -> int:- return len(self.files)-- @property- def countSelected(self) -> int:- return sum(1 for file in self.files if file.selected)-- @property- def isDirectory(self) -> bool:- return self.sourceType == "dir"+ def _loadRecord(self) -> list[FtpSubworker]:+ recordPath = Path(self.outputPath + ".ghd")+ if not recordPath.exists():+ return []+ try:+ subworkers = []+ with open(recordPath, "rb") as f:+ index = 0+ while data := f.read(24):+ start, position, end = unpack("<QQQ", data)+ subworkers.append(FtpSubworker(+ index=index, start=start, end=end,+ receivedBytes=position - start,+ ))+ index += 1+ return subworkers+ except Exception as e:+ logger.opt(exception=e).error("恢复 FTP 下载分片失败 {}", self.outputPath)+ return []- @property- def selectedStages(self) -> list["FtpStage"]:- return [- stage- for stage in self.stages- if self.fileByIndex(stage.fileIndex).selected- ]+ def _buildSubworkers(self) -> list[FtpSubworker]:+ if not self.canUseRangeRequests:+ return [FtpSubworker(index=0, start=0, end=SpecialFileSize.NOT_SUPPORTED)]- def currentSnapshot(self) -> tuple[float, int, int]:- selectedStages = self.selectedStages- if not selectedStages:- return 0.0, 0, 0+ if self.fileSize <= 0:+ return [FtpSubworker(index=0, start=0, end=SpecialFileSize.UNKNOWN)]- receivedBytes = 0- speed = 0- progressSum = 0.0- for stage in selectedStages:- receivedBytes += stage.receivedBytes- speed += stage.speed- progressSum += stage.progress+ count = min(self.subworkerCount, self.fileSize)+ chunkSize = self.fileSize // count+ if chunkSize <= 0:+ return [FtpSubworker(index=0, start=0, end=max(0, self.fileSize - 1))]- if self.fileSize > 0:- progress = receivedBytes / self.fileSize * 100- else:- progress = progressSum / len(selectedStages)+ subworkers = []+ start = 0+ for i in range(count - 1):+ end = start + chunkSize - 1+ subworkers.append(FtpSubworker(index=i, start=start, end=end))+ start = end + 1+ subworkers.append(FtpSubworker(index=count - 1, start=start, end=self.fileSize - 1))+ return subworkers- return progress, speed, receivedBytes+ def _deleteRecord(self) -> None:+ target = Path(self.outputPath + ".ghd")+ try:+ if target.is_file() or target.is_symlink():+ target.unlink()+ except Exception as e:+ logger.opt(exception=e).error("删除进度文件失败 {}", target)- def cleanup(self):- if self.isDirectory:- removePath(Path(self.outputFolder))+ def _reassignSubworker(self) -> None:+ if self._stopping or self.task.status != TaskStatus.RUNNING or self.fileSize <= 0:return- for stage in self.stages:- outputFile = getattr(stage, "outputFile", "").strip()- if not outputFile:- continue- target = Path(outputFile)- removePath(target)- removePath(Path(str(target) + ".ghd"))-- def fileByIndex(self, index: int) -> FtpFile:- return self._filesByIndex[index]-- def updateStagePaths(self):- rootPath = Path(self.path) / self.title- if not self.isDirectory:- outputFile = str(rootPath)- for stage in self.stages:- stage.outputFile = outputFile+ slowest = max(self._subworkers, key=lambda sw: sw.end - sw.position + 1)+ remainingBytes = slowest.end - slowest.position + 1+ if remainingBytes < cfg.maxReassignSize.value * 1024:return- for stage in self.stages:- file = self.fileByIndex(stage.fileIndex)- stage.outputFile = str(- rootPath / Path(*PurePosixPath(file.relativePath).parts)- )-- def setTitle(self, title: str):- self.title = toSafeFilename(title, fallback=self.title or "ftp_download")- self.updateStagePaths()-- def _recalculateSelection(self):- self.fileSize = sum(file.size for file in self.files if file.selected)-- def _syncFiles(self):- stageByFileIndex = {stage.fileIndex: stage for stage in self.stages}-- for file in self.files:- stage = stageByFileIndex[file.index]- file.downloadedBytes = max(0, int(stage.receivedBytes))- file.completed = stage.status == TaskStatus.COMPLETED- if file.completed and file.size > 0:- file.downloadedBytes = max(file.downloadedBytes, file.size)+ base = remainingBytes // 2+ remainder = remainingBytes % 2+ oldEnd = slowest.end+ slowest.end = slowest.position + base + remainder - 1- def setSelection(self, selectedIndexes: set[int]):- if not selectedIndexes:- raise ValueError("至少需要选择一个文件")+ newSubworker = FtpSubworker(+ index=len(self._subworkers),+ start=slowest.end + 1,+ end=oldEnd,+ )+ self._subworkers.insert(self._subworkers.index(slowest) + 1, newSubworker)+ self._startSubworkerTask(newSubworker)- changed = False- for file in self.files:- selected = file.index in selectedIndexes- if file.selected != selected:- changed = True- file.selected = selected+ def _autoSpeedUp(self) -> None:+ if self.isAccelerated or not cfg.autoSpeedUp.value:+ return- if not changed:+ self._speedHistory.append(self.speed)+ if len(self._speedHistory) > 5:+ self._speedHistory.pop(0)+ if len(self._speedHistory) < 5:return- self._recalculateSelection()- self._syncFiles()- self.updateStatus()+ avgSpeed = sum(self._speedHistory) / len(self._speedHistory)+ if avgSpeed == 0:+ return- def updateStatus(self) -> TaskStatus:- self._syncFiles()- selectedStages = self.selectedStages- if not selectedStages:- self.status = TaskStatus.WAITING- return self.status+ maxDeviation = max(abs(s - avgSpeed) / avgSpeed for s in self._speedHistory)+ if maxDeviation > 0.15:+ return- stageStatus = [stage.status for stage in selectedStages]- activeStatuses = {- status for status in stageStatus if status != TaskStatus.COMPLETED- }- if TaskStatus.FAILED in activeStatuses:- self.status = TaskStatus.FAILED- elif not activeStatuses:- self.status = TaskStatus.COMPLETED- elif TaskStatus.RUNNING in activeStatuses:- self.status = TaskStatus.RUNNING- elif activeStatuses == {TaskStatus.PAUSED}:- self.status = TaskStatus.PAUSED+ if self._accelCheckTime == 0:+ self._accelInitialWorkers = len(self._subworkers)+ self._accelInitialSpeed = avgSpeed+ self._accelCheckTime = asyncio.get_event_loop().time()+ for _ in range(4):+ self._reassignSubworker()else:- self.status = TaskStatus.WAITING-- return self.status-- def setStatus(self, status: TaskStatus) -> TaskStatus:- selectedStageIds = {stage.stageId for stage in self.selectedStages}- for stage in self.stages:- if stage.stageId not in selectedStageIds:- continue- if stage.status == TaskStatus.COMPLETED:- continue- if status == TaskStatus.RUNNING and stage.status == TaskStatus.FAILED:- stage.reset(sync=False)- stage.setStatus(status, sync=False)-- return self.updateStatus()-- def reset(self) -> TaskStatus:- for file in self.files:- file.downloadedBytes = 0- file.completed = False- for stage in self.stages:- stage.reset(sync=False)- return self.updateStatus()-- def reopen(self) -> bool:- if self.status != TaskStatus.COMPLETED:- return False-- pendingSelectedStages = [- stage for stage in self.selectedStages if stage.status != TaskStatus.COMPLETED- ]- if not pendingSelectedStages:- return False-- for stage in pendingSelectedStages:- stage.setStatus(TaskStatus.PAUSED, sync=False)-- self._syncFiles()- self.updateStatus()- return True-- def applySettings(self, payload: dict[str, Any]):- super().applySettings(payload)- if "proxies" in payload:- self.proxies = payload["proxies"]- self.updateStagePaths()+ elapsed = asyncio.get_event_loop().time() - self._accelCheckTime+ if elapsed <= 5:+ return- @property- def canPause(self) -> bool:- selectedStages = self.selectedStages- return bool(selectedStages) and all(stage.supportsRange for stage in selectedStages)+ workerRatio = (len(self._subworkers) - self._accelInitialWorkers) / self._accelInitialWorkers+ speedRatio = (avgSpeed - self._accelInitialSpeed) / self._accelInitialSpeed- def pendingStages(self):- self.stages.sort(key=lambda stage: stage.stageIndex)- for stage in self.selectedStages:- if self.status != TaskStatus.RUNNING:- break- if stage.status == TaskStatus.COMPLETED:- continue- yield stage-- async def run(self):- currentStage = None+ if speedRatio < 0.8 * workerRatio:+ self.isAccelerated = True+ logger.info("自动加速已禁用,subworker 增加比: {:.2%}, 速度提升比: {:.2%}",+ workerRatio, speedRatio)+ else:+ self._accelCheckTime = 0+ logger.info("继续自动加速,subworker 增加比: {:.2%}, 速度提升比: {:.2%}",+ workerRatio, speedRatio)++ async def _supervise(self) -> None:+ recordFile = None+ if self.canUseRangeRequests:+ recordFile = open(self.outputPath + ".ghd", "wb")try:- for stage in self.pendingStages():- currentStage = stage- await FtpWorker(stage).run()- except CancelledError:- logger.info(f"{self.title} 停止下载")- raise- except Exception as e:- if currentStage is not None and not currentStage.error:- currentStage.setError(e)- logger.opt(exception=e).error("{} 下载失败", self.title)- raise---@dataclass-class FtpSubworker:- start: int- progress: int- end: int-+ self.receivedBytes = sum(sw.receivedBytes for sw in self._subworkers)+ while True:+ if recordFile is not None:+ data = tuple(+ val for sw in self._subworkers+ for val in (sw.start, sw.position, sw.end)+ )+ recordFile.seek(0)+ recordFile.write(pack("<" + "Q" * len(data), *data))+ recordFile.flush()+ recordFile.truncate()++ receivedBytes = sum(sw.receivedBytes for sw in self._subworkers)+ self.speed = receivedBytes - self.receivedBytes+ self.receivedBytes = receivedBytes+ if self.fileSize > 0:+ self.progress = (receivedBytes / self.fileSize) * 100+ else:+ self.progress = 0-class FtpWorker(Worker):- def __init__(self, stage: FtpStage):- super().__init__(stage)- self.stage = stage- self.task: FtpTask = stage._task- self.speedHistory: list[int] = []- self.accelCheckTime = 0.0- self.subworkerTasks: set[asyncio.Task] = set()- self._stopping = False+ self._autoSpeedUp()+ await asyncio.sleep(1)+ except CancelledError:+ pass+ finally:+ if recordFile is not None:+ recordFile.close()def _closeTransfer(self, client: aioftp.Client | None, stream):with suppress(Exception):@@ -359,550 +308,284 @@ class FtpWorker(Worker):if client is not None:client.close()- def _startSubworker(self, subworker: FtpSubworker):- if self._stopping:- return-- task = asyncio.create_task(self.handleSubworker(subworker))- self.subworkerTasks.add(task)- task.add_done_callback(self.subworkerTasks.discard)-- async def _stopSubworkers(self):- if self._stopping:- return-- self._stopping = True- runningTasks = tuple(task for task in self.subworkerTasks if not task.done())-- for task in runningTasks:- task.cancel()-- if not runningTasks:- return-- done, pending = await asyncio.wait(runningTasks, timeout=5)- for finishedTask in done:- with suppress(Exception, CancelledError):- finishedTask.result()-- if pending:- logger.warning(- "{} 仍有 {} 个 FTP 子任务未及时退出,已继续结束当前任务",- self.stage.outputFile,- len(pending),- )-- def reassignSubworker(self):- if self._stopping or self.task.status != TaskStatus.RUNNING or self.stage.fileSize <= 0:- return-- slowestSubworker = max(- self.subworkers,- key=lambda subworker: subworker.end - subworker.progress,- )- remainingBytes = slowestSubworker.end - slowestSubworker.progress- if remainingBytes < cfg.maxReassignSize.value * 1048576:- return-- base = remainingBytes // 2- remainder = remainingBytes % 2- slowestSubworker.end = slowestSubworker.progress + base + remainder- newSubworker = FtpSubworker(- slowestSubworker.end + 1,- slowestSubworker.end + 1,- slowestSubworker.end + base,- )- self.subworkers.insert(- self.subworkers.index(slowestSubworker) + 1,- newSubworker,- )- self._startSubworker(newSubworker)-- async def _downloadRange(self, subworker: FtpSubworker):- client = None- stream = None- try:- client = await _openClient(self.task.connectionInfo, self.task.proxies)- stream = await client.download_stream(- PurePosixPath(self.stage.remotePath),- offset=subworker.progress,- )+ async def _runSubworker(self, subworker: FtpSubworker, fd: int) -> None:+ ftpTask: FtpTask = self.task- remaining = subworker.end - subworker.progress + 1- while remaining > 0:- chunk = await stream.read(min(FTP_CHUNK_SIZE, remaining))- if not chunk:- raise RuntimeError("FTP 数据流提前结束")- chunkSize = len(chunk)-- await cfg.checkSpeedLimitation()- pwrite(self.fileHandle, chunk, subworker.progress)- subworker.progress += chunkSize- remaining -= chunkSize- cfg.globalSpeed += chunkSize- finally:- self._closeTransfer(client, stream)-- async def _downloadUnknown(self, subworker: FtpSubworker):- client = None- stream = None- try:- client = await _openClient(self.task.connectionInfo, self.task.proxies)- stream = await client.download_stream(- PurePosixPath(self.stage.remotePath),- offset=subworker.progress,- )-- while True:- chunk = await stream.read(FTP_CHUNK_SIZE)- if not chunk:- return- chunkSize = len(chunk)-- await cfg.checkSpeedLimitation()- pwrite(self.fileHandle, chunk, subworker.progress)- subworker.progress += chunkSize- cfg.globalSpeed += chunkSize- finally:- self._closeTransfer(client, stream)-- async def _downloadWholeFile(self, subworker: FtpSubworker):- client = None- stream = None- try:- client = await _openClient(self.task.connectionInfo, self.task.proxies)- stream = await client.download_stream(PurePosixPath(self.stage.remotePath))-- ftruncate(self.fileHandle, 0)- subworker.progress = 0-- while True:- chunk = await stream.read(FTP_CHUNK_SIZE)- if not chunk:- ftruncate(self.fileHandle, subworker.progress)- return- chunkSize = len(chunk)-- await cfg.checkSpeedLimitation()- pwrite(self.fileHandle, chunk, subworker.progress)- subworker.progress += chunkSize- cfg.globalSpeed += chunkSize- finally:- self._closeTransfer(client, stream)-- async def handleSubworker(self, subworker: FtpSubworker):if subworker.end == SpecialFileSize.UNKNOWN:while True:+ client = None+ stream = Nonetry:- await self._downloadUnknown(subworker)- return+ client = await ftpTask.connectionInfo.connect()+ stream = await client.download_stream(+ PurePosixPath(self.remotePath),+ offset=subworker.position,+ )+ while True:+ chunk = await stream.read(65536)+ if not chunk:+ return+ pwrite(fd, chunk, subworker.position)+ subworker.receivedBytes += len(chunk)+ speedMeter.addSpeed(len(chunk))+ await speedMeter.waitForSpeedLimit()except Exception as e:if self._stopping or self.task.status != TaskStatus.RUNNING:raise CancelledError- logger.opt(exception=e).error(- "{} 的未知大小分片 {} 连接中断,5 秒后重试",- self.stage.outputFile,- subworker,- )+ logger.opt(exception=e).error("{} 的未知大小分片连接中断,5 秒后重试", self.outputPath)await asyncio.sleep(FTP_RETRY_DELAY)+ finally:+ self._closeTransfer(client, stream)+elif subworker.end == SpecialFileSize.NOT_SUPPORTED:while True:+ client = None+ stream = Nonetry:- await self._downloadWholeFile(subworker)- return+ client = await ftpTask.connectionInfo.connect()+ stream = await client.download_stream(PurePosixPath(self.remotePath))+ ftruncate(fd, 0)+ subworker.receivedBytes = 0+ while True:+ chunk = await stream.read(65536)+ if not chunk:+ ftruncate(fd, subworker.receivedBytes)+ return+ pwrite(fd, chunk, subworker.receivedBytes)+ subworker.receivedBytes += len(chunk)+ speedMeter.addSpeed(len(chunk))+ await speedMeter.waitForSpeedLimit()except Exception as e:if self._stopping or self.task.status != TaskStatus.RUNNING:raise CancelledError- logger.opt(exception=e).error(- "{} 不支持断点续传,已从头开始重试",- self.stage.outputFile,- )+ logger.opt(exception=e).error("{} 不支持断点续传,已从头开始重试", self.outputPath)await asyncio.sleep(FTP_RETRY_DELAY)+ finally:+ self._closeTransfer(client, stream)+else:- while subworker.progress <= subworker.end:+ while subworker.position <= subworker.end:+ client = None+ stream = Nonetry:- await self._downloadRange(subworker)+ client = await ftpTask.connectionInfo.connect()+ stream = await client.download_stream(+ PurePosixPath(self.remotePath),+ offset=subworker.position,+ )+ remaining = subworker.end - subworker.position + 1+ while remaining > 0:+ chunk = await stream.read(min(65536, remaining))+ if not chunk:+ raise RuntimeError("FTP 数据流提前结束")+ pwrite(fd, chunk, subworker.position)+ chunkSize = len(chunk)+ subworker.receivedBytes += chunkSize+ remaining -= chunkSize+ speedMeter.addSpeed(chunkSize)+ await speedMeter.waitForSpeedLimit()breakexcept Exception as e:if self._stopping or self.task.status != TaskStatus.RUNNING:raise CancelledError- logger.opt(exception=e).error(- "{} 的分片 {} 连接中断,5 秒后重试",- self.stage.outputFile,- subworker,- )+ logger.opt(exception=e).error("{} 的分片连接中断,5 秒后重试", self.outputPath)await asyncio.sleep(FTP_RETRY_DELAY)+ finally:+ self._closeTransfer(client, stream)- if subworker.progress > subworker.end:- subworker.progress = subworker.end + 1+ if subworker.position > subworker.end:+ subworker.receivedBytes = subworker.end - subworker.start + 1- self.reassignSubworker()-- def _trySpeedUp(self):- if self.stage.accelerated or not cfg.autoSpeedUp.value:- return+ self._reassignSubworker()- self.speedHistory.append(self.stage.speed)- if len(self.speedHistory) > 5:- self.speedHistory.pop(0)- if len(self.speedHistory) < 5:- return-- avgSpeed = sum(self.speedHistory) / len(self.speedHistory)- if avgSpeed == 0:- return-- maxDeviation = max(- abs(speed - avgSpeed) / avgSpeed for speed in self.speedHistory- )- if maxDeviation > 0.15:- return-- if self.accelCheckTime == 0:- self.accelInitialWorkers = len(self.subworkers)- self.accelInitialSpeed = avgSpeed- self.accelCheckTime = asyncio.get_event_loop().time()-- for _ in range(4):- self.reassignSubworker()- else:- elapsedTime = asyncio.get_event_loop().time() - self.accelCheckTime- if elapsedTime <= 5:- return-- currentWorkers = len(self.subworkers)- workerIncreaseRatio = (- (currentWorkers - self.accelInitialWorkers) / self.accelInitialWorkers- )- speedIncreaseRatio = (- (avgSpeed - self.accelInitialSpeed) / self.accelInitialSpeed- )-- if speedIncreaseRatio < 0.8 * workerIncreaseRatio:- self.stage.accelerated = True- logger.info(- "FTP 自动加速已禁用,subworker 增加比: {:.2%}, 速度提升比: {:.2%}",- workerIncreaseRatio,- speedIncreaseRatio,- )- else:- self.accelCheckTime = 0- logger.info(- "继续 FTP 自动加速,subworker 增加比: {:.2%}, 速度提升比: {:.2%}",- workerIncreaseRatio,- speedIncreaseRatio,- )-- async def supervisor(self):- recordFileHandle = None- if self.stage.supportsRange:- recordFileHandle = open(Path(self.stage.outputFile + ".ghd"), "wb")- try:- self.stage.receivedBytes = sum(- subworker.progress - subworker.start for subworker in self.subworkers- )- while True:- if recordFileHandle is not None:- data = tuple(- value- for subworker in self.subworkers- for value in (- subworker.start,- subworker.progress,- subworker.end,- )- )- recordFileHandle.seek(0)- recordFileHandle.write(pack("<" + "Q" * len(data), *data))- recordFileHandle.flush()- recordFileHandle.truncate()-- receivedBytes = sum(- subworker.progress - subworker.start- for subworker in self.subworkers- )- self.stage.speed = receivedBytes - self.stage.receivedBytes- self.stage.receivedBytes = receivedBytes- if self.stage.fileSize > 0:- self.stage.progress = (receivedBytes / self.stage.fileSize) * 100- else:- self.stage.progress = 0-- self._trySpeedUp()- await asyncio.sleep(1)- except CancelledError:- logger.info(f"{self.stage.outputFile} 停止下载")- except Exception as e:- logger.opt(exception=e).error(- "{} 的监控协程异常退出",- self.stage.outputFile,- )- finally:- if recordFileHandle is not None:- recordFileHandle.close()-- def _restoreProgress(self) -> bool:- recordFile = Path(self.stage.outputFile + ".ghd")- if not recordFile.exists():- return False-- try:- with open(recordFile, "rb") as f:- while True:- data = f.read(24)- if not data:- break- start, progress, end = unpack("<QQQ", data)- self.subworkers.append(FtpSubworker(start, progress, end))- return True- except Exception as e:- logger.opt(exception=e).error("恢复 FTP 下载分片失败 {}", self.stage.outputFile)- self.subworkers.clear()- return False-- def _generateSubworkers(self):- if not self.stage.supportsRange:- self.subworkers.append(FtpSubworker(0, 0, SpecialFileSize.NOT_SUPPORTED))- return-- if self.stage.fileSize <= 0:- self.subworkers.append(FtpSubworker(0, 0, SpecialFileSize.UNKNOWN))+ def _startSubworkerTask(self, subworker: FtpSubworker):+ if self._stopping:return+ task = asyncio.create_task(self._runSubworker(subworker, self._fd))+ self._subworkerTasks.add(task)+ task.add_done_callback(self._subworkerTasks.discard)- step = self.stage.fileSize // self.task.blockNum- if step <= 0:- self.subworkers.append(FtpSubworker(0, 0, max(0, self.stage.fileSize - 1)))+ async def _stopSubworkerTasks(self):+ if self._stopping:return-- start = 0- for _ in range(self.task.blockNum - 1):- end = start + step - 1- self.subworkers.append(FtpSubworker(start, start, end))- start = end + 1-- self.subworkers.append(FtpSubworker(start, start, self.stage.fileSize - 1))-- def _cleanupRecordFile(self):- target = Path(self.stage.outputFile + ".ghd")- try:- if target.is_file() or target.is_symlink():- target.unlink()- except Exception as e:- logger.opt(exception=e).error("failed to cleanup temporary file {}", target)-- async def run(self):- self.subworkers: list[FtpSubworker] = []- self.subworkerTasks.clear()+ self._stopping = True+ running = tuple(t for t in self._subworkerTasks if not t.done())+ for t in running:+ t.cancel()+ if running:+ done, _ = await asyncio.wait(running, timeout=5)+ for t in done:+ with suppress(Exception, CancelledError):+ t.result()++ async def run(self) -> None:+ self._subworkers: list[FtpSubworker] = []+ self._subworkerTasks: set[asyncio.Task] = set()+ self._speedHistory: list[int] = []+ self._accelCheckTime = 0.0self._stopping = False- shouldCleanupRecordFile = False- Path(self.stage.outputFile).parent.mkdir(parents=True, exist_ok=True)+ shouldDeleteRecord = False++ Path(self.outputPath).parent.mkdir(parents=True, exist_ok=True)restored = False- if self.stage.supportsRange:- restored = self._restoreProgress()- else:- self._cleanupRecordFile()+ if self.canUseRangeRequests:+ loaded = self._loadRecord()+ if loaded:+ self._subworkers = loaded+ restored = Trueif not restored:- logger.info("正在为 {} 生成 FTP 下载分片", self.stage.outputFile)- self._generateSubworkers()- else:- logger.info("从进度文件恢复 FTP 下载分片 {}", self.stage.outputFile)+ if not self.canUseRangeRequests:+ self._deleteRecord()+ self._subworkers = self._buildSubworkers()openMode = os.O_RDWR | os.O_CREAT- if not self.stage.supportsRange:+ if not self.canUseRangeRequests:openMode |= os.O_TRUNC- self.fileHandle = os.open(self.stage.outputFile, openMode, 0o666)+ self._fd = os.open(self.outputPath, openMode, 0o666)- if not restored and self.stage.fileSize > 0:+ if not restored and self.fileSize > 0:try:- ftruncate(self.fileHandle, self.stage.fileSize)+ ftruncate(self._fd, self.fileSize)except Exception as e:- logger.opt(exception=e).error("{} 预分配文件大小失败", self.stage.outputFile)+ logger.opt(exception=e).error("{} 预分配文件大小失败", self.outputPath)- supervisor = asyncio.create_task(self.supervisor())+ supervisor = asyncio.create_task(self._supervise())try:- for subworker in self.subworkers:- self._startSubworker(subworker)-- while self.subworkerTasks:- currentTasks = tuple(self.subworkerTasks)- done, _ = await asyncio.wait(- currentTasks,- return_when=asyncio.FIRST_EXCEPTION,- )- for finishedTask in done:- if finishedTask.cancelled():+ for subworker in self._subworkers:+ self._startSubworkerTask(subworker)++ while self._subworkerTasks:+ currentTasks = tuple(self._subworkerTasks)+ done, _ = await asyncio.wait(currentTasks, return_when=asyncio.FIRST_EXCEPTION)+ for finished in done:+ if finished.cancelled():raise CancelledError- exception = finishedTask.exception()- if exception is not None:- raise exception+ exc = finished.exception()+ if exc is not None:+ raise exc- self.stage.setStatus(TaskStatus.COMPLETED)- shouldCleanupRecordFile = True- logger.info("{} 下载完成", self.stage.outputFile)+ self.setStatus(TaskStatus.COMPLETED)+ shouldDeleteRecord = Trueexcept CancelledError:- await self._stopSubworkers()- self.stage.setStatus(TaskStatus.PAUSED)+ await self._stopSubworkerTasks()+ self.setStatus(TaskStatus.PAUSED)raiseexcept Exception as e:- await self._stopSubworkers()- self.stage.setError(e)- logger.opt(exception=e).error("{} 下载阶段失败", self.stage.outputFile)+ await self._stopSubworkerTasks()+ self.setError(e)raisefinally:if not supervisor.done():supervisor.cancel()- with suppress(asyncio.CancelledError):+ with suppress(CancelledError):await supervisor- self.subworkerTasks.clear()- os.close(self.fileHandle)- if shouldCleanupRecordFile:- self._cleanupRecordFile()---async def _openClient(connectionInfo: FtpConnectionInfo, proxies: dict | None) -> aioftp.Client:- scheme = connectionInfo.scheme.lower()- if scheme != "ftps":- attempts = [(connectionInfo.port, "plain")]- elif not connectionInfo.portSpecified:- attempts = [(FTP_DEFAULT_PORT, "explicit"), (FTPS_DEFAULT_PORT, "implicit")]- elif connectionInfo.port == FTPS_DEFAULT_PORT:- attempts = [(connectionInfo.port, "implicit")]- else:- attempts = [(connectionInfo.port, "explicit"), (connectionInfo.port, "implicit")]-- lastError: Exception | None = None-- for index, (port, mode) in enumerate(attempts):- client = aioftp.Client(- **_buildArgs(proxies),- ssl=ssl.create_default_context() if mode == "implicit" else None,- )- try:- await client.connect(connectionInfo.host, port)- if mode == "explicit":- await client.upgrade_to_tls()- await client.login(connectionInfo.username, connectionInfo.password)- return client- except Exception as e:- client.close()- lastError = e- if index < len(attempts) - 1:- logger.info(- "{}://{}:{} 使用 {} TLS 连接失败,尝试下一种模式: {}",- connectionInfo.scheme.lower(),- connectionInfo.host,- port,- mode,- repr(e),- )-- raise lastError or RuntimeError("无法建立 FTP 连接")----async def _supportsRange(client: aioftp.Client) -> bool:- try:- await client.command("TYPE I", "200")- await client.command("REST 1", "350")- return True- except Exception as e:- logger.info("FTP 服务器不支持 REST 断点续传: {}", repr(e))- return False+ self._subworkerTasks.clear()+ os.close(self._fd)+ if shouldDeleteRecord:+ self._deleteRecord()-async def resolve(payload: dict) -> FtpTask:- url = str(payload["url"]).strip()- parsedUrl = urlparse(url)- scheme = parsedUrl.scheme.lower()- if scheme not in {"ftp", "ftps"}:- raise ValueError("不是有效的 FTP/FTPS 链接")- if not parsedUrl.hostname:- raise ValueError("FTP/FTPS 链接缺少主机名")-- sourcePath = PurePosixPath(unquote(parsedUrl.path or "/"))- connectionInfo = FtpConnectionInfo(- scheme=scheme,- host=parsedUrl.hostname,- port=parsedUrl.port or FTP_DEFAULT_PORT,- username=unquote(parsedUrl.username or "anonymous"),- password=unquote(parsedUrl.password or "anon@"),- sourcePath=str(sourcePath),- portSpecified=parsedUrl.port is not None,- )- proxies = payload.get("proxies", getProxies())- path = Path(payload.get("path", cfg.downloadFolder.value))- blockNum = payload.get("preBlockNum", cfg.preBlockNum.value)-- client = await _openClient(connectionInfo, proxies)- try:- sourceInfo = await client.stat(sourcePath)- sourceType = sourceInfo["type"]- if sourceType not in {"file", "dir"}:- raise ValueError("当前 FTP 路径既不是普通文件,也不是目录")-- supportsRange = await _supportsRange(client)- files: list[FtpFile] = []- stages: list[FtpStage] = []-- if sourceType == "file":- files.append(- FtpFile(- index=0,- remotePath=str(sourcePath),- relativePath=sourcePath.name or "ftp_file",- size=_parseSize(sourceInfo.get("size")),- )- )+@dataclass(kw_only=True, eq=False)+class FtpTask(Task):+ packId: str = "ftp"+ canEdit = True+ fileType = FtpFile+ connectionInfo: FtpConnectionInfo+ sourceType: str = "file"+ stepType: type = field(default=FtpStep, repr=False)++ def __post_init__(self):+ if isinstance(self.connectionInfo, dict):+ self.connectionInfo = FtpConnectionInfo(**self.connectionInfo)+ super().__post_init__()++ @property+ def isFolder(self) -> bool:+ return self.sourceType == "dir"++ @property+ def countSelected(self) -> int:+ return sum(1 for file in self.files if file.selected)++ def _updateFilesFromSteps(self) -> None:+ if not self.files:+ return+ for step in self.steps:+ fileIndex = getattr(step, "fileIndex", None)+ if fileIndex is not None and fileIndex < len(self.files):+ file = self.files[fileIndex]+ file.downloadedBytes = step.receivedBytes+ file.completed = step.status == TaskStatus.COMPLETED++ def updateStatus(self) -> TaskStatus:+ self._updateFilesFromSteps()+ selected = [s for s in self.steps if self._isStepSelected(s)]+ if not selected:+ self.status = TaskStatus.COMPLETED+ return self.status+ statuses = [s.status for s in selected]+ if any(s == TaskStatus.FAILED for s in statuses):+ self.status = TaskStatus.FAILED+ elif all(s == TaskStatus.COMPLETED for s in statuses):+ self.status = TaskStatus.COMPLETED+ elif any(s == TaskStatus.RUNNING for s in statuses):+ self.status = TaskStatus.RUNNING+ elif all(s == TaskStatus.PAUSED for s in statuses):+ self.status = TaskStatus.PAUSEDelse:- entries = [item async for item in client.list(sourcePath, recursive=True)]- index = 0- for remotePath, info in entries:- if info["type"] != "file":- continue- files.append(- FtpFile(- index=index,- remotePath=str(remotePath),- relativePath=(str(remotePath.relative_to(sourcePath)) if sourcePath in remotePath.parents else remotePath.name),- size=_parseSize(info.get("size")),- )- )- index += 1-- if not files:- raise ValueError("该 FTP 目录中没有可下载的普通文件")-- for file in files:- stages.append(- FtpStage(- stageIndex=len(stages) + 1,- fileIndex=file.index,- remotePath=file.remotePath,- fileSize=file.size,- outputFile="",- supportsRange=supportsRange,- )- )+ self.status = TaskStatus.WAITING+ return self.status- task = FtpTask(- title=toSafeFilename(sourcePath.name, fallback="ftp_download") if sourcePath.name else toSafeFilename(connectionInfo.host, fallback="ftp_download"),- url=url,- fileSize=sum(file.size for file in files),- path=path,- stages=stages,- connectionInfo=connectionInfo,- sourceType=sourceType,- files=files,- proxies=proxies,- blockNum=blockNum if isinstance(blockNum, int) else cfg.preBlockNum.value,- )- return task- finally:- if client is not None:- try:- await client.quit()- except Exception:- client.close()+ def setStatus(self, status: TaskStatus) -> TaskStatus:+ for step in self.steps:+ if not self._isStepSelected(step):+ continue+ if step.status == TaskStatus.COMPLETED:+ continue+ if status == TaskStatus.RUNNING and step.status == TaskStatus.FAILED:+ step.reset(sync=False)+ step.setStatus(status, sync=False)+ return self.updateStatus()++ def pendingSteps(self):+ self.steps.sort(key=lambda step: step.stepIndex)+ for step in self.steps:+ if self.status != TaskStatus.RUNNING:+ break+ if not self._isStepSelected(step):+ continue+ if step.status == TaskStatus.COMPLETED:+ continue+ yield step++ def currentSnapshot(self) -> tuple[float, int, int]:+ selected = [s for s in self.steps if self._isStepSelected(s)]+ if not selected:+ return 0.0, 0, 0+ progress = sum(s.progress for s in selected) / len(selected)+ speed = sum(s.speed for s in selected)+ receivedBytes = sum(s.receivedBytes for s in selected)+ return progress, speed, receivedBytes++ def deleteFiles(self):+ if self.isFolder:+ deletePath(Path(self.outputPath))+ return+ for step in self.steps:+ target = Path(step.outputPath)+ deletePath(target)+ deletePath(Path(f"{target}.ghd"))++ def _isStepSelected(self, step) -> bool:+ if not self.files:+ return True+ fileIndex = getattr(step, "fileIndex", None)+ if fileIndex is None:+ return True+ for file in self.files:+ if file.index == fileIndex:+ return file.selected+ return Falsediff --git a/features/github_pack/config.py b/features/github_pack/config.pyindex 2ad70571..7d66272e 100644--- a/features/github_pack/config.py+++ b/features/github_pack/config.py@@ -1,66 +1,23 @@-import asyncio-from time import perf_counter-from typing import TYPE_CHECKING-from urllib.parse import urlparse--import niquests-from PySide6.QtCore import Qt-from loguru import logger-from qfluentwidgets import (- BoolValidator,- ComboBox,- ConfigItem,- ConfigValidator,- FluentIcon,- HyperlinkButton,- LineEdit,- MessageBoxBase,- OptionsConfigItem,- OptionsValidator,- PlainTextEdit,- SettingCard,- SubtitleLabel,- SwitchSettingCard,- ToolButton,- ToolTipFilter,-)+from __future__ import annotations-from app.bases.models import PackConfig-from app.services.core_service import coreService-from app.supports.config import cfg-from app.supports.utils import getProxies-from app.view.components.setting_card_group import CollapsibleSettingCardGroup--if TYPE_CHECKING:- from app.view.pages.setting_page import SettingPage+from urllib.parse import urlparse+from app.client import buildClient+from app.config.cfg import ConfigItem+from app.models.pack import PackConfig+from qfluentwidgets import BoolValidator, ComboBox, ConfigValidator, FluentIcon, LineEdit, SettingCard, ToolButton, ToolTipFilterGITHUB_PROXY_SITES = (- "https://gh-proxy.com/",- "https://ghproxy.vip/",- "https://ghproxy.homeboyc.cn/",- "https://gh.llkk.cc/",+ "https://gh-proxy.com",+ "https://ghproxy.vip",+ "https://ghproxy.homeboyc.cn",+ "https://gh.llkk.cc",)-GITHUB_CUSTOM_PROXY_SITE = "__custom__"-GITHUB_PROBE_TARGET = "https://raw.githubusercontent.com/asjdf/ghproxy/main/src/index.ts"--GITHUB_USER_AGREEMENT = """使用前请确认以下风险并自行承担:--1. GitHub Pack 使用的是第三方 GitHub 反向代理站,这些站点并非由 Ghost Downloader 或 GitHub 官方运营。-2. 当你启用该功能后,请求会先经过你选定的代理站,代理站可能获取你的请求地址、IP、请求头等网络信息。-3. 请不要使用该功能下载包含 Cookie、Token、私有仓库鉴权信息、签名链接或其他敏感凭据的 GitHub 链接。-4. 第三方代理站可能出现内容篡改、缓存过期、服务中断、限流、劫持或记录访问日志等风险。-5. 对于重要文件,请在下载完成后自行校验哈希值、签名或文件来源,确认文件完整性与可信性。-6. 代理站的可用性、速度和合规性会随时变化;是否继续使用以及由此产生的后果,由你自行判断并负责。--继续启用即表示你已阅读、理解并同意以上内容。"""-+CUSTOM_SITE_KEY = "__custom__"+PROBE_TARGET = "https://raw.githubusercontent.com/asjdf/ghproxy/main/src/index.ts"-def _siteName(site: str) -> str:- return urlparse(site).netloc or site.rstrip("/")--def _normalizeSite(site: str) -> str:+def toProxySite(site: str) -> str:value = str(site or "").strip()if not value:return ""@@ -69,129 +26,72 @@ def _normalizeSite(site: str) -> str:return value.rstrip("/")+def selectedProxySite() -> str:+ if githubConfig.selectedSite.value == CUSTOM_SITE_KEY:+ return githubConfig.customSite.value+ return githubConfig.selectedSite.value+++async def probeProxyLatencies() -> dict[str, int]:+ import asyncio+ from time import perf_counter++ sites = list(GITHUB_PROXY_SITES)+ custom = githubConfig.customSite.value+ if custom:+ sites.append(custom)++ async def probeOne(site: str) -> tuple[str, int]:+ url = f"{site.rstrip('/')}/{PROBE_TARGET}"+ client = buildClient()+ try:+ start = perf_counter()+ response = await asyncio.wait_for(client.get(url), timeout=10)+ elapsed = int((perf_counter() - start) * 1000)+ return site, elapsed if response.status.as_int() < 400 else -1+ except Exception:+ return site, -1+ finally:+ client.close()++ results = await asyncio.gather(*(probeOne(s) for s in sites))+ return dict(results)++class GitHubProxySiteValidator(ConfigValidator):def validate(self, value) -> bool:- site = _normalizeSite(value)+ site = toProxySite(value)if not site:return False-- parsedSite = urlparse(site)+ parsed = urlparse(site)return (- parsedSite.scheme in {"http", "https"}- and bool(parsedSite.netloc)- and not parsedSite.params- and not parsedSite.query- and not parsedSite.fragment+ parsed.scheme in {"http", "https"}+ and bool(parsed.netloc)+ and not parsed.params+ and not parsed.query+ and not parsed.fragment)def correct(self, value) -> str:- site = _normalizeSite(value)+ site = toProxySite(value)return site if self.validate(site) else ""-def selectedProxySite() -> str:- if githubConfig.proxySite.value == GITHUB_CUSTOM_PROXY_SITE:- return githubConfig.customProxySite.value- return githubConfig.proxySite.value---def _siteText(site: str, latency: int | None) -> str:- if latency is None:- return _siteName(site)- if latency < 0:- return f"{_siteName(site)} (超时)"- return f"{_siteName(site)} ({latency} ms)"---def _customSiteText(site: str, latency: int | None) -> str:- if not site:- return "自定义"- if latency is None:- return "自定义"- if latency < 0:- return "自定义 (超时)"- return f"自定义 ({latency} ms)"---class GitHubAgreementDialog(MessageBoxBase):- def __init__(self, parent=None, requireAcceptance: bool = False):- super().__init__(parent)- self.requireAcceptance = requireAcceptance- self.titleLabel = SubtitleLabel(self.tr("GitHub 加速用户协议"), self)- self.contentEdit = PlainTextEdit(self)-- self._initWidget()-- def _initWidget(self):- self.widget.setMinimumWidth(560)- self.contentEdit.setReadOnly(True)- self.contentEdit.setPlainText(self.tr(GITHUB_USER_AGREEMENT))- self.contentEdit.setMinimumHeight(260)-- if self.requireAcceptance:- self.yesButton.setText(self.tr("同意并启用"))- self.cancelButton.setText(self.tr("取消"))- else:- self.yesButton.setText(self.tr("关闭"))- self.cancelButton.hide()-- self.viewLayout.addWidget(self.titleLabel)- self.viewLayout.addSpacing(8)- self.viewLayout.addWidget(self.contentEdit)---async def measureProxyLatencies() -> dict[str, int]:- sites = list(GITHUB_PROXY_SITES)- customSite = githubConfig.customProxySite.value- if customSite and customSite not in sites:- sites.append(customSite)-- async with niquests.AsyncSession(happy_eyeballs=True) as session:- session.trust_env = False-- async def measureSiteLatency(site: str) -> tuple[str, int]:- startedAt = perf_counter()- try:- response = await session.get(- f"{site.rstrip('/')}/{GITHUB_PROBE_TARGET}",- timeout=15,- proxies=getProxies(),- verify=cfg.SSLVerify.value,- allow_redirects=True,- stream=True,- )- try:- response.raise_for_status()- finally:- await response.close()-- return site, max(1, int((perf_counter() - startedAt) * 1000))- except Exception as e:- logger.opt(exception=e).error("{} 测速失败", site)- return site, -1-- results = await asyncio.gather(*(measureSiteLatency(site) for site in sites))-- return dict(results)--class GitHubProxySiteCard(SettingCard):def __init__(self, parent=None):super().__init__(- FluentIcon.GLOBE,- self.tr("代理站"),- self.tr("选择 GitHub 反向代理站,延迟仅供参考"),- parent,+ FluentIcon.GLOBE, self.tr("代理站"),+ self.tr("选择 GitHub 反向代理站,延迟仅供参考"), parent,)- self.latencies = {site: None for site in GITHUB_PROXY_SITES}+ self._latencies: dict[str, int | None] = {s: None for s in GITHUB_PROXY_SITES}+ self._isRefreshing = Falseself.comboBox = ComboBox(self)self.customSiteEdit = LineEdit(self)self.refreshButton = ToolButton(FluentIcon.SYNC, self)- self.isRefreshing = Falseself._initWidget()- self._reloadItems()- self._connectSignalToSlot()+ self._initLayout()+ self._bind()def _initWidget(self):self.comboBox.setMinimumWidth(260)@@ -200,6 +100,22 @@ class GitHubProxySiteCard(SettingCard):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)@@ -207,128 +123,92 @@ class GitHubProxySiteCard(SettingCard):self.hBoxLayout.addWidget(self.refreshButton)self.hBoxLayout.addSpacing(16)- def _connectSignalToSlot(self):+ def _bind(self):self.comboBox.currentIndexChanged.connect(self._onCurrentIndexChanged)self.customSiteEdit.editingFinished.connect(self._onCustomSiteEditingFinished)self.refreshButton.clicked.connect(self.refreshLatencies)- def _reloadItems(self):- currentSite = githubConfig.proxySite.value- if currentSite not in (*GITHUB_PROXY_SITES, GITHUB_CUSTOM_PROXY_SITE):- currentSite = GITHUB_PROXY_SITES[0]- customSite = githubConfig.customProxySite.value- customLatency = self.latencies.get(customSite)-- self.comboBox.blockSignals(True)- self.customSiteEdit.blockSignals(True)- self.comboBox.clear()- for site in GITHUB_PROXY_SITES:- self.comboBox.addItem(_siteText(site, self.latencies[site]))- self.comboBox.addItem(_customSiteText(customSite, customLatency))- if currentSite == GITHUB_CUSTOM_PROXY_SITE:- self.comboBox.setCurrentIndex(len(GITHUB_PROXY_SITES))+ def _refreshLatencyLabels(self):+ for i, site in enumerate(GITHUB_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 = githubConfig.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:- self.comboBox.setCurrentIndex(GITHUB_PROXY_SITES.index(currentSite))- self.customSiteEdit.setText(customSite)- self.customSiteEdit.setVisible(currentSite == GITHUB_CUSTOM_PROXY_SITE)- self.comboBox.blockSignals(False)- self.customSiteEdit.blockSignals(False)+ customLabel = f"{self.tr('自定义')} ({customLatency} ms)"+ self.comboBox.setItemText(len(GITHUB_PROXY_SITES), customLabel)def _onCurrentIndexChanged(self, index: int):+ from app.config.cfg import cfgif index < 0:returnif index < len(GITHUB_PROXY_SITES):- cfg.set(githubConfig.proxySite, GITHUB_PROXY_SITES[index])+ cfg.set(githubConfig.selectedSite, GITHUB_PROXY_SITES[index])else:- cfg.set(githubConfig.proxySite, GITHUB_CUSTOM_PROXY_SITE)- self._reloadItems()+ cfg.set(githubConfig.selectedSite, CUSTOM_SITE_KEY)+ self.customSiteEdit.setVisible(index >= len(GITHUB_PROXY_SITES))def _onCustomSiteEditingFinished(self):- oldCustomSite = githubConfig.customProxySite.value- cfg.set(githubConfig.customProxySite, self.customSiteEdit.text())- if oldCustomSite and oldCustomSite not in GITHUB_PROXY_SITES:- self.latencies.pop(oldCustomSite, None)- self._reloadItems()+ from app.config.cfg import cfg+ cfg.set(githubConfig.customSite, self.customSiteEdit.text().strip())def refreshLatencies(self):- if self.isRefreshing:+ if self._isRefreshing:return-- self.isRefreshing = True- self.latencies = {site: None for site in GITHUB_PROXY_SITES}- self._reloadItems()+ self._isRefreshing = True+ self._latencies = {s: None for s in GITHUB_PROXY_SITES}+ self._refreshLatencyLabels()self.refreshButton.setEnabled(False)- coreService.runCoroutine(measureProxyLatencies(), self._onLatencyUpdated)+ from app.services.coroutine_runner import coroutineRunner- def _onLatencyUpdated(self, latencies: dict[str, int] | None, error: str | None = None):- self.isRefreshing = False- self.refreshButton.setEnabled(True)+ coroutineRunner.submit(+ probeProxyLatencies(),+ done=self._onLatenciesDone, failed=self._onLatenciesFailed,+ owner=self,+ )- if error:- logger.error("GitHub 代理站测速失败: {}", error)- return- if latencies is None:- return+ def _onLatenciesDone(self, latencies: dict[str, int]):+ self._isRefreshing = False+ self.refreshButton.setEnabled(True)+ self._latencies.update(latencies)+ self._refreshLatencyLabels()- self.latencies.update(latencies)- self._reloadItems()+ def _onLatenciesFailed(self, error):+ self._isRefreshing = False+ self.refreshButton.setEnabled(True)class GitHubConfig(PackConfig):enabled = ConfigItem("GitHub", "Enabled", False, BoolValidator())- proxySite = OptionsConfigItem(- "GitHub",- "ProxySite",- GITHUB_PROXY_SITES[0],- OptionsValidator([*GITHUB_PROXY_SITES, GITHUB_CUSTOM_PROXY_SITE]),- )- customProxySite = ConfigItem(- "GitHub",- "CustomProxySite",- "",- GitHubProxySiteValidator(),- )-- def setupSettings(self, settingPage: "SettingPage"):- self.githubGroup = CollapsibleSettingCardGroup(self.tr("GitHub 加速"), "github", settingPage.container)- self.enableCard = SwitchSettingCard(- FluentIcon.LINK,- self.tr("启用 GitHub 加速"),- self.tr("命中 GitHub 文件链接时,自动改写为所选反向代理站"),- self.enabled,- self.githubGroup,- )- self.viewAgreementButton = HyperlinkButton(self.enableCard)- self.viewAgreementButton.setText(self.tr("查看协议"))- self.proxySiteCard = GitHubProxySiteCard(self.githubGroup)-- self.enableCard.hBoxLayout.insertSpacing(5, 16)- self.enableCard.hBoxLayout.insertWidget(5, self.viewAgreementButton, 0, Qt.AlignmentFlag.AlignRight)- self.githubGroup.addSettingCard(self.enableCard)- self.githubGroup.addSettingCard(self.proxySiteCard)+ selectedSite = ConfigItem("GitHub", "SelectedSite", GITHUB_PROXY_SITES[0], GitHubProxySiteValidator())+ customSite = ConfigItem("GitHub", "CustomSite", "", GitHubProxySiteValidator())- settingPage.addSettingGroup(self.githubGroup)+ def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:+ from qfluentwidgets import FluentIcon, SwitchSettingCard+ from app.view.components.setting_card_group import CollapsibleSettingCardGroup- self.enableCard.checkedChanged.connect(self._onEnabledChanged)- self.viewAgreementButton.clicked.connect(self._showAgreement)-- def _showAgreementDialog(self, parent, requireAcceptance: bool) -> bool:- dialog = GitHubAgreementDialog(parent, requireAcceptance=requireAcceptance)- accepted = dialog.exec()- dialog.deleteLater()- return accepted-- def _onEnabledChanged(self, checked: bool):- if not checked:- return-- if self._showAgreementDialog(self.enableCard.window(), requireAcceptance=True):- return-- cfg.set(self.enabled, False)+ githubGroup = CollapsibleSettingCardGroup(self.tr("GitHub 加速"), "github", parent)+ enableCard = SwitchSettingCard(+ FluentIcon.LINK, self.tr("启用 GitHub 加速"),+ self.tr("命中 GitHub 文件链接时,自动改写为所选反向代理站"),+ self.enabled, githubGroup,+ )+ proxySiteCard = GitHubProxySiteCard(githubGroup)- def _showAgreement(self):- self._showAgreementDialog(self.enableCard.window(), requireAcceptance=False)+ githubGroup.addSettingCards([enableCard, proxySiteCard])+ return [githubGroup]githubConfig = GitHubConfig()diff --git a/features/github_pack/pack.py b/features/github_pack/pack.pyindex eae4ba71..fc10822e 100644--- a/features/github_pack/pack.py+++ b/features/github_pack/pack.py@@ -1,17 +1,10 @@-from typing import TYPE_CHECKINGfrom urllib.parse import urlparse-from app.bases.interfaces import FeaturePack-from app.bases.models import Task+from app.models.pack import FeaturePack, TaskParser+from app.models.task import Task, TaskOptionsfrom .config import githubConfig, selectedProxySite-if TYPE_CHECKING:- from features.http_pack.pack import HttpPack-else:- from http_pack.pack import HttpPack---_SUPPORTED_GITHUB_HOSTS = {+GITHUB_HOSTS = {"api.github.com","codeload.github.com","gist.github.com",@@ -24,7 +17,7 @@ _SUPPORTED_GITHUB_HOSTS = {}-def _isSupportedGitHubUrl(url: str) -> bool:+def isGitHubFileUrl(url: str) -> bool:parsedUrl = urlparse(url)scheme = parsedUrl.scheme.lower()host = (parsedUrl.hostname or "").lower().removeprefix("www.")@@ -33,7 +26,7 @@ def _isSupportedGitHubUrl(url: str) -> bool:if scheme not in {"http", "https"} or not host:return False- if host in _SUPPORTED_GITHUB_HOSTS:+ if host in GITHUB_HOSTS:return Trueif host != "github.com":@@ -47,25 +40,34 @@ def _isSupportedGitHubUrl(url: str) -> bool:)-class GitHubPack(FeaturePack):- packId = "github"+class GitHubParser(TaskParser):priority = 90- config = githubConfig- def matches(self, url: str) -> bool:- return self.config.enabled.value and bool(selectedProxySite()) and _isSupportedGitHubUrl(url)+ def match(self, options: TaskOptions) -> bool:+ return (+ githubConfig.enabled.value+ and bool(selectedProxySite())+ and isGitHubFileUrl(options.url)+ )++ async def parse(self, options: TaskOptions) -> Task:+ from dataclasses import replace+ from app.services.feature_service import featureService++ proxiedUrl = f"{selectedProxySite().rstrip('/')}/{options.url.lstrip('/')}"+ task = await featureService.parse(replace(options, url=proxiedUrl))+ task.url = options.url+ task.packId = "github"+ return task- async def parse(self, payload: dict) -> Task:- originalUrl = str(payload["url"]).strip()- proxiedPayload = payload.copy()- proxiedPayload["url"] = f"{selectedProxySite().rstrip('/')}/{originalUrl.lstrip('/')}"- httpPack = HttpPack()- task = await httpPack.parse(proxiedPayload)- task.url = originalUrl- task.packId = self.packId- return task+class GitHubPack(FeaturePack):+ packId = "github"+ config = githubConfig++ def parsers(self):+ return [GitHubParser()]- def taskCard(self, task: Task, parent=None):+ def taskCard(self, task, parent=None):from http_pack.cards import HttpTaskCardreturn HttpTaskCard(task, parent)diff --git a/features/http_pack/cards.py b/features/http_pack/cards.pyindex de6bd013..b60ca813 100644--- a/features/http_pack/cards.py+++ b/features/http_pack/cards.py@@ -1,42 +1,32 @@from PySide6.QtCore import Qt, QRectF, QTimer-from PySide6.QtGui import QColor, QPainter+from PySide6.QtGui import QColor, QPainter, QPaintEventfrom PySide6.QtWidgets import QWidgetfrom qfluentwidgets import isDarkTheme, themeColor-from app.view.components.cards import UniversalTaskCard-from .task import HttpTaskStage+from app.view.cards.task_cards import UniversalTaskCard+from .task import HttpTaskStepFILL_EASING = 0.25class SegmentedProgressBar(QWidget):- """多连接下载的分段进度条-- 整条代表文件 [0, fileSize], 每个分片按真实字节区间 [start, progress) 填充,- 分片间的待下载区天然留缝. 配色与 qfluentwidgets.ProgressBar 对齐.- """-- def __init__(self, stage: HttpTaskStage, parent: QWidget = None):+ def __init__(self, step: HttpTaskStep, parent=None):super().__init__(parent)- self._stage = stage+ self._step = stepself._isPaused = Falseself._isError = Falseself._fillProgress: dict[int, float] = {}self._spans: list[tuple[float, float]] = []self._fillTimer = QTimer(self, interval=16)- self._bind()-- def _bind(self):self._fillTimer.timeout.connect(self._onFillTimeout)def setValue(self, value: float):- # 数值不看: 段位置取自 subworkers; 立即推进一步免挂载首帧空白self._fillTimer.start()self._onFillTimeout()def _onFillTimeout(self):- live = {sw.start: sw.progress for sw in list(self._stage.subworkers)}- fresh = not self._fillProgress # 首次填充(挂载/恢复运行): 直接到位, 不从头爬+ live = {sw.start: sw.position for sw in list(self._step.subworkers)}+ fresh = not self._fillProgresssettled = Truefor start, target in live.items():shown = self._fillProgress.get(start, target if fresh else start)@@ -45,11 +35,10 @@ class SegmentedProgressBar(QWidget):settled = Falseelse:self._fillProgress[start] = target- self._fillProgress = {start: self._fillProgress[start] for start in live} # 剪掉消失的段+ self._fillProgress = {start: self._fillProgress[start] for start in live}self._spans = self._toMergedSpans()- if not self._spans and self._stage.receivedBytes > 0:- # worker 没跑过(重启恢复/等待中): 退化成单根, 按已收字节画- self._spans = [(0, self._stage.receivedBytes)]+ if not self._spans and self._step.receivedBytes > 0:+ self._spans = [(0, self._step.receivedBytes)]if settled:self._fillTimer.stop()self.update()@@ -60,9 +49,8 @@ class SegmentedProgressBar(QWidget):self._isPaused = Falseself.update()- def error(self):- self._isError = True- self.update()+ def error(self) -> bool:+ return self._isErrordef pause(self):self._isPaused = True@@ -76,7 +64,6 @@ class SegmentedProgressBar(QWidget):return themeColor()def _toMergedSpans(self) -> list[tuple[float, float]]:- # 相邻分片下载完后首尾恰好相接, 合并掉以免接缝处冒出假凹口intervals = sorted((start, shown) for start, shown in self._fillProgress.items() if shown > start)@@ -88,8 +75,8 @@ class SegmentedProgressBar(QWidget):merged.append((start, end))return merged- def paintEvent(self, e):- fileSize = self._stage.fileSize+ def paintEvent(self, event: QPaintEvent):+ fileSize = self._step.fileSizeif fileSize <= 0 or not self._spans:return@@ -108,10 +95,8 @@ class SegmentedProgressBar(QWidget):class HttpTaskCard(UniversalTaskCard):- """HTTP 任务卡片: 已知大小且支持续传时用分段进度条, 否则退回通用进度条"""-- def createProgressBar(self) -> QWidget:- stage = self.task.stages[0]- if isinstance(stage, HttpTaskStage) and self.task.fileSize > 0 and stage.supportsRange:- return SegmentedProgressBar(stage, self)- return super().createProgressBar()+ def _buildProgressBar(self) -> QWidget:+ step = self.task.steps[0] if self.task.steps else None+ if isinstance(step, HttpTaskStep) and step.canUseRangeRequests and step.subworkerCount > 1:+ return SegmentedProgressBar(step, self)+ return super()._buildProgressBar()diff --git a/features/http_pack/pack.py b/features/http_pack/pack.pyindex 61ff485f..cc0f9cbf 100644--- a/features/http_pack/pack.py+++ b/features/http_pack/pack.py@@ -1,209 +1,234 @@+from __future__ import annotations+import refrom email.message import Messagefrom email.utils import collapse_rfc2231_valuefrom mimetypes import guess_extension-from pathlib import Pathfrom time import time_nsfrom urllib.parse import unquote, urlparse, parse_qs-import niquestsfrom loguru import logger-from app.bases.interfaces import FeaturePack-from app.bases.models import Task, SpecialFileSize-from app.supports.config import cfg, defaultHeaders-from app.supports.utils import getProxies, toSafeFilename, splitCookies-from .task import HttpTask, HttpTaskStage---def _contentLength(headers: dict[str, str]) -> int:- value = headers.get("content-length", "").strip()- if not value:- return SpecialFileSize.UNKNOWN-- try:- length = int(value)- except ValueError:- return SpecialFileSize.UNKNOWN-- return length if length > 0 else SpecialFileSize.UNKNOWN---def _rangeSize(headers: dict[str, str]) -> int:- contentRange = headers.get("content-range", "").strip()- if not contentRange or "/" not in contentRange:- return SpecialFileSize.UNKNOWN-- _, _, total = contentRange.rpartition("/")- if not total or total == "*":- return SpecialFileSize.UNKNOWN-- try:- size = int(total)- except ValueError:- return SpecialFileSize.UNKNOWN-- return size if size > 0 else SpecialFileSize.UNKNOWN----async def _sendProbe(client: niquests.AsyncSession, url: str, headers: dict, proxies: dict) -> tuple[int, dict[str, str], str]:- requestHeaders, requestCookies = splitCookies(headers)- response = await client.get(- url,- headers=requestHeaders,- cookies=requestCookies,- proxies=proxies,- verify=cfg.SSLVerify.value,- allow_redirects=True,- stream=True,- )-- try:- if response.status_code not in {200, 206, 416}:- response.raise_for_status()- return response.status_code, {k.lower(): v for k, v in response.headers.items()}, str(response.url)- finally:- await response.close()---async def _probe(url: str, headers: dict, proxies: dict) -> tuple[int, bool, str, dict[str, str]]:- async with niquests.AsyncSession(happy_eyeballs=True) as client:- client.trust_env = False-- statusCode, responseHeaders, finalUrl = await _sendProbe(- client,- url,- {**headers, "range": "bytes=1-1", "accept-encoding": "identity"},- proxies,- )-- fileSize = _rangeSize(responseHeaders)- supportsRange = statusCode == 206 and "content-range" in responseHeaders-- if supportsRange:- logger.info("偏移 Range 探测成功, content-range: {}, fileSize: {}",- responseHeaders.get("content-range", ""), fileSize)- return fileSize, True, finalUrl, responseHeaders-- fileSize = _contentLength(responseHeaders)-- if statusCode == 200:- logger.info("偏移 Range 探测返回 200, content-length: {}",- responseHeaders.get("content-length", ""))- if fileSize in {SpecialFileSize.UNKNOWN, 1}:- # bytes=0- 和 bytes=0-0 哪个更好存疑- fallbackStatus, fallbackHeaders, _ = await _sendProbe(- client,- url,- {**headers, "range": "bytes=0-0", "accept-encoding": "identity"},- proxies,- )- fallbackSize = _rangeSize(fallbackHeaders)- if fallbackStatus == 206 and "content-range" in fallbackHeaders:- logger.info("回退 Range 探测成功, content-range: {}, fileSize: {}",- fallbackHeaders.get("content-range", ""), fallbackSize)- return fallbackSize, True, finalUrl, fallbackHeaders-- if fileSize == SpecialFileSize.UNKNOWN:- fileSize = _contentLength(fallbackHeaders)- if fileSize == SpecialFileSize.UNKNOWN and fallbackStatus == 416:- fileSize = _rangeSize(fallbackHeaders)-- if fileSize == SpecialFileSize.UNKNOWN:- logger.info("文件大小未知,按不支持断点续传处理")- else:- logger.info("文件大小已知但未探测到 Range 支持, fileSize: {}", fileSize)-- return fileSize, False, finalUrl, responseHeaders---def _fileName(url: str, headers: dict) -> str:- fileName = ""+from app.client import buildClient, toEmulation+from app.config.cfg import cfg+from app.models.pack import FeaturePack, TaskParser+from app.models.task import (+ Task, TaskOptions, ResourceTaskOptions, SpecialFileSize,+)+from app.platform.filesystem import toSafeFilename+from .task import HttpTask, HttpTaskStep- cd = headers.get("content-disposition", "")- if cd:- msg = Message()- msg["Content-Disposition"] = cd- params = msg.get_params(header="Content-Disposition")- paramDict = {k.lower(): v for k, v in params}- fileName = collapse_rfc2231_value(- paramDict.get("filename") or paramDict.get("filename*") or ""- ).strip("\"' ")- if not fileName and "content-location" in headers:- cl = headers["content-location"]- fileName = unquote(urlparse(cl).path.split("/")[-1])+DOWNLOADABLE_EXTENSIONS = frozenset({+ ".mp4", ".mkv", ".avi", ".mov", ".wmv", ".flv", ".webm", ".ts", ".m2ts",+ ".mp3", ".flac", ".wav", ".aac", ".ogg", ".m4a", ".wma", ".opus",+ ".zip", ".rar", ".7z", ".tar", ".gz", ".bz2", ".xz", ".zst",+ ".exe", ".msi", ".dmg", ".deb", ".rpm", ".appimage", ".pkg",+ ".iso", ".img",+ ".pdf", ".epub",+ ".apk", ".ipa",+})- if not fileName:- parsedUrl = urlparse(url)- queryParams = parse_qs(parsedUrl.query)- rcd = queryParams.get("response-content-disposition", [""])[0]- if "filename=" in rcd.lower():- match = re.search(r'filename\s*=\s*["\']?([^"\';]+)["\']?', rcd, re.IGNORECASE)- if match:- fileName = unquote(match.group(1)).strip("\"' ")- if not fileName:- path = urlparse(url).path- if path and "/" in path:- cleanPath = path.split(";")[0]- fileName = unquote(cleanPath.split("/")[-1])-- contentType = headers.get("content-type", "").split(";", 1)[0].lower().strip()- standardExt = guess_extension(contentType) if contentType else ""- standardExt = standardExt or ""-- if not fileName:- fileName = f"file_{int(time_ns())}{standardExt}"- elif "." not in fileName and standardExt:- fileName = f"{fileName}{standardExt}"-- return toSafeFilename(fileName, fallback=f"file_{int(time_ns())}")---class HttpPack(FeaturePack):- packId = "http"+class HttpParser(TaskParser):priority = 100- def matches(self, url: str) -> bool:- return urlparse(url).scheme.lower() in {"http", "https"}-- def taskCard(self, task: Task, parent=None):- from .cards import HttpTaskCard- return HttpTaskCard(task, parent)-- async def parse(self, payload: dict) -> Task:- url: str = payload["url"]- headers: dict = payload.get("headers", defaultHeaders())- proxies: dict = payload.get("proxies", getProxies())- blockNum: int = payload.get("preBlockNum", cfg.preBlockNum.value)- path: Path = payload.get("path", Path(cfg.downloadFolder.value))-- fileName = str(payload.get("filename") or "").strip()- fileSize = payload.get("fileSize") or SpecialFileSize.UNKNOWN- supportsRange = payload.get("supportsRange", False)-- if not fileName:- fileSize, supportsRange, finalUrl, head = await _probe(url, headers, proxies)- fileName = _fileName(finalUrl, head)+ def match(self, options: TaskOptions) -> bool:+ return urlparse(options.url).scheme.lower() in {"http", "https"}++ def matchPassive(self, options: TaskOptions) -> bool:+ parsed = urlparse(options.url)+ if parsed.scheme.lower() not in {"http", "https"}:+ return False+ path = parsed.path.lower()+ return any(path.endswith(ext) for ext in DOWNLOADABLE_EXTENSIONS)++ async def parse(self, options: TaskOptions) -> Task:+ url = options.url+ headers = dict(options.headers)+ clientProfile = options.clientProfile+ subworkerCount = options.subworkerCount+ outputFolder = options.outputFolder++ name = ""+ fileSize = SpecialFileSize.UNKNOWN+ canUseRangeRequests = False+ lastModified = ""++ if isinstance(options, ResourceTaskOptions) and options.name:+ name = toSafeFilename(options.name, fallback=f"file_{time_ns()}")+ fileSize = options.size if options.size > 0 else SpecialFileSize.UNKNOWN+ canUseRangeRequests = options.canUseRangeRequestselse:- fileName = toSafeFilename(fileName, fallback=f"file_{int(time_ns())}")+ emulation = toEmulation(+ options.clientProfile or cfg.clientProfile.value,+ options.sourceUserAgent,+ )+ client = buildClient(emulation=emulation)++ def rangeTotal(h: dict) -> int:+ cr = h.get("content-range", "")+ if not cr or "/" not in cr:+ return SpecialFileSize.UNKNOWN+ _, _, total = cr.rpartition("/")+ if not total or total == "*":+ return SpecialFileSize.UNKNOWN+ try:+ size = int(total)+ except ValueError:+ return SpecialFileSize.UNKNOWN+ return size if size > 0 else SpecialFileSize.UNKNOWN++ def bodyLength(h: dict) -> int:+ val = h.get("content-length", "").strip()+ if not val:+ return SpecialFileSize.UNKNOWN+ try:+ length = int(val)+ except ValueError:+ return SpecialFileSize.UNKNOWN+ return length if length > 0 else SpecialFileSize.UNKNOWN++ async def request(rangeValue: str = "") -> tuple[int, dict[str, str], str]:+ probeHeaders = dict(headers)+ probeHeaders["accept-encoding"] = "identity"+ if rangeValue:+ probeHeaders["range"] = rangeValue+ response = await client.get(url, headers=probeHeaders)+ try:+ status = response.status.as_int()+ if status not in {200, 206, 416}:+ response.raise_for_status()+ return (+ status,+ {k.decode().lower(): v.decode() for k, v in response.headers},+ str(response.url),+ )+ finally:+ response.close()++ try:+ statusCode, responseHeaders, finalUrl = await request("bytes=1-1")++ fileSize = rangeTotal(responseHeaders)+ canUseRangeRequests = statusCode == 206 and "content-range" in responseHeaders++ if canUseRangeRequests:+ logger.info(+ "偏移 Range 探测成功, content-range: {}, fileSize: {}",+ responseHeaders.get("content-range", ""), fileSize,+ )+ else:+ fileSize = bodyLength(responseHeaders)+ logger.info(+ "偏移 Range 探测返回 {}, content-length: {}",+ statusCode, responseHeaders.get("content-length", ""),+ )++ if statusCode == 200 and fileSize in {SpecialFileSize.UNKNOWN, 1}:+ fbStatus, fbHeaders, _ = await request("bytes=0-0")+ fbSize = rangeTotal(fbHeaders)+ if fbStatus == 206 and "content-range" in fbHeaders:+ logger.info(+ "回退 Range 探测成功, content-range: {}, fileSize: {}",+ fbHeaders.get("content-range", ""), fbSize,+ )+ fileSize = fbSize+ canUseRangeRequests = True+ else:+ if fileSize == SpecialFileSize.UNKNOWN:+ fileSize = bodyLength(fbHeaders)+ if fileSize == SpecialFileSize.UNKNOWN and fbStatus == 416:+ fileSize = rangeTotal(fbHeaders)++ cd = responseHeaders.get("content-disposition", "")+ if cd:+ msg = Message()+ msg["Content-Disposition"] = cd+ params = msg.get_params(header="Content-Disposition")+ paramDict = {k.lower(): v for k, v in params}+ name = collapse_rfc2231_value(+ paramDict.get("filename") or paramDict.get("filename*") or ""+ ).strip("\"' ")++ if not name and "content-location" in responseHeaders:+ cl = responseHeaders["content-location"]+ name = unquote(urlparse(cl).path.split("/")[-1])++ if not name:+ queryParams = parse_qs(urlparse(finalUrl).query)+ rcd = queryParams.get("response-content-disposition", [""])[0]+ if "filename=" in rcd.lower():+ m = re.search(r'filename\s*=\s*["\']?([^"\';]+)["\']?', rcd, re.IGNORECASE)+ if m:+ name = unquote(m.group(1)).strip("\"' ")++ if not name:+ path = urlparse(finalUrl).path+ if path and "/" in path:+ cleanPath = path.split(";")[0]+ name = unquote(cleanPath.split("/")[-1])++ contentType = responseHeaders.get("content-type", "").split(";", 1)[0].lower().strip()+ standardExt = guess_extension(contentType) if contentType else ""+ standardExt = standardExt or ""++ if not name:+ name = f"file_{time_ns()}{standardExt}"+ elif "." not in name and standardExt:+ name = f"{name}{standardExt}"++ name = toSafeFilename(name, fallback=f"file_{time_ns()}")+ lastModified = responseHeaders.get("last-modified", "")+ finally:+ client.close()task = HttpTask(- title=fileName,+ name=name,url=url,fileSize=fileSize,- path=path,+ outputFolder=outputFolder,)- stage = HttpTaskStage(- stageIndex=1,+ task.addStep(HttpTaskStep(+ stepIndex=1,url=url,fileSize=fileSize,headers=headers,- proxies=proxies,- blockNum=blockNum,- supportsRange=supportsRange,- )- task.addStage(stage)+ clientProfile=clientProfile,+ subworkerCount=subworkerCount,+ canUseRangeRequests=canUseRangeRequests,+ lastModified=lastModified,+ ))return task+++class HttpPack(FeaturePack):+ packId = "http"++ def parsers(self):+ return [HttpParser()]++ def optionCards(self, task, parent=None):+ from app.view.components.option_cards import (+ ClientProfileCard, HeadersEditCard, OutputFolderCard, SubworkerCountCard,+ )+ step = task.steps[0] if task.steps else None+ if not isinstance(step, HttpTaskStep):+ return []+ return [+ OutputFolderCard(parent, initial=task.outputFolder),+ HeadersEditCard(parent, initial=step.headers),+ ClientProfileCard(parent, initial=step.clientProfile),+ SubworkerCountCard(parent, initial=step.subworkerCount),+ ]++ def editCards(self, task, parent=None):+ from app.view.components.option_cards import UrlEditCard+ return [+ UrlEditCard(parent, initial=task.url),+ *self.optionCards(task, parent),+ ]++ def taskCard(self, task, parent=None):+ from .cards import HttpTaskCard+ return HttpTaskCard(task, parent)diff --git a/features/http_pack/task.py b/features/http_pack/task.pyindex ecd1c582..262e1077 100644--- a/features/http_pack/task.py+++ b/features/http_pack/task.py@@ -1,3 +1,5 @@+from __future__ import annotations+import asyncioimport osfrom asyncio import TaskGroup, CancelledError@@ -5,452 +7,393 @@ from contextlib import suppressfrom dataclasses import field, dataclassfrom pathlib import Pathfrom struct import unpack, pack-from typing import ClassVar, TYPE_CHECKING-import niquestsfrom loguru import logger-from app.bases.interfaces import Worker-from app.bases.models import Task, TaskStage, TaskStatus, SpecialFileSize-from app.supports.config import cfg-from app.supports.sysio import ftruncate, pwrite-from app.supports.utils import splitCookies+from app.client import buildClient, toEmulation+from app.config.cfg import cfg+from app.models.task import Task, TaskStep, TaskStatus, SpecialFileSize+from app.platform.sysio import ftruncate, pwrite+from app.services.speed_meter import speedMeter-if TYPE_CHECKING:- from app.view.components.cards import ParseSettingCard+PERMANENT_STATUS = frozenset({400, 401, 403, 404, 405, 410, 451})-@dataclass(kw_only=True, eq=False)-class HttpTask(Task):- packId: str = "http"- supportsEdit: ClassVar[bool] = True- @property- def stage(self) -> "HttpTaskStage":- return self.stages[0]+class PermanentDownloadError(Exception):+ pass- @property- def headers(self) -> dict:- return self.stage.headers- @property- def proxies(self) -> dict | None:- return self.stage.proxies+@dataclass+class HttpSubworker:+ index: int+ start: int+ end: int+ receivedBytes: int = 0@property- def blockNum(self) -> int:- return self.stage.blockNum-- def editorCards(self, parent) -> list["ParseSettingCard"]:- from app.view.components.add_task_dialog import SelectFolderCard- from app.view.components.edit_task_cards import (- HeadersEditCard,- ProxiesEditCard,- UrlEditCard,- )- from qfluentwidgets import FluentIcon-- return [- UrlEditCard(FluentIcon.LINK, parent.tr("下载链接"), parent, initial=self.url),- HeadersEditCard(FluentIcon.GLOBE, parent.tr("请求标头"), parent, initial=self.headers),- ProxiesEditCard(FluentIcon.CERTIFICATE, parent.tr("代理服务器"), parent, initial=self.proxies),- SelectFolderCard(FluentIcon.DOWNLOAD, parent.tr("下载到"), parent, initial=self.path),- ]-- def applySettings(self, payload):- super().applySettings(payload)- if "url" in payload:- self.url = payload["url"]- self.stage.url = payload["url"]- if "headers" in payload:- self.stage.headers = payload["headers"]- if "proxies" in payload:- self.stage.proxies = payload["proxies"]-- def tryKeepProgress(self, newTask: Task) -> bool:- if not isinstance(newTask, HttpTask):- return False- if self.fileSize <= 0 or self.fileSize != newTask.fileSize:- return False- oldStage, newStage = self.stage, newTask.stage- oldStage.url = newStage.url- oldStage.headers = newStage.headers- oldStage.proxies = newStage.proxies- oldStage.supportsRange = newStage.supportsRange- self.url = newTask.url- return True+ def position(self) -> int:+ return self.start + self.receivedBytes-@dataclass(kw_only=True)-class HttpTaskStage(TaskStage):- workerType: type = field(init=False, repr=False)- canPause: bool = field(init=False, default=True)-- url: str- fileSize: int- headers: dict- proxies: dict- blockNum: int- supportsRange: bool = True- accelerated: bool = False- outputFileOverride: str = ""- subworkers: list = field(default_factory=list, repr=False) # worker 运行时挂上引用供分段进度条读取, repr=False 不落盘+@dataclass(kw_only=True, eq=False)+class HttpTask(Task):+ packId: str = "http"+ canEdit = True++ def canReuseProgress(self, newTask: Task) -> bool:+ return (+ isinstance(newTask, HttpTask)+ and self.fileSize > 0+ and self.fileSize == newTask.fileSize+ )- @property- def outputFile(self) -> str:- return self.outputFileOverride or str(Path(self.task.path) / self.task.title)- @outputFile.setter- def outputFile(self, value: str):- self.outputFileOverride = value+@dataclass(kw_only=True)+class HttpTaskStep(TaskStep):+ url: str = ""+ fileSize: int = 0+ headers: dict[str, str] = field(default_factory=dict)+ clientProfile: str = ""+ subworkerCount: int = 8+ canUseRangeRequests: bool = False+ lastModified: str = ""+ isAccelerated: bool = False+ outputFile: str = ""+ subworkers: list[HttpSubworker] = field(default_factory=list, repr=False)def __post_init__(self):- self.canPause = self.supportsRange+ self.canPause = self.canUseRangeRequests++ def deleteFiles(self):+ from app.platform.filesystem import deletePath+ path = Path(self.outputPath)+ deletePath(path)+ deletePath(Path(f"{path}.ghd"))++ def setOptions(self, options: dict) -> None:+ if "headers" in options:+ self.headers = options["headers"]+ if "clientProfile" in options:+ self.clientProfile = options["clientProfile"]+ if "subworkerCount" in options:+ self.subworkerCount = options["subworkerCount"]+ @property+ def outputPath(self) -> str:+ if self.outputFile:+ return self.outputFile+ return str(self.task.outputFolder / self.task.name)++ def _loadRecord(self) -> list[HttpSubworker]:+ recordPath = Path(self.outputPath + ".ghd")+ if not recordPath.exists():+ return []+ try:+ subworkers = []+ with open(recordPath, "rb") as f:+ index = 0+ while data := f.read(24):+ start, position, end = unpack("<QQQ", data)+ subworkers.append(HttpSubworker(+ index=index, start=start, end=end,+ receivedBytes=position - start,+ ))+ index += 1+ return subworkers+ except Exception as e:+ logger.opt(exception=e).error("恢复下载分片失败 {}", self.outputPath)+ return []-@dataclass-class HttpSubworker:- start: int- progress: int- end: int+ def _buildSubworkers(self) -> list[HttpSubworker]:+ if not self.canUseRangeRequests:+ return [HttpSubworker(index=0, start=0, end=SpecialFileSize.NOT_SUPPORTED)]+ if self.fileSize == SpecialFileSize.UNKNOWN:+ return [HttpSubworker(index=0, start=0, end=SpecialFileSize.UNKNOWN)]++ count = min(self.subworkerCount, self.fileSize)+ chunkSize = self.fileSize // count+ subworkers = []+ start = 0+ for i in range(count - 1):+ end = start + chunkSize - 1+ subworkers.append(HttpSubworker(index=i, start=start, end=end))+ start = end + 1+ subworkers.append(HttpSubworker(index=count - 1, start=start, end=self.fileSize - 1))+ return subworkers-class HttpWorker(Worker):- def __init__(self, stage: HttpTaskStage):- super().__init__(stage)- self.stage = stage- self.speedHistory = []- self.accelCheckTime = 0- self.requestHeaders, self.requestCookies = splitCookies(stage.headers)+ def _deleteRecord(self) -> None:+ target = Path(self.outputPath + ".ghd")+ try:+ if target.is_file() or target.is_symlink():+ target.unlink()+ except Exception as e:+ logger.opt(exception=e).error("删除进度文件失败 {}", target)- def reassignSubworker(self):- if self.stage.fileSize <= 0:+ def _reassignSubworker(self) -> None:+ if self.fileSize <= 0:return- slowestSubworker = max(self.subworkers, key=lambda sw: sw.end - sw.progress + 1)- remainingBytes = slowestSubworker.end - slowestSubworker.progress + 1- if remainingBytes < cfg.maxReassignSize.value * 1048576:+ slowest = max(self.subworkers, key=lambda sw: sw.end - sw.position + 1)+ remainingBytes = slowest.end - slowest.position + 1+ if remainingBytes < cfg.maxReassignSize.value * 1024:return+base = remainingBytes // 2remainder = remainingBytes % 2- oldEnd = slowestSubworker.end- slowestSubworker.end = slowestSubworker.progress + base + remainder - 1- newSubworker = HttpSubworker(slowestSubworker.end + 1, slowestSubworker.end + 1, oldEnd)- self.subworkers.insert(self.subworkers.index(slowestSubworker) + 1, newSubworker)- self.taskGroup.create_task(self.handleSubworker(newSubworker))-- def _buildRangeHeaders(self, rangeValue: str) -> dict:- requestHeaders = self.requestHeaders.copy()- requestHeaders["range"] = rangeValue- requestHeaders["accept-encoding"] = "identity"- return requestHeaders-- async def handleSubworker(self, subworker: HttpSubworker):- if subworker.end == SpecialFileSize.UNKNOWN: # 支持断点续传, 但文件大小未知+ oldEnd = slowest.end+ slowest.end = slowest.position + base + remainder - 1++ newSubworker = HttpSubworker(+ index=len(self.subworkers),+ start=slowest.end + 1,+ end=oldEnd,+ )+ self.subworkers.insert(self.subworkers.index(slowest) + 1, newSubworker)+ self._taskGroup.create_task(self._runSubworker(newSubworker, self._fd))++ def _autoSpeedUp(self) -> None:+ if self.isAccelerated or not cfg.autoSpeedUp.value:+ return++ self._speedHistory.append(self.speed)+ if len(self._speedHistory) > 5:+ self._speedHistory.pop(0)+ if len(self._speedHistory) < 5:+ return++ avgSpeed = sum(self._speedHistory) / len(self._speedHistory)+ if avgSpeed == 0:+ return++ maxDeviation = max(abs(s - avgSpeed) / avgSpeed for s in self._speedHistory)+ if maxDeviation > 0.15:+ return++ if self._accelCheckTime == 0:+ self._accelInitialWorkers = len(self.subworkers)+ self._accelInitialSpeed = avgSpeed+ self._accelCheckTime = asyncio.get_event_loop().time()+ for _ in range(4):+ self._reassignSubworker()+ else:+ elapsed = asyncio.get_event_loop().time() - self._accelCheckTime+ if elapsed <= 5:+ return++ workerRatio = (len(self.subworkers) - self._accelInitialWorkers) / self._accelInitialWorkers+ speedRatio = (avgSpeed - self._accelInitialSpeed) / self._accelInitialSpeed++ if speedRatio < 0.8 * workerRatio:+ self.isAccelerated = True+ logger.info("自动加速已禁用,subworker 增加比: {:.2%}, 速度提升比: {:.2%}",+ workerRatio, speedRatio)+ else:+ self._accelCheckTime = 0+ logger.info("继续自动加速,subworker 增加比: {:.2%}, 速度提升比: {:.2%}",+ workerRatio, speedRatio)++ async def _supervise(self) -> None:+ recordFile = None+ if self.canUseRangeRequests:+ recordFile = open(self.outputPath + ".ghd", "wb")+ try:+ self.receivedBytes = sum(sw.receivedBytes for sw in self.subworkers)while True:- try:- res = await self.client.get(- self.stage.url,- headers=self._buildRangeHeaders(f"bytes={subworker.progress}-"),- cookies=self.requestCookies,- proxies=self.stage.proxies,- verify=cfg.SSLVerify.value,- allow_redirects=True,- stream=True,+ if recordFile is not None:+ data = tuple(+ val for sw in self.subworkers+ for val in (sw.start, sw.position, sw.end))- try:- res.raise_for_status()- if res.status_code != 206:- raise Exception(f"服务器拒绝了范围请求,状态码:{res.status_code}")+ recordFile.seek(0)+ recordFile.write(pack("<" + "Q" * len(data), *data))+ recordFile.flush()+ recordFile.truncate()++ receivedBytes = sum(sw.receivedBytes for sw in self.subworkers)+ self.speed = receivedBytes - self.receivedBytes+ self.receivedBytes = receivedBytes+ if self.fileSize > 0:+ self.progress = (receivedBytes / self.fileSize) * 100+ else:+ self.progress = 0- async for chunk in await res.iter_raw(chunk_size=65536):+ self._autoSpeedUp()+ await asyncio.sleep(1)+ except CancelledError:+ pass+ finally:+ if recordFile is not None:+ recordFile.close()++ async def _runSubworker(self, subworker: HttpSubworker, fd: int) -> None:+ if subworker.end == SpecialFileSize.UNKNOWN:+ while True:+ try:+ headers = {**self.headers, "range": f"bytes={subworker.position}-", "accept-encoding": "identity"}+ response = await self._client.get(self.url, headers=headers)+ try:+ status = response.status.as_int()+ if status in PERMANENT_STATUS or response.headers.contains_key("cf-mitigated"):+ raise PermanentDownloadError(f"服务器返回了永久错误,状态码:{status}")+ if status != 206:+ raise Exception(f"服务器拒绝了范围请求,状态码:{status}")+ async for chunk in response.stream():if not chunk:continue- await cfg.checkSpeedLimitation()- pwrite(self.fileHandle, chunk, subworker.progress)- chunkSize = len(chunk)- subworker.progress += chunkSize- cfg.globalSpeed += chunkSize+ pwrite(fd, chunk, subworker.position)+ subworker.receivedBytes += len(chunk)+ speedMeter.addSpeed(len(chunk))+ await speedMeter.waitForSpeedLimit()finally:- await res.close()-+ response.close()return+ except CancelledError:+ raise+ except PermanentDownloadError:+ raiseexcept Exception as e:- logger.opt(exception=e).error(- "{} 的未知大小分片连接中断,5 秒后重试", self.stage.outputFile,- )+ logger.opt(exception=e).error("下载分片失败,将在 5 秒后重试 {}", self.outputPath)await asyncio.sleep(5)- elif subworker.end == SpecialFileSize.NOT_SUPPORTED: # 不支持断点续传+ elif subworker.end == SpecialFileSize.NOT_SUPPORTED:while True:try:- ftruncate(self.fileHandle, 0)- subworker.progress = 0- requestHeaders = self.requestHeaders.copy()- requestHeaders.pop("range", None)-- res = await self.client.get(- self.stage.url,- headers=requestHeaders,- cookies=self.requestCookies,- proxies=self.stage.proxies,- verify=cfg.SSLVerify.value,- allow_redirects=True,- stream=True,- )+ ftruncate(fd, 0)+ subworker.receivedBytes = 0+ response = await self._client.get(self.url, headers=dict(self.headers))try:- res.raise_for_status()- if res.status_code != 200:- raise Exception(f"服务器返回了异常状态码:{res.status_code}")-- async for chunk in await res.iter_content(chunk_size=65536):+ status = response.status.as_int()+ if status in PERMANENT_STATUS or response.headers.contains_key("cf-mitigated"):+ raise PermanentDownloadError(f"服务器返回了永久错误,状态码:{status}")+ if status != 200:+ raise Exception(f"服务器返回了异常状态码:{status}")+ async for chunk in response.stream():if not chunk:continue- await cfg.checkSpeedLimitation()- pwrite(self.fileHandle, chunk, subworker.progress)- chunkSize = len(chunk)- subworker.progress += chunkSize- cfg.globalSpeed += chunkSize+ pwrite(fd, chunk, subworker.receivedBytes)+ subworker.receivedBytes += len(chunk)+ speedMeter.addSpeed(len(chunk))+ await speedMeter.waitForSpeedLimit()finally:- await res.close()-- ftruncate(self.fileHandle, subworker.progress)+ response.close()+ ftruncate(fd, subworker.receivedBytes)return+ except CancelledError:+ raise+ except PermanentDownloadError:+ raiseexcept Exception as e:- logger.opt(exception=e).error(- "{} 不支持断点续传,已从头开始重试", self.stage.outputFile,- )+ logger.opt(exception=e).error("下载分片失败,将在 5 秒后重试 {}", self.outputPath)await asyncio.sleep(5)- else: # 正常下载- while subworker.progress <= subworker.end:+ else:+ while subworker.position <= subworker.end:try:- res = await self.client.get(- self.stage.url,- headers=self._buildRangeHeaders(f"bytes={subworker.progress}-{subworker.end}"),- cookies=self.requestCookies,- proxies=self.stage.proxies,- verify=cfg.SSLVerify.value,- allow_redirects=True,- stream=True,- )+ headers = {+ **self.headers,+ "range": f"bytes={subworker.position}-{subworker.end}",+ "accept-encoding": "identity",+ }+ response = await self._client.get(self.url, headers=headers)try:- res.raise_for_status()- if res.status_code != 206:- raise Exception(f"服务器拒绝了范围请求,状态码:{res.status_code}")-- async for chunk in await res.iter_raw(chunk_size=65536):+ status = response.status.as_int()+ if status in PERMANENT_STATUS or response.headers.contains_key("cf-mitigated"):+ raise PermanentDownloadError(f"服务器返回了永久错误,状态码:{status}")+ if status != 206:+ raise Exception(f"服务器拒绝了范围请求,状态码:{status}")+ async for chunk in response.stream():if not chunk:continue- remainingBytes = subworker.end - subworker.progress + 1- if len(chunk) > remainingBytes:- chunk = chunk[:remainingBytes]- await cfg.checkSpeedLimitation()- pwrite(self.fileHandle, chunk, subworker.progress)- chunkSize = len(chunk)- subworker.progress += chunkSize- cfg.globalSpeed += chunkSize- if subworker.progress > subworker.end:+ remaining = subworker.end - subworker.position + 1+ if len(chunk) > remaining:+ chunk = chunk[:remaining]+ pwrite(fd, chunk, subworker.position)+ subworker.receivedBytes += len(chunk)+ speedMeter.addSpeed(len(chunk))+ await speedMeter.waitForSpeedLimit()+ if subworker.position > subworker.end:breakfinally:- await res.close()+ response.close()- if subworker.progress > subworker.end:- subworker.progress = subworker.end + 1+ if subworker.position > subworker.end:+ subworker.receivedBytes = subworker.end - subworker.start + 1+ except CancelledError:+ raise+ except PermanentDownloadError:+ raiseexcept Exception as e:- logger.opt(exception=e).error(- "{} 的分片连接中断,5 秒后重试", self.stage.outputFile,- )+ logger.opt(exception=e).error("下载分片失败,将在 5 秒后重试 {}", self.outputPath)await asyncio.sleep(5)- self.reassignSubworker()-- def checkIfAutoAcceleration(self):- if self.stage.accelerated or not cfg.autoSpeedUp.value:- return+ self._reassignSubworker()- self.speedHistory.append(self.stage.speed)- if len(self.speedHistory) > 5:- self.speedHistory.pop(0)- if len(self.speedHistory) < 5:- return+ async def run(self) -> None:+ self._taskGroup = TaskGroup()+ self._speedHistory: list[int] = []+ self._accelCheckTime = 0+ self.subworkers = []+ shouldDeleteRecord = False- avgSpeed = sum(self.speedHistory) / len(self.speedHistory)- if avgSpeed == 0:- return+ Path(self.outputPath).parent.mkdir(parents=True, exist_ok=True)- maxDeviation = max(abs(speed - avgSpeed) / avgSpeed for speed in self.speedHistory)- if maxDeviation > 0.15:- return-- if self.accelCheckTime == 0:- self.accelInitialWorkers = len(self.subworkers)- self.accelInitialSpeed = avgSpeed- self.accelCheckTime = asyncio.get_event_loop().time()-- for _ in range(4):- self.reassignSubworker()- else:- elapsedTime = asyncio.get_event_loop().time() - self.accelCheckTime- if elapsedTime <= 5:- return-- currentWorkers = len(self.subworkers)- workerIncreaseRatio = (currentWorkers - self.accelInitialWorkers) / self.accelInitialWorkers- speedIncreaseRatio = (avgSpeed - self.accelInitialSpeed) / self.accelInitialSpeed-- if speedIncreaseRatio < 0.8 * workerIncreaseRatio:- self.stage.accelerated = True- logger.info(- "自动加速已禁用,subworker 增加比: {:.2%}, 速度提升比: {:.2%}",- workerIncreaseRatio, speedIncreaseRatio,- )- else:- self.accelCheckTime = 0- logger.info(- "继续自动加速,subworker 增加比: {:.2%}, 速度提升比: {:.2%}",- workerIncreaseRatio, speedIncreaseRatio,- )-- async def supervisor(self):- recordFileHandle = None- if self.stage.supportsRange:- recordFileHandle = open(Path(self.stage.outputFile + ".ghd"), "wb")- try:- self.stage.receivedBytes = sum(sw.progress - sw.start for sw in self.subworkers)- while True:- if recordFileHandle is not None:- data = tuple(val for sw in self.subworkers for val in (sw.start, sw.progress, sw.end))- recordFileHandle.seek(0)- recordFileHandle.write(pack("<" + "Q" * len(data), *data))- recordFileHandle.flush()- recordFileHandle.truncate()-- receivedBytes = sum(sw.progress - sw.start for sw in self.subworkers)- self.stage.speed = receivedBytes - self.stage.receivedBytes- self.stage.receivedBytes = receivedBytes- if self.stage.fileSize > 0:- self.stage.progress = (receivedBytes / self.stage.fileSize) * 100- else:- self.stage.progress = 0-- self.checkIfAutoAcceleration()- await asyncio.sleep(1)- except CancelledError:- pass- finally:- if recordFileHandle is not None:- recordFileHandle.close()-- def restoreProgress(self) -> bool:- recordFile = Path(self.stage.outputFile + ".ghd")- if recordFile.exists():- try:- with open(recordFile, "rb") as f:- while True:- data = f.read(24) # 每个 subworker 3 个 uint64, 共 24 字节- if not data:- break- start, progress, end = unpack("<QQQ", data)- self.subworkers.append(HttpSubworker(start, progress, end))- return True- except Exception as e:- logger.opt(exception=e).error("恢复下载分片失败 {}", self.stage.outputFile)- self.subworkers.clear()- return False- return False-- def generateSubworkers(self):- if not self.stage.supportsRange:- self.subworkers.append(HttpSubworker(0, 0, SpecialFileSize.NOT_SUPPORTED))- return-- if self.stage.fileSize == SpecialFileSize.UNKNOWN:- self.subworkers.append(HttpSubworker(0, 0, SpecialFileSize.UNKNOWN))- return-- blockNum = min(self.stage.blockNum, self.stage.fileSize)- step = self.stage.fileSize // blockNum- start = 0- for _ in range(blockNum - 1):- end = start + step - 1- self.subworkers.append(HttpSubworker(start, start, end))- start = end + 1-- self.subworkers.append(HttpSubworker(start, start, self.stage.fileSize - 1))-- def _cleanupRecordFile(self):- target = Path(self.stage.outputFile + ".ghd")- try:- if target.is_file() or target.is_symlink():- target.unlink()- except Exception as e:- logger.opt(exception=e).error("failed to cleanup temporary file {}", target)-- async def run(self):- self.taskGroup = TaskGroup()- self.subworkers: list[HttpSubworker] = []- self.stage.subworkers = self.subworkers- self.client = niquests.AsyncSession(happy_eyeballs=True, pool_maxsize=256)- self.client.trust_env = False- shouldCleanupRecordFile = False- Path(self.stage.outputFile).parent.mkdir(parents=True, exist_ok=True)-- # 故意提前占位——HTTP 阶段只落 .video/.audio 中间产物, .mp4 要等 merge- # 完才有, 这段窗口期同名任务过 deduplicateFilename 看不到就会撞名- finalOutput = Path(self.stage.task.outputFolder)- if finalOutput != Path(self.stage.outputFile):- finalOutput.touch(exist_ok=True)+ emulation = toEmulation(self.clientProfile or cfg.clientProfile.value, "")+ self._client = buildClient(emulation=emulation)restored = False- if self.stage.supportsRange:- restored = self.restoreProgress()- else:- self._cleanupRecordFile()+ if self.canUseRangeRequests:+ loaded = self._loadRecord()+ if loaded:+ self.subworkers = loaded+ restored = Trueif not restored:- logger.info("正在为 {} 生成下载分片", self.stage.outputFile)- self.generateSubworkers()- else:- logger.info("从进度文件恢复下载分片 {}", self.stage.outputFile)+ if not self.canUseRangeRequests:+ self._deleteRecord()+ self.subworkers = self._buildSubworkers()openMode = os.O_RDWR | os.O_CREAT- if not self.stage.supportsRange:+ if not self.canUseRangeRequests:openMode |= os.O_TRUNC- self.fileHandle = os.open(self.stage.outputFile, openMode, 0o666)+ self._fd = os.open(self.outputPath, openMode, 0o666)- if not restored and self.stage.fileSize > 0:+ if not restored and self.fileSize > 0:try:- ftruncate(self.fileHandle, self.stage.fileSize)+ ftruncate(self._fd, self.fileSize)except Exception as e:- logger.opt(exception=e).error("{} 预分配文件大小失败", self.stage.outputFile)+ logger.opt(exception=e).error("{} 预分配文件大小失败", self.outputPath)- supervisor = asyncio.create_task(self.supervisor())+ supervisor = asyncio.create_task(self._supervise())try:- async with self.taskGroup:+ async with self._taskGroup:for subworker in self.subworkers:- self.taskGroup.create_task(self.handleSubworker(subworker))+ self._taskGroup.create_task(self._runSubworker(subworker, self._fd))- self.stage.setStatus(TaskStatus.COMPLETED)- shouldCleanupRecordFile = True- logger.info("{} 下载完成", self.stage.outputFile)+ self.setStatus(TaskStatus.COMPLETED)+ shouldDeleteRecord = Trueexcept CancelledError:- self.stage.setStatus(TaskStatus.PAUSED)+ self.setStatus(TaskStatus.PAUSED)raiseexcept Exception as e:- self.stage.setError(e)+ self.setError(e)raisefinally:if not supervisor.done():supervisor.cancel()- with suppress(asyncio.CancelledError):+ with suppress(CancelledError):await supervisor- os.close(self.fileHandle)- await self.client.close()- if shouldCleanupRecordFile:- self._cleanupRecordFile()---HttpTaskStage.workerType = HttpWorker+ os.close(self._fd)+ self._client.close()+ if shouldDeleteRecord:+ self._deleteRecord()+ if cfg.shouldPreserveLastModified.value and self.lastModified:+ try:+ from email.utils import parsedate_to_datetime+ mtime = parsedate_to_datetime(self.lastModified).timestamp()+ os.utime(self.outputPath, (mtime, mtime))+ except Exception as e:+ logger.opt(exception=e).warning("设置文件修改时间失败 {}", self.outputPath)diff --git a/features/huggingface_pack/cards.py b/features/huggingface_pack/cards.pynew file mode 100644index 00000000..1f12a386--- /dev/null+++ b/features/huggingface_pack/cards.py@@ -0,0 +1,90 @@+from __future__ import annotations++from qfluentwidgets import FluentIcon, ToolButton, ToolTipFilter, TransparentToolButton++from app.format import toReadableSize+from app.models.task import TaskStatus+from app.view.cards.draft_cards import UniversalDraftCard+from app.view.cards.task_cards import UniversalTaskCard+from app.view.dialogs.file_select import FileSelectDialog+from .task import HuggingFaceTask+++class HuggingFaceDraftCard(UniversalDraftCard):++ @property+ def task(self) -> HuggingFaceTask:+ return self._task++ def _initWidget(self) -> None:+ super()._initWidget()+ self._selectFilesButton = None+ if self.task.files and len(self.task.files) > 1:+ self._selectFilesButton = TransparentToolButton(FluentIcon.LIBRARY, self)+ self._selectFilesButton.setFixedSize(28, 28)+ self._selectFilesButton.setToolTip(self.tr("选择文件"))+ self._selectFilesButton.installEventFilter(ToolTipFilter(self._selectFilesButton))+ self._refreshSummary()++ def _initLayout(self) -> None:+ super()._initLayout()+ if self._selectFilesButton is not None:+ self.layout().addWidget(self._selectFilesButton)++ def _bind(self) -> None:+ super()._bind()+ if self._selectFilesButton is not None:+ self._selectFilesButton.clicked.connect(self._onSelectFilesClicked)++ def _refreshSummary(self) -> None:+ if not self.task.files or len(self.task.files) <= 1:+ self.sizeLabel.setText(toReadableSize(self.task.fileSize))+ return+ self.sizeLabel.setText(+ self.tr("{0}/{1} 个文件 · {2}").format(+ self.task.countSelected,+ len(self.task.files),+ toReadableSize(self.task.fileSize),+ )+ )++ def _onSelectFilesClicked(self) -> None:+ dialog = FileSelectDialog(self.task, self.window())+ try:+ if dialog.exec():+ self.task.setSelection(dialog.selectedIndexes())+ self._refreshSummary()+ self.nameLabel.setText(self.task.name)+ finally:+ dialog.deleteLater()+++class HuggingFaceTaskCard(UniversalTaskCard):+ def __init__(self, task: HuggingFaceTask, parent=None):+ super().__init__(task, parent)+ self.selectFilesButton = ToolButton(FluentIcon.LIBRARY, self)+ self.hBoxLayout.insertWidget(+ self.hBoxLayout.indexOf(self.verifyHashButton),+ self.selectFilesButton,+ )+ self.selectFilesButton.clicked.connect(self._onSelectFilesClicked)++ def refresh(self) -> None:+ super().refresh()+ hasMultipleFiles = self._task.files and len(self._task.files) > 1+ self.selectFilesButton.setVisible(hasMultipleFiles)+ self.selectFilesButton.setEnabled(self._task.status != TaskStatus.RUNNING)++ if self._task.status in {TaskStatus.WAITING, TaskStatus.COMPLETED} and hasMultipleFiles:+ selected = sum(1 for f in self._task.files if f.selected)+ self.statusLabel.setText(self.tr("{0}/{1} 个文件").format(selected, len(self._task.files)))++ def _onSelectFilesClicked(self) -> None:+ if self._task.status == TaskStatus.RUNNING:+ return+ dialog = FileSelectDialog(self._task, self.window())+ try:+ if dialog.exec():+ self._task.setSelection(dialog.selectedIndexes())+ finally:+ dialog.deleteLater()diff --git a/features/huggingface_pack/config.py b/features/huggingface_pack/config.pynew file mode 100644index 00000000..4da3dc39--- /dev/null+++ b/features/huggingface_pack/config.py@@ -0,0 +1,246 @@+from __future__ import annotations++from urllib.parse import urlparse++from app.client import buildClient+from app.config.cfg import ConfigItem+from 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",+)+CUSTOM_SITE_KEY = "__custom__"+PROBE_TARGET = "https://huggingface.co/api/models/gpt2"+TOKEN_URL = "https://huggingface.co/settings/tokens"+++def toProxySite(site: str) -> str:+ value = str(site or "").strip()+ if not value:+ return ""+ if "://" not in value:+ value = f"https://{value}"+ return value.rstrip("/")+++def selectedProxySite() -> str:+ if huggingFaceConfig.selectedSite.value == CUSTOM_SITE_KEY:+ return huggingFaceConfig.customSite.value+ return huggingFaceConfig.selectedSite.value+++def accessToken() -> str:+ return huggingFaceConfig.accessToken.value+++async def probeProxyLatencies() -> dict[str, int]:+ import asyncio+ from time import perf_counter++ sites = list(HF_PROXY_SITES)+ custom = huggingFaceConfig.customSite.value+ if custom:+ sites.append(custom)++ async def probeOne(site: str) -> tuple[str, int]:+ url = f"{site.rstrip('/')}/{PROBE_TARGET}"+ client = buildClient()+ try:+ start = perf_counter()+ response = await asyncio.wait_for(client.get(url), timeout=10)+ elapsed = int((perf_counter() - start) * 1000)+ return site, elapsed if response.status.as_int() < 400 else -1+ except Exception:+ return site, -1+ finally:+ client.close()++ results = await asyncio.gather(*(probeOne(s) for s in sites))+ return dict(results)+++class HuggingFaceProxySiteValidator(ConfigValidator):+ def validate(self, value) -> bool:+ site = toProxySite(value)+ if not site:+ return False+ parsed = urlparse(site)+ return (+ parsed.scheme in {"http", "https"}+ and bool(parsed.netloc)+ and not parsed.params+ and not parsed.query+ and not parsed.fragment+ )++ def correct(self, value) -> str:+ site = toProxySite(value)+ return site if self.validate(site) else ""+++class HuggingFaceProxySiteCard(SettingCard):+ def __init__(self, parent=None):+ 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)+ from app.services.coroutine_runner import coroutineRunner+ coroutineRunner.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", "", HuggingFaceProxySiteValidator())+ customSite = ConfigItem("HuggingFace", "CustomSite", "", HuggingFaceProxySiteValidator())+ accessToken = ConfigItem("HuggingFace", "AccessToken", "")++ def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:+ from qfluentwidgets import FluentIcon, SwitchSettingCard+ from app.view.components.setting_card_group import CollapsibleSettingCardGroup++ group = CollapsibleSettingCardGroup(self.tr("HuggingFace"), "huggingface", parent)+ group.addSettingCards([+ SwitchSettingCard(+ FluentIcon.CONNECT, self.tr("启用 HuggingFace 加速"),+ self.tr("命中 HuggingFace 链接时,自动改写为所选镜像站"),+ self.isEnabled, group,+ ),+ HuggingFaceProxySiteCard(group),+ HuggingFaceTokenCard(group),+ ])+ return [group]+++huggingFaceConfig = HuggingFaceConfig()diff --git a/features/huggingface_pack/manifest.toml b/features/huggingface_pack/manifest.tomlnew file mode 100644index 00000000..784ec150--- /dev/null+++ b/features/huggingface_pack/manifest.toml@@ -0,0 +1,3 @@+[pack]+entry = "pack.py"+dependencies = ["http_pack"]diff --git a/features/huggingface_pack/pack.py b/features/huggingface_pack/pack.pynew file mode 100644index 00000000..dd6da235--- /dev/null+++ b/features/huggingface_pack/pack.py@@ -0,0 +1,211 @@+from __future__ import annotations++import re+from dataclasses import replace+from urllib.parse import urlparse++from app.client import buildClient+from app.models.pack import FeaturePack, TaskParser+from app.models.task import Task, TaskFile, TaskOptions+from app.platform.filesystem import toSafeFilename+from .config import accessToken, huggingFaceConfig, selectedProxySite+from .task import HuggingFaceFile, HuggingFaceStep, HuggingFaceTask++from features.http_pack.task import HttpTaskStep++HF_HOSTS = {"huggingface.co", "www.huggingface.co"}+REPO_PATTERN = re.compile(+ r"^/(?P<type>(?:datasets|spaces)/)?(?P<org>[^/]+)/(?P<repo>[^/]+)"+ r"(?:/(?:resolve|blob|tree)/(?P<rev>[^/]+)(?:/(?P<path>.+))?)?$"+)+API_BASE = "https://huggingface.co"+++def parseHuggingFaceUrl(url: str) -> dict | None:+ parsed = urlparse(url)+ host = (parsed.hostname or "").lower().removeprefix("www.")+ if host not in {"huggingface.co"}:+ proxySite = selectedProxySite()+ if proxySite:+ proxyHost = (urlparse(proxySite).hostname or "").lower()+ if host != proxyHost:+ return None+ else:+ return None++ m = REPO_PATTERN.match(parsed.path)+ if m is None:+ return None++ repoType = "model"+ typePrefix = m.group("type") or ""+ if typePrefix.startswith("datasets"):+ repoType = "dataset"+ elif typePrefix.startswith("spaces"):+ repoType = "space"++ return {+ "org": m.group("org"),+ "repo": m.group("repo"),+ "repoType": repoType,+ "revision": m.group("rev") or "main",+ "filePath": m.group("path") or "",+ }+++class HuggingFaceParser(TaskParser):+ priority = 85++ def match(self, options: TaskOptions) -> bool:+ return parseHuggingFaceUrl(options.url) is not None++ async def parse(self, options: TaskOptions) -> Task:+ info = parseHuggingFaceUrl(options.url)+ if info is None:+ raise ValueError("无法解析 HuggingFace 链接")++ repoId = f"{info['org']}/{info['repo']}"+ repoType = info["repoType"]+ revision = info["revision"]+ filePath = info["filePath"]++ headers: dict[str, str] = {}+ token = accessToken()+ if token:+ headers["authorization"] = f"Bearer {token}"++ from app.config.cfg import cfg++ if filePath:+ downloadUrl = self._fileUrl(repoId, repoType, revision, filePath)+ name = toSafeFilename(filePath.rsplit("/", 1)[-1], fallback="download")++ client = buildClient(headers=headers)+ try:+ response = await client.head(downloadUrl)+ fileSize = 0+ cl = response.headers.get("content-length")+ if cl:+ fileSize = int(cl.decode() if isinstance(cl, bytes) else cl)+ canUseRange = response.headers.contains_key("accept-ranges")+ finally:+ client.close()++ task = HuggingFaceTask(+ name=name,+ url=options.url,+ fileSize=fileSize,+ outputFolder=options.outputFolder,+ repoId=repoId,+ repoType=repoType,+ revision=revision,+ )+ task.addStep(HttpTaskStep(+ stepIndex=1,+ url=downloadUrl,+ fileSize=fileSize,+ headers=headers,+ subworkerCount=cfg.preBlockNum.value,+ canUseRangeRequests=canUseRange,+ ))+ return task++ apiPrefix = {"dataset": "datasets", "space": "spaces"}.get(repoType, "models")+ base = selectedProxySite() or API_BASE+ apiUrl = f"{base}/api/{apiPrefix}/{repoId}/tree/{revision}"++ client = buildClient(headers=headers)+ try:+ entries = await self._fetchTree(client, apiUrl)+ finally:+ client.close()++ if not entries:+ raise ValueError(f"仓库 {repoId} 为空或无法访问")++ files: list[HuggingFaceFile] = []+ for i, entry in enumerate(entries):+ path = entry.get("path", "")+ size = entry.get("size", 0)+ lfs = entry.get("lfs")+ if lfs and isinstance(lfs, dict):+ size = lfs.get("size", size)+ files.append(HuggingFaceFile(+ index=i,+ relativePath=path,+ size=size,+ downloadUrl=self._fileUrl(repoId, repoType, revision, path),+ ))++ repoName = toSafeFilename(repoId.replace("/", "_"), fallback="huggingface")++ task = HuggingFaceTask(+ name=repoName,+ url=options.url,+ fileSize=sum(f.size for f in files),+ outputFolder=options.outputFolder,+ repoId=repoId,+ repoType=repoType,+ revision=revision,+ files=files,+ )++ for file in files:+ task.addStep(HuggingFaceStep(+ stepIndex=file.index + 1,+ url=file.downloadUrl,+ fileSize=file.size,+ headers=headers,+ subworkerCount=cfg.preBlockNum.value,+ canUseRangeRequests=file.size > 0,+ fileIndex=file.index,+ ))++ return task++ async def _fetchTree(self, client, apiUrl: str) -> list[dict]:+ entries: list[dict] = []+ url = apiUrl+ while url:+ response = await client.get(url)+ if response.status.as_int() == 401:+ raise PermissionError("该仓库需要授权,请在设置中配置 HuggingFace Access Token")+ response.raise_for_status()+ page = await response.json()+ if isinstance(page, list):+ for entry in page:+ if entry.get("type") == "file":+ entries.append(entry)+ elif entry.get("type") == "directory":+ subUrl = f"{apiUrl}/{entry['path']}"+ subEntries = await self._fetchTree(client, subUrl)+ entries.extend(subEntries)+ break+ else:+ break+ return entries++ def _fileUrl(self, repoId: str, repoType: str, revision: str, filePath: str) -> str:+ base = selectedProxySite() or API_BASE+ typePrefix = {"dataset": "datasets/", "space": "spaces/"}.get(repoType, "")+ return f"{base}/{typePrefix}{repoId}/resolve/{revision}/{filePath}"+++class HuggingFacePack(FeaturePack):+ packId = "huggingface"+ config = huggingFaceConfig++ def parsers(self) -> list[TaskParser]:+ return [HuggingFaceParser()]++ def draftCard(self, task, parent=None):+ from .cards import HuggingFaceDraftCard+ return HuggingFaceDraftCard(task, parent)++ def taskCard(self, task, parent=None):+ from .cards import HuggingFaceTaskCard+ return HuggingFaceTaskCard(task, parent)++ def optionCards(self, task, parent=None):+ from app.view.components.option_cards import OutputFolderCard+ return [OutputFolderCard(parent, initial=task.outputFolder)]diff --git a/features/huggingface_pack/task.py b/features/huggingface_pack/task.pynew file mode 100644index 00000000..a57d6658--- /dev/null+++ b/features/huggingface_pack/task.py@@ -0,0 +1,67 @@+from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path++from app.models.task import Task, TaskFile, TaskStep+from app.platform.filesystem import deletePath++from features.http_pack.task import HttpTaskStep+++@dataclass(kw_only=True)+class HuggingFaceFile(TaskFile):+ downloadUrl: str = ""+++@dataclass(kw_only=True)+class HuggingFaceStep(HttpTaskStep):+ fileIndex: int = -1++ @property+ def outputPath(self) -> str:+ if self.fileIndex >= 0 and self.task.files:+ for file in self.task.files:+ if file.index == self.fileIndex:+ return str(self.task.outputFolder / file.relativePath)+ return super().outputPath++ def deleteFiles(self) -> None:+ path = Path(self.outputPath)+ deletePath(path)+ deletePath(Path(f"{path}.ghd"))++ @classmethod+ def fromFile(cls, file: TaskFile, task: Task) -> TaskStep:+ from app.config.cfg import cfg+ hfFile: HuggingFaceFile = file+ return cls(+ stepIndex=file.index + 1,+ url=hfFile.downloadUrl,+ fileSize=file.size,+ headers=task.steps[0].headers if task.steps else {},+ subworkerCount=cfg.preBlockNum.value,+ canUseRangeRequests=file.size > 0,+ fileIndex=file.index,+ )+++@dataclass(kw_only=True, eq=False)+class HuggingFaceTask(Task):+ packId: str = "huggingface"+ canEdit = True+ fileType = HuggingFaceFile+ stepType = HuggingFaceStep+ repoId: str = ""+ repoType: str = "model"+ revision: str = "main"++ @property+ def countSelected(self) -> int:+ return sum(1 for f in self.files if f.selected) if self.files else 0++ def deleteFiles(self) -> None:+ for step in self.steps:+ step.deleteFiles()+ if self.files:+ deletePath(Path(self.outputFolder / self.name))diff --git a/features/jack_yao/pack.py b/features/jack_yao/pack.pyindex ca1771fe..9896ff2a 100644--- a/features/jack_yao/pack.py+++ b/features/jack_yao/pack.py@@ -1,462 +1,293 @@+from __future__ import annotations++import jsonimport sysfrom base64 import b64decodefrom pathlib import Path-from typing import TYPE_CHECKING--import niquests-from PySide6.QtCore import Signal, Qt, QSize, QUrl-from PySide6.QtGui import QPixmap, QColor, QDesktopServices, QPainter-from PySide6.QtWidgets import QWidget, QVBoxLayout, QSizePolicy, QHBoxLayout, QFileDialog-from loguru import logger-from orjson import loads-from qfluentwidgets import MaskDialogBase, \- FluentStyleSheet, SettingCardGroup, OptionsConfigItem, OptionsValidator, ComboBoxSettingCard, FluentIcon, \- PlainTextEdit, PushSettingCard, RangeSettingCard, RangeConfigItem, RangeValidator, PrimaryPushButton, PushButton, \- PixmapLabel, TitleLabel, BodyLabel, PrimarySplitPushButton, SimpleCardWidget, RoundMenu, Action, IconWidget, \- CaptionLabel, isDarkTheme, InfoBar, InfoBarPosition--from app.bases.interfaces import FeaturePack-from app.services.core_service import coreService-from app.supports.config import cfg, defaultHeaders-from app.supports.utils import getProxies++from PySide6.QtCore import QCoreApplication, Qt, QUrl, Signal+from PySide6.QtGui import QColor, QDesktopServices, QPixmap+from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget+from qfluentwidgets import (+ BodyLabel,+ CaptionLabel,+ FluentIcon,+ IconWidget,+ IndeterminateProgressRing,+ MessageBoxBase,+ OptionsConfigItem,+ OptionsValidator,+ ComboBoxSettingCard,+ PrimaryPushButton,+ PushButton,+ PixmapLabel,+ SettingCardGroup,+ SimpleCardWidget,+ TitleLabel,+ ToolTipFilter,+ TransparentToolButton,+)++from app.client import buildClient+from app.config.cfg import cfg+from app.models.pack import FeaturePack, PackPageif sys.platform != "darwin":from qfluentwidgets import SmoothScrollArea as ScrollAreaelse:from qfluentwidgets import ScrollArea-if TYPE_CHECKING:- from app.view.windows.main_window import MainWindow+CATALOG_API = "https://xineko-my.sharepoint.com/personal/os_store_xineko_onmicrosoft_com/_layouts/52/download.aspx?share=IQCK7kKU1-8oSqWDNNPss2xeAbmG3v4cItTXNqW2NG9Hzwc"+CONTENT_MARGIN = 16-class JackYaoPack(FeaturePack):- packId = "jack_yao"-- def setup(self, mainWindow:"MainWindow"):- mainWindow.resourceInterface = ResourceInterface()- mainWindow.addSubInterface(mainWindow.resourceInterface, FluentIcon.CLOUD_DOWNLOAD, "资源下载")+async def fetchCatalog() -> list[dict]:+ client = buildClient()+ try:+ response = await client.get(CATALOG_API)+ response.raise_for_status()+ return json.loads(await response.text())["OS"]+ finally:+ client.close()-async def run():- async with niquests.AsyncSession(happy_eyeballs=True) as client:- client.trust_env = False- result = await client.get(- url="https://xineko-my.sharepoint.com/personal/os_store_xineko_onmicrosoft_com/_layouts/52/download.aspx?share=IQCK7kKU1-8oSqWDNNPss2xeAbmG3v4cItTXNqW2NG9Hzwc",- headers={- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64"},- proxies=getProxies(), allow_redirects=True)- return loads(result.text)["OS"]+class CatalogPage(PackPage, ScrollArea):+ icon = FluentIcon.CLOUD_DOWNLOAD+ title = QCoreApplication.translate("CatalogPage", "资源下载")+ def __init__(self, parent=None):+ super().__init__(parent)+ self.setObjectName("CatalogPage")+ self._cards: list[CatalogCard] = []-class LoadingStatusWidget(QWidget):- retrySignal = Signal()+ self._scrollWidget = QWidget()+ self._layout = QVBoxLayout(self._scrollWidget)+ self._loadingWidget = LoadingWidget(self._scrollWidget)- def __init__(self, parent=None):- super().__init__(parent=parent)- self.iconWidget = IconWidget(FluentIcon.SYNC, self)- self.label = CaptionLabel("正在加载...", self)- self.retryButton = PushButton("重试", self)- self.vBoxLayout = QVBoxLayout(self)- self.borderRadius = 10+ self._initWidget()+ self._initLayout()+ self._bind()+ self._loadCatalog()- self.initWidget()+ def _initWidget(self):+ self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)- def initWidget(self):- self.iconWidget.setFixedSize(64, 64)+ def _initLayout(self):+ self._layout.setSpacing(8)+ self._layout.setContentsMargins(CONTENT_MARGIN, CONTENT_MARGIN, CONTENT_MARGIN, CONTENT_MARGIN)+ self._layout.addWidget(self._loadingWidget, 1, Qt.AlignmentFlag.AlignCenter)- self.label.setTextColor(QColor(96, 96, 96), QColor(216, 216, 216))- self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)- self.label.setWordWrap(True)+ self.setWidget(self._scrollWidget)+ self.setWidgetResizable(True)+ self.enableTransparentBackground()- self.retryButton.setVisible(False)- self.retryButton.clicked.connect(self.onRetryClicked)+ def _bind(self):+ self._loadingWidget.retryRequested.connect(self._loadCatalog)- self.vBoxLayout.setSpacing(10)- self.vBoxLayout.setContentsMargins(16, 20, 16, 20)- self.vBoxLayout.addWidget(self.iconWidget, 0, Qt.AlignmentFlag.AlignHCenter)- self.vBoxLayout.addWidget(self.label, 0, Qt.AlignmentFlag.AlignHCenter)- self.vBoxLayout.addWidget(self.retryButton, 0, Qt.AlignmentFlag.AlignHCenter)+ def _loadCatalog(self):+ from app.services.coroutine_runner import coroutineRunner+ self._loadingWidget.setLoading()+ coroutineRunner.submit(+ fetchCatalog(),+ done=self._onCatalogLoaded, failed=self._onCatalogFailed,+ owner=self,+ )- def setLoading(self):- """设置为加载状态"""- self.iconWidget.setIcon(FluentIcon.SYNC)- self.label.setText("正在加载...")- self.retryButton.setVisible(False)+ def _onCatalogLoaded(self, items: list[dict]):+ for card in self._cards:+ self._layout.removeWidget(card)+ card.deleteLater()+ self._cards.clear()- def setError(self, errorText: str):- """设置为错误状态"""- self.iconWidget.setIcon(FluentIcon.CANCEL)- self.label.setText(errorText)- self.retryButton.setVisible(True)+ self._layout.removeWidget(self._loadingWidget)+ self._loadingWidget.setParent(None)+ self._loadingWidget.deleteLater()- def onRetryClicked(self):- """重试按钮点击事件"""- self.setLoading()- self.retrySignal.emit()+ for item in items:+ card = CatalogCard(item, self._scrollWidget)+ self._layout.addWidget(card)+ self._cards.append(card)- @property- def backgroundColor(self):- return QColor(255, 255, 255, 13 if isDarkTheme() else 200)+ self._layout.addStretch(1)- def paintEvent(self, e):- painter = QPainter(self)- painter.setRenderHints(QPainter.RenderHint.Antialiasing)- painter.setBrush(self.backgroundColor)- painter.setPen(Qt.PenStyle.NoPen)+ def _onCatalogFailed(self, error: str):+ self._loadingWidget.setError(self.tr("加载失败,请检查网络后重试\n") + str(error))- r = self.borderRadius- painter.drawRoundedRect(self.rect(), r, r)+class LoadingWidget(QWidget):+ retryRequested = Signal()-class ResourceInterface(ScrollArea):def __init__(self, parent=None):- super().__init__(parent=parent)-- self.setObjectName("ResourceInterface")- self.cards = []- self.jsonData = []-- self.initWidget()- self.initLayout()- self.connectSignalToSlot()- self.loadData()-- def initWidget(self):- """初始化UI组件"""- self.scrollWidget = QWidget()- self.scrollWidget.setMinimumWidth(816)- self.expandLayout = QVBoxLayout(self.scrollWidget)- self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)-- self.loadingStatusWidget = LoadingStatusWidget(self.scrollWidget)- self.expandLayout.addWidget(self.loadingStatusWidget, 0, Qt.AlignmentFlag.AlignCenter)+ super().__init__(parent)+ self._ring = IndeterminateProgressRing(self)+ self._ring.setFixedSize(48, 48)+ self._label = CaptionLabel(self.tr("正在加载..."), self)+ self._errorIcon = IconWidget(FluentIcon.CANCEL, self)+ self._errorIcon.setFixedSize(48, 48)+ self._errorIcon.hide()+ self._retryButton = PushButton(self.tr("重试"), self)+ self._retryButton.hide()++ self._label.setTextColor(QColor(96, 96, 96), QColor(206, 206, 206))+ self._label.setAlignment(Qt.AlignmentFlag.AlignCenter)+ self._label.setWordWrap(True)++ self._retryButton.clicked.connect(self.retryRequested)++ layout = QVBoxLayout(self)+ layout.setSpacing(12)+ layout.setAlignment(Qt.AlignmentFlag.AlignCenter)+ layout.addWidget(self._ring, 0, Qt.AlignmentFlag.AlignHCenter)+ layout.addWidget(self._errorIcon, 0, Qt.AlignmentFlag.AlignHCenter)+ layout.addWidget(self._label, 0, Qt.AlignmentFlag.AlignHCenter)+ layout.addWidget(self._retryButton, 0, Qt.AlignmentFlag.AlignHCenter)- def initLayout(self):- """设置布局"""- self.setWidget(self.scrollWidget)- self.setWidgetResizable(True)- self.enableTransparentBackground()+ def setLoading(self):+ self._ring.show()+ self._errorIcon.hide()+ self._label.setText(self.tr("正在加载..."))+ self._retryButton.hide()+ self.show()++ def setError(self, text: str):+ self._ring.hide()+ self._errorIcon.show()+ self._label.setText(text)+ self._retryButton.show()+++class CatalogCard(SimpleCardWidget):+ def __init__(self, item: dict, parent=None):+ super().__init__(parent)+ self._catalogItems: list[dict] = item["List"]+ self._videoUrl: str = item["Video"]+ self.setFixedHeight(91)- def connectSignalToSlot(self):- """初始化信号连接"""- self.loadingStatusWidget.retrySignal.connect(self.loadData)+ self._logoLabel = PixmapLabel(self)+ self._logoLabel.setFixedSize(71, 71)+ self._logoLabel.setScaledContents(True)+ pixmap = QPixmap()+ pixmap.loadFromData(b64decode(item["Icon"]))+ self._logoLabel.setPixmap(pixmap)+ self._logoLabel.setFixedSize(71, 71)++ self._titleLabel = TitleLabel(item["Name"], self)+ self._bodyLabel = BodyLabel(item["Intro"].replace(r"\n", "\n"), self)+ self._bodyLabel.setMaximumHeight(61)+ self._bodyLabel.setWordWrap(True)++ self._downloadButton = PrimaryPushButton(FluentIcon.DOWNLOAD, self.tr("下载"), self)+ self._downloadButton.setFixedWidth(100)+ self._videoButton = TransparentToolButton(FluentIcon.VIDEO, self)+ self._videoButton.installEventFilter(ToolTipFilter(self._videoButton))+ self._videoButton.setToolTip(self.tr("观看视频"))+ self._videoButton.setEnabled(bool(self._videoUrl))++ self._initLayout()+ self._bind()++ def _initLayout(self):+ textLayout = QVBoxLayout()+ textLayout.setSpacing(0)+ textLayout.addWidget(self._titleLabel)+ textLayout.addWidget(self._bodyLabel)++ mainLayout = QHBoxLayout(self)+ mainLayout.setSpacing(12)+ mainLayout.addWidget(self._logoLabel)+ mainLayout.addLayout(textLayout, 1)+ mainLayout.addWidget(self._downloadButton)+ mainLayout.addWidget(self._videoButton)++ def _bind(self):+ self._downloadButton.clicked.connect(self._onDownloadClicked)+ self._videoButton.clicked.connect(lambda: QDesktopServices.openUrl(QUrl(self._videoUrl)))++ def _onDownloadClicked(self):+ dialog = CatalogDownloadDialog(self.window(), self._catalogItems)+ dialog.exec()- def loadData(self):- """加载数据"""- self.loadingStatusWidget.setLoading()- coreService.runCoroutine(run(), self.loadInfoCards)- def loadInfoCards(self, jsonData: list, error: str):- """加载信息卡片"""- if error:- self.loadingStatusWidget.setError(f"加载失败: {error}")- return+class CatalogDownloadDialog(MessageBoxBase):+ def __init__(self, parent=None, catalogItems: list[dict] | None = None):+ from app.view.components.card_groups import OptionCardGroup+ from app.view.components.editors import AutoSizingEdit+ from app.view.components.option_cards import OutputFolderCard, SubworkerCountCard- self.jsonData = jsonData+ super().__init__(parent)+ self._items = catalogItems or []- # 清除现有的卡片- for card in self.cards:- self.expandLayout.removeWidget(card)- card.deleteLater()- self.cards.clear()-- for item in self.jsonData:- card = SystemInfoCard(self.scrollWidget)- self.cards.append(card)-- card.listData = item["List"]- card.titleLabel.setText(item["Name"])-- logger.debug(f'Loading System Card: {item["Name"]}')-- # 从字节数据中创建QPixmap对象- pixmap = QPixmap()- pixmap.loadFromData(b64decode(item["Icon"]))- card.logoPixmapLabel.setPixmap(pixmap)- card.logoPixmapLabel.setFixedSize(71, 71)-- card.bodyLabel.setText(item["Intro"].replace(r"\n", "\n"))- card.videoUrl = item["Video"]-- card.connectSignalToSlot()- self.expandLayout.addWidget(card)- card.show()-- self.hideLoadingStatusWidget()-- def hideLoadingStatusWidget(self):- """隐藏加载状态控件"""- self.expandLayout.removeWidget(self.loadingStatusWidget)- self.loadingStatusWidget.hide()- self.loadingStatusWidget.setParent(None)- self.loadingStatusWidget.deleteLater()---class DownloadOptionDialog(MaskDialogBase):- startSignal = Signal()-- def __init__(self, parent=None, listData=None, cardData=None):- super().__init__(parent=parent)-- FluentStyleSheet.DIALOG.apply(self.widget)-- self.cardData = cardData- self.listData = listData- self.versions = []-- self.initWidget()- self.initGroups()- self.initButtons()- self.initLayout()- self.connectSignalToSlot()-- def initWidget(self):- """初始化UI基础设置"""- self.setShadowEffect(60, (0, 10), QColor(0, 0, 0, 50))- self.setMaskColor(QColor(0, 0, 0, 76))-- self.mainLayout = QVBoxLayout(self.widget)- self.mainLayout.setContentsMargins(18, 18, 18, 18)- self.widget.setLayout(self.mainLayout)- self.widget.setMinimumSize(510, 580)- self.widget.setMaximumSize(680, 580)-- def initGroups(self):- """设置各功能组"""- self.initVersionGroup()- self.initLogGroup()- self.initSettingGroup()-- def initVersionGroup(self):- """设置版本选择组"""- self.versionGroup = SettingCardGroup("选择版本", self.widget)-- for item in self.listData:- self.versions.append(item["Version"])-- versionItem = OptionsConfigItem(- "Material", "Version", self.versions[0], OptionsValidator(self.versions))-- self.versionCard = ComboBoxSettingCard(- versionItem,- FluentIcon.VIEW,- "选择版本",- "选择你想下载的版本",- texts=self.versions,- parent=self.versionGroup- )+ versions = [item["Version"] for item in self._items]+ versionItem = OptionsConfigItem("Material", "Version", versions[0], OptionsValidator(versions))- self.versionGroup.addSettingCard(self.versionCard)-- def initLogGroup(self):- """设置日志组"""- self.logGroup = SettingCardGroup("更新日志", self.widget)-- self.logTextEdit = PlainTextEdit(self.logGroup)- self.logTextEdit.setReadOnly(True)- self.logTextEdit.setMinimumHeight(140)- self.logTextEdit.setPlainText(self.listData[0]["Log"])-- sizePolicy = QSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Maximum)- self.logTextEdit.setSizePolicy(sizePolicy)- self.logGroup.addSettingCard(self.logTextEdit)-- def initSettingGroup(self):- """设置下载设置组"""- self.settingGroup = SettingCardGroup("下载设置", self.widget)-- # 下载目录设置卡- self.downloadFolderCard = PushSettingCard(- "选择下载目录",- FluentIcon.DOWNLOAD,- "下载目录",- cfg.downloadFolder.value,- self.settingGroup+ self._versionGroup = SettingCardGroup(self.tr("选择版本"), self)+ self._versionCard = ComboBoxSettingCard(+ versionItem, FluentIcon.VIEW, self.tr("选择版本"), self.tr("选择你想下载的版本"),+ texts=versions, parent=self._versionGroup,)+ self._versionGroup.addSettingCard(self._versionCard)- # 下载线程数设置卡- self.threadCountCard = RangeSettingCard(- RangeConfigItem("Material", "AcrylicBlurRadius", 24, RangeValidator(1, 256)),- FluentIcon.CHAT,- "下载线程数",- '下载线程越多,下载越快,同时也越吃性能',- self.settingGroup- )+ self._logGroup = SettingCardGroup(self.tr("更新日志"), self)+ self._logEdit = AutoSizingEdit(self._logGroup, minimumVisibleLines=3, maximumVisibleLines=8)+ self._logEdit.setReadOnly(True)+ self._logEdit.setPlainText(self._items[0]["Log"] if self._items else "")+ self._logGroup.addSettingCard(self._logEdit)- self.settingGroup.addSettingCards([self.downloadFolderCard, self.threadCountCard])-- def initButtons(self):- """设置按钮"""- self.buttonLayout = QHBoxLayout()-- self.cancelButton = PushButton(self)- self.cancelButton.setObjectName("cancelButton")- self.cancelButton.setText("取消下载")-- self.startButton = PrimaryPushButton(self)- self.startButton.setObjectName("startButton")- self.startButton.setText("开始下载")-- self.buttonLayout.addWidget(self.cancelButton)- self.buttonLayout.addWidget(self.startButton)- self.buttonLayout.setSpacing(18)-- def initLayout(self):- """设置整体布局"""- self.mainLayout.addWidget(self.versionGroup)- self.mainLayout.addWidget(self.logGroup)- self.mainLayout.addWidget(self.settingGroup)- self.mainLayout.addLayout(self.buttonLayout)-- def connectSignalToSlot(self):- """连接信号槽"""- self.downloadFolderCard.clicked.connect(self.onDownloadFolderClicked)- self.cancelButton.clicked.connect(self.close)- self.startButton.clicked.connect(self.startDownload)- self.versionCard.comboBox.currentIndexChanged.connect(self.onVersionChanged)-- def startDownload(self):- """开始下载任务"""- payload = {- "url": self.listData[self.versionCard.comboBox.currentIndex()]["Url"],- "headers": defaultHeaders(),- "proxies": getProxies(),- "path": Path(cfg.downloadFolder.value),- }- coreService.runCoroutine(- coreService._parse(payload),- lambda task, error: self._onAssetParsed(task, error),- )- self.close()+ self._optionGroup = OptionCardGroup(self)+ self._optionGroup.addCard(OutputFolderCard(self._optionGroup))+ self._optionGroup.addCard(SubworkerCountCard(self._optionGroup))++ self.yesButton.setText(self.tr("开始下载"))+ self.cancelButton.setText(self.tr("取消"))- def _onAssetParsed(self, task, error):- if error:- InfoBar.error(self.tr("下载失败"), error, duration=-1, position=InfoBarPosition.BOTTOM_RIGHT, parent=self.window())- return-- window: "MainWindow" = self.window()- if window.addTask(task):- InfoBar.success(self.tr("下载任务已添加"), content=task.title, duration=2000, position=InfoBarPosition.BOTTOM_RIGHT, parent=window)+ self.viewLayout.addWidget(self._versionGroup)+ self.viewLayout.addWidget(self._logGroup)+ self.viewLayout.addWidget(self._optionGroup)- def onDownloadFolderClicked(self):- """下载目录点击事件"""- folder = QFileDialog.getExistingDirectory(self, "选择文件夹", "./")- if not folder or self.downloadFolderCard.contentLabel.text() == folder:- return+ self.widget.setFixedWidth(700)- self.downloadFolderCard.setContent(folder)+ self._versionCard.comboBox.currentIndexChanged.connect(+ lambda i: self._logEdit.setPlainText(self._items[i]["Log"] if i < len(self._items) else "")+ )+ self.yesButton.clicked.disconnect()+ self.yesButton.clicked.connect(self._onStartClicked)++ def _onStartClicked(self):+ from qfluentwidgets import InfoBar, InfoBarPosition+ from app.models.task import ResourceTaskOptions+ from app.services.coroutine_runner import coroutineRunner+ from app.services.feature_service import featureService+ from app.services.task_service import taskService++ index = self._versionCard.comboBox.currentIndex()+ item = self._items[index]+ options = self._optionGroup.options()+ window = self.window()+ failedTitle = self.tr("下载失败")++ def onParsed(task):+ for step in task.steps:+ step.setOptions(options)+ taskService.add(task)++ def onFailed(error):+ InfoBar.error(failedTitle, str(error), duration=-1,+ position=InfoBarPosition.BOTTOM_RIGHT, parent=window)++ coroutineRunner.submit(+ featureService.parse(ResourceTaskOptions(+ url=item["Url"],+ outputFolder=options.get("outputFolder", Path(cfg.downloadFolder.value)),+ )),+ done=onParsed,+ failed=onFailed,+ owner=window,+ )+ self.accept()- def onVersionChanged(self, index: int):- """版本选择变化事件"""- self.logTextEdit.setPlainText(self.listData[index]["Log"])+class JackYaoPack(FeaturePack):+ packId = "jack_yao"-class SystemInfoCard(SimpleCardWidget):- def __init__(self, parent=None):- super().__init__(parent=parent)-- self.listData = []- self.videoUrl = ""- self.pixmap = None-- self.initWidget()- self.initMenu()- self.initButtonText()-- def initWidget(self):- """初始化UI组件"""- self.setObjectName("SystemInfoCard")- self.setFixedHeight(91)-- self.initMainLayout()- self.initLogoLabel()- self.initTextLayout()- self.initTitleLabel()- self.initBodyLabel()- self.initDownloadButton()-- def initMainLayout(self):- """设置主布局"""- self.horizontalLayout = QHBoxLayout(self)- self.horizontalLayout.setSpacing(12)- self.horizontalLayout.setObjectName("horizontalLayout")-- def initLogoLabel(self):- """设置Logo标签"""- self.logoPixmapLabel = PixmapLabel(self)- self.logoPixmapLabel.setObjectName("logoPixmapLabel")- self.logoPixmapLabel.setMinimumSize(QSize(71, 71))- self.logoPixmapLabel.setMaximumSize(QSize(71, 71))- self.logoPixmapLabel.setScaledContents(True)- self.logoPixmapLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)- self.horizontalLayout.addWidget(self.logoPixmapLabel)-- def initTextLayout(self):- """设置文本布局"""- self.bodyVBoxLayout = QVBoxLayout()- self.bodyVBoxLayout.setSpacing(0)- self.bodyVBoxLayout.setObjectName("bodyVBoxLayout")-- def initTitleLabel(self):- """设置标题标签"""- self.titleLabel = TitleLabel(self)- self.titleLabel.setObjectName("titleLabel")-- sizePolicy = QSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)- sizePolicy.setHorizontalStretch(0)- sizePolicy.setVerticalStretch(0)- sizePolicy.setHeightForWidth(self.titleLabel.sizePolicy().hasHeightForWidth())- self.titleLabel.setSizePolicy(sizePolicy)- self.bodyVBoxLayout.addWidget(self.titleLabel)-- def initBodyLabel(self):- """设置内容标签"""- self.bodyLabel = BodyLabel(self)- self.bodyLabel.setObjectName("bodyLabel")-- sizePolicy = QSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Maximum)- sizePolicy.setHorizontalStretch(0)- sizePolicy.setVerticalStretch(0)- sizePolicy.setHeightForWidth(self.bodyLabel.sizePolicy().hasHeightForWidth())- self.bodyLabel.setSizePolicy(sizePolicy)- self.bodyLabel.setMaximumSize(QSize(16777215, 61))- self.bodyLabel.setWordWrap(True)- self.bodyVBoxLayout.addWidget(self.bodyLabel)- self.horizontalLayout.addLayout(self.bodyVBoxLayout)-- def initDownloadButton(self):- """设置下载按钮"""- self.downloadButton = PrimarySplitPushButton(self)- self.downloadButton.setObjectName("downloadButton")- self.downloadButton.setFixedSize(QSize(121, 31))- self.downloadButton.setText(" 下载 ")- self.horizontalLayout.addWidget(self.downloadButton)-- def initMenu(self):- """设置菜单"""- self.menu = RoundMenu(parent=self)- self.videoAction = Action(FluentIcon.VIDEO, "视频")- self.menu.addAction(self.videoAction)- self.downloadButton.setFlyout(self.menu)-- def initButtonText(self):- """设置按钮文本"""- self.downloadButton.setText(" 下载 ")-- def connectSignalToSlot(self):- """连接信号槽"""- self.videoAction.triggered.connect(self.openVideoUrl)- self.downloadButton.clicked.connect(self.openDownloadDialog)-- def openVideoUrl(self):- """打开视频链接"""- QDesktopServices.openUrl(QUrl(self.videoUrl))-- def openDownloadDialog(self):- """打开下载对话框"""- dialog = DownloadOptionDialog(- self.window(),- self.listData,- {"pixmap": self.pixmap, "name": self.titleLabel.text()}- )- dialog.exec()+ def pages(self):+ return [CatalogPage]diff --git a/features/m3u8_pack/cards.py b/features/m3u8_pack/cards.pyindex 3b8be5d8..400128b1 100644--- a/features/m3u8_pack/cards.py+++ b/features/m3u8_pack/cards.py@@ -1,418 +1,246 @@+from __future__ import annotations+from pathlib import Path-from typing import TYPE_CHECKING, Any, cast--from PySide6.QtCore import QFileInfo, Signal-from PySide6.QtGui import QColor, QPainter-from PySide6.QtWidgets import QFileDialog, QFileIconProvider, QHBoxLayout, QVBoxLayout, QWidget-from qfluentwidgets import (- BodyLabel,- ComboBox,- CompactSpinBox,- FluentIcon,- IconWidget,- ImageLabel,- LineEdit,- PushButton,- TransparentToolButton,- isDarkTheme,-)--from loguru import logger--from app.bases.models import Task, TaskStatus-from app.services.core_service import coreService-from app.services.task_service import taskService-from app.supports.utils import toReadableSize, toReadableTime-from app.view.components.cards import ParseSettingCard, ResultCard, UniversalTaskCard+from typing import TYPE_CHECKING++from PySide6.QtWidgets import QFileDialog, QHBoxLayout, QVBoxLayout+from qfluentwidgets import BodyLabel, ComboBox, CompactSpinBox, FluentIcon, TransparentToolButton++from app.format import toReadableSize+from app.models.task import TaskStatus+from app.view.cards.draft_cards import UniversalDraftCard+from app.view.cards.task_cards import UniversalTaskCardfrom app.view.components.editors import AutoSizingEdit-from app.view.components.labels import EditableLabel+from app.view.components.option_cards import OptionCardif TYPE_CHECKING:- from .task import M3U8TaskStage+ from .task import M3U8TaskStep+++class M3U8DraftCard(UniversalDraftCard):+ passclass M3U8TaskCard(UniversalTaskCard):- def _renderTaskState(self):- progress, speed, receivedBytes = self.task.currentSnapshot()- self.progressBar.setValue(progress)- if self.task.fileSize > 1:- self.progressLabel.setText(f"{toReadableSize(receivedBytes)}/{toReadableSize(self.task.fileSize)}")- else:- self.progressLabel.setText(self.tr("{0} / {1:.2f}%").format(toReadableSize(receivedBytes), progress))-- if self.task.status == TaskStatus.RUNNING:- self.progressBar.setError(False)- if self.infoLabel.isVisible():- self.infoLabel.hide()- self.speedLabel.show()- self.leftTimeLabel.show()- self.progressLabel.show()- self.speedLabel.setText(f"{toReadableSize(speed)}/s")- if self.task.fileSize > 1 and speed > 0:- self.leftTimeLabel.setText(toReadableTime(int((self.task.fileSize - receivedBytes) / speed)))- else:- self.leftTimeLabel.setText("--")- elif self.task.status == TaskStatus.COMPLETED:- self.progressBar.setError(False)- self.progressBar.hide()- self.showStatusInfo(self.tr("任务已经完成"))- elif self.task.status == TaskStatus.FAILED:- self.progressBar.error()- self.onTaskFailed()- elif self.task.status == TaskStatus.PAUSED:- self.progressBar.setError(False)- self.progressBar.pause()- self.showStatusInfo(self.tr("任务已经暂停"))- else:- self.progressBar.setError(False)- self.progressBar.pause()- self.showStatusInfo(self.tr("任务正在等待"))-- self.refreshToggleButton()---class M3U8LiveTaskCard(M3U8TaskCard):- """直播录制卡:主按钮为「停止并定案」,展示 录制中/等待 与已录时长"""-- def _renderTaskState(self):- progress, speed, _ = self.task.currentSnapshot()- self.progressBar.setValue(progress)- stage = cast("M3U8TaskStage", self.task.stages[0])-- if self.task.status == TaskStatus.RUNNING:- self.progressBar.setError(False)- if self.infoLabel.isVisible():- self.infoLabel.hide()- self.speedLabel.show()- self.leftTimeLabel.show()- self.progressLabel.show()- self.speedLabel.setText(f"{toReadableSize(speed)}/s")- self.leftTimeLabel.setText(self._liveTimeText(stage))- if stage.liveStatus == "Waiting":- self.progressLabel.setText(self.tr("等待中"))- self.progressBar.pause()- else:- self.progressLabel.setText(self.tr("录制中"))- self.progressBar.resume()- elif self.task.status == TaskStatus.COMPLETED:- self.progressBar.setError(False)- self.progressBar.hide()- self.showStatusInfo(self.tr("录制已结束"))- elif self.task.status == TaskStatus.FAILED:- self.progressBar.error()- self.onTaskFailed()- else:- self.progressBar.setError(False)- self.progressBar.pause()- self.showStatusInfo(self.tr("等待录制"))-- self.refreshToggleButton()-- def _liveTimeText(self, stage: "M3U8TaskStage") -> str:- elapsed = stage.liveElapsed or "00m00s"- return f"{elapsed} / {stage.recordLimit}" if stage.recordLimit else elapsed-- def refreshToggleButton(self):- status = self.task.status- if status == TaskStatus.RUNNING:- self.toggleRunningStatusButton.setIcon(FluentIcon.ACCEPT)- self.toggleRunningStatusButton.setToolTip(self.tr("停止并定案"))- self.toggleRunningStatusButton.setEnabled(True)- elif status == TaskStatus.COMPLETED:- self.toggleRunningStatusButton.setIcon(FluentIcon.ACCEPT)- self.toggleRunningStatusButton.setEnabled(False)- else:- self.toggleRunningStatusButton.setIcon(FluentIcon.PLAY)- self.toggleRunningStatusButton.setEnabled(True)+ def refresh(self):+ super().refresh()+ if self._task.status == TaskStatus.RUNNING and self._task.fileSize <= 1:+ step = self._step()+ if step is not None:+ progress = step.progress+ self.sizeLabel.setText(+ f"{toReadableSize(step.receivedBytes)} / {progress:.1f}%"+ )- self.verifyHashButton.setVisible(status == TaskStatus.COMPLETED)- self.verifyHashButton.setEnabled(status == TaskStatus.COMPLETED)+ def _step(self) -> M3U8TaskStep | None:+ return self._task.steps[0] if self._task.steps else None- def toggleRunningStatus(self):- if self.task.status == TaskStatus.RUNNING:- self.finalizeRecording()- else:- self.resumeTask()- def finalizeRecording(self):- # 直播无暂停:停止=取消进程, worker 收尾标 COMPLETED;不走 stopTask 以免 PAUSED 闪烁- self.toggleRunningStatusButton.setDisabled(True)- coreService.runCoroutine(coreService._stopTask(self.task), self._onRecordingFinalized)+class M3U8LiveTaskCard(UniversalTaskCard):- def _onRecordingFinalized(self, _result=None, error: str | None = None):- if error:- logger.warning("停止直播录制失败 {}: {}", self.task.title, error)- self._renderTaskState()+ def refresh(self):+ super().refresh()+ step = self._step()+ if step is None:return- if self.task.status == TaskStatus.COMPLETED and self.cardStatus != TaskStatus.COMPLETED:- self.onTaskFinished()- self._renderTaskState()- if self.task.status != self.cardStatus:- taskService.scheduleFlush()- self.cardStatus = self.task.status---class M3U8ResultCard(ResultCard):- def __init__(self, task: Task, parent: QWidget = None):- super().__init__(task, parent)- self.iconLabel = ImageLabel(self)- self.filenameLabel = EditableLabel(self.task.title, self, onEdit=self._enterEditMode)- self.filenameEdit = LineEdit(self)- self.metaLabel = BodyLabel(self._metaText(), self)- self.mainLayout = QHBoxLayout(self)+ if self._task.status == TaskStatus.RUNNING:+ elapsed = step.liveElapsed or "00m00s"+ timeText = f"{elapsed} / {step.recordLimit}" if step.recordLimit else elapsed+ self.etaLabel.setText(timeText)+ if step.liveStatus == "Waiting":+ self.sizeLabel.setText(self.tr("等待中"))+ else:+ self.sizeLabel.setText(self.tr("录制中"))+ elif self._task.status == TaskStatus.COMPLETED:+ self._showStatus(self.tr("录制已结束"))++ def _refreshButtons(self) -> None:+ if self._task.status == TaskStatus.RUNNING:+ self.toggleButton.setIcon(FluentIcon.ACCEPT)+ self.toggleButton.setToolTip(self.tr("停止并定案"))+ self.toggleButton.setEnabled(True)+ elif self._task.status == TaskStatus.COMPLETED:+ self.toggleButton.setIcon(FluentIcon.ACCEPT)+ self.toggleButton.setEnabled(False)+ else:+ self.toggleButton.setIcon(FluentIcon.PLAY)+ self.toggleButton.setEnabled(True)+ self.verifyHashButton.setVisible(self._task.status == TaskStatus.COMPLETED)+ self.verifyHashButton.setEnabled(self._task.status == TaskStatus.COMPLETED)++ def _onToggleClicked(self) -> None:+ if self._task.status == TaskStatus.RUNNING:+ self.toggleButton.setEnabled(False)+ step = self._step()+ if step is not None:+ step.terminate()+ else:+ from app.services.task_service import taskService+ taskService.start(self._task)+ self.refresh()- self._initWidget()- self._initLayout()- self._renderCategoryButton()+ def _step(self) -> M3U8TaskStep | None:+ return self._task.steps[0] if self._task.steps else None- def _initWidget(self):- self.setFixedHeight(35)- self._refreshIcon()- self.filenameEdit.setText(self.task.title)- self.filenameEdit.editingFinished.connect(self._onEditingFinished)- self.filenameEdit.hide()- def _initLayout(self):- self.mainLayout.setContentsMargins(10, 2, 10, 2)- self.mainLayout.setSpacing(12)- self.mainLayout.addWidget(self.iconLabel)- self.mainLayout.addWidget(self.filenameLabel, 1)- self.mainLayout.addWidget(self.filenameEdit, 1)- self.mainLayout.addWidget(self.metaLabel)- self.mainLayout.addWidget(self.editButton)- self.mainLayout.addWidget(self.categoryButton)-- def _metaText(self) -> str:- manifestText = "DASH" if self.task.manifestType == "mpd" else "HLS"- modeText = self.tr("直播") if self.task.isLive else self.tr("点播")- return f"{manifestText} · {modeText}"-- def _refreshIcon(self):- icon = QFileIconProvider().icon(QFileInfo(self.task.outputFolder))- self.iconLabel.setImage(icon.pixmap(16, 16))- self.iconLabel.setFixedSize(16, 16)-- def _enterEditMode(self):- self.filenameLabel.hide()- self.filenameEdit.show()- self.filenameEdit.setFocus()- self.filenameEdit.selectAll()-- def _onEditingFinished(self):- newFilename = self.filenameEdit.text().strip()- if newFilename and newFilename != self.task.title:- self.task.setTitle(newFilename)- self.filenameLabel.setText(self.task.title)- self.filenameEdit.setText(self.task.title)- self._refreshIcon()-- self.filenameEdit.hide()- self.filenameLabel.show()-- def getTask(self) -> Task:- return self.task---class _M3U8EditCard(QWidget):- """编辑对话框里的多行设置卡,提供 payloadChanged 信号与顶部分隔线"""-- payloadChanged = Signal()-- def paintEvent(self, event):- painter = QPainter(self)- painter.setRenderHints(QPainter.RenderHint.Antialiasing)- painter.setPen(QColor(0, 0, 0, 96 if isDarkTheme() else 48))- painter.drawLine(self.rect().topLeft(), self.rect().topRight())---class M3U8TrackEditCard(ParseSettingCard):- def __init__(self, icon, title: str, parent=None, *, streams: list, initial: str = "") -> None:+class StreamSelectCard(OptionCard):+ def __init__(self, parent=None, *, streams: list, initial: str = ""):+ super().__init__(parent)self._streams = streams- self._initialExpr = initial- super().__init__(icon, title, parent)+ self._initial = initial+ self.comboBox = ComboBox(self)- def initCustomWidget(self) -> None:- self.trackCombo = ComboBox(self)self._initWidget()self._initLayout()- self._bind()- def _initWidget(self) -> None:- self.trackCombo.setMinimumWidth(220)- self.trackCombo.addItem(self.tr("默认(最佳)"), userData="")+ def _initWidget(self):+ self.comboBox.setMinimumWidth(220)+ self.comboBox.addItem(self.tr("默认(最佳)"), userData="")selectedIndex = 0for index, stream in enumerate(self._streams, start=1):- expr = stream.get("selectExpr", "")- self.trackCombo.addItem(stream.get("label", ""), userData=expr)- if self._initialExpr and expr == self._initialExpr:+ width = stream.get("width", 0)+ height = stream.get("height", 0)+ codecs = stream.get("codecs", "")+ frameRate = stream.get("frameRate")+ label = f"{width}×{height}"+ if codecs:+ label += f" · {codecs}"+ if frameRate:+ label += f" · {frameRate}fps"+ selectExpr = f"res=\"{width}x{height}\""+ if frameRate:+ selectExpr += f":frame=\"{int(frameRate)}*\""+ self.comboBox.addItem(label, userData=selectExpr)+ if self._initial and selectExpr == self._initial:selectedIndex = index- self.trackCombo.setCurrentIndex(selectedIndex)-- def _initLayout(self) -> None:- self.hBoxLayout.addWidget(self.trackCombo)- self.hBoxLayout.addSpacing(16)+ self.comboBox.setCurrentIndex(selectedIndex)- def _bind(self) -> None:- self.trackCombo.currentIndexChanged.connect(lambda _: self.payloadChanged.emit())-- @property- def payload(self) -> dict[str, Any]:- return {"selectVideo": self.trackCombo.currentData() or ""}+ def _initLayout(self):+ layout = QHBoxLayout(self)+ layout.setContentsMargins(16, 8, 16, 8)+ layout.addWidget(self.comboBox)+ layout.addStretch(1)+ def options(self) -> dict:+ return {"selectVideo": self.comboBox.currentData() or ""}-class M3U8RecordLimitEditCard(ParseSettingCard):- def __init__(self, icon, title: str, parent=None, *, initial: str = "") -> None:- self._initialLimit = initial- super().__init__(icon, title, parent)- def initCustomWidget(self) -> None:+class RecordLimitCard(OptionCard):+ def __init__(self, parent=None, *, initial: str = ""):+ super().__init__(parent)+ self._initial = initialself.hourSpinBox = CompactSpinBox(self)self.minuteSpinBox = CompactSpinBox(self)self.secondSpinBox = CompactSpinBox(self)+self._initWidget()self._initLayout()- self._bind()- def _initWidget(self) -> None:+ def _initWidget(self):self.hourSpinBox.setRange(0, 99)self.minuteSpinBox.setRange(0, 59)self.secondSpinBox.setRange(0, 59)for box in (self.hourSpinBox, self.minuteSpinBox, self.secondSpinBox):box.setFixedWidth(64)- self._applyLimit(self._initialLimit)-- def _initLayout(self) -> None:- self.hBoxLayout.addWidget(self.hourSpinBox)- self.hBoxLayout.addWidget(BodyLabel(":", self))- self.hBoxLayout.addWidget(self.minuteSpinBox)- self.hBoxLayout.addWidget(BodyLabel(":", self))- self.hBoxLayout.addWidget(self.secondSpinBox)- self.hBoxLayout.addSpacing(16)+ parts = self._initial.split(":") if self._initial else []+ if len(parts) == 3:+ try:+ self.hourSpinBox.setValue(int(parts[0]))+ self.minuteSpinBox.setValue(int(parts[1]))+ self.secondSpinBox.setValue(int(parts[2]))+ except ValueError:+ pass- def _bind(self) -> None:- for box in (self.hourSpinBox, self.minuteSpinBox, self.secondSpinBox):- box.valueChanged.connect(lambda _: self.payloadChanged.emit())-- def _applyLimit(self, limit: str) -> None:- parts = limit.split(":") if limit else []- if len(parts) != 3:- return- try:- hours, minutes, seconds = (int(part) for part in parts)- except ValueError:- return- self.hourSpinBox.setValue(hours)- self.minuteSpinBox.setValue(minutes)- self.secondSpinBox.setValue(seconds)-- @property- def payload(self) -> dict[str, Any]:- hours = self.hourSpinBox.value()- minutes = self.minuteSpinBox.value()- seconds = self.secondSpinBox.value()- limit = f"{hours:02}:{minutes:02}:{seconds:02}" if hours + minutes + seconds > 0 else ""+ def _initLayout(self):+ layout = QHBoxLayout(self)+ layout.setContentsMargins(16, 8, 16, 8)+ layout.addWidget(self.hourSpinBox)+ layout.addWidget(BodyLabel(":", self))+ layout.addWidget(self.minuteSpinBox)+ layout.addWidget(BodyLabel(":", self))+ layout.addWidget(self.secondSpinBox)+ layout.addStretch(1)++ def options(self) -> dict:+ h, m, s = self.hourSpinBox.value(), self.minuteSpinBox.value(), self.secondSpinBox.value()+ limit = f"{h:02}:{m:02}:{s:02}" if h + m + s > 0 else ""return {"recordLimit": limit}-class M3U8DecryptionEditCard(_M3U8EditCard):- def __init__(self, icon, title: str, parent=None, *, keys: list | None = None, keyTextFile: str = "") -> None:+class DecryptionKeyCard(OptionCard):+ def __init__(self, parent=None, *, keys: list | None = None, keyTextFile: str = ""):super().__init__(parent)self._keyTextFile = keyTextFile-- # instant widget- self.iconWidget = IconWidget(icon, self)- self.titleLabel = BodyLabel(title, self)+ self.titleLabel = BodyLabel(self.tr("解密密钥"), self)self.keyFileButton = TransparentToolButton(FluentIcon.FOLDER_ADD, self)- self.keysEdit = AutoSizingEdit(self, minimumVisibleLines=3, maximumVisibleLines=10)self.keyFileLabel = BodyLabel(self)-- # instant layout- self.vBoxLayout = QVBoxLayout(self)- self.titleRowLayout = QHBoxLayout()+ self.keysEdit = AutoSizingEdit(self, minimumVisibleLines=3, maximumVisibleLines=10)self._initWidget(keys or [])self._initLayout()self._bind()- def _initWidget(self, keys: list) -> None:- self.iconWidget.setFixedSize(16, 16)+ def _initWidget(self, keys: list):self.keyFileButton.setToolTip(self.tr("选择 KEY 文本文件"))self.keysEdit.setPlaceholderText("KID1:KEY1\nKID2:KEY2")self.keysEdit.setPlainText("\n".join(keys))- self._refreshKeyFileLabel()-- def _initLayout(self) -> None:- self.titleRowLayout.setSpacing(15)- self.titleRowLayout.addWidget(self.iconWidget)- self.titleRowLayout.addWidget(self.titleLabel)- self.titleRowLayout.addStretch(1)- self.titleRowLayout.addWidget(self.keyFileLabel)- self.titleRowLayout.addWidget(self.keyFileButton)-- self.vBoxLayout.setContentsMargins(24, 10, 24, 12)- self.vBoxLayout.setSpacing(10)- self.vBoxLayout.addLayout(self.titleRowLayout)- self.vBoxLayout.addWidget(self.keysEdit)-- def _bind(self) -> None:- self.keysEdit.textChanged.connect(self.payloadChanged.emit)+ self.keyFileLabel.setText(Path(self._keyTextFile).name if self._keyTextFile else "")++ def _initLayout(self):+ titleRow = QHBoxLayout()+ titleRow.setSpacing(15)+ titleRow.addWidget(self.titleLabel)+ titleRow.addStretch(1)+ titleRow.addWidget(self.keyFileLabel)+ titleRow.addWidget(self.keyFileButton)++ layout = QVBoxLayout(self)+ layout.setContentsMargins(24, 10, 24, 12)+ layout.setSpacing(10)+ layout.addLayout(titleRow)+ layout.addWidget(self.keysEdit)++ def _bind(self):self.keyFileButton.clicked.connect(self._onChooseKeyFile)- def _onChooseKeyFile(self) -> None:+ def _onChooseKeyFile(self):path, _ = QFileDialog.getOpenFileName(self, self.tr("选择 KEY 文本文件"))if not path:returnself._keyTextFile = path- self._refreshKeyFileLabel()- self.payloadChanged.emit()+ self.keyFileLabel.setText(Path(path).name)- def _refreshKeyFileLabel(self) -> None:- self.keyFileLabel.setText(Path(self._keyTextFile).name if self._keyTextFile else "")-- @property- def payload(self) -> dict[str, Any]:+ def options(self) -> dict:keys = [line.strip() for line in self.keysEdit.toPlainText().splitlines() if line.strip()]- return {"decryptionKeys": keys, "keyTextFile": self._keyTextFile}+ return {"decryptionKeys": keys, "decryptionKeyFile": self._keyTextFile}-class M3U8MuxImportEditCard(_M3U8EditCard):- def __init__(self, icon, title: str, parent=None, *, initial: list | None = None) -> None:+class MuxImportCard(OptionCard):+ def __init__(self, parent=None, *, initial: list | None = None):super().__init__(parent)-- # instant widget- self.iconWidget = IconWidget(icon, self)- self.titleLabel = BodyLabel(title, self)+ self.titleLabel = BodyLabel(self.tr("导入音轨/字幕"), self)self.importEdit = AutoSizingEdit(self, minimumVisibleLines=3, maximumVisibleLines=10)- # instant layout- self.vBoxLayout = QVBoxLayout(self)- self.titleRowLayout = QHBoxLayout()-self._initWidget(initial or [])self._initLayout()- self._bind()- def _initWidget(self, imports: list) -> None:- self.iconWidget.setFixedSize(16, 16)+ def _initWidget(self, imports: list):self.importEdit.setPlaceholderText('path="aud.m4a":lang=eng:name="Audio"')self.importEdit.setPlainText("\n".join(imports))- def _initLayout(self) -> None:- self.titleRowLayout.setSpacing(15)- self.titleRowLayout.addWidget(self.iconWidget)- self.titleRowLayout.addWidget(self.titleLabel)- self.titleRowLayout.addStretch(1)-- self.vBoxLayout.setContentsMargins(24, 10, 24, 12)- self.vBoxLayout.setSpacing(10)- self.vBoxLayout.addLayout(self.titleRowLayout)- self.vBoxLayout.addWidget(self.importEdit)-- def _bind(self) -> None:- self.importEdit.textChanged.connect(self.payloadChanged.emit)-- @property- def payload(self) -> dict[str, Any]:+ def _initLayout(self):+ titleRow = QHBoxLayout()+ titleRow.setSpacing(15)+ titleRow.addWidget(self.titleLabel)+ titleRow.addStretch(1)++ layout = QVBoxLayout(self)+ layout.setContentsMargins(24, 10, 24, 12)+ layout.setSpacing(10)+ layout.addLayout(titleRow)+ layout.addWidget(self.importEdit)++ def options(self) -> dict:imports = [line.strip() for line in self.importEdit.toPlainText().splitlines() if line.strip()]return {"muxImports": imports}diff --git a/features/m3u8_pack/config.py b/features/m3u8_pack/config.pyindex 58a69259..3b3a9c25 100644--- a/features/m3u8_pack/config.py+++ b/features/m3u8_pack/config.py@@ -1,345 +1,216 @@-import asyncio+from __future__ import annotations++import platformimport sysfrom pathlib import Path-from typing import TYPE_CHECKING-from PySide6.QtCore import Qtfrom qfluentwidgets import (BoolValidator,- ComboBoxSettingCard,ConfigItem,- FluentIcon,FolderValidator,- InfoBar,OptionsConfigItem,OptionsValidator,- PrimaryPushButton,RangeConfigItem,- RangeSettingCard,RangeValidator,- SettingCard,- SwitchSettingCard,- ToolButton,)-from app.bases.models import PackConfig-from app.services.core_service import coreService-from app.supports.android import IS_ANDROID, nativeLibraryDir-from app.supports.paths import APP_DATA_DIR-from app.supports.utils import findExecutable, toPosixPath-from app.view.components.setting_card_group import CollapsibleSettingCardGroup-from app.view.components.setting_cards import InstallFolderCard, LineEditSettingCard, SelectFileCard, SpinBoxSettingCard--if TYPE_CHECKING:- from app.view.pages.setting_page import SettingPage- from app.view.windows.main_window import MainWindow--try:- from ffmpeg_pack.config import ffmpegPaths-except ImportError:- from features.ffmpeg_pack.config import ffmpegPaths---def downloaderPath() -> str:- if IS_ANDROID:- nativeDir = nativeLibraryDir()- if not nativeDir:- return ""- binary = Path(nativeDir) / "libnm3u8dlre.so"- return str(binary) if binary.exists() else ""- return findExecutable(Path(m3u8Config.installFolder.value), "N_m3u8DL-RE")---async def probeM3U8Runtime() -> dict[str, str]:- execPath = downloaderPath()- ffmpegPath, _ = ffmpegPaths()- runtimeInfo = {- "downloaderPath": execPath,- "version": "",- "installPath": "",- "ffmpegPath": ffmpegPath,- }- if not execPath:- return runtimeInfo-- process = await asyncio.create_subprocess_exec(- execPath,- "--version",- stdin=asyncio.subprocess.DEVNULL,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- )- stdout, stderr = await process.communicate()- if process.returncode != 0:- return runtimeInfo-- output = stdout.decode("utf-8", errors="ignore") or stderr.decode("utf-8", errors="ignore")- lines = [line.strip() for line in output.splitlines() if line.strip()]- runtimeInfo["version"] = lines[0] if lines else ""- runtimeInfo["installPath"] = toPosixPath(Path(execPath).parent)- return runtimeInfo---class M3U8RuntimeCard(SettingCard):- def __init__(self, parent=None):- super().__init__(FluentIcon.INFO, self.tr("当前 N_m3u8DL-RE"), self.tr("正在检测运行时..."), parent)- self.installButton = PrimaryPushButton(self.tr("一键安装"), self)- self.refreshButton = ToolButton(FluentIcon.SYNC, self)-- self._initLayout()- self._bind()-- def _initLayout(self):- self.hBoxLayout.addWidget(self.installButton, 0, Qt.AlignmentFlag.AlignRight)- self.hBoxLayout.addSpacing(8)- self.hBoxLayout.addWidget(self.refreshButton, 0, Qt.AlignmentFlag.AlignRight)- self.hBoxLayout.addSpacing(16)-- def _bind(self):- self.installButton.clicked.connect(self._onInstallClicked)- self.refreshButton.clicked.connect(self.refreshStatus)-- def refreshStatus(self):- self.refreshButton.setEnabled(False)- self.setContent(self.tr("正在检测运行时..."))- coreService.runCoroutine(probeM3U8Runtime(), self._onRuntimeLoaded)-- def _onRuntimeLoaded(self, result, error: str | None):- self.refreshButton.setEnabled(True)- if error:- self.setContent(self.tr("检测运行时失败"))- return+from app.client import buildClient+from app.config.paths import APP_DATA_DIR+from app.models.pack import BinaryRuntime, PackConfig+from app.models.task import Task+from app.platform.android import IS_ANDROID, nativeLibraryDir+from app.platform.filesystem import findExecutable- runtimeInfo = result or {}- executablePath = runtimeInfo.get("downloaderPath", "")- version = runtimeInfo.get("version", "")- installPath = runtimeInfo.get("installPath", "")- ffmpegPath = runtimeInfo.get("ffmpegPath", "")-- if executablePath:- ffmpegText = ffmpegPath if ffmpegPath else self.tr("未检测到,部分流可能无法自动混流")- content = self.tr("版本: {0}\n安装路径: {1}\nFFmpeg: {2}").format(- version or self.tr("未知"),- installPath or executablePath,- ffmpegText,- )- else:- content = self.tr("未检测到可用的 N_m3u8DL-RE")- self.setContent(content)-- def _onInstallClicked(self):- from .pack import createInstallTask-- self.installButton.setEnabled(False)- self.installButton.setText(self.tr("准备中..."))- coreService.runCoroutine(createInstallTask(), self._onInstallTaskCreated)-- def _onInstallTaskCreated(self, result, error: str | None):- self.installButton.setEnabled(True)- self.installButton.setText(self.tr("一键安装"))-- mainWindow: "MainWindow" = self.window()- if error or result is None:- InfoBar.error(self.tr("安装 N_m3u8DL-RE 失败"), error or self.tr("无法创建安装任务"), duration=-1, parent=mainWindow)- return-- mainWindow.addTask(result)+RELEASE_TAG = "v0.5.1-beta"+RELEASE_API = f"https://api.github.com/repos/nilaoda/N_m3u8DL-RE/releases/tags/{RELEASE_TAG}"class M3U8Config(PackConfig):- installFolder = ConfigItem(- "M3U8",- "InstallFolder",- f"{APP_DATA_DIR}/M3U8DL",- FolderValidator(),- )+ installFolder = ConfigItem("M3U8", "InstallFolder", f"{APP_DATA_DIR}/M3U8DL", FolderValidator())associateFileTypes = ConfigItem("M3U8", "AssociateFileTypes", False, BoolValidator())-outputFormat = OptionsConfigItem("M3U8", "OutputFormat", "mp4", OptionsValidator(["mp4", "mkv"]))threadCount = RangeConfigItem("M3U8", "ThreadCount", 8, RangeValidator(1, 64))retryCount = RangeConfigItem("M3U8", "RetryCount", 3, RangeValidator(0, 20))requestTimeout = RangeConfigItem("M3U8", "RequestTimeout", 100, RangeValidator(5, 600))- autoSelect = ConfigItem("M3U8", "AutoSelect", True, BoolValidator())- concurrentDownload = ConfigItem("M3U8", "ConcurrentDownload", True, BoolValidator())- appendUrlParams = ConfigItem("M3U8", "AppendUrlParams", False, BoolValidator())- binaryMerge = ConfigItem("M3U8", "BinaryMerge", False, BoolValidator())- checkSegmentsCount = ConfigItem("M3U8", "CheckSegmentsCount", True, BoolValidator())-- # 直播(real-time-merge 对直播恒开,不设开关)- liveKeepSegments = ConfigItem("M3U8", "LiveKeepSegments", False, BoolValidator())- livePipeMux = ConfigItem("M3U8", "LivePipeMux", False, BoolValidator())- liveFixVtt = ConfigItem("M3U8", "LiveFixVtt", False, BoolValidator())+ shouldAutoSelect = ConfigItem("M3U8", "AutoSelect", True, BoolValidator())+ shouldConcurrentDownload = ConfigItem("M3U8", "ConcurrentDownload", True, BoolValidator())+ shouldAppendUrlParams = ConfigItem("M3U8", "AppendUrlParams", False, BoolValidator())+ shouldBinaryMerge = ConfigItem("M3U8", "BinaryMerge", False, BoolValidator())+ shouldCheckSegmentsCount = ConfigItem("M3U8", "CheckSegmentsCount", True, BoolValidator())+ shouldKeepLiveSegments = ConfigItem("M3U8", "LiveKeepSegments", False, BoolValidator())+ shouldUseLivePipeMux = ConfigItem("M3U8", "LivePipeMux", False, BoolValidator())+ shouldFixLiveVtt = ConfigItem("M3U8", "LiveFixVtt", False, BoolValidator())liveWaitTime = RangeConfigItem("M3U8", "LiveWaitTime", 0, RangeValidator(0, 100000))liveTakeCount = RangeConfigItem("M3U8", "LiveTakeCount", 0, RangeValidator(0, 1000))-decryptionEngine = OptionsConfigItem("M3U8", "DecryptionEngine", "FFmpeg",OptionsValidator(["FFmpeg", "MP4Decrypt", "Shaka Packager"]),)decryptionBinaryPath = ConfigItem("M3U8", "DecryptionBinaryPath", "")- mp4RealTimeDecryption = ConfigItem("M3U8", "MP4RealTimeDecryption", True, BoolValidator())-+ shouldUseMp4RealTimeDecryption = ConfigItem("M3U8", "MP4RealTimeDecryption", True, BoolValidator())maxSpeed = RangeConfigItem("M3U8", "MaxSpeed", -1, RangeValidator(-1, 1000000))speedUnit = OptionsConfigItem("M3U8", "SpeedUnit", "Mbps", OptionsValidator(["Mbps", "Kbps"]))adKeyword = ConfigItem("M3U8", "AdKeyword", "")subtitleFormat = OptionsConfigItem("M3U8", "SubtitleFormat", "SRT", OptionsValidator(["SRT", "VTT"]))- noDateInfo = ConfigItem("M3U8", "NoDateInfo", False, BoolValidator())- keepImageSegments = ConfigItem("M3U8", "KeepImageSegments", False, BoolValidator())- delAfterDone = ConfigItem("M3U8", "DelAfterDone", True, BoolValidator())+ shouldOmitDateInfo = ConfigItem("M3U8", "NoDateInfo", False, BoolValidator())+ shouldKeepImageSegments = ConfigItem("M3U8", "KeepImageSegments", False, BoolValidator())+ shouldDeleteTemp = ConfigItem("M3U8", "DelAfterDone", True, BoolValidator())customMuxAfterDone = ConfigItem("M3U8", "CustomMuxAfterDone", "")- selectAllAudioSubtitle = ConfigItem("M3U8", "SelectAllAudioSubtitle", True, BoolValidator())+ shouldSelectAllAudioSubtitle = ConfigItem("M3U8", "SelectAllAudioSubtitle", True, BoolValidator())++ def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:+ import sys+ from qfluentwidgets import ComboBoxSettingCard, FluentIcon, RangeSettingCard, SwitchSettingCard+ from app.view.components.setting_card_group import CollapsibleSettingCardGroup+ from app.view.components.setting_cards import (+ SelectFolderSettingCard, LineEditSettingCard, RuntimeCard, SelectFileCard, SpinBoxSettingCard,+ )- def setupSettings(self, settingPage: "SettingPage"):- self.m3u8Group = CollapsibleSettingCardGroup(self.tr("流媒体下载"), "m3u8", settingPage.container)- self.installFolderCard = InstallFolderCard(- self.installFolder,- f"{APP_DATA_DIR}/M3U8DL",+ m3u8Group = CollapsibleSettingCardGroup(self.tr("M3U8 下载"), "m3u8", parent)+ installFolderCard = SelectFolderSettingCard(+ self.installFolder, f"{APP_DATA_DIR}/M3U8DL",self.tr("N_m3u8DL-RE 安装目录"),- self.tr("选择 N_m3u8DL-RE 安装目录"),- self.m3u8Group,+ m3u8Group,)- self.runtimeCard = M3U8RuntimeCard(self.m3u8Group)+ runtimeCard = RuntimeCard(m3u8Runtime, m3u8Group)- cards = [self.installFolderCard, self.runtimeCard]- # macOS 的文件关联在构建时烘进 Info.plist, 运行时开关无意义, 不创建也不显示+ cards = [installFolderCard, runtimeCard]if sys.platform != "darwin":cards.append(SwitchSettingCard(- FluentIcon.LINK,- self.tr("关联 M3U8/MPD 文件"),+ FluentIcon.LINK, self.tr("关联 M3U8/MPD 文件"),self.tr("把 .m3u8/.m3u/.mpd 文件的打开方式设为 Ghost Downloader"),- self.associateFileTypes,- self.m3u8Group,+ self.associateFileTypes, m3u8Group,))cards += [- ComboBoxSettingCard(- self.outputFormat, FluentIcon.VIDEO, self.tr("输出容器"),- self.tr("点播下载完成后优先使用 ffmpeg 混流为指定容器"),- texts=["MP4", "MKV"], parent=self.m3u8Group,- ),- RangeSettingCard(- self.threadCount, FluentIcon.CLOUD, self.tr("分片线程数"),- self.tr("传给 N_m3u8DL-RE 的下载线程数"), self.m3u8Group,- ),- RangeSettingCard(- self.retryCount, FluentIcon.SYNC, self.tr("分片重试次数"),- self.tr("单个分片下载失败时的最大重试次数"), self.m3u8Group,- ),- SpinBoxSettingCard(- FluentIcon.HISTORY, self.tr("请求超时"), self.tr("HTTP 请求超时时间"),- " s", self.requestTimeout, self.m3u8Group, 5,- ),- SwitchSettingCard(- FluentIcon.ACCEPT, self.tr("自动选择最佳轨道"),- self.tr("默认选择最佳音视频轨道,避免每个链接都手动挑选"),- self.autoSelect, self.m3u8Group,- ),- SwitchSettingCard(- FluentIcon.PAUSE, self.tr("并发下载音视频"),- self.tr("同时下载已选择的音频、视频和字幕轨道"),- self.concurrentDownload, self.m3u8Group,- ),- SwitchSettingCard(- FluentIcon.LINK, self.tr("追加 URL 参数"),- self.tr("把输入链接上的 Query 参数追加到分片请求"),- self.appendUrlParams, self.m3u8Group,- ),- SwitchSettingCard(- FluentIcon.ALIGNMENT, self.tr("二进制合并"),- self.tr("让 N_m3u8DL-RE 使用二进制方式合并分片"),- self.binaryMerge, self.m3u8Group,- ),- SwitchSettingCard(- FluentIcon.SEARCH, self.tr("校验分片数量"),- self.tr("下载完成后检查实际分片数是否与预期一致"),- self.checkSegmentsCount, self.m3u8Group,- ),- SwitchSettingCard(- FluentIcon.SAVE, self.tr("直播保留原始分片"),- self.tr("实时合并录制时仍保留下载的原始分片"),- self.liveKeepSegments, self.m3u8Group,- ),- SwitchSettingCard(- FluentIcon.CODE, self.tr("直播管道混流"),- self.tr("录制时通过管道交给 ffmpeg 实时混流为封装容器"),- self.livePipeMux, self.m3u8Group,- ),- SwitchSettingCard(- FluentIcon.FONT, self.tr("直播校正 VTT 字幕"),- self.tr("根据音频起始时间校正 VTT 字幕时间轴"),- self.liveFixVtt, self.m3u8Group,- ),- SpinBoxSettingCard(- FluentIcon.STOP_WATCH, self.tr("直播刷新等待时间"),- self.tr("两次拉取直播清单之间的等待秒数,0 为自动"),- " s", self.liveWaitTime, self.m3u8Group, 1,- ),- SpinBoxSettingCard(- FluentIcon.DOWNLOAD, self.tr("直播每次取片数"),- self.tr("每次刷新最多取走的分片数量,0 为自动"),- "", self.liveTakeCount, self.m3u8Group, 1,- ),- ComboBoxSettingCard(- self.decryptionEngine, FluentIcon.CERTIFICATE, self.tr("解密引擎"),- self.tr("调用的第三方解密程序"),- texts=["FFmpeg", "MP4Decrypt", "Shaka Packager"], parent=self.m3u8Group,- ),- SelectFileCard(- self.decryptionBinaryPath, FluentIcon.COMMAND_PROMPT, self.tr("解密引擎二进制路径"),+ ComboBoxSettingCard(self.outputFormat, FluentIcon.VIDEO, self.tr("输出容器"),+ self.tr("点播下载完成后优先使用 ffmpeg 混流为指定容器"), texts=["MP4", "MKV"], parent=m3u8Group),+ RangeSettingCard(self.threadCount, FluentIcon.CLOUD, self.tr("分片线程数"),+ self.tr("传给 N_m3u8DL-RE 的下载线程数"), m3u8Group),+ RangeSettingCard(self.retryCount, FluentIcon.SYNC, self.tr("分片重试次数"),+ self.tr("单个分片下载失败时的最大重试次数"), m3u8Group),+ SpinBoxSettingCard(FluentIcon.HISTORY, self.tr("请求超时"), self.tr("HTTP 请求超时时间"),+ " s", self.requestTimeout, m3u8Group, 5),+ SwitchSettingCard(FluentIcon.ACCEPT, self.tr("自动选择最佳轨道"),+ self.tr("默认选择最佳音视频轨道"), self.shouldAutoSelect, m3u8Group),+ SwitchSettingCard(FluentIcon.PAUSE, self.tr("并发下载音视频"),+ self.tr("同时下载已选择的音频、视频和字幕轨道"), self.shouldConcurrentDownload, m3u8Group),+ SwitchSettingCard(FluentIcon.LINK, self.tr("追加 URL 参数"),+ self.tr("把输入链接上的 Query 参数追加到分片请求"), self.shouldAppendUrlParams, m3u8Group),+ SwitchSettingCard(FluentIcon.ALIGNMENT, self.tr("二进制合并"),+ self.tr("让 N_m3u8DL-RE 使用二进制方式合并分片"), self.shouldBinaryMerge, m3u8Group),+ SwitchSettingCard(FluentIcon.SEARCH, self.tr("校验分片数量"),+ self.tr("下载完成后检查实际分片数是否与预期一致"), self.shouldCheckSegmentsCount, m3u8Group),+ SwitchSettingCard(FluentIcon.SAVE, self.tr("直播保留原始分片"),+ self.tr("实时合并录制时仍保留下载的原始分片"), self.shouldKeepLiveSegments, m3u8Group),+ SwitchSettingCard(FluentIcon.CODE, self.tr("直播管道混流"),+ self.tr("录制时通过管道交给 ffmpeg 实时混流为封装容器"), self.shouldUseLivePipeMux, m3u8Group),+ SwitchSettingCard(FluentIcon.FONT, self.tr("直播校正 VTT 字幕"),+ self.tr("根据音频起始时间校正 VTT 字幕时间轴"), self.shouldFixLiveVtt, m3u8Group),+ SpinBoxSettingCard(FluentIcon.STOP_WATCH, self.tr("直播刷新等待时间"),+ self.tr("两次拉取直播清单之间的等待秒数,0 为自动"), " s", self.liveWaitTime, m3u8Group, 1),+ SpinBoxSettingCard(FluentIcon.DOWNLOAD, self.tr("直播每次取片数"),+ self.tr("每次刷新最多取走的分片数量,0 为自动"), "", self.liveTakeCount, m3u8Group, 1),+ ComboBoxSettingCard(self.decryptionEngine, FluentIcon.CERTIFICATE, self.tr("解密引擎"),+ self.tr("调用的第三方解密程序"), texts=["FFmpeg", "MP4Decrypt", "Shaka Packager"], parent=m3u8Group),+ SelectFileCard(FluentIcon.COMMAND_PROMPT, self.tr("解密引擎二进制路径"),self.tr("MP4Decrypt / Shaka Packager 可执行文件路径,留空则使用 FFmpeg"),- self.tr("选择解密引擎可执行文件"), self.m3u8Group,- ),- SwitchSettingCard(- FluentIcon.FINGERPRINT, self.tr("MP4 实时解密"),- self.tr("下载 MP4 分片时实时解密"),- self.mp4RealTimeDecryption, self.m3u8Group,- ),- SpinBoxSettingCard(- FluentIcon.SPEED_HIGH, self.tr("限速"),- self.tr("最大下载速度,-1 为不限速"),- "", self.maxSpeed, self.m3u8Group, 1,- ),- ComboBoxSettingCard(- self.speedUnit, FluentIcon.TAG, self.tr("限速单位"),- self.tr("限速数值的单位"), texts=["Mbps", "Kbps"], parent=self.m3u8Group,- ),- LineEditSettingCard(- FluentIcon.REMOVE, self.tr("广告过滤"),- self.tr("匹配广告分片 URL 的正则表达式"),- self.adKeyword, self.m3u8Group, placeholder=self.tr("正则表达式"),- ),- ComboBoxSettingCard(- self.subtitleFormat, FluentIcon.DICTIONARY, self.tr("字幕格式"),- self.tr("字幕输出格式"), texts=["SRT", "VTT"], parent=self.m3u8Group,- ),- SwitchSettingCard(- FluentIcon.DATE_TIME, self.tr("不写入日期信息"),- self.tr("混流时不写入日期信息"), self.noDateInfo, self.m3u8Group,- ),- SwitchSettingCard(- FluentIcon.PHOTO, self.tr("保留图形分片"),- self.tr("把图形字幕转图片后保留原始分片"),- self.keepImageSegments, self.m3u8Group,- ),- SwitchSettingCard(- FluentIcon.DELETE, self.tr("完成后删除临时文件"),- self.tr("下载完成后删除分片临时目录"), self.delAfterDone, self.m3u8Group,- ),- SwitchSettingCard(- FluentIcon.MUSIC, self.tr("下载全部音轨与字幕"),- self.tr("默认拉取全部音频与字幕轨道,而非仅最佳"),- self.selectAllAudioSubtitle, self.m3u8Group,- ),- LineEditSettingCard(- FluentIcon.VIDEO, self.tr("自定义混流参数"),+ configItem=self.decryptionBinaryPath, parent=m3u8Group),+ SwitchSettingCard(FluentIcon.FINGERPRINT, self.tr("MP4 实时解密"),+ self.tr("下载 MP4 分片时实时解密"), self.shouldUseMp4RealTimeDecryption, m3u8Group),+ SpinBoxSettingCard(FluentIcon.SPEED_HIGH, self.tr("限速"),+ self.tr("最大下载速度,-1 为不限速"), "", self.maxSpeed, m3u8Group, 1),+ ComboBoxSettingCard(self.speedUnit, FluentIcon.TAG, self.tr("限速单位"),+ self.tr("限速数值的单位"), texts=["Mbps", "Kbps"], parent=m3u8Group),+ LineEditSettingCard(FluentIcon.REMOVE, self.tr("广告过滤"),+ self.tr("匹配广告分片 URL 的正则表达式"), self.adKeyword, m3u8Group, placeholder=self.tr("正则表达式")),+ ComboBoxSettingCard(self.subtitleFormat, FluentIcon.DICTIONARY, self.tr("字幕格式"),+ self.tr("字幕输出格式"), texts=["SRT", "VTT"], parent=m3u8Group),+ SwitchSettingCard(FluentIcon.DATE_TIME, self.tr("不写入日期信息"),+ self.tr("混流时不写入日期信息"), self.shouldOmitDateInfo, m3u8Group),+ SwitchSettingCard(FluentIcon.PHOTO, self.tr("保留图形分片"),+ self.tr("把图形字幕转图片后保留原始分片"), self.shouldKeepImageSegments, m3u8Group),+ SwitchSettingCard(FluentIcon.DELETE, self.tr("完成后删除临时文件"),+ self.tr("下载完成后删除分片临时目录"), self.shouldDeleteTemp, m3u8Group),+ SwitchSettingCard(FluentIcon.MUSIC, self.tr("下载全部音轨与字幕"),+ self.tr("默认拉取全部音频与字幕轨道"), self.shouldSelectAllAudioSubtitle, m3u8Group),+ LineEditSettingCard(FluentIcon.VIDEO, self.tr("自定义混流参数"),self.tr("自定义 --mux-after-done,留空则按输出容器自动混流"),- self.customMuxAfterDone, self.m3u8Group, placeholder="format=mp4",- ),+ self.customMuxAfterDone, m3u8Group, placeholder="format=mp4"),]- self.m3u8Group.addSettingCards(cards)-- self.installFolderCard.pathChanged.connect(lambda _: self.runtimeCard.refreshStatus())- settingPage.addSettingGroup(self.m3u8Group)- self.runtimeCard.refreshStatus()+ m3u8Group.addSettingCards(cards)+ installFolderCard.pathChanged.connect(runtimeCard._onInstallFolderChanged)+ runtimeCard.refreshStatus()+ return [m3u8Group]m3u8Config = M3U8Config()+++class M3U8Runtime(BinaryRuntime):+ name = "N_m3u8DL-RE"+ canInstall = not IS_ANDROID++ def path(self) -> str:+ if IS_ANDROID:+ nativeDir = nativeLibraryDir()+ if not nativeDir:+ return ""+ binary = Path(nativeDir) / "libnm3u8dlre.so"+ return str(binary) if binary.exists() else ""+ return findExecutable(Path(m3u8Config.installFolder.value), "N_m3u8DL-RE")++ async def installTask(self) -> Task:+ machine = platform.machine().lower()+ if sys.platform == "win32":+ if machine in {"amd64", "x86_64"}:+ target = "win-x64"+ elif machine in {"arm64", "aarch64"}:+ target = "win-arm64"+ else:+ target = "win-NT6.0-x86"+ elif sys.platform == "darwin":+ target = "osx-arm64" if machine in {"arm64", "aarch64"} else "osx-x64"+ elif sys.platform == "linux":+ libcName = platform.libc_ver()[0].lower()+ if machine in {"arm64", "aarch64"}:+ target = "linux-musl-arm64" if libcName == "musl" else "linux-arm64"+ else:+ target = "linux-musl-x64" if libcName == "musl" else "linux-x64"+ else:+ raise RuntimeError(f"当前平台暂不支持一键安装 N_m3u8DL-RE: {sys.platform}")++ client = buildClient(headers={"accept": "application/vnd.github+json"})+ try:+ response = await client.get(RELEASE_API)+ response.raise_for_status()+ release = await response.json()+ finally:+ client.close()++ assets = release.get("assets")+ if not isinstance(assets, list):+ raise RuntimeError("GitHub Release 返回了无效的 assets 数据")++ asset = next((item for item in assets if target in item["name"]), None)+ if asset is None:+ raise RuntimeError(f"未找到适用于当前平台的 N_m3u8DL-RE 安装包: {target}")++ url = asset["browser_download_url"].strip()+ fileName = asset["name"].strip()+ fileSize = asset["size"]+ if not url or not fileName or fileSize <= 0:+ raise RuntimeError("GitHub Release 返回了不完整的安装包信息")++ from app.services.feature_service import featureService+ from app.models.task import BinaryInstallOptions++ binaryName = "N_m3u8DL-RE.exe" if sys.platform == "win32" else "N_m3u8DL-RE"+ return await featureService.parse(BinaryInstallOptions(+ url=url,+ outputFolder=Path(m3u8Config.installFolder.value),+ name=f"N_m3u8DL-RE 安装 ({target})",+ executableNames=(binaryName,),+ ))+++m3u8Runtime = M3U8Runtime()diff --git a/features/m3u8_pack/pack.py b/features/m3u8_pack/pack.pyindex 649b42ea..0b4db528 100644--- a/features/m3u8_pack/pack.py+++ b/features/m3u8_pack/pack.py@@ -1,412 +1,297 @@+from __future__ import annotations+import asyncio-import platform-import sysfrom email.message import Messagefrom email.utils import collapse_rfc2231_valuefrom pathlib import Path-from typing import TYPE_CHECKING, Literalfrom urllib.parse import parse_qs, unquote, urlparse-from urllib.request import url2pathnameimport m3u8-import niquestsfrom loguru import loggerfrom mpegdash.parser import MPEGDASHParser-from app.bases.interfaces import FeaturePack, FileType-from app.bases.models import Task-from app.supports import file_association-from app.supports.config import activeUserAgent, cfg, defaultHeaders-from app.supports.utils import getProxies, splitCookies, toExecutable, toSafeFilename-from app.view.components.cards import UniversalTaskCard-from .cards import M3U8LiveTaskCard, M3U8ResultCard, M3U8TaskCard+from app.client import buildClient, toEmulation+from app.config.cfg import cfg+from app.models.pack import FeaturePack, TaskParser, FileType+from app.models.task import Task, TaskOptions+from app.platform.filesystem import localFilePath, toSafeFilenamefrom .config import m3u8Config-from .task import M3U8Task, M3U8TaskStage--if TYPE_CHECKING:- from features.disk_pack.pack import buildToolInstallTask-else:- from disk_pack.pack import buildToolInstallTask+from .task import M3U8Task, M3U8TaskStep-_M3U8DL_RELEASE_TAG = "v0.5.1-beta"-_M3U8DL_RELEASE_API = f"https://api.github.com/repos/nilaoda/N_m3u8DL-RE/releases/tags/{_M3U8DL_RELEASE_TAG}"-_M3U8DL_RELEASE_HEADERS = {- "accept": "application/vnd.github+json",- "user-agent": activeUserAgent(),-}-_KNOWN_SUFFIXES = {+MEDIA_SUFFIXES = {".m3u8", ".m3u", ".mpd", ".mp4", ".mkv",".ts", ".webm", ".m4a", ".m4v", ".vtt", ".srt",}-_MANIFEST_SUFFIXES = {".m3u8", ".m3u", ".mpd"}---def _stem(name: str) -> str:- suffix = Path(name).suffix- if suffix.lower() in _KNOWN_SUFFIXES:- return name[:-len(suffix)]- return name---def _manifestType(url: str, headers: dict[str, str], body: str) -> Literal["m3u8", "mpd"]:- loweredUrl = url.lower()- contentType = headers.get("content-type", "").lower()- sample = body.lstrip()[:256].lower()- if ".mpd" in loweredUrl or "dash+xml" in contentType or sample.startswith("<mpd"):- return "mpd"- return "m3u8"---def _title(url: str, headers: dict[str, str], extension: str) -> str:- candidates: list[str] = []-- cd = headers.get("content-disposition", "")- if cd:- msg = Message()- msg["Content-Disposition"] = cd- params = msg.get_params(header="Content-Disposition")- paramDict = {key.lower(): value for key, value in params}- fileName = collapse_rfc2231_value(- paramDict.get("filename") or paramDict.get("filename*") or ""- ).strip("\"' ")- if fileName:- candidates.append(fileName)-- parsedUrl = urlparse(url)- query = parse_qs(parsedUrl.query)- for key in ("filename", "file", "name", "title"):- values = query.get(key)- if values:- candidates.append(values[0])-- if parsedUrl.path:- candidates.append(unquote(Path(parsedUrl.path).name))-- for candidate in candidates:- name = _stem(toSafeFilename(candidate, fallback="stream"))- if name:- return f"{name}.{extension}"-- return f"stream.{extension}"---def loadLocalManifest(source: str) -> Path | None:- text = str(source).strip()- if not text:- return None-- parsed = urlparse(text)- if parsed.scheme.lower() == "file":- location = f"//{parsed.netloc}{parsed.path}" if parsed.netloc else parsed.path- path = Path(url2pathname(unquote(location))).expanduser()- return path if path.suffix.lower() in _MANIFEST_SUFFIXES else None-- if "://" in text:- return None-- path = Path(text).expanduser()- return path if path.suffix.lower() in _MANIFEST_SUFFIXES else None---def _toFrameRate(value) -> float | None:- if not value:- return None- text = str(value)- if "/" in text:- num, den = text.split("/")- return int(num) / int(den) if int(den) else None- return float(text)---def _isVideoRepresentation(adaptationSet, representation) -> bool:- if (adaptationSet.content_type or "").lower() == "video":- return True- mimeType = (adaptationSet.mime_type or representation.mime_type or "").lower()- if mimeType.startswith("video"):- return True- return bool(representation.id and "video" in representation.id)---def _streamEntry(width: int, height: int, codecs: str | None, frameRate: float | None) -> dict:- label = [f"{width}×{height}"]- if codecs:- label.append(codecs)- if frameRate:- label.append(f"{frameRate:.0f}fps")- selectExpr = [f'res="{width}*"']- if frameRate:- selectExpr.append(f'frame="{int(frameRate)}*"')- return {"label": " · ".join(label), "selectExpr": ":".join(selectExpr)}---def _hlsStreams(body: str) -> list[dict]:- playlist = m3u8.loads(body)- streams = []- for variant in playlist.playlists:- resolution = variant.stream_info.resolution- if not resolution:- continue- width, height = resolution- streams.append(_streamEntry(width, height, variant.stream_info.codecs, variant.stream_info.frame_rate))- return streams---def _mpdStreams(body: str) -> list[dict]:- mpd = MPEGDASHParser.parse(body)- if not mpd.periods:- return []- streams = []- for adaptationSet in mpd.periods[0].adaptation_sets:- for representation in adaptationSet.representations:- if not representation.width or not _isVideoRepresentation(adaptationSet, representation):- continue- streams.append(_streamEntry(- representation.width,- representation.height,- representation.codecs,- _toFrameRate(representation.frame_rate),- ))- return streams---def resolveStreams(manifestType: str, body: str) -> list[dict]:- # 枚举失败不该阻断下载——auto-select 仍能工作, 仅轨道下拉缺项- try:- return _mpdStreams(body) if manifestType == "mpd" else _hlsStreams(body)- except Exception as e:- logger.warning("枚举可选视频流失败: {}", repr(e))- return []---async def _resolveLive(manifestType: str, body: str, baseUrl: str, headers: dict, proxies) -> bool:- if manifestType == "mpd":- lowered = body.lower()- return 'type="dynamic"' in lowered or "type='dynamic'" in lowered-- playlist = m3u8.loads(body, uri=baseUrl)- if playlist.segments:- return not playlist.is_endlist- if not playlist.playlists:- return "#ext-x-endlist" not in body.lower()-- # master playlist 本身无 ENDLIST, 真伪直播只能看其变体 media playlist- variantUrl = playlist.playlists[0].absolute_uri or ""- if not variantUrl.lower().startswith(("http://", "https://")):- return False- try:- requestHeaders, requestCookies = splitCookies(headers)- async with niquests.AsyncSession(timeout=30, happy_eyeballs=True) as client:- client.trust_env = False- response = await client.get(- variantUrl,- headers=requestHeaders,- cookies=requestCookies,- proxies=proxies,- verify=cfg.SSLVerify.value,- allow_redirects=True,- )- response.raise_for_status()- variantBody = response.text- return not m3u8.loads(variantBody, uri=variantUrl).is_endlist- except Exception as e:- logger.warning("取变体清单判活失败, 按点播处理: {}", repr(e))- return False+MANIFEST_SUFFIXES = {".m3u8", ".m3u", ".mpd"}-class M3U8Pack(FeaturePack):- packId = "m3u8"+class M3U8Parser(TaskParser):priority = 80- config = m3u8Config- def matches(self, url: str) -> bool:- if loadLocalManifest(url) is not None:+ def match(self, options: TaskOptions) -> bool:+ if localFilePath(options.url, MANIFEST_SUFFIXES) is not None:return True- parsedUrl = urlparse(url)- if parsedUrl.scheme.lower() not in {"http", "https"}:- return False- loweredUrl = url.lower()- return ".m3u" in loweredUrl or ".mpd" in loweredUrl-- def fileTypes(self):- return [- FileType(- extensions=(".m3u8", ".m3u"),- displayName=self.tr("M3U8 播放列表"),- mimeType="application/vnd.apple.mpegurl",- icon="m3u8",- ),- FileType(- extensions=(".mpd",),- displayName=self.tr("DASH 清单"),- mimeType="application/dash+xml",- icon="m3u8",- ),- ]-- def taskCard(self, task, parent=None):- from disk_pack.task import InstallTask- if isinstance(task, InstallTask):- return UniversalTaskCard(task, parent)- if getattr(task, "isLive", False):- return M3U8LiveTaskCard(task, parent)- return M3U8TaskCard(task, parent)-- def resultCard(self, task, parent=None):- return M3U8ResultCard(task, parent)-- def setup(self, mainWindow):- if m3u8Config.associateFileTypes.value:- file_association.register(self.fileTypes())- m3u8Config.associateFileTypes.valueChanged.connect(self._onAssociationToggled)-- def _onAssociationToggled(self, enabled: bool):- if enabled:- file_association.register(self.fileTypes())- else:- file_association.unregister(self.fileTypes())-- async def parse(self, payload: dict) -> Task:- url = payload["url"].strip()- rawHeaders = payload.get("headers")- headers = rawHeaders.copy() if isinstance(rawHeaders, dict) and rawHeaders else defaultHeaders()- proxies = payload.get("proxies", getProxies())- path = Path(payload.get("path", cfg.downloadFolder.value))-- localManifest = loadLocalManifest(url)- if localManifest is not None:- # N_m3u8DL-RE 的位置参数直接吃本地路径(_buildArgs 透传 task.url), 所以还原成 plain 路径而不留 file://- url = str(localManifest.resolve())- body = await asyncio.to_thread(localManifest.read_text, encoding="utf-8", errors="ignore")- # 工具按输入路径解析相对段 → 落到本地不存在的文件; 只有带绝对 URL 段的清单可下,- # 这里提前拦截纯相对清单, 避免下到一半才报错+ lowered = options.url.lower()+ return ".m3u" in lowered or ".mpd" in lowered++ async def parse(self, options: TaskOptions) -> Task:+ url = options.url.strip()+ headers = dict(options.headers)+ outputFolder = options.outputFolder++ localPath = localFilePath(url, MANIFEST_SUFFIXES)+ if localPath is not None:+ url = str(localPath.resolve())+ body = await asyncio.to_thread(localPath.read_text, encoding="utf-8", errors="ignore")if "http://" not in body and "https://" not in body:raise ValueError("该本地清单只含相对段路径, 缺少 base URL 无法下载, 请改用原始在线链接")manifestUrl = url- loweredHeaders = {}+ responseHeaders: dict[str, str] = {}else:- requestHeaders, requestCookies = splitCookies(headers)- async with niquests.AsyncSession(timeout=30, happy_eyeballs=True) as client:- client.trust_env = False- response = await client.get(- url,- headers=requestHeaders,- cookies=requestCookies,- proxies=proxies,- verify=cfg.SSLVerify.value,- allow_redirects=True,- )+ emulation = toEmulation(+ options.clientProfile or cfg.clientProfile.value,+ options.sourceUserAgent,+ )+ client = buildClient(emulation=emulation, headers=headers)+ try:+ response = await client.get(url)response.raise_for_status()- body = response.text- loweredHeaders = {key.lower(): value for key, value in response.headers.items()}- manifestUrl = response.url+ body = await response.text()+ responseHeaders = {k.decode().lower(): v.decode() for k, v in response.headers}+ manifestUrl = str(response.url)+ finally:+ client.close()++ loweredUrl = manifestUrl.lower()+ contentType = responseHeaders.get("content-type", "").lower()+ sample = body.lstrip()[:256].lower()+ if ".mpd" in loweredUrl or "dash+xml" in contentType or sample.startswith("<mpd"):+ manifestType = "mpd"+ else:+ manifestType = "m3u8"++ if manifestType == "mpd":+ lowered = body.lower()+ isLive = 'type="dynamic"' in lowered or "type='dynamic'" in lowered+ else:+ playlist = m3u8.loads(body, uri=manifestUrl)+ if playlist.segments:+ isLive = not playlist.is_endlist+ elif playlist.playlists:+ variantUrl = playlist.playlists[0].absolute_uri or ""+ if variantUrl.lower().startswith(("http://", "https://")):+ try:+ variantClient = buildClient(emulation=toEmulation(+ options.clientProfile or cfg.clientProfile.value,+ options.sourceUserAgent,+ ), headers=headers)+ try:+ variantResponse = await variantClient.get(variantUrl)+ variantResponse.raise_for_status()+ variantBody = await variantResponse.text()+ finally:+ variantClient.close()+ isLive = not m3u8.loads(variantBody, uri=variantUrl).is_endlist+ except Exception as e:+ logger.warning("取变体清单判活失败, 按点播处理: {}", repr(e))+ isLive = False+ else:+ isLive = False+ else:+ isLive = "#ext-x-endlist" not in body.lower()- manifestType = _manifestType(manifestUrl, loweredHeaders, body)- isLive = await _resolveLive(manifestType, body, manifestUrl, headers, proxies)- # 直播恒走 real-time-merge 直出 .ts;点播按输出容器extension = "ts" if isLive else m3u8Config.outputFormat.value- title = _title(manifestUrl, loweredHeaders, extension)- streams = resolveStreams(manifestType, body)+ streams = self._parseStreams(body, manifestType)++ cd = responseHeaders.get("content-disposition", "")+ name = ""+ if cd:+ msg = Message()+ msg["Content-Disposition"] = cd+ params = msg.get_params(header="Content-Disposition")+ paramDict = {k.lower(): v for k, v in params}+ name = collapse_rfc2231_value(+ paramDict.get("filename") or paramDict.get("filename*") or ""+ ).strip("\"' ")++ if not name:+ parsedManifest = urlparse(manifestUrl)+ for key in ("filename", "file", "name", "title"):+ values = parse_qs(parsedManifest.query).get(key)+ if values:+ name = values[0]+ break++ if not name and urlparse(manifestUrl).path:+ name = unquote(Path(urlparse(manifestUrl).path).name)++ if name:+ suffix = Path(name).suffix+ stem = name[:-len(suffix)] if suffix.lower() in MEDIA_SUFFIXES else name+ name = toSafeFilename(stem, fallback="stream")+ name = f"{name}.{extension}"+ else:+ name = f"stream.{extension}"task = M3U8Task(- title=title,+ name=name,url=url,fileSize=1,- path=path,+ outputFolder=outputFolder,manifestType=manifestType,isLive=isLive,streams=streams,)- stage = M3U8TaskStage(- stageIndex=1,+ step = M3U8TaskStep(+ stepIndex=1,headers=headers,- proxies=proxies if isinstance(proxies, dict) else {},+threadCount=m3u8Config.threadCount.value,retryCount=m3u8Config.retryCount.value,requestTimeout=m3u8Config.requestTimeout.value,- autoSelect=m3u8Config.autoSelect.value,- concurrentDownload=m3u8Config.concurrentDownload.value,- appendUrlParams=m3u8Config.appendUrlParams.value,- binaryMerge=m3u8Config.binaryMerge.value,- checkSegmentsCount=m3u8Config.checkSegmentsCount.value,- delAfterDone=m3u8Config.delAfterDone.value,+ shouldAutoSelect=m3u8Config.shouldAutoSelect.value,+ shouldConcurrentDownload=m3u8Config.shouldConcurrentDownload.value,+ shouldAppendUrlParams=m3u8Config.shouldAppendUrlParams.value,+ shouldBinaryMerge=m3u8Config.shouldBinaryMerge.value,+ shouldCheckSegmentsCount=m3u8Config.shouldCheckSegmentsCount.value,+ shouldDeleteTemp=m3u8Config.shouldDeleteTemp.value,outputFormat=m3u8Config.outputFormat.value,customMuxAfterDone=m3u8Config.customMuxAfterDone.value,subtitleFormat=m3u8Config.subtitleFormat.value,- selectAllAudioSubtitle=m3u8Config.selectAllAudioSubtitle.value,+ shouldSelectAllAudioSubtitle=m3u8Config.shouldSelectAllAudioSubtitle.value,maxSpeed=m3u8Config.maxSpeed.value,speedUnit=m3u8Config.speedUnit.value,adKeyword=m3u8Config.adKeyword.value,- noDateInfo=m3u8Config.noDateInfo.value,- keepImageSegments=m3u8Config.keepImageSegments.value,+ shouldOmitDateInfo=m3u8Config.shouldOmitDateInfo.value,+ shouldKeepImageSegments=m3u8Config.shouldKeepImageSegments.value,decryptionEngine=m3u8Config.decryptionEngine.value,decryptionBinaryPath=m3u8Config.decryptionBinaryPath.value,- mp4RealTimeDecryption=m3u8Config.mp4RealTimeDecryption.value,- liveKeepSegments=m3u8Config.liveKeepSegments.value,- livePipeMux=m3u8Config.livePipeMux.value,- liveFixVtt=m3u8Config.liveFixVtt.value,+ shouldUseMp4RealTimeDecryption=m3u8Config.shouldUseMp4RealTimeDecryption.value,+ shouldKeepLiveSegments=m3u8Config.shouldKeepLiveSegments.value,+ shouldUseLivePipeMux=m3u8Config.shouldUseLivePipeMux.value,+ shouldFixLiveVtt=m3u8Config.shouldFixLiveVtt.value,liveWaitTime=m3u8Config.liveWaitTime.value,liveTakeCount=m3u8Config.liveTakeCount.value,)- task.addStage(stage)+ task.addStep(step)return task+ def _parseStreams(self, body: str, manifestType: str) -> list[dict]:+ try:+ if manifestType == "mpd":+ return self._mpdStreams(body)+ return self._hlsStreams(body)+ except Exception as e:+ logger.warning("枚举可选视频流失败: {}", repr(e))+ return []++ def _hlsStreams(self, body: str) -> list[dict]:+ playlist = m3u8.loads(body)+ streams = []+ for variant in playlist.playlists:+ resolution = variant.stream_info.resolution+ if not resolution:+ continue+ width, height = resolution+ streams.append({+ "width": width,+ "height": height,+ "codecs": variant.stream_info.codecs,+ "frameRate": variant.stream_info.frame_rate,+ })+ return streams++ def _mpdStreams(self, body: str) -> list[dict]:+ mpd = MPEGDASHParser.parse(body)+ if not mpd.periods:+ return []+ streams = []+ for adaptationSet in mpd.periods[0].adaptation_sets:+ for representation in adaptationSet.representations:+ if not representation.width:+ continue+ contentType = (adaptationSet.content_type or "").lower()+ mimeType = (adaptationSet.mime_type or representation.mime_type or "").lower()+ isVideo = (+ contentType == "video"+ or mimeType.startswith("video")+ or (representation.id and "video" in representation.id)+ )+ if not isVideo:+ continue++ frameRate = None+ if representation.frame_rate:+ text = str(representation.frame_rate)+ if "/" in text:+ num, den = text.split("/")+ frameRate = int(num) / int(den) if int(den) else None+ else:+ frameRate = float(text)++ streams.append({+ "width": representation.width,+ "height": representation.height,+ "codecs": representation.codecs,+ "frameRate": frameRate,+ })+ return streams-async def createInstallTask() -> Task:- machine = platform.machine().lower()- if sys.platform == "win32":- if machine in {"amd64", "x86_64"}:- target, archLabel = "win-x64", "Windows x64"- elif machine in {"arm64", "aarch64"}:- target, archLabel = "win-arm64", "Windows ARM64"- else:- target, archLabel = "win-NT6.0-x86", "Windows x86"- elif sys.platform == "darwin":- if machine in {"arm64", "aarch64"}:- target, archLabel = "osx-arm64", "macOS Apple Silicon"- else:- target, archLabel = "osx-x64", "macOS Intel"- elif sys.platform == "linux":- libcName = platform.libc_ver()[0].lower()- if machine in {"arm64", "aarch64"}:- target, archLabel = ("linux-musl-arm64", "Linux musl ARM64") if libcName == "musl" else ("linux-arm64", "Linux ARM64")- else:- target, archLabel = ("linux-musl-x64", "Linux musl x64") if libcName == "musl" else ("linux-x64", "Linux x64")- else:- raise RuntimeError(f"当前平台暂不支持一键安装 N_m3u8DL-RE: {sys.platform}")-- async with niquests.AsyncSession(headers=_M3U8DL_RELEASE_HEADERS, timeout=30, happy_eyeballs=True) as client:- client.trust_env = False- response = await client.get(- _M3U8DL_RELEASE_API,- proxies=getProxies(),- verify=cfg.SSLVerify.value,- allow_redirects=True,- )- response.raise_for_status()- payload = response.json()-- assets = payload.get("assets")- if not isinstance(assets, list):- raise RuntimeError("GitHub Release 返回了无效的 assets 数据")-- asset = next((item for item in assets if target in item["name"]), None)- if asset is None:- raise RuntimeError(f"未找到适用于当前平台的 N_m3u8DL-RE 安装包: {target}")-- downloadUrl = asset["browser_download_url"].strip()- assetName = asset["name"].strip()- size = asset["size"]- if not downloadUrl or not assetName or size <= 0:- raise RuntimeError("GitHub Release 返回了不完整的安装包信息")-- return await buildToolInstallTask(- packId="m3u8",- title=f"N_m3u8DL-RE 安装 ({archLabel})",- downloadUrl=downloadUrl,- fallbackAssetName=assetName,- fallbackSize=size,- installFolder=Path(m3u8Config.installFolder.value),- executableNames=[toExecutable("N_m3u8DL-RE")],- )++class M3U8Pack(FeaturePack):+ packId = "m3u8"++ def __init__(self):+ self.config = m3u8Config++ def parsers(self):+ return [M3U8Parser()]++ def taskCard(self, task, parent=None):+ from .cards import M3U8TaskCard, M3U8LiveTaskCard+ if getattr(task, "isLive", False):+ return M3U8LiveTaskCard(task, parent)+ return M3U8TaskCard(task, parent)++ def draftCard(self, task, parent=None):+ from .cards import M3U8DraftCard+ return M3U8DraftCard(task, parent)++ def optionCards(self, task, parent=None):+ from app.view.components.option_cards import HeadersEditCard, OutputFolderCard+ from .cards import StreamSelectCard, RecordLimitCard, DecryptionKeyCard, MuxImportCard+ from .task import M3U8TaskStep++ step = task.steps[0] if task.steps else None+ if not isinstance(step, M3U8TaskStep):+ return []++ cards = [+ OutputFolderCard(parent, initial=task.outputFolder),+ HeadersEditCard(parent, initial=step.headers),+ ]+ if len(task.streams) > 1:+ cards.append(StreamSelectCard(parent, streams=task.streams, initial=step.selectVideo))+ if task.isLive:+ cards.append(RecordLimitCard(parent, initial=step.recordLimit))+ cards.append(DecryptionKeyCard(parent, keys=step.decryptionKeys, keyTextFile=step.decryptionKeyFile))+ cards.append(MuxImportCard(parent, initial=step.muxImports))+ return cards++ def fileTypes(self):+ return [+ FileType(+ extensions=(".m3u8", ".m3u"),+ displayName=self.tr("M3U8 播放列表"),+ mimeType="application/vnd.apple.mpegurl",+ icon="m3u8",+ ),+ FileType(+ extensions=(".mpd",),+ displayName=self.tr("DASH 清单"),+ mimeType="application/dash+xml",+ icon="m3u8",+ ),+ ]diff --git a/features/m3u8_pack/task.py b/features/m3u8_pack/task.pyindex b705faff..dbec0263 100644--- a/features/m3u8_pack/task.py+++ b/features/m3u8_pack/task.py@@ -1,307 +1,231 @@+from __future__ import annotations+import asyncioimport osimport refrom contextlib import suppressfrom dataclasses import dataclass, fieldfrom pathlib import Path-from typing import ClassVar, TYPE_CHECKING--from typing import Literal--from app.bases.interfaces import Worker-from app.bases.models import Task, TaskStage, TaskStatus-from app.supports.utils import removePath, toBytes, toPosixPath-from .config import downloaderPath--if TYPE_CHECKING:- from app.view.components.cards import ParseSettingCard- from features.ffmpeg_pack.config import ffmpegPaths-else:- from ffmpeg_pack.config import ffmpegPaths+from app.config.cfg import cfg+from app.format import toBytes+from app.models.task import Task, TaskStep, TaskStatus+from app.platform.filesystem import deletePath, toPosixPath+from .config import m3u8Runtime-_VOD_PROGRESS_PATTERN = re.compile(+VOD_PROGRESS_PATTERN = re.compile(r"(\d+)/(\d+)\s+(\d+\.\d+)%\s+(\d+\.\d+)(KB|MB|GB|B)/(\d+\.\d+)(KB|MB|GB|B)\s+(\d+\.\d+)(GBps|MBps|KBps|Bps)\s+(.+)")-_LIVE_PROGRESS_PATTERN = re.compile(+LIVE_PROGRESS_PATTERN = re.compile(r"(\d{2}m\d{2}s)/(\d{2}m\d{2}s)\s+\d+/\d+\s+(Recording|Waiting)\s+(\d+)%\s+(-|(\d+\.\d+)(GBps|MBps|KBps|Bps))")-_IGNORED_OUTPUT_SUFFIXES = {".json", ".txt", ".log", ".tmp", ".ghd"}-_DECRYPTION_ENGINES = {+IGNORED_OUTPUT_SUFFIXES = {".json", ".txt", ".log", ".tmp", ".ghd"}+DECRYPTION_ENGINES = {"FFmpeg": "FFMPEG","MP4Decrypt": "MP4DECRYPT","Shaka Packager": "SHAKA_PACKAGER",}-def _toBool(value: bool) -> str:- return "true" if value else "false"-+@dataclass(kw_only=True, eq=False)+class M3U8Task(Task):+ packId: str = "m3u8"+ canEdit = True+ manifestType: str = "m3u8"+ isLive: bool = False+ streams: list[dict] = field(default_factory=list)-@dataclass(kw_only=True)-class M3U8TaskStage(TaskStage):- workerType: type = field(init=False, repr=False)+ def _move(self, newFolder: Path) -> None:+ from shutil import move+ oldTemp = self.outputFolder / ".gd3_m3u8" / self.taskId+ if oldTemp.exists():+ newTemp = newFolder / ".gd3_m3u8" / self.taskId+ newTemp.parent.mkdir(parents=True, exist_ok=True)+ move(str(oldTemp), str(newTemp))+ super()._move(newFolder)- actualExtension: str = ""- lastMessage: str = ""- liveStatus: str = ""- liveElapsed: str = ""- liveTotal: str = ""+@dataclass(kw_only=True)+class M3U8TaskStep(TaskStep):headers: dict[str, str] = field(default_factory=dict)- proxies: dict[str, str] = field(default_factory=dict)-- threadCount: int = 16+ threadCount: int = 8retryCount: int = 3- requestTimeout: int = 10- autoSelect: bool = True- concurrentDownload: bool = True- appendUrlParams: bool = False- binaryMerge: bool = False- checkSegmentsCount: bool = True- delAfterDone: bool = True-+ requestTimeout: int = 100+ shouldAutoSelect: bool = True+ shouldConcurrentDownload: bool = True+ shouldAppendUrlParams: bool = False+ shouldBinaryMerge: bool = False+ shouldCheckSegmentsCount: bool = True+ shouldDeleteTemp: bool = TrueoutputFormat: str = "mp4"customMuxAfterDone: str = ""subtitleFormat: str = "SRT"selectVideo: str = ""- selectAllAudioSubtitle: bool = True+ shouldSelectAllAudioSubtitle: bool = TruemaxSpeed: int = -1speedUnit: str = "Mbps"adKeyword: str = ""- noDateInfo: bool = False- keepImageSegments: bool = False-+ shouldOmitDateInfo: bool = False+ shouldKeepImageSegments: bool = FalsedecryptionEngine: str = "FFmpeg"decryptionBinaryPath: str = ""- mp4RealTimeDecryption: bool = True+ shouldUseMp4RealTimeDecryption: bool = TruedecryptionKeys: list[str] = field(default_factory=list)- keyTextFile: str = ""-+ decryptionKeyFile: str = ""muxImports: list[str] = field(default_factory=list)-- # 直播(real-time-merge 对直播恒开,不设字段)- liveKeepSegments: bool = False- livePipeMux: bool = False- liveFixVtt: bool = False+ shouldKeepLiveSegments: bool = False+ shouldUseLivePipeMux: bool = False+ shouldFixLiveVtt: bool = FalseliveWaitTime: int = 0liveTakeCount: int = 0recordLimit: str = ""+ lastMessage: str = ""+ liveStatus: str = ""+ liveElapsed: str = ""+ liveTotal: str = ""+ actualExtension: str = ""@propertydef canPause(self) -> bool:- # 直播无暂停语义——只有「停止并定案」return not self.task.isLive@property- def outputFile(self) -> str:- return toPosixPath(Path(self.task.path) / self.task.title)+ def outputPath(self) -> str:+ return toPosixPath(self.task.outputFolder / self.task.name)@property- def tempDir(self) -> str:- return toPosixPath(Path(self.task.path) / ".gd3_m3u8" / self.task.taskId)+ def _tempFolder(self) -> str:+ return toPosixPath(self.task.outputFolder / ".gd3_m3u8" / self.task.taskId)@property- def saveName(self) -> str:- return Path(self.task.title).stem-- def cleanup(self):- removePath(Path(self.tempDir))---@dataclass(kw_only=True, eq=False)-class M3U8Task(Task):- packId: str = "m3u8"- supportsEdit: ClassVar[bool] = True-- manifestType: Literal["m3u8", "mpd"] = "m3u8"- isLive: bool = False- # parse() 时枚举的可选视频流 [{"label","selectExpr"}];只服务于轨道下拉, 不持久化- streams: list = field(default_factory=list, repr=False)-- @property- def stage(self) -> "M3U8TaskStage":- return self.stages[0]-- @property- def headers(self) -> dict:- return self.stage.headers-- @property- def proxies(self) -> dict | None:- return self.stage.proxies-- def editorCards(self, parent) -> list["ParseSettingCard"]:- from qfluentwidgets import FluentIcon-- from app.view.components.add_task_dialog import SelectFolderCard- from app.view.components.edit_task_cards import HeadersEditCard, ProxiesEditCard- from .cards import (- M3U8DecryptionEditCard,- M3U8MuxImportEditCard,- M3U8RecordLimitEditCard,- M3U8TrackEditCard,- )-- cards: list["ParseSettingCard"] = [- HeadersEditCard(FluentIcon.GLOBE, parent.tr("请求标头"), parent, initial=self.headers),- ProxiesEditCard(FluentIcon.CERTIFICATE, parent.tr("代理服务器"), parent, initial=self.proxies),- ]- if len(self.streams) > 1:- cards.append(M3U8TrackEditCard(- FluentIcon.VIDEO, parent.tr("视频轨道"), parent,- streams=self.streams, initial=self.stage.selectVideo,- ))- if self.isLive:- cards.append(M3U8RecordLimitEditCard(- FluentIcon.STOP_WATCH, parent.tr("录制时长上限"), parent,- initial=self.stage.recordLimit,- ))- cards += [- M3U8DecryptionEditCard(- FluentIcon.VPN, parent.tr("解密密钥"), parent,- keys=self.stage.decryptionKeys, keyTextFile=self.stage.keyTextFile,- ),- M3U8MuxImportEditCard(- FluentIcon.MUSIC, parent.tr("导入音轨/字幕"), parent,- initial=self.stage.muxImports,- ),- SelectFolderCard(FluentIcon.DOWNLOAD, parent.tr("下载到"), parent, initial=self.path),- ]- return cards-- def applySettings(self, payload):- super().applySettings(payload)- if "headers" in payload:- self.stage.headers = payload["headers"]- if "proxies" in payload:- self.stage.proxies = payload["proxies"]- if "selectVideo" in payload:- self.stage.selectVideo = payload["selectVideo"]- if "recordLimit" in payload:- self.stage.recordLimit = payload["recordLimit"]- if "decryptionKeys" in payload:- self.stage.decryptionKeys = payload["decryptionKeys"]- if "keyTextFile" in payload:- self.stage.keyTextFile = payload["keyTextFile"]- if "muxImports" in payload:- self.stage.muxImports = payload["muxImports"]-- def cleanup(self):- super().cleanup()- # N_m3u8DL-RE 在 task.path 留下同前缀的中间产物(.m3u8、.ts、log 等),- # 用前缀匹配兜底删除;输出文件本身在 super().cleanup() 里已经处理。- outputDirectory = Path(self.path)- if not outputDirectory.exists():+ def _saveName(self) -> str:+ return Path(self.task.name).stem++ def setOptions(self, options: dict) -> None:+ if "headers" in options:+ self.headers = options["headers"]+ if "selectVideo" in options:+ self.selectVideo = options["selectVideo"]+ if "recordLimit" in options:+ self.recordLimit = options["recordLimit"]+ if "decryptionKeys" in options:+ self.decryptionKeys = options["decryptionKeys"]+ if "decryptionKeyFile" in options:+ self.decryptionKeyFile = options["decryptionKeyFile"]+ if "muxImports" in options:+ self.muxImports = options["muxImports"]++ def terminate(self) -> None:+ self._stopping = True+ if self._process is not None and self._process.returncode is None:+ self._process.terminate()++ def deleteFiles(self):+ deletePath(Path(self._tempFolder))+ outputDir = self.task.outputFolder+ if not outputDir.is_dir():return- prefix = f"{self.title}."- outputName = Path(self.outputFolder).name- for candidate in outputDirectory.iterdir():- if candidate.name == outputName:- continue- if candidate.is_file() and candidate.name.startswith(prefix):+ prefix = f"{self._saveName}."+ for candidate in outputDir.iterdir():+ if candidate.is_file() and candidate.name.startswith(prefix) and candidate.name != self.task.name:candidate.unlink(missing_ok=True)+ def _buildCommand(self) -> list[str]:+ def toBool(v: bool) -> str:+ return "true" if v else "false"-class M3U8Worker(Worker):- def __init__(self, stage: M3U8TaskStage):- super().__init__(stage)- self.stage = stage-- def _buildArgs(self) -> list[str]:- stage = self.stageargs = [- stage.task.url,- f"--save-dir={toPosixPath(stage.task.path)}",- f"--save-name={stage.saveName}",- f"--tmp-dir={stage.tempDir}",- f"--thread-count={stage.threadCount}",- f"--download-retry-count={stage.retryCount}",- f"--http-request-timeout={stage.requestTimeout}",- f"--concurrent-download={_toBool(stage.concurrentDownload)}",- f"--append-url-params={_toBool(stage.appendUrlParams)}",- f"--binary-merge={_toBool(stage.binaryMerge)}",- f"--check-segments-count={_toBool(stage.checkSegmentsCount)}",- f"--del-after-done={_toBool(stage.delAfterDone)}",- f"--sub-format={stage.subtitleFormat}",+ self.task.url,+ f"--save-dir={toPosixPath(self.task.outputFolder)}",+ f"--save-name={self._saveName}",+ f"--tmp-dir={self._tempFolder}",+ f"--thread-count={self.threadCount}",+ f"--download-retry-count={self.retryCount}",+ f"--http-request-timeout={self.requestTimeout}",+ f"--concurrent-download={toBool(self.shouldConcurrentDownload)}",+ f"--append-url-params={toBool(self.shouldAppendUrlParams)}",+ f"--binary-merge={toBool(self.shouldBinaryMerge)}",+ f"--check-segments-count={toBool(self.shouldCheckSegmentsCount)}",+ f"--del-after-done={toBool(self.shouldDeleteTemp)}",+ f"--sub-format={self.subtitleFormat}","--write-meta-json=false","--no-log=true","--no-ansi-color=true","--disable-update-check=true",]- # 拿全部音轨/字幕时需绕开 auto-select 对其的"仅最佳"——显式选视频(最佳或所选)+全部音字幕- if stage.selectAllAudioSubtitle:- args.append(f"--select-video={stage.selectVideo or 'best'}")+ if self.shouldSelectAllAudioSubtitle:+ args.append(f"--select-video={self.selectVideo or 'best'}")args.append("--select-audio=all")args.append("--select-subtitle=all")- elif stage.selectVideo:- args.append(f"--select-video={stage.selectVideo}")- args.append(f"--auto-select={_toBool(stage.autoSelect)}")+ elif self.selectVideo:+ args.append(f"--select-video={self.selectVideo}")+ args.append(f"--auto-select={toBool(self.shouldAutoSelect)}")else:- args.append(f"--auto-select={_toBool(stage.autoSelect)}")-- if stage.maxSpeed > 0:- args.append(f"--max-speed={stage.maxSpeed}{stage.speedUnit}")- if stage.adKeyword:- args.append(f"--ad-keyword={stage.adKeyword}")- if stage.noDateInfo:+ args.append(f"--auto-select={toBool(self.shouldAutoSelect)}")++ if self.maxSpeed > 0:+ args.append(f"--max-speed={self.maxSpeed}{self.speedUnit}")+ elif cfg.isSpeedLimitEnabled.value:+ args.append(f"--max-speed={int(cfg.speedLimitation.value)}Bps")+ if self.adKeyword:+ args.append(f"--ad-keyword={self.adKeyword}")+ if self.shouldOmitDateInfo:args.append("--no-date-info=true")- proxyUrl = next((v for v in stage.proxies.values() if v), "")- # N_m3u8DL-RE 的 .NET HttpClient 不识别 socks5h scheme,等价转为 socks5- if proxyUrl.startswith("socks5h://"):+ from app.config.cfg import proxy+ proxyUrl = proxy()+ if proxyUrl and proxyUrl.startswith("socks5h://"):proxyUrl = "socks5://" + proxyUrl[len("socks5h://"):]args.append("--use-system-proxy=false")if proxyUrl:args.append(f"--custom-proxy={proxyUrl}")- ffmpegPath, _ = ffmpegPaths()+ from ffmpeg_pack.config import ffmpegRuntime+ ffmpegPath = ffmpegRuntime.path()if ffmpegPath:args.append(f"--ffmpeg-binary-path={ffmpegPath}")- args.append(f"--decryption-engine={_DECRYPTION_ENGINES.get(stage.decryptionEngine, 'FFMPEG')}")- args.append(f"--mp4-real-time-decryption={_toBool(stage.mp4RealTimeDecryption)}")- if stage.decryptionBinaryPath:- args.append(f"--decryption-binary-path={toPosixPath(Path(stage.decryptionBinaryPath))}")- for key in stage.decryptionKeys:+ args.append(f"--decryption-engine={DECRYPTION_ENGINES.get(self.decryptionEngine, 'FFMPEG')}")+ args.append(f"--mp4-real-time-decryption={toBool(self.shouldUseMp4RealTimeDecryption)}")+ if self.decryptionBinaryPath:+ args.append(f"--decryption-binary-path={toPosixPath(Path(self.decryptionBinaryPath))}")+ for key in self.decryptionKeys:text = key.strip()if text:args.append(f"--key={text}")- if stage.keyTextFile:- args.append(f"--key-text-file={toPosixPath(Path(stage.keyTextFile))}")+ if self.decryptionKeyFile:+ args.append(f"--key-text-file={toPosixPath(Path(self.decryptionKeyFile))}")- if stage.task.isLive:- # 直播恒开 real-time-merge:硬杀停止时文件已落盘可用+ if self.task.isLive:args.append("--live-real-time-merge=true")- args.append(f"--live-keep-segments={_toBool(stage.liveKeepSegments)}")- args.append(f"--live-pipe-mux={_toBool(stage.livePipeMux)}")- if stage.liveFixVtt:+ args.append(f"--live-keep-segments={toBool(self.shouldKeepLiveSegments)}")+ args.append(f"--live-pipe-mux={toBool(self.shouldUseLivePipeMux)}")+ if self.shouldFixLiveVtt:args.append("--live-fix-vtt-by-audio=true")- if stage.liveWaitTime > 0:- args.append(f"--live-wait-time={stage.liveWaitTime}")- if stage.liveTakeCount > 0:- args.append(f"--live-take-count={stage.liveTakeCount}")- if stage.recordLimit:- args.append(f"--live-record-limit={stage.recordLimit}")- elif stage.customMuxAfterDone:- args.append(f"--mux-after-done={stage.customMuxAfterDone}")+ if self.liveWaitTime > 0:+ args.append(f"--live-wait-time={self.liveWaitTime}")+ if self.liveTakeCount > 0:+ args.append(f"--live-take-count={self.liveTakeCount}")+ if self.recordLimit:+ args.append(f"--live-record-limit={self.recordLimit}")+ elif self.customMuxAfterDone:+ args.append(f"--mux-after-done={self.customMuxAfterDone}")else:- muxOption = f"format={stage.outputFormat}:muxer=ffmpeg"+ muxOption = f"format={self.outputFormat}:muxer=ffmpeg"if ffmpegPath:muxOption += f":bin_path={ffmpegPath}"args.append(f"--mux-after-done={muxOption}")- for imp in stage.muxImports:+ for imp in self.muxImports:text = imp.strip()if text:args.append(f"--mux-import={text}")- for name, value in stage.headers.items():+ for name, value in self.headers.items():text = value.strip()- if not text:- continue- args.extend(["-H", f"{name}: {text}"])+ if text:+ args.extend(["-H", f"{name}: {text}"])return args@@ -310,144 +234,129 @@ class M3U8Worker(Worker):if not text:return- self.stage.lastMessage = text[:1000]+ self.lastMessage = text[:1000]- vodMatch = _VOD_PROGRESS_PATTERN.search(text)+ vodMatch = VOD_PROGRESS_PATTERN.search(text)if vodMatch:- self.stage.progress = float(vodMatch.group(3))- self.stage.receivedBytes = toBytes(vodMatch.group(4), vodMatch.group(5))- self.stage.speed = toBytes(vodMatch.group(8), vodMatch.group(9))+ self.progress = float(vodMatch.group(3))+ self.receivedBytes = toBytes(vodMatch.group(4), vodMatch.group(5))+ self.speed = toBytes(vodMatch.group(8), vodMatch.group(9))totalSize = toBytes(vodMatch.group(6), vodMatch.group(7))if totalSize > 0:- self.stage.task.fileSize = totalSize+ self.task.fileSize = totalSizereturn- liveMatch = _LIVE_PROGRESS_PATTERN.search(text)+ liveMatch = LIVE_PROGRESS_PATTERN.search(text)if liveMatch:- self.stage.liveElapsed = liveMatch.group(1)- self.stage.liveTotal = liveMatch.group(2)- self.stage.liveStatus = liveMatch.group(3)- self.stage.progress = float(liveMatch.group(4))- self.stage.speed = 0 if liveMatch.group(5) == "-" else toBytes(liveMatch.group(6), liveMatch.group(7))+ self.liveElapsed = liveMatch.group(1)+ self.liveTotal = liveMatch.group(2)+ self.liveStatus = liveMatch.group(3)+ self.progress = float(liveMatch.group(4))+ self.speed = 0 if liveMatch.group(5) == "-" else toBytes(liveMatch.group(6), liveMatch.group(7))- async def supervisor(self, stream: asyncio.StreamReader):+ async def _readOutput(self, stream: asyncio.StreamReader):buffer = ""while True:chunk = await stream.read(4096)if not chunk:break-buffer += chunk.decode("utf-8", errors="ignore")buffer = buffer.replace("\r\n", "\n").replace("\r", "\n")lines = buffer.split("\n")buffer = lines.pop()for line in lines:self._parseOutputLine(line)-if buffer.strip():self._parseOutputLine(buffer)- def _updateOutput(self):- # 进程已结束, 占位旁标去重使命完成——清掉(暂停/失败不走这里, 旁标留作并发去重)- Path(f"{self.stage.outputFile}.ghd").unlink(missing_ok=True)- target = Path(self.stage.outputFile)+ def _findOutputFile(self):+ Path(f"{self.outputPath}.ghd").unlink(missing_ok=True)+ target = Path(self.outputPath)if target.is_file() and target.stat().st_size > 0:- self.stage.actualExtension = target.suffix.lstrip(".")- self.stage.task.fileSize = max(self.stage.task.fileSize, target.stat().st_size)+ self.actualExtension = target.suffix.lstrip(".")+ self.task.fileSize = max(self.task.fileSize, target.stat().st_size)returntarget.unlink(missing_ok=True)- outputDir = self.stage.task.path+ outputDir = self.task.outputFolderif not outputDir.is_dir():return- fallbackExtension = "ts" if self.stage.task.isLive else self.stage.outputFormat- expectedSuffix = f".{self.stage.actualExtension or fallbackExtension}"- prefix = self.stage.saveName.lower()+ fallbackExt = "ts" if self.task.isLive else self.outputFormat+ expectedSuffix = f".{self.actualExtension or fallbackExt}"+ prefix = self._saveName.lower()candidates = [- candidate- for candidate in outputDir.iterdir()- if candidate.is_file()- and candidate.suffix.lower() not in _IGNORED_OUTPUT_SUFFIXES- and candidate.name.lower().startswith(prefix)+ c for c in outputDir.iterdir()+ if c.is_file()+ and c.suffix.lower() not in IGNORED_OUTPUT_SUFFIXES+ and c.name.lower().startswith(prefix)]if not candidates:return- candidates.sort(- key=lambda path: (- path.suffix.lower() != expectedSuffix,- -path.stat().st_mtime,- )- )+ candidates.sort(key=lambda p: (p.suffix.lower() != expectedSuffix, -p.stat().st_mtime))found = candidates[0]- self.stage.actualExtension = found.suffix.lstrip(".")- self.stage.task.fileSize = max(self.stage.task.fileSize, found.stat().st_size)- if found.name != self.stage.task.title:- self.stage.task.setTitle(found.name)+ self.actualExtension = found.suffix.lstrip(".")+ self.task.fileSize = max(self.task.fileSize, found.stat().st_size)+ if found.name != self.task.name:+ self.task.setName(found.name)- async def run(self):- execPath = downloaderPath()+ async def run(self) -> None:+ self._stopping = False+ self._process = None++ execPath = m3u8Runtime.path()if not execPath:raise RuntimeError("未找到可用的 N_m3u8DL-RE,请先在设置中安装或配置运行时")- self.stage.task.path.mkdir(parents=True, exist_ok=True)- Path(self.stage.tempDir).mkdir(parents=True, exist_ok=True)- # 用 .ghd 旁标占位, 让后续同名任务被 deduplicateFilename 检测到; 不占用产物名,- # 否则 N_m3u8DL-RE 发现同名已存在会把产物写成 <name>.copy.<ext>- Path(f"{self.stage.outputFile}.ghd").touch(exist_ok=True)+ self.task.outputFolder.mkdir(parents=True, exist_ok=True)+ Path(self._tempFolder).mkdir(parents=True, exist_ok=True)+ Path(f"{self.outputPath}.ghd").touch(exist_ok=True)env = None- if self.stage.keepImageSegments:+ if self.shouldKeepImageSegments:env = {**os.environ, "RE_KEEP_IMAGE_SEGMENTS": "1"}- process = None- supervisorTask = None+ outputTask = Nonetry:- args = self._buildArgs()- process = await asyncio.create_subprocess_exec(- execPath,- *args,+ command = self._buildCommand()+ self._process = await asyncio.create_subprocess_exec(+ execPath, *command,cwd=Path(execPath).parent,env=env,stdin=asyncio.subprocess.DEVNULL,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT,)- supervisorTask = asyncio.create_task(self.supervisor(process.stdout))+ outputTask = asyncio.create_task(self._readOutput(self._process.stdout))- await process.wait()- await supervisorTask+ await self._process.wait()+ await outputTask- if process.returncode != 0:- message = self.stage.lastMessage or f"N_m3u8DL-RE 退出码异常: {process.returncode}"- raise RuntimeError(message)+ if self._process.returncode != 0 and not self._stopping:+ raise RuntimeError(self.lastMessage or f"N_m3u8DL-RE 退出码异常: {self._process.returncode}")- self._updateOutput()- self.stage.setStatus(TaskStatus.COMPLETED)+ self._findOutputFile()+ self.setStatus(TaskStatus.COMPLETED)except asyncio.CancelledError:- if process is not None and process.returncode is None:- process.terminate()+ if self._process is not None and self._process.returncode is None:+ self._process.terminate()try:- await asyncio.wait_for(process.wait(), timeout=3)+ await asyncio.wait_for(self._process.wait(), timeout=3)except asyncio.TimeoutError:- process.kill()- await process.wait()- if supervisorTask is not None and not supervisorTask.done():- supervisorTask.cancel()+ self._process.kill()+ await self._process.wait()+ if outputTask is not None and not outputTask.done():+ outputTask.cancel()with suppress(asyncio.CancelledError):- await supervisorTask- if self.stage.task.isLive:- # 直播无暂停语义:硬杀后 real-time-merge 的文件已落盘,收尾标完成- self._updateOutput()- self.stage.setStatus(TaskStatus.COMPLETED)+ await outputTask+ if self.task.isLive:+ self._findOutputFile()+ self.setStatus(TaskStatus.COMPLETED)else:- self.stage.setStatus(TaskStatus.PAUSED)+ self.setStatus(TaskStatus.PAUSED)raiseexcept Exception as e:- self.stage.setError(e)+ self.setError(e)raise---M3U8TaskStage.workerType = M3U8Workerdiff --git a/features/yt_dlp_pack/cards.py b/features/yt_dlp_pack/cards.pyindex c9fd015c..d0f5fd08 100644--- a/features/yt_dlp_pack/cards.py+++ b/features/yt_dlp_pack/cards.py@@ -1,76 +1,382 @@-from PySide6.QtWidgets import QWidget-from qfluentwidgets import ComboBox--from app.bases.models import SpecialFileSize, Task-from app.services.core_service import coreService-from app.supports.utils import getProxies, toReadableSize-from app.view.components.cards import UniversalResultCard-from .task import DEFAULT_VIDEO_FORMAT, probeMediaInfo--_QUALITY_TIERS = (- ("最佳画质", DEFAULT_VIDEO_FORMAT),- ("1080p", "bv*[height<=1080]+ba/b[height<=1080]"),- ("720p", "bv*[height<=720]+ba/b[height<=720]"),- ("480p", "bv*[height<=480]+ba/b[height<=480]"),- ("仅音频", "ba/b"),+from __future__ import annotations++from PySide6.QtCore import Qt+from PySide6.QtGui import QColor, QStandardItem, QStandardItemModel+from PySide6.QtWidgets import QAbstractItemView, QHBoxLayout, QHeaderView, QWidget+from qfluentwidgets import (+ BodyLabel, ComboBox, FluentIcon, IndeterminateProgressRing,+ MessageBoxBase, PrimaryPushButton, ProgressBar, PushButton, SubtitleLabel,+ ToolTipFilter, TransparentToolButton,)-_UNKNOWN_SIZES = (SpecialFileSize.UNKNOWN, SpecialFileSize.NOT_SUPPORTED)---class YtDlpResultCard(UniversalResultCard):- def __init__(self, task: Task, parent: QWidget = None):- super().__init__(task, parent)- self._pendingFormat = self.task.stage.videoFormat- self._sizeByFormat: dict[str, int] = {}- if self.task.fileSize not in _UNKNOWN_SIZES:- self._sizeByFormat[self._pendingFormat] = self.task.fileSize- self._renderSize(self.task.fileSize)- self.qualityCombo.currentIndexChanged.connect(lambda _: self._onQualityChanged())-- def initWidget(self):- super().initWidget()- self.qualityCombo = ComboBox(self)- self.qualityCombo.setMinimumWidth(140)- selectedIndex = 0- for index, (label, expr) in enumerate(_QUALITY_TIERS):- self.qualityCombo.addItem(label, userData=expr)- if expr == self.task.stage.videoFormat:- selectedIndex = index- self.qualityCombo.setCurrentIndex(selectedIndex)-- def initLayout(self):- super().initLayout()- self.mainLayout.insertWidget(self.mainLayout.indexOf(self.sizeLabel), self.qualityCombo)-- def _onQualityChanged(self):- videoFormat = self.qualityCombo.currentData() or DEFAULT_VIDEO_FORMAT- self.task.applySettings({"videoFormat": videoFormat})- self._pendingFormat = videoFormat- if videoFormat in self._sizeByFormat:- self._applySize(self._sizeByFormat[videoFormat])++from app.format import toReadableSize+from app.models.task import TaskStatus+from app.view.cards.draft_cards import UniversalDraftCard+from app.view.cards.task_cards import UniversalTaskCard+from app.view.components.tree_view import AutoSizingTreeView+from .config import ytDlpConfig+from .task import YtDlpTask+++def buildQualityTiers(mediaInfo: dict) -> list[tuple[str, str]]:+ formats = mediaInfo.get("formats") or []+ seen: set[tuple[int, int]] = set()+ tiers: list[tuple[int, int]] = []++ for f in formats:+ if f.get("vcodec") in (None, "none"):+ continue+ height = f.get("height") or 0+ fps = f.get("fps") or 0+ if height <= 0:+ continue+ key = (height, 60 if fps > 30 else 0)+ if key not in seen:+ seen.add(key)+ tiers.append(key)++ tiers.sort(key=lambda t: (t[0], t[1]), reverse=True)++ result: list[tuple[str, str]] = []+ if tiers:+ bestH, bestFps = tiers[0]+ result.append(("bv*+ba/b", f"最佳画质 ({bestH}p{'60' if bestFps else ''})"))++ for height, fps in tiers:+ fpsLabel = "60" if fps else ""+ result.append((f"bv*[height<={height}]+ba/b", f"{height}p{fpsLabel}"))++ result.append(("ba/b", "仅音频"))+ return result+++def buildSubtitleChoices(mediaInfo: dict) -> list[tuple[str, str, bool]]:+ choices: list[tuple[str, str, bool]] = []+ seen: set[str] = set()++ for lang in (mediaInfo.get("subtitles") or {}):+ if lang not in seen:+ seen.add(lang)+ choices.append((lang, lang, False))++ for lang in (mediaInfo.get("automatic_captions") or {}):+ if lang not in seen:+ seen.add(lang)+ choices.append((lang, f"{lang} (自动)", True))++ return choices+++class YtDlpDraftCard(UniversalDraftCard):++ def _initWidget(self) -> None:+ super()._initWidget()+ task: YtDlpTask = self._task+ mediaInfo: dict = getattr(task, "_mediaInfo", {})++ self._qualityTiers = buildQualityTiers(mediaInfo)+ self._subtitleChoices = buildSubtitleChoices(mediaInfo)++ self._qualityCombo = ComboBox(self)+ self._qualityCombo.setMinimumWidth(160)+ for _selector, label in self._qualityTiers:+ self._qualityCombo.addItem(label)+ if self._qualityTiers:+ self._qualityCombo.setCurrentIndex(0)++ self._subtitleButton = TransparentToolButton(FluentIcon.LANGUAGE, self)+ self._subtitleButton.installEventFilter(ToolTipFilter(self._subtitleButton))+ self._subtitleButton.setToolTip(self.tr("选择字幕"))+ self._subtitleButton.setEnabled(bool(self._subtitleChoices))++ self._videoSelectButton = TransparentToolButton(FluentIcon.LIBRARY, self)+ self._videoSelectButton.installEventFilter(ToolTipFilter(self._videoSelectButton))+ self._videoSelectButton.setToolTip(self.tr("选择视频"))+ self._videoSelectButton.setVisible(task.isPlaylist)++ self._playlistSpinner = IndeterminateProgressRing(self)+ self._playlistSpinner.setFixedSize(20, 20)+ self._playlistSpinner.setStrokeWidth(3)+ self._playlistSpinner.hide()++ def _initLayout(self) -> None:+ super()._initLayout()+ self.layout().addWidget(self._qualityCombo)+ self.layout().addWidget(self._subtitleButton)+ self.layout().addWidget(self._videoSelectButton)+ self.layout().addWidget(self._playlistSpinner)++ def _bind(self) -> None:+ super()._bind()+ self._qualityCombo.currentIndexChanged.connect(self._onQualityChanged)+ self._subtitleButton.clicked.connect(self._onSubtitleClicked)+ self._videoSelectButton.clicked.connect(self._onVideoSelectClicked)++ def _onQualityChanged(self, index: int) -> None:+ if 0 <= index < len(self._qualityTiers):+ self._task.videoFormat = self._qualityTiers[index][0]++ def _onSubtitleClicked(self) -> None:+ dialog = SubtitleSelectDialog(self._subtitleChoices, self.window())+ if dialog.exec():+ langs, includeAuto = dialog.selectedLanguages()+ self._task.subtitleLanguages = langs+ self._task.shouldIncludeAutoSubs = includeAuto++ def _onVideoSelectClicked(self) -> None:+ task: YtDlpTask = self._task+ if not task.videos:+ self._videoSelectButton.hide()+ self._playlistSpinner.show()+ from app.services.coroutine_runner import coroutineRunner+ from features.yt_dlp_pack.pack import YouTubeParser+ parser = YouTubeParser()+ coroutineRunner.submit(+ parser.probePlaylist(task.url),+ done=self._onPlaylistLoaded,+ failed=self._onPlaylistFailed,+ )return- self.sizeLabel.setText(self.tr("计算中…"))- coreService.runCoroutine(- probeMediaInfo(self.task.url, getProxies(), videoFormat, self.task.stage.headers),- lambda result, error, fmt=videoFormat: self._onSizeProbed(fmt, result, error),+ dialog = VideoSelectDialog(task.videos, self.window())+ if dialog.exec():+ task.setSelectedVideos(dialog.selectedIndices())+ self.nameLabel.setText(task.name)++ def _onPlaylistLoaded(self, videos: list[dict]) -> None:+ self._playlistSpinner.hide()+ self._videoSelectButton.show()+ task: YtDlpTask = self._task+ if videos:+ task.setVideos(videos)+ self._onVideoSelectClicked()+ else:+ self._videoSelectButton.setEnabled(False)+ self._videoSelectButton.setToolTip(self.tr("未找到播放列表"))++ def _onPlaylistFailed(self, error: str) -> None:+ self._playlistSpinner.hide()+ self._videoSelectButton.show()+ self._videoSelectButton.setToolTip(self.tr("加载播放列表失败"))+++class SubtitleSelectDialog(MessageBoxBase):++ def __init__(self, choices: list[tuple[str, str, bool]], parent=None):+ super().__init__(parent)+ self._choices = choices++ self.titleLabel = SubtitleLabel(self.tr("选择字幕语言"), self)+ self.summaryLabel = BodyLabel("", self)++ self.selectAllButton = PrimaryPushButton(self.tr("全选"), self)+ self.clearButton = PushButton(self.tr("全不选"), self)++ self.treeView = AutoSizingTreeView(self, minimumVisibleRows=3, maximumVisibleRows=16)+ self.treeModel = QStandardItemModel(self.treeView)++ self._initWidget()+ self._initLayout()+ self._bind()+ self._refreshSummary()++ def _initWidget(self) -> None:+ self.widget.setMinimumWidth(400)+ self.yesButton.setText(self.tr("确定"))+ self.cancelButton.setText(self.tr("取消"))++ self.treeView.setRootIsDecorated(False)+ self.treeView.setUniformRowHeights(True)+ self.treeView.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)+ self.treeView.setHeaderHidden(True)++ self.treeView.setModel(self.treeModel)++ defaultLangs = {s.strip() for s in ytDlpConfig.subtitleLanguages.value.split(",") if s.strip()}++ for langCode, label, _isAuto in self._choices:+ item = QStandardItem(label)+ item.setCheckable(True)+ item.setCheckState(Qt.CheckState.Checked if langCode in defaultLangs else Qt.CheckState.Unchecked)+ item.setData(langCode, Qt.ItemDataRole.UserRole)+ item.setData(_isAuto, Qt.ItemDataRole.UserRole + 1)+ self.treeModel.appendRow(item)++ def _initLayout(self) -> None:+ actionsLayout = QHBoxLayout()+ actionsLayout.setContentsMargins(0, 0, 0, 0)+ actionsLayout.setSpacing(8)+ actionsLayout.addWidget(self.selectAllButton)+ actionsLayout.addWidget(self.clearButton)+ actionsLayout.addStretch(1)+ actionsLayout.addWidget(self.summaryLabel)++ self.viewLayout.addWidget(self.titleLabel)+ self.viewLayout.addSpacing(8)+ self.viewLayout.addWidget(self.treeView)+ self.viewLayout.addSpacing(4)+ self.viewLayout.addLayout(actionsLayout)++ def _bind(self) -> None:+ self.selectAllButton.clicked.connect(lambda: self._setAll(True))+ self.clearButton.clicked.connect(lambda: self._setAll(False))+ self.treeModel.itemChanged.connect(lambda _: self._refreshSummary())++ def _setAll(self, checked: bool) -> None:+ state = Qt.CheckState.Checked if checked else Qt.CheckState.Unchecked+ for row in range(self.treeModel.rowCount()):+ self.treeModel.item(row, 0).setCheckState(state)++ def _refreshSummary(self) -> None:+ count = sum(+ 1 for row in range(self.treeModel.rowCount())+ if self.treeModel.item(row, 0).checkState() == Qt.CheckState.Checked)+ self.summaryLabel.setText(self.tr("{0}/{1} 种语言").format(count, self.treeModel.rowCount()))- def _onSizeProbed(self, videoFormat: str, result, error):- if videoFormat != self._pendingFormat:- return- if error or not result:- self._renderSize(SpecialFileSize.UNKNOWN)- return- _, size = result- self._sizeByFormat[videoFormat] = size- self._applySize(size)+ def selectedLanguages(self) -> tuple[str, bool]:+ langs: list[str] = []+ hasAuto = False+ for row in range(self.treeModel.rowCount()):+ item = self.treeModel.item(row, 0)+ if item.checkState() == Qt.CheckState.Checked:+ langs.append(item.data(Qt.ItemDataRole.UserRole))+ if item.data(Qt.ItemDataRole.UserRole + 1):+ hasAuto = True+ return ",".join(langs), hasAuto- def _applySize(self, size: int):- self.task.fileSize = size- self._renderSize(size)- def _renderSize(self, size: int):- if size in _UNKNOWN_SIZES:- self.sizeLabel.setText(self.tr("未知"))- else:- self.sizeLabel.setText(self.tr("约 {0}").format(toReadableSize(size)))+class VideoSelectDialog(MessageBoxBase):++ def __init__(self, videos: list[dict], parent=None):+ super().__init__(parent)+ self._videos = videos++ self.titleLabel = SubtitleLabel(self.tr("选择视频"), self)+ self.summaryLabel = BodyLabel("", self)++ self.selectAllButton = PrimaryPushButton(self.tr("全选"), self)+ self.clearButton = PushButton(self.tr("全不选"), self)+ self.invertButton = PushButton(self.tr("反选"), self)++ self.treeView = AutoSizingTreeView(self, minimumVisibleRows=3, maximumVisibleRows=16)+ self.treeModel = QStandardItemModel(self.treeView)++ self._initWidget()+ self._initLayout()+ self._bind()+ self._refreshSummary()++ def _initWidget(self) -> None:+ self.widget.setMinimumWidth(550)+ self.yesButton.setText(self.tr("确定"))+ self.cancelButton.setText(self.tr("取消"))++ self.treeView.setRootIsDecorated(False)+ self.treeView.setUniformRowHeights(True)+ self.treeView.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)++ self.treeModel.setHorizontalHeaderLabels([self.tr("标题"), self.tr("时长")])+ self.treeView.setModel(self.treeModel)+ self.treeView.header().setStretchLastSection(False)+ self.treeView.header().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)+ self.treeView.header().setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)++ for i, video in enumerate(self._videos):+ title = str(video.get("title") or f"视频 {i + 1}").strip()+ duration = video.get("duration")++ nameItem = QStandardItem(f"{i + 1}. {title}")+ nameItem.setCheckable(True)+ nameItem.setCheckState(Qt.CheckState.Checked if video.get("selected", True) else Qt.CheckState.Unchecked)++ durationText = ""+ if duration and isinstance(duration, (int, float)) and duration > 0:+ minutes, seconds = divmod(int(duration), 60)+ durationText = f"{minutes}:{seconds:02d}"+ durationItem = QStandardItem(durationText)+ durationItem.setEditable(False)++ self.treeModel.appendRow([nameItem, durationItem])++ def _initLayout(self) -> None:+ actionsLayout = QHBoxLayout()+ actionsLayout.setContentsMargins(0, 0, 0, 0)+ actionsLayout.setSpacing(8)+ actionsLayout.addWidget(self.selectAllButton)+ actionsLayout.addWidget(self.clearButton)+ actionsLayout.addWidget(self.invertButton)+ actionsLayout.addStretch(1)+ actionsLayout.addWidget(self.summaryLabel)++ self.viewLayout.addWidget(self.titleLabel)+ self.viewLayout.addSpacing(8)+ self.viewLayout.addWidget(self.treeView)+ self.viewLayout.addSpacing(4)+ self.viewLayout.addLayout(actionsLayout)++ def _bind(self) -> None:+ self.selectAllButton.clicked.connect(lambda: self._setAll(True))+ self.clearButton.clicked.connect(lambda: self._setAll(False))+ self.invertButton.clicked.connect(self._onInvert)+ self.treeModel.itemChanged.connect(lambda _: self._refreshSummary())++ def _setAll(self, checked: bool) -> None:+ state = Qt.CheckState.Checked if checked else Qt.CheckState.Unchecked+ for row in range(self.treeModel.rowCount()):+ self.treeModel.item(row, 0).setCheckState(state)++ def _onInvert(self) -> None:+ for row in range(self.treeModel.rowCount()):+ item = self.treeModel.item(row, 0)+ item.setCheckState(+ Qt.CheckState.Unchecked if item.checkState() == Qt.CheckState.Checked else Qt.CheckState.Checked+ )++ def _refreshSummary(self) -> None:+ count = sum(+ 1 for row in range(self.treeModel.rowCount())+ if self.treeModel.item(row, 0).checkState() == Qt.CheckState.Checked+ )+ self.summaryLabel.setText(self.tr("{0}/{1} 个视频").format(count, self.treeModel.rowCount()))+ self.yesButton.setEnabled(count > 0)++ def selectedIndices(self) -> set[int]:+ return {+ row for row in range(self.treeModel.rowCount())+ if self.treeModel.item(row, 0).checkState() == Qt.CheckState.Checked+ }+++class YtDlpTaskCard(UniversalTaskCard):++ def _buildProgressBar(self) -> QWidget:+ bar = ProgressBar(self)+ bar.setCustomBackgroundColor(QColor(0, 0, 0, 0), QColor(0, 0, 0, 0))+ return bar++ def refresh(self) -> None:+ super().refresh()+ task: YtDlpTask = self._task+ if len(task.steps) <= 1:+ return+ completedCount = sum(1 for s in task.steps if s.status == TaskStatus.COMPLETED)+ totalCount = len(task.steps)+ if task.status == TaskStatus.RUNNING:+ currentStep = next((s for s in task.steps if s.status == TaskStatus.RUNNING), None)+ if currentStep:+ title = currentStep.videoTitle or task.name+ self.nameLabel.setText(f"{title} ({completedCount + 1}/{totalCount})")+ totalBytes = getattr(currentStep, "_totalBytes", 0)+ if totalBytes > 0:+ self.sizeLabel.setText(+ f"{toReadableSize(currentStep.receivedBytes)}/{toReadableSize(totalBytes)}"+ )+ else:+ self.sizeLabel.setText(toReadableSize(currentStep.receivedBytes))+ self.sizeLabel.show()+ elif task.status == TaskStatus.COMPLETED:+ receivedBytes = sum(s.receivedBytes for s in task.steps)+ self.sizeLabel.setText(+ self.tr("{0} 个视频 · {1}").format(totalCount, toReadableSize(receivedBytes))+ )+ self.sizeLabel.show()diff --git a/features/yt_dlp_pack/config.py b/features/yt_dlp_pack/config.pyindex 052e8f9f..70f33557 100644--- a/features/yt_dlp_pack/config.py+++ b/features/yt_dlp_pack/config.py@@ -1,139 +1,129 @@-import asyncio-from pathlib import Path-from typing import TYPE_CHECKING--from PySide6.QtCore import Qt-from qfluentwidgets import (- ConfigItem,- FluentIcon,- FolderValidator,- InfoBar,- PrimaryPushButton,- SettingCard,- ToolButton,-)--from app.bases.models import PackConfig-from app.services.core_service import coreService-from app.supports.paths import APP_DATA_DIR-from app.supports.utils import findExecutable, toPosixPath-from app.view.components.setting_card_group import CollapsibleSettingCardGroup-from app.view.components.setting_cards import InstallFolderCard--if TYPE_CHECKING:- from app.view.pages.setting_page import SettingPage- from app.view.windows.main_window import MainWindow---def downloaderPath() -> str:- return findExecutable(Path(ytDlpConfig.installFolder.value), "yt-dlp")---async def probeYtDlpRuntime() -> dict[str, str]:- execPath = downloaderPath()- info = {"downloaderPath": execPath, "version": "", "installPath": ""}- if not execPath:- return info-- process = await asyncio.create_subprocess_exec(- execPath,- "--version",- stdin=asyncio.subprocess.DEVNULL,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- )- stdout, stderr = await process.communicate()- if process.returncode != 0:- return info-- output = stdout.decode("utf-8", errors="ignore") or stderr.decode("utf-8", errors="ignore")- lines = [line.strip() for line in output.splitlines() if line.strip()]- info["version"] = lines[0] if lines else ""- info["installPath"] = toPosixPath(Path(execPath).parent)- return info---class YtDlpRuntimeCard(SettingCard):- def __init__(self, parent=None):- super().__init__(FluentIcon.INFO, self.tr("当前 yt-dlp"), self.tr("正在检测运行时..."), parent)- self.installButton = PrimaryPushButton(self.tr("一键安装"), self)- self.refreshButton = ToolButton(FluentIcon.SYNC, self)-- self._initLayout()- self._bind()-- def _initLayout(self):- self.hBoxLayout.addWidget(self.installButton, 0, Qt.AlignmentFlag.AlignRight)- self.hBoxLayout.addSpacing(8)- self.hBoxLayout.addWidget(self.refreshButton, 0, Qt.AlignmentFlag.AlignRight)- self.hBoxLayout.addSpacing(16)-- def _bind(self):- self.installButton.clicked.connect(self._onInstallClicked)- self.refreshButton.clicked.connect(self.refreshStatus)-- def refreshStatus(self):- self.refreshButton.setEnabled(False)- self.setContent(self.tr("正在检测运行时..."))- coreService.runCoroutine(probeYtDlpRuntime(), self._onRuntimeLoaded)-- def _onRuntimeLoaded(self, result, error: str | None):- self.refreshButton.setEnabled(True)- if error:- self.setContent(self.tr("检测运行时失败"))- return-- info = result or {}- executablePath = info.get("downloaderPath", "")- if executablePath:- content = self.tr("版本: {0}\n安装路径: {1}").format(- info.get("version") or self.tr("未知"),- info.get("installPath") or executablePath,- )- else:- content = self.tr("未检测到可用的 yt-dlp")- self.setContent(content)-- def _onInstallClicked(self):- from .pack import createInstallTask-- self.installButton.setEnabled(False)- self.installButton.setText(self.tr("准备中..."))- coreService.runCoroutine(createInstallTask(), self._onInstallTaskCreated)+from __future__ import annotations- def _onInstallTaskCreated(self, result, error: str | None):- self.installButton.setEnabled(True)- self.installButton.setText(self.tr("一键安装"))+import platform+import sys+from pathlib import Path- mainWindow: "MainWindow" = self.window()- if error or result is None:- InfoBar.error(self.tr("安装 yt-dlp 失败"), error or self.tr("无法创建安装任务"), duration=-1, parent=mainWindow)- return+from PySide6.QtWidgets import QWidget+from qfluentwidgets import BoolValidator, ConfigItem, FolderValidator, OptionsConfigItem, OptionsValidator, RangeConfigItem, RangeValidator- mainWindow.addTask(result)+from app.config.paths import APP_DATA_DIR+from app.models.pack import BinaryRuntime, PackConfig+from app.models.task import Task+from app.platform.android import IS_ANDROID+from app.platform.filesystem import findExecutableclass YtDlpConfig(PackConfig):installFolder = ConfigItem("YtDlp", "InstallFolder", f"{APP_DATA_DIR}/YtDlp", FolderValidator())-- def setupSettings(self, settingPage: "SettingPage"):- self.group = CollapsibleSettingCardGroup(self.tr("YouTube 下载"), "ytdlp", settingPage.container)- self.installFolderCard = InstallFolderCard(- self.installFolder,- f"{APP_DATA_DIR}/YtDlp",+ parallelFragments = RangeConfigItem("YtDlp", "ParallelFragments", 4, RangeValidator(1, 16))+ loginBrowser = OptionsConfigItem(+ "YtDlp", "LoginBrowser", "",+ OptionsValidator(["", "chrome", "firefox", "edge", "safari"]),+ )+ shouldPreferMp4 = ConfigItem("YtDlp", "PreferMp4", True, BoolValidator())+ subtitleLanguages = ConfigItem("YtDlp", "SubtitleLanguages", "en")+ shouldEmbedThumbnail = ConfigItem("YtDlp", "EmbedThumbnail", True, BoolValidator())+ shouldEmbedChapters = ConfigItem("YtDlp", "EmbedChapters", True, BoolValidator())+ shouldEmbedMetadata = ConfigItem("YtDlp", "EmbedMetadata", True, BoolValidator())++ def settingGroups(self, parent: QWidget) -> list:+ from qfluentwidgets import ComboBoxSettingCard, FluentIcon, SwitchSettingCard+ from app.view.components.setting_card_group import CollapsibleSettingCardGroup+ from app.view.components.setting_cards import SelectFolderSettingCard, RuntimeCard, SpinBoxSettingCard++ group = CollapsibleSettingCardGroup(self.tr("YouTube 下载"), "ytdlp", parent)+ installFolderCard = SelectFolderSettingCard(+ ytDlpConfig.installFolder, f"{APP_DATA_DIR}/YtDlp",self.tr("yt-dlp 安装目录"),- self.tr("选择 yt-dlp 安装目录"),- self.group,+ group,)- self.runtimeCard = YtDlpRuntimeCard(self.group)- self.group.addSettingCards([- self.installFolderCard,- self.runtimeCard,+ runtimeCard = RuntimeCard(ytDlpRuntime, group)+ installFolderCard.pathChanged.connect(runtimeCard._onInstallFolderChanged)++ group.addSettingCards([+ installFolderCard,+ runtimeCard,+ SpinBoxSettingCard(+ FluentIcon.SPEED_HIGH,+ self.tr("并行分片数"),+ self.tr("同时下载的视频分片数量,越高越快但可能被限流"),+ configItem=self.parallelFragments,+ parent=group,+ ),+ ComboBoxSettingCard(+ self.loginBrowser,+ FluentIcon.PEOPLE,+ self.tr("登录浏览器"),+ self.tr("从指定浏览器读取 YouTube 登录状态,用于下载需要登录的内容"),+ texts=[self.tr("不使用"), "Chrome", "Firefox", "Edge", "Safari"],+ parent=group,+ ),+ SwitchSettingCard(+ FluentIcon.VIDEO,+ self.tr("优先 MP4 格式"),+ self.tr("优先选择 H.264/MP4 编码,避免输出 WebM/MKV"),+ self.shouldPreferMp4,+ group,+ ),+ SwitchSettingCard(+ FluentIcon.PHOTO,+ self.tr("嵌入缩略图"),+ self.tr("下载完成后通过 FFmpeg 将封面嵌入文件"),+ self.shouldEmbedThumbnail,+ group,+ ),+ SwitchSettingCard(+ FluentIcon.BOOK_SHELF,+ self.tr("嵌入章节"),+ self.tr("下载完成后通过 FFmpeg 将章节标记嵌入文件"),+ self.shouldEmbedChapters,+ group,+ ),+ SwitchSettingCard(+ FluentIcon.INFO,+ self.tr("嵌入元数据"),+ self.tr("下载完成后通过 FFmpeg 将标题、作者等信息嵌入文件"),+ self.shouldEmbedMetadata,+ group,+ ),])-- self.installFolderCard.pathChanged.connect(lambda _: self.runtimeCard.refreshStatus())- settingPage.addSettingGroup(self.group)- self.runtimeCard.refreshStatus()+ runtimeCard.refreshStatus()+ return [group]ytDlpConfig = YtDlpConfig()+++class YtDlpRuntime(BinaryRuntime):+ name = "yt-dlp"+ canInstall = not IS_ANDROID++ def path(self) -> str:+ return findExecutable(Path(ytDlpConfig.installFolder.value), "yt-dlp")++ async def installTask(self) -> Task:+ from app.services.feature_service import featureService+ from app.models.task import BinaryInstallOptions++ machine = platform.machine().lower()+ if sys.platform == "win32":+ asset = "yt-dlp.exe"+ elif sys.platform == "darwin":+ asset = "yt-dlp_macos"+ elif machine in {"arm64", "aarch64"}:+ asset = "yt-dlp_linux_aarch64"+ else:+ asset = "yt-dlp_linux"++ binaryName = "yt-dlp.exe" if sys.platform == "win32" else "yt-dlp"+ url = f"https://github.com/yt-dlp/yt-dlp/releases/latest/download/{asset}"+ return await featureService.parse(BinaryInstallOptions(+ url=url,+ outputFolder=Path(ytDlpConfig.installFolder.value),+ name=f"yt-dlp 安装 ({asset})",+ executableNames=(binaryName,),+ ))+++ytDlpRuntime = YtDlpRuntime()diff --git a/features/yt_dlp_pack/pack.py b/features/yt_dlp_pack/pack.pyindex 730bc354..a2a8c245 100644--- a/features/yt_dlp_pack/pack.py+++ b/features/yt_dlp_pack/pack.py@@ -1,124 +1,118 @@-import platform-import sys-from pathlib import Path-from urllib.parse import urlparse--import niquests--from app.bases.interfaces import FeaturePack-from app.bases.models import Task-from app.supports.config import activeUserAgent, cfg, defaultHeaders-from app.supports.utils import getProxies, toExecutable, toPosixPath, toSafeFilename-from .config import ytDlpConfig-from .task import DEFAULT_VIDEO_FORMAT, YtDlpInstallStage, YtDlpTask, YtDlpTaskStage, probeMediaInfo--_YTDLP_RELEASE_API = "https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest"-_YTDLP_RELEASE_HEADERS = {- "accept": "application/vnd.github+json",- "user-agent": activeUserAgent(),-}-_YOUTUBE_HOSTS = ("youtube.com", "youtu.be")---def _assetName() -> str:- machine = platform.machine().lower()- if sys.platform == "win32":- return "yt-dlp.exe"- if sys.platform == "darwin":- return "yt-dlp_macos"- if machine in {"arm64", "aarch64"}:- return "yt-dlp_linux_aarch64"- return "yt-dlp_linux"---class YtDlpPack(FeaturePack):- packId = "ytdlp"+from __future__ import annotations++import asyncio+import json+from urllib.parse import urlparse, parse_qs++from app.models.pack import FeaturePack, TaskParser+from app.models.task import Task, TaskOptions, SpecialFileSize+from app.platform.filesystem import toSafeFilename+from .config import ytDlpConfig, ytDlpRuntime+from .task import DEFAULT_VIDEO_FORMAT, YtDlpTask, YtDlpTaskStep, toInt+++YOUTUBE_HOSTS = ("youtube.com", "youtu.be")+++class YouTubeParser(TaskParser):priority = 70- config = ytDlpConfig-- def matches(self, url: str) -> bool:- host = (urlparse(url).hostname or "").lower()- return any(host == h or host.endswith(f".{h}") for h in _YOUTUBE_HOSTS)-- def resultCard(self, task, parent=None):- from .cards import YtDlpResultCard- return YtDlpResultCard(task, parent)-- async def parse(self, payload: dict) -> Task:- url = payload["url"].strip()- proxies = payload.get("proxies", getProxies())- if not isinstance(proxies, dict):- proxies = {}- path = Path(payload.get("path", cfg.downloadFolder.value))- rawHeaders = payload.get("headers")- headers = rawHeaders.copy() if isinstance(rawHeaders, dict) and rawHeaders else {}- videoFormat = DEFAULT_VIDEO_FORMAT- probedTitle, probedSize = await probeMediaInfo(url, proxies, videoFormat, headers)- title = toSafeFilename(probedTitle or payload.get("pageTitle") or "YouTube 视频")-- task = YtDlpTask(title=title, url=url, fileSize=probedSize, path=path)- task.addStage(YtDlpTaskStage(- stageIndex=1,- videoFormat=videoFormat,++ def match(self, options: TaskOptions) -> bool:+ host = (urlparse(options.url).hostname or "").lower()+ return any(host == h or host.endswith(f".{h}") for h in YOUTUBE_HOSTS)++ async def parse(self, options: TaskOptions) -> Task:+ url = options.url.strip()+ headers = dict(options.headers)++ mediaInfo = {}+ stdout = await self._runCommand([url, "--dump-json", "--no-playlist", "--no-warnings"])+ if stdout:+ mediaInfo = json.loads(stdout.decode("utf-8", errors="ignore"))++ title = str(mediaInfo.get("title") or "").strip()+ name = toSafeFilename(title) if title else "YouTube 视频"+ fileSize = toInt(str(mediaInfo.get("filesize_approx") or 0)) or SpecialFileSize.UNKNOWN+ isPlaylist = bool(parse_qs(urlparse(url).query).get("list"))++ task = YtDlpTask(+ name=f"{name}.mp4",+ url=url,+ fileSize=fileSize,+ outputFolder=options.outputFolder,+ isPlaylist=isPlaylist,+ )+ task.addStep(YtDlpTaskStep(+ stepIndex=1,headers=headers,- proxies=proxies,))++ task._mediaInfo = mediaInforeturn task+ async def probePlaylist(self, url: str) -> list[dict]:+ stdout = await self._runCommand([url, "--flat-playlist", "--dump-json", "--no-warnings"], timeout=60)+ entries: list[dict] = []+ if stdout:+ for line in stdout.decode("utf-8", errors="ignore").strip().splitlines():+ line = line.strip()+ if line:+ try:+ entries.append(json.loads(line))+ except json.JSONDecodeError:+ continue+ return entries++ async def _runCommand(self, args: list[str], timeout: int = 30) -> bytes | None:+ execPath = ytDlpRuntime.path()+ if not execPath:+ return None++ from app.config.cfg import proxy+ proxyUrl = proxy()+ if proxyUrl:+ args.extend(["--proxy", proxyUrl])+ browser = ytDlpConfig.loginBrowser.value+ if browser:+ args.extend(["--cookies-from-browser", browser])++ process = await asyncio.create_subprocess_exec(+ execPath, *args,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)+ if process.returncode == 0:+ return stdout-async def createInstallTask() -> Task:- from app.services.feature_service import featureService- from disk_pack.task import InstallTask+ errorText = stderr.decode("utf-8", errors="ignore").strip()+ for line in reversed(errorText.splitlines()):+ if "ERROR:" in line:+ errorText = line.split("ERROR:", 1)[-1].strip()+ break+ raise RuntimeError(errorText or f"yt-dlp 退出码异常: {process.returncode}")- assetName = _assetName()- installFolder = Path(ytDlpConfig.installFolder.value)- binaryPath = installFolder / toExecutable("yt-dlp")- async with niquests.AsyncSession(headers=_YTDLP_RELEASE_HEADERS, timeout=30, happy_eyeballs=True) as client:- client.trust_env = False- response = await client.get(- _YTDLP_RELEASE_API,- proxies=getProxies(),- verify=cfg.SSLVerify.value,- allow_redirects=True,- )- response.raise_for_status()- payload = response.json()-- assets = payload.get("assets")- if not isinstance(assets, list):- raise RuntimeError("GitHub Release 返回了无效的 assets 数据")-- asset = next((item for item in assets if item.get("name") == assetName), None)- if asset is None:- raise RuntimeError(f"未找到适用于当前平台的 yt-dlp 安装包: {assetName}")-- downloadUrl = asset["browser_download_url"].strip()- size = asset["size"]- if not downloadUrl or size <= 0:- raise RuntimeError("GitHub Release 返回了不完整的安装包信息")-- downloadTask = await featureService.parse({- "url": downloadUrl,- "headers": defaultHeaders(),- "proxies": getProxies(),- "path": installFolder,- })- if not downloadTask.stages:- raise RuntimeError("解析 yt-dlp 下载链接后未获取到下载阶段")- downloadStage = downloadTask.stages[0]- downloadStage.stageIndex = 1- downloadStage.outputFile = toPosixPath(binaryPath)-- task = InstallTask(- title=f"yt-dlp 安装 ({assetName})",- url=downloadUrl,- packId="ytdlp",- fileSize=size,- path=installFolder,- usesSlot=False,- installFolder=str(installFolder),- )- task.addStage(downloadStage)- task.addStage(YtDlpInstallStage(stageIndex=2, binaryPath=toPosixPath(binaryPath)))- return task+class YouTubePack(FeaturePack):+ packId = "ytdlp"++ def __init__(self):+ self.config = ytDlpConfig++ def parsers(self):+ return [YouTubeParser()]++ def taskCard(self, task, parent=None):+ from .cards import YtDlpTaskCard+ return YtDlpTaskCard(task, parent)++ def draftCard(self, task, parent=None):+ from .cards import YtDlpDraftCard+ return YtDlpDraftCard(task, parent)++ def optionCards(self, task, parent=None):+ from app.view.components.option_cards import OutputFolderCard+ return [+ OutputFolderCard(parent, initial=task.outputFolder),+ ]diff --git a/features/yt_dlp_pack/task.py b/features/yt_dlp_pack/task.pyindex 1b182498..6a31acd8 100644--- a/features/yt_dlp_pack/task.py+++ b/features/yt_dlp_pack/task.py@@ -1,42 +1,25 @@+from __future__ import annotations+import asyncio-import sysfrom contextlib import suppressfrom dataclasses import dataclass, fieldfrom pathlib import Path-from typing import ClassVar, TYPE_CHECKING--from app.bases.interfaces import Worker-from app.bases.models import SpecialFileSize, Task, TaskStage, TaskStatus-from app.supports.utils import removePath, toPosixPath-from .config import downloaderPath--if TYPE_CHECKING:- from features.ffmpeg_pack.config import ffmpegPaths-else:- from ffmpeg_pack.config import ffmpegPaths+from app.models.task import Task, TaskStep, TaskStatus+from app.platform.filesystem import toPosixPath+from .config import ytDlpConfig, ytDlpRuntime-_PROGRESS_SENTINEL = "#GD3PROG#"-_FINAL_SENTINEL = "#GD3FILE#"-_PROGRESS_TEMPLATE = (- f"download:{_PROGRESS_SENTINEL}"+DEFAULT_VIDEO_FORMAT = "bv*+ba/b"+PROGRESS_TOKEN = "__GD3_PROGRESS__"+FINAL_FILE_TOKEN = "__GD3_FINAL__"+PROGRESS_TEMPLATE = (+ f"download:{PROGRESS_TOKEN}""%(progress.downloaded_bytes)s|%(progress.total_bytes)s|""%(progress.total_bytes_estimate)s|%(progress.speed)s")-_FINAL_TEMPLATE = f"after_move:{_FINAL_SENTINEL}%(filepath)s"-_OUTPUT_TEMPLATE = "%(title)s.%(ext)s"--DEFAULT_VIDEO_FORMAT = "bv*+ba/b"-+FINAL_TEMPLATE = f"after_move:{FINAL_FILE_TOKEN}%(filepath)s"-def _toInt(value: str) -> int:- try:- return int(float(value))- except (TypeError, ValueError):- return 0---_ERROR_HINTS = (+ERROR_HINTS = (("is not available in your country", "该视频在当前地区不可用,可在设置里配置代理后重试"),("video unavailable", "视频不可用(可能已被删除或设为私有)"),("private video", "私有视频,需要有权限账号的 cookies"),@@ -48,156 +31,166 @@ _ERROR_HINTS = ()-def _toFriendlyError(message: str) -> str:- lowered = message.lower()- for needle, hint in _ERROR_HINTS:- if needle in lowered:- return hint- return message---def _networkArgs(proxies: dict | None, headers: dict | None) -> list[str]:- args: list[str] = []- proxyUrl = next((v for v in (proxies or {}).values() if v), "")- if proxyUrl:- args.extend(["--proxy", proxyUrl])- for name, value in (headers or {}).items():- text = str(value).strip()- if text:- args.extend(["--add-header", f"{name}:{text}"])- return args---async def probeMediaInfo(url: str, proxies: dict | None, videoFormat: str, headers: dict | None = None) -> tuple[str, int]:- """探测真实标题与选定画质的预估总大小;受限/超时回落 ("", UNKNOWN)。"""- execPath = downloaderPath()- if not execPath:- return "", SpecialFileSize.UNKNOWN-- args = [- url, "-f", videoFormat, "--no-playlist", "--skip-download", "--no-warnings",- "--print", "%(title)s", "--print", "%(filesize_approx)s",- *_networkArgs(proxies, headers),- ]+def toInt(value: str) -> int:try:- process = await asyncio.create_subprocess_exec(- execPath, *args,- stdin=asyncio.subprocess.DEVNULL,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.DEVNULL,- )- stdout, _ = await asyncio.wait_for(process.communicate(), timeout=20)- except asyncio.TimeoutError:- process.kill()- with suppress(Exception):- await process.wait()- return "", SpecialFileSize.UNKNOWN- except OSError:- return "", SpecialFileSize.UNKNOWN+ return int(float(value))+ except (TypeError, ValueError):+ return 0- if process.returncode != 0:- return "", SpecialFileSize.UNKNOWN- lines = stdout.decode("utf-8", errors="ignore").strip().splitlines()- title = lines[0].strip() if lines else ""- size = _toInt(lines[1]) if len(lines) > 1 else SpecialFileSize.UNKNOWN- return title, size+@dataclass(kw_only=True, eq=False)+class YtDlpTask(Task):+ packId: str = "ytdlp"+ canEdit = True+ videoFormat: str = DEFAULT_VIDEO_FORMAT+ subtitleLanguages: str = ""+ shouldIncludeAutoSubs: bool = False+ isPlaylist: bool = False+ videos: list[dict] = field(default_factory=list)++ def currentSnapshot(self) -> tuple[float, int, int]:+ if not self.steps or len(self.steps) == 1:+ return super().currentSnapshot()+ completedCount = sum(1 for s in self.steps if s.status == TaskStatus.COMPLETED)+ currentStep = next((s for s in self.steps if s.status == TaskStatus.RUNNING), None)+ totalCount = len(self.steps)+ if currentStep:+ progress = (completedCount * 100 + currentStep.progress) / totalCount+ speed = currentStep.speed+ else:+ progress = completedCount * 100 / totalCount+ speed = 0+ receivedBytes = sum(s.receivedBytes for s in self.steps)+ return progress, speed, receivedBytes++ def setVideos(self, videos: list[dict]) -> None:+ self.videos = videos+ self._rebuildSteps()++ def setSelectedVideos(self, indices: set[int]) -> None:+ for i, video in enumerate(self.videos):+ video["selected"] = i in indices+ self._rebuildSteps()++ def _rebuildSteps(self) -> None:+ self._savedHeaders = self.steps[0].headers if self.steps else getattr(self, "_savedHeaders", {})+ self.steps.clear()+ if not self.videos:+ self.addStep(YtDlpTaskStep(stepIndex=1, headers=self._savedHeaders))+ return+ for video in self.videos:+ if not video.get("selected", True):+ continue+ self.addStep(YtDlpTaskStep(+ stepIndex=len(self.steps) + 1,+ videoUrl=f"https://www.youtube.com/watch?v={video['id']}",+ videoTitle=str(video.get("title") or ""),+ headers=self._savedHeaders,+ ))+ if not self.steps:+ self.addStep(YtDlpTaskStep(stepIndex=1, headers=self._savedHeaders))@dataclass(kw_only=True)-class YtDlpTaskStage(TaskStage):- workerType: type = field(init=False, repr=False)-- videoFormat: str = DEFAULT_VIDEO_FORMAT+class YtDlpTaskStep(TaskStep):+ videoUrl: str = ""+ videoTitle: str = ""+ outputFile: str = ""headers: dict[str, str] = field(default_factory=dict)- proxies: dict[str, str] = field(default_factory=dict)lastMessage: str = ""@property- def tempDir(self) -> str:- return toPosixPath(Path(self.task.path) / ".gd3_ytdlp" / self.task.taskId)-- def cleanup(self):- removePath(Path(self.tempDir))---@dataclass(kw_only=True, eq=False)-class YtDlpTask(Task):- packId: str = "ytdlp"- supportsEdit: ClassVar[bool] = True-- @property- def stage(self) -> "YtDlpTaskStage":- return self.stages[0]-- def editorCards(self, parent):- from qfluentwidgets import FluentIcon+ def _outputTemplate(self) -> str:+ return toPosixPath(self.task.outputFolder / "%(title)s.%(ext)s")- from app.view.components.add_task_dialog import SelectFolderCard+ def _buildCommand(self) -> list[str]:+ from ffmpeg_pack.config import ffmpegRuntime- return [- SelectFolderCard(FluentIcon.DOWNLOAD, parent.tr("下载到"), parent, initial=self.path),- ]-- def applySettings(self, payload: dict):- super().applySettings(payload)- if "videoFormat" in payload:- self.stage.videoFormat = payload["videoFormat"]---class YtDlpWorker(Worker):- def __init__(self, stage: YtDlpTaskStage):- super().__init__(stage)- self.stage = stage- self._finalPath = ""- self._streamBytes: dict[int, int] = {}-- def _buildArgs(self) -> list[str]:- stage = self.stage+ url = self.videoUrl or self.task.url+ task: YtDlpTask = self.taskargs = [- stage.task.url,- "-f", stage.videoFormat,- "-o", _OUTPUT_TEMPLATE,- "-P", f"home:{toPosixPath(stage.task.path)}",- "-P", f"temp:{stage.tempDir}",+ url,+ "-f", task.videoFormat,+ "-o", self._outputTemplate,"--no-playlist","--newline","--no-color","--no-simulate","--progress",- "--progress-template", _PROGRESS_TEMPLATE,- "--print", _FINAL_TEMPLATE,- *_networkArgs(stage.proxies, stage.headers),+ "--progress-template", PROGRESS_TEMPLATE,+ "--print", FINAL_TEMPLATE,]- ffmpegPath, _ = ffmpegPaths()++ if ytDlpConfig.shouldPreferMp4.value:+ args.extend(["--format-sort", "ext:mp4:m4a"])++ ffmpegPath = ffmpegRuntime.path()if ffmpegPath:args.extend(["--ffmpeg-location", ffmpegPath])++ from app.config.cfg import cfg, proxy+ proxyUrl = proxy()+ if proxyUrl:+ args.extend(["--proxy", proxyUrl])+ if cfg.isSpeedLimitEnabled.value:+ args.extend(["--limit-rate", str(cfg.speedLimitation.value)])++ fragments = ytDlpConfig.parallelFragments.value+ if fragments > 1:+ args.extend(["--concurrent-fragments", str(fragments)])++ browser = ytDlpConfig.loginBrowser.value+ if browser:+ args.extend(["--cookies-from-browser", browser])++ if task.subtitleLanguages:+ args.extend(["--write-subs", "--sub-langs", task.subtitleLanguages])+ if task.shouldIncludeAutoSubs:+ args.append("--write-auto-subs")++ if ytDlpConfig.shouldEmbedThumbnail.value:+ # Convert to jpg so embedding never needs FFmpeg's png/zlib path — our+ # minimal FFmpeg ships mjpeg only (webp/jpg thumbnails, no png).+ args.extend(["--embed-thumbnail", "--convert-thumbnails", "jpg"])+ if ytDlpConfig.shouldEmbedChapters.value:+ args.append("--embed-chapters")+ if ytDlpConfig.shouldEmbedMetadata.value:+ args.append("--embed-metadata")++ for name, value in self.headers.items():+ text = value.strip()+ if text:+ args.extend(["--add-header", f"{name}:{text}"])+return args- def _parseOutputLine(self, line: str):+ def _parseOutputLine(self, line: str) -> None:text = line.strip()if not text:return- if text.startswith(_FINAL_SENTINEL):- self._finalPath = text[len(_FINAL_SENTINEL):].strip()+ if text.startswith(FINAL_FILE_TOKEN):+ self._finalPath = text[len(FINAL_FILE_TOKEN):].strip()return- if text.startswith(_PROGRESS_SENTINEL):- parts = text[len(_PROGRESS_SENTINEL):].split("|")+ if text.startswith(PROGRESS_TOKEN):+ parts = text[len(PROGRESS_TOKEN):].split("|")if len(parts) >= 4:- downloaded = _toInt(parts[0])- total = _toInt(parts[1]) or _toInt(parts[2])- self.stage.speed = _toInt(parts[3])+ downloaded = toInt(parts[0])+ total = toInt(parts[1]) or toInt(parts[2])+ self.speed = toInt(parts[3])+ self.receivedBytes = self._completedBytes + downloadedif total > 0:- self._streamBytes[total] = downloaded- received = sum(self._streamBytes.values())- self.stage.task.fileSize = max(self.stage.task.fileSize, sum(self._streamBytes.keys()))- self.stage.receivedBytes = received- if self.stage.task.fileSize > 0:- self.stage.progress = min(99.5, received / self.stage.task.fileSize * 100)+ if self._totalBytes > 0 and total != self._totalBytes:+ self._completedBytes += self._totalBytes+ self.receivedBytes += self._totalBytes+ self._totalBytes = total+ allTotal = self._completedBytes + total+ if len(self.task.steps) == 1:+ self.task.fileSize = max(self.task.fileSize, allTotal)+ self.progress = min(99.5, self.receivedBytes / allTotal * 100)return- self.stage.lastMessage = text[:1000]+ self.lastMessage = text[:1000]- async def supervisor(self, stream: asyncio.StreamReader):+ async def _readOutput(self, stream: asyncio.StreamReader) -> None:buffer = ""while True:chunk = await stream.read(4096)@@ -212,94 +205,59 @@ class YtDlpWorker(Worker):if buffer.strip():self._parseOutputLine(buffer)- def _applyFinalFile(self):- if not self._finalPath:- return- path = Path(self._finalPath)- if not path.is_file():- return- size = path.stat().st_size- if size <= 0:- return- self.stage.task.fileSize = max(self.stage.task.fileSize, size)- if path.name != self.stage.task.title:- self.stage.task.setTitle(path.name)-- async def run(self):- execPath = downloaderPath()+ async def run(self) -> None:+ execPath = ytDlpRuntime.path()if not execPath:raise RuntimeError("未找到可用的 yt-dlp,请先在设置中安装或配置运行时")- self.stage.task.path.mkdir(parents=True, exist_ok=True)- process = None- supervisorTask = None- try:- process = await asyncio.create_subprocess_exec(- execPath,- *self._buildArgs(),- cwd=Path(execPath).parent,- stdin=asyncio.subprocess.DEVNULL,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.STDOUT,- )- supervisorTask = asyncio.create_task(self.supervisor(process.stdout))+ self._finalPath = ""+ self._totalBytes = 0+ self._completedBytes = 0+ self.task.outputFolder.mkdir(parents=True, exist_ok=True)+ process = await asyncio.create_subprocess_exec(+ execPath,+ *self._buildCommand(),+ cwd=Path(execPath).parent,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.STDOUT,+ )+ readerTask = asyncio.create_task(self._readOutput(process.stdout))++ try:await process.wait()- await supervisorTask+ await readerTaskif process.returncode != 0:- raise RuntimeError(_toFriendlyError(self.stage.lastMessage) or f"yt-dlp 退出码异常: {process.returncode}")-- self._applyFinalFile()- self.stage.cleanup()- self.stage.setStatus(TaskStatus.COMPLETED)+ lowered = self.lastMessage.lower()+ hint = next((h for needle, h in ERROR_HINTS if needle in lowered), "")+ raise RuntimeError(hint or self.lastMessage or f"yt-dlp 退出码异常: {process.returncode}")++ if self._finalPath:+ self.outputFile = self._finalPath+ path = Path(self._finalPath)+ if path.is_file() and path.stat().st_size > 0:+ if len(self.task.steps) == 1:+ self.task.fileSize = max(self.task.fileSize, path.stat().st_size)+ if path.name != self.task.name:+ self.task.setName(path.name)++ self.setStatus(TaskStatus.COMPLETED)except asyncio.CancelledError:- if process is not None and process.returncode is None:+ if process.returncode is None:process.terminate()try:await asyncio.wait_for(process.wait(), timeout=3)except asyncio.TimeoutError:process.kill()await process.wait()- if supervisorTask is not None and not supervisorTask.done():- supervisorTask.cancel()+ if not readerTask.done():+ readerTask.cancel()with suppress(asyncio.CancelledError):- await supervisorTask- self.stage.setStatus(TaskStatus.PAUSED)- raise- except Exception as e:- self.stage.setError(e)- raise---@dataclass(kw_only=True)-class YtDlpInstallStage(TaskStage):- workerType: type = field(init=False, repr=False)- canPause: bool = field(init=False, default=False)-- binaryPath: str---class YtDlpInstallWorker(Worker):- def __init__(self, stage: YtDlpInstallStage):- super().__init__(stage)- self.stage = stage-- async def run(self):- path = Path(self.stage.binaryPath)- try:- if not path.is_file():- raise FileNotFoundError(f"未找到已下载的 yt-dlp: {path}")- if sys.platform != "win32":- path.chmod(path.stat().st_mode | 0o755)- self.stage.setStatus(TaskStatus.COMPLETED)- except asyncio.CancelledError:- self.stage.setStatus(TaskStatus.PAUSED)+ await readerTask+ self.setStatus(TaskStatus.PAUSED)raiseexcept Exception as e:- self.stage.setError(e)+ self.setError(e)raise---YtDlpTaskStage.workerType = YtDlpWorker-YtDlpInstallStage.workerType = YtDlpInstallWorker