The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(bittorrent): 添加BitTorrent功能支持
XiaoYouChR281987dcf5c9
diff --git a/app/bases/models.py b/app/bases/models.pyindex 7727acfe..890170da 100644--- a/app/bases/models.py+++ b/app/bases/models.py@@ -1,4 +1,4 @@-from dataclasses import asdict, dataclass, field, is_dataclass+from dataclasses import asdict, dataclass, field, fields as dataclass_fields, is_dataclassfrom enum import auto, IntEnumfrom pathlib import Pathfrom time import time_ns@@ -32,6 +32,11 @@ def _toSerializable(obj: Any) -> Any:return obj+def _filterDataclassKwargs(cls: type, obj: dict[str, Any]) -> dict[str, Any]:+ allowed = {field.name for field in dataclass_fields(cls) if field.init}+ return {key: value for key, value in obj.items() if key in allowed}++class TaskStatus(IntEnum):"""Enumeration for the lifecycle status of an individual TaskStage.@@ -119,7 +124,7 @@ class TaskStage:if "path" in obj and isinstance(obj["path"], str):obj["path"] = Path(obj["path"])- return stageCls(**obj)+ return stageCls(**_filterDataclassKwargs(stageCls, obj))@dataclass(kw_only=True)@@ -245,13 +250,19 @@ class Task:stages.append(TaskStage.deserialize(raw))obj["stages"] = stages- return targetCls(**obj)+ return targetCls(**_filterDataclassKwargs(targetCls, obj))def applyPayloadToTask(self, payload: dict[str, Any]):path = payload.get("path")if isinstance(path, (str, Path)):self.path = Path(path)+ def occupiesDownloadSlot(self) -> bool:+ return self.status == TaskStatus.RUNNING++ def willOccupyDownloadSlotWhenStarted(self) -> bool:+ return True+async def run(self):self.stages.sort(key=lambda stage: stage.stageIndex)raise NotImplementedErrordiff --git a/app/services/core_service.py b/app/services/core_service.pyindex 6067b051..bbb884c1 100644--- a/app/services/core_service.py+++ b/app/services/core_service.py@@ -146,8 +146,17 @@ class CoreService(QThread):return callbackId+ def _downloadSlotTaskIds(self) -> list[str]:+ taskIds: list[str] = []+ for taskId in self.runningTasks:+ task = self.getTaskById(taskId)+ if task is None or not task.occupiesDownloadSlot():+ continue+ taskIds.append(taskId)+ return taskIds+def _runningTaskCount(self) -> int:- return sum(1 for task in self.tasks if task.status == TaskStatus.RUNNING)+ return len(self._downloadSlotTaskIds())def _removeWaitingTask(self, task: Task):self.waitingTasks = [queuedTask for queuedTask in self.waitingTasks if queuedTask.taskId != task.taskId]@@ -166,6 +175,9 @@ class CoreService(QThread):if self.loop.is_running():self.loop.call_soon_threadsafe(lambda: self.loop.create_task(self._syncTaskLimit()))+ def notifyTaskSchedulingChanged(self):+ self._syncTaskLimitSoon()+def _scheduleWaitingTasks(self):while self.waitingTasks and self._runningTaskCount() < cfg.maxTaskNum.value:task = self.waitingTasks.pop(0)@@ -192,10 +204,7 @@ class CoreService(QThread):self._enqueueTask(task)async def _syncTaskLimit(self):- runningTaskIds = [- taskId for taskId in self.runningTasks- if (task := self.getTaskById(taskId)) and task.status == TaskStatus.RUNNING- ]+ runningTaskIds = self._downloadSlotTaskIds()overflowTaskIds = runningTaskIds[cfg.maxTaskNum.value:]for taskId in overflowTaskIds:@@ -218,7 +227,7 @@ class CoreService(QThread):if task.taskId in self.runningTasks:return- if self._runningTaskCount() >= cfg.maxTaskNum.value:+ if task.willOccupyDownloadSlotWhenStarted() and self._runningTaskCount() >= cfg.maxTaskNum.value:self._enqueueTask(task)returndiff --git a/features/bittorrent_pack/cards.py b/features/bittorrent_pack/cards.pynew file mode 100644index 00000000..f1f8c331--- /dev/null+++ b/features/bittorrent_pack/cards.py@@ -0,0 +1,375 @@+import shutil+from pathlib import Path, PurePosixPath++from PySide6.QtCore import Qt+from PySide6.QtWidgets import (+ QHeaderView,+ QHBoxLayout,+ QTreeWidget,+ QTreeWidgetItem,+ QVBoxLayout,+ QWidget,+)+from qfluentwidgets import (+ BodyLabel,+ CaptionLabel,+ FluentIcon,+ ImageLabel,+ InfoBar,+ MessageBoxBase,+ PrimaryPushButton,+ PushButton,+ StrongBodyLabel,+ ToolButton,+)++from app.bases.models import TaskStatus+from app.supports.utils import getReadableSize, getReadableTime+from app.view.components.cards import ResultCard, UniversalTaskCard+from app.view.components.labels import IconBodyLabel++from .task import BitTorrentFile, BitTorrentTask+++def _removePath(path: Path):+ if not path.exists():+ return+ if path.is_dir():+ shutil.rmtree(path, ignore_errors=True)+ return+ path.unlink(missing_ok=True)+++def _openFileSelection(task: BitTorrentTask, parent) -> set[int] | None:+ dialog = TorrentFileSelectDialog(task, parent)+ try:+ if not dialog.exec():+ return None+ selectedIndexes = dialog.selectedIndexes()+ task.updateSelectedFiles(selectedIndexes)+ return selectedIndexes+ finally:+ dialog.deleteLater()+++def _setIcon(label: IconBodyLabel, icon: FluentIcon):+ label.icon = icon+ label.cachedIconKey = label.preCacheIcon()+ label.update()+++class TorrentFileSelectDialog(MessageBoxBase):+ def __init__(self, task: BitTorrentTask, parent=None):+ super().__init__(parent=parent)+ self.task = task+ self._itemToFile: dict[QTreeWidgetItem, BitTorrentFile] = {}+ self._updatingChecks = False++ self.widget.setMinimumSize(720, 520)+ self.titleLabel = StrongBodyLabel(self.tr("选择下载文件"), self.widget)+ self.summaryLabel = CaptionLabel("", self.widget)+ self.treeWidget = QTreeWidget(self.widget)+ self.actionsWidget = QWidget(self.widget)+ self.actionsLayout = QHBoxLayout(self.actionsWidget)+ self.selectAllButton = PushButton(self.tr("全选"), self.actionsWidget)+ self.clearButton = PushButton(self.tr("全不选"), self.actionsWidget)++ self.yesButton.setText(self.tr("应用"))+ self.cancelButton.setText(self.tr("取消"))++ self._initWidget()+ self._buildTree()+ self._updateSummary()++ def _initWidget(self):+ self.treeWidget.setColumnCount(2)+ self.treeWidget.setHeaderLabels([self.tr("文件"), self.tr("大小")])+ self.treeWidget.header().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)+ self.treeWidget.header().setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)+ self.treeWidget.itemChanged.connect(self._onItemChanged)++ self.actionsLayout.setContentsMargins(0, 0, 0, 0)+ self.actionsLayout.setSpacing(8)+ self.actionsLayout.addWidget(self.selectAllButton)+ self.actionsLayout.addWidget(self.clearButton)+ self.actionsLayout.addStretch(1)++ self.selectAllButton.clicked.connect(self._selectAll)+ self.clearButton.clicked.connect(self._clearAll)++ self.viewLayout.addWidget(self.titleLabel)+ self.viewLayout.addWidget(self.summaryLabel)+ self.viewLayout.addSpacing(8)+ self.viewLayout.addWidget(self.treeWidget)+ self.viewLayout.addSpacing(8)+ self.viewLayout.addWidget(self.actionsWidget)++ def _buildTree(self):+ folderItems: dict[tuple[str, ...], QTreeWidgetItem] = {}+ self._updatingChecks = True+ try:+ for file in self.task.files:+ path = PurePosixPath(self.task.mappedRelativePath(file))+ parts = path.parts+ parent = self.treeWidget.invisibleRootItem()+ prefix: list[str] = []++ for part in parts[:-1]:+ prefix.append(part)+ key = tuple(prefix)+ item = folderItems.get(key)+ if item is None:+ item = QTreeWidgetItem(parent, [part, ""])+ item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsAutoTristate)+ item.setCheckState(0, Qt.CheckState.Unchecked)+ folderItems[key] = item+ parent = item++ item = QTreeWidgetItem(parent, [parts[-1], getReadableSize(file.size)])+ item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable)+ item.setCheckState(0, Qt.CheckState.Checked if file.selected else Qt.CheckState.Unchecked)+ self._itemToFile[item] = file++ self.treeWidget.expandAll()+ self._refreshParentCheckStates()+ finally:+ self._updatingChecks = False++ def _refreshParentCheckStates(self):+ root = self.treeWidget.invisibleRootItem()+ for i in range(root.childCount()):+ self._updateBranchState(root.child(i))++ def _updateBranchState(self, item: QTreeWidgetItem):+ if item.childCount() == 0:+ return item.checkState(0)++ states = []+ for i in range(item.childCount()):+ states.append(self._updateBranchState(item.child(i)))++ if all(state == Qt.CheckState.Checked for state in states):+ item.setCheckState(0, Qt.CheckState.Checked)+ elif all(state == Qt.CheckState.Unchecked for state in states):+ item.setCheckState(0, Qt.CheckState.Unchecked)+ else:+ item.setCheckState(0, Qt.CheckState.PartiallyChecked)+ return item.checkState(0)++ def _setChildrenState(self, item: QTreeWidgetItem, state: Qt.CheckState):+ for i in range(item.childCount()):+ child = item.child(i)+ child.setCheckState(0, state)+ self._setChildrenState(child, state)++ def _collectSelectedIndexes(self) -> set[int]:+ return {+ file.index+ for item, file in self._itemToFile.items()+ if item.checkState(0) == Qt.CheckState.Checked+ }++ def _updateSummary(self):+ selectedIndexes = self._collectSelectedIndexes()+ selectedFiles = [file for file in self.task.files if file.index in selectedIndexes]++ self.summaryLabel.setText(+ self.tr("已选择 {0}/{1} 个文件,共 {2}").format(+ len(selectedFiles),+ self.task.totalFileCount,+ getReadableSize(sum(file.size for file in selectedFiles)),+ )+ )++ def _onItemChanged(self, item: QTreeWidgetItem, column: int):+ if column != 0 or self._updatingChecks:+ return++ self._updatingChecks = True+ try:+ state = item.checkState(0)+ if item.childCount() > 0 and state != Qt.CheckState.PartiallyChecked:+ self._setChildrenState(item, state)+ self._refreshParentCheckStates()+ self._updateSummary()+ finally:+ self._updatingChecks = False++ def _setRootCheckState(self, state: Qt.CheckState):+ self._updatingChecks = True+ try:+ root = self.treeWidget.invisibleRootItem()+ for i in range(root.childCount()):+ item = root.child(i)+ item.setCheckState(0, state)+ self._setChildrenState(item, state)+ self._refreshParentCheckStates()+ self._updateSummary()+ finally:+ self._updatingChecks = False++ def _selectAll(self):+ self._setRootCheckState(Qt.CheckState.Checked)++ def _clearAll(self):+ self._setRootCheckState(Qt.CheckState.Unchecked)++ def validate(self) -> bool:+ if self._collectSelectedIndexes():+ return True++ InfoBar.warning(+ self.tr("至少选择一个文件"),+ self.tr("当前没有任何文件被勾选"),+ parent=self,+ )+ return False++ def selectedIndexes(self) -> set[int]:+ return self._collectSelectedIndexes()+++class BitTorrentResultCard(ResultCard):+ def __init__(self, task: BitTorrentTask, parent: QWidget = None):+ super().__init__(task, parent)+ self.task = task++ self.mainLayout = QHBoxLayout(self)+ self.textLayout = QVBoxLayout()+ self.iconLabel = ImageLabel(self)+ self.titleLabel = StrongBodyLabel(self.task.title, self)+ self.sourceLabel = CaptionLabel(self._sourceText(), self)+ self.summaryLabel = BodyLabel("", self)+ self.selectFilesButton = PrimaryPushButton(self.tr("选择文件"), self)++ self._initWidget()+ self._initLayout()+ self._refreshSummary()++ def _initWidget(self):+ self.setFixedHeight(56)+ self.iconLabel.setFixedSize(18, 18)+ icon = FluentIcon.DOCUMENT if self.task.isSingleFileTorrent else FluentIcon.FOLDER+ self.iconLabel.setImage(icon.icon().pixmap(18, 18))+ self.selectFilesButton.clicked.connect(self._onSelectFilesClicked)++ 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.AlignTop)+ self.mainLayout.addLayout(self.textLayout)+ self.mainLayout.addStretch(1)+ self.mainLayout.addWidget(self.summaryLabel)+ self.mainLayout.addSpacing(12)+ self.mainLayout.addWidget(self.selectFilesButton)++ 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++ def _refreshSummary(self):+ self.summaryLabel.setText(+ self.tr("{0}/{1} 个文件 · {2}").format(+ self.task.selectedFileCount,+ self.task.totalFileCount,+ getReadableSize(self.task.fileSize),+ )+ )++ def _onSelectFilesClicked(self):+ if _openFileSelection(self.task, self.window()) is not None:+ self._refreshSummary()++ def getTask(self) -> BitTorrentTask:+ return self.task+++class BitTorrentTaskCard(UniversalTaskCard):+ def __init__(self, task: BitTorrentTask, parent=None):+ self.metaInfoLabel = None+ self.selectFilesButton = None+ super().__init__(task, parent)+ self.task: BitTorrentTask = task+ _setIcon(self.speedLabel, FluentIcon.DOWNLOAD)+ _setIcon(self.leftTimeLabel, FluentIcon.SHARE)+ self.metaInfoLabel = IconBodyLabel("", FluentIcon.INFO, self)+ self.infoLayout.insertWidget(self.infoLayout.count() - 2, self.metaInfoLabel)+ self.selectFilesButton = ToolButton(FluentIcon.LIBRARY, self)+ self.hBoxLayout.insertWidget(self.hBoxLayout.count() - 3, self.selectFilesButton)+ self.selectFilesButton.clicked.connect(self._onSelectFilesClicked)+ self._refreshInfoLayout()++ def _metaText(self) -> str:+ stage = self.task.stage+ if stage is None:+ return ""++ parts: list[str] = []+ if stage.stateText and stage.stateText not in {"下载中", "做种中"}:+ parts.append(stage.stateText)+ if stage.isSeeding and stage.shareRatioPercent > 0:+ parts.append(self.tr("分享率 {0:.2f}%").format(stage.shareRatioPercent))+ if stage.isSeeding and stage.seedingTimeSeconds > 0:+ parts.append(self.tr("做种 {0}").format(getReadableTime(stage.seedingTimeSeconds)))+ if stage.peerCount or stage.seedCount:+ parts.append(+ self.tr("Peers {0} / Seeds {1}").format(+ stage.peerCount,+ stage.seedCount,+ )+ )+ return " · ".join(parts)++ def _refreshInfoLayout(self):+ stage = self.task.stage+ if self.task.status == TaskStatus.RUNNING and stage is not None:+ self.speedLabel.setText(f"{getReadableSize(stage.downloadRate)}/s")+ self.leftTimeLabel.setText(f"{getReadableSize(stage.uploadRate)}/s")+ metaText = self._metaText()+ self.metaInfoLabel.setText(metaText)+ self.metaInfoLabel.setVisible(bool(metaText))+ self.speedLabel.show()+ self.leftTimeLabel.show()+ self.progressLabel.show()+ if not metaText:+ self.metaInfoLabel.hide()+ self.infoLabel.hide()+ return++ self.metaInfoLabel.hide()++ def _onSelectFilesClicked(self):+ previousSelected = {file.index for file in self.task.files if file.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.reopenForAdditionalFiles():+ self.resumeTask()++ def refresh(self):+ super().refresh()+ self._refreshInfoLayout()+ self.verifyHashButton.setVisible(+ self.task.isSingleFileTorrent+ and self.task.status == TaskStatus.COMPLETED+ and Path(self.task.resolvePath).is_file()+ )+ self.selectFilesButton.setEnabled(self.task.status != TaskStatus.COMPLETED or self.task.hasUnselectedFiles)++ def onTaskDeleted(self, completely: bool = False):+ if not completely:+ return+ _removePath(Path(self.task.resolvePath))++ def onTaskFinished(self):+ super().onTaskFinished()+ self._refreshInfoLayout()diff --git a/features/bittorrent_pack/config.py b/features/bittorrent_pack/config.pynew file mode 100644index 00000000..7989945e--- /dev/null+++ b/features/bittorrent_pack/config.py@@ -0,0 +1,372 @@+from typing import TYPE_CHECKING++from qfluentwidgets import (+ BodyLabel,+ BoolValidator,+ ComboBoxSettingCard,+ ConfigItem,+ ConfigValidator,+ FluentIcon,+ InfoBar,+ LineEdit,+ MessageBoxBase,+ OptionsConfigItem,+ OptionsValidator,+ PlainTextEdit,+ PrimaryPushButton,+ RangeConfigItem,+ RangeSettingCard,+ RangeValidator,+ SettingCard,+ SettingCardGroup,+ SwitchSettingCard,+ ToolButton,+ ToolTipFilter,+)++from app.bases.models import PackConfig+from app.services.core_service import coreService+from app.supports.config import cfg+from app.view.components.setting_cards import SpinBoxSettingCard+from .trackers import fetchWebTrackers, formatTrackers, normalizeTrackerSource, parseTrackerText++if TYPE_CHECKING:+ from app.view.pages.setting_page import SettingPage+++DEFAULT_WEB_TRACKER_SOURCE = "https://cf.trackerslist.com/best.txt"+++class WebTrackerSourceValidator(ConfigValidator):+ def validate(self, value) -> bool:+ return bool(normalizeTrackerSource(str(value or "")))++ def correct(self, value) -> str:+ source = normalizeTrackerSource(str(value or ""))+ return source or DEFAULT_WEB_TRACKER_SOURCE+++class WebTrackerListValidator(ConfigValidator):+ def validate(self, value) -> bool:+ return isinstance(value, str)++ def correct(self, value) -> str:+ return value if isinstance(value, str) else ""+++def getCachedWebTrackers() -> list[str]:+ return parseTrackerText(bittorrentConfig.webTrackerList.value)+++def saveCachedWebTrackers(trackers: list[str]):+ cfg.set(bittorrentConfig.webTrackerList, formatTrackers(trackers))+++async def refreshConfiguredWebTrackers(sourceUrl: str | None = None) -> list[str]:+ source = normalizeTrackerSource(sourceUrl or bittorrentConfig.webTrackerSource.value)+ if not source:+ raise ValueError("Web Tracker 源地址无效")+ trackers = await fetchWebTrackers(source)+ cfg.set(bittorrentConfig.webTrackerSource, source)+ saveCachedWebTrackers(trackers)+ return trackers+++class WebTrackerDialog(MessageBoxBase):+ def __init__(self, parent=None):+ super().__init__(parent)+ self.widget.setMinimumSize(720, 560)+ self.sourceLabel = BodyLabel(self.tr("Tracker 源地址"), self.widget)+ self.sourceEdit = LineEdit(self.widget)+ self.trackersLabel = BodyLabel(self.tr("当前 Tracker 列表"), self.widget)+ self.trackersEdit = PlainTextEdit(self.widget)+ self.refreshButton = PrimaryPushButton(self.tr("从源刷新"), self.widget)++ self.yesButton.setText(self.tr("保存"))+ self.cancelButton.setText(self.tr("取消"))+ self.sourceEdit.setPlaceholderText(DEFAULT_WEB_TRACKER_SOURCE)+ self.sourceEdit.setText(bittorrentConfig.webTrackerSource.value)+ self.trackersEdit.setPlainText(bittorrentConfig.webTrackerList.value)+ self.refreshButton.clicked.connect(self._onRefreshClicked)++ self.viewLayout.addWidget(self.sourceLabel)+ self.viewLayout.addWidget(self.sourceEdit)+ self.viewLayout.addWidget(self.trackersLabel)+ self.viewLayout.addWidget(self.trackersEdit)+ self.viewLayout.addWidget(self.refreshButton, 0)++ def _onRefreshClicked(self):+ source = normalizeTrackerSource(self.sourceEdit.text())+ if not source:+ InfoBar.error(self.tr("源地址无效"), self.tr("请输入有效的 HTTP/HTTPS 地址"), parent=self)+ return++ self.refreshButton.setEnabled(False)+ self.refreshButton.setText(self.tr("刷新中..."))+ coreService.runCoroutine(fetchWebTrackers(source), self._onTrackersLoaded)++ def _onTrackersLoaded(self, result, error: str | None):+ self.refreshButton.setEnabled(True)+ self.refreshButton.setText(self.tr("从源刷新"))+ if error:+ InfoBar.error(self.tr("刷新失败"), error, parent=self)+ return+ self.trackersEdit.setPlainText(formatTrackers(result or []))+ InfoBar.success(+ self.tr("刷新完成"),+ self.tr("已加载 {0} 条 Tracker").format(len(result or [])),+ parent=self,+ )++ def validate(self) -> bool:+ source = normalizeTrackerSource(self.sourceEdit.text())+ if not source:+ InfoBar.error(self.tr("源地址无效"), self.tr("请输入有效的 HTTP/HTTPS 地址"), parent=self)+ return False++ cfg.set(bittorrentConfig.webTrackerSource, source)+ saveCachedWebTrackers(parseTrackerText(self.trackersEdit.toPlainText()))+ return True+++class WebTrackerCard(SettingCard):+ def __init__(self, parent=None):+ super().__init__(+ FluentIcon.GLOBE,+ self.tr("Web Tracker"),+ "",+ parent,+ )+ self.manageButton = PrimaryPushButton(self.tr("管理"), self)+ self.refreshButton = ToolButton(FluentIcon.SYNC, self)+ self.hBoxLayout.addWidget(self.manageButton, 0)+ self.hBoxLayout.addSpacing(8)+ self.hBoxLayout.addWidget(self.refreshButton, 0)+ self.hBoxLayout.addSpacing(16)+ self.refreshButton.setToolTip(self.tr("刷新缓存"))+ self.refreshButton.installEventFilter(ToolTipFilter(self.refreshButton))+ self.manageButton.clicked.connect(self._onManageClicked)+ self.refreshButton.clicked.connect(self._onRefreshClicked)+ self.refreshContent()++ def refreshContent(self):+ trackers = getCachedWebTrackers()+ self.setContent(+ self.tr("来源: {0}\n当前缓存: {1} 条 Tracker").format(+ bittorrentConfig.webTrackerSource.value,+ len(trackers),+ )+ )++ def _onManageClicked(self):+ dialog = WebTrackerDialog(self.window())+ try:+ if dialog.exec():+ self.refreshContent()+ finally:+ dialog.deleteLater()++ def _onRefreshClicked(self):+ self.refreshButton.setEnabled(False)+ coreService.runCoroutine(refreshConfiguredWebTrackers(), self._onRefreshFinished)++ def _onRefreshFinished(self, result, error: str | None):+ self.refreshButton.setEnabled(True)+ if error:+ InfoBar.error(self.tr("刷新 Web Tracker 失败"), error, parent=self.window())+ return+ self.refreshContent()+ InfoBar.success(+ self.tr("刷新完成"),+ self.tr("已缓存 {0} 条 Tracker").format(len(result or [])),+ parent=self.window(),+ )+++class BitTorrentConfig(PackConfig):+ listenPort = RangeConfigItem("BitTorrent", "ListenPort", 0, RangeValidator(0, 65535))+ metadataTimeout = RangeConfigItem("BitTorrent", "MetadataTimeout", 30, RangeValidator(5, 300))+ connectionsLimit = RangeConfigItem("BitTorrent", "ConnectionsLimit", 200, RangeValidator(20, 2000))+ downloadRateLimit = RangeConfigItem(+ "BitTorrent",+ "DownloadRateLimit",+ 0,+ RangeValidator(0, 1024 * 1024 * 100),+ )+ uploadRateLimit = RangeConfigItem(+ "BitTorrent",+ "UploadRateLimit",+ 0,+ RangeValidator(0, 1024 * 1024 * 100),+ )+ 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))+ enableWebTrackers = ConfigItem("BitTorrent", "EnableWebTrackers", True, BoolValidator())+ autoRefreshWebTrackers = ConfigItem("BitTorrent", "AutoRefreshWebTrackers", True, BoolValidator())+ webTrackerSource = ConfigItem(+ "BitTorrent",+ "WebTrackerSource",+ DEFAULT_WEB_TRACKER_SOURCE,+ WebTrackerSourceValidator(),+ )+ webTrackerList = ConfigItem("BitTorrent", "WebTrackerList", "", WebTrackerListValidator())+ storageMode = OptionsConfigItem(+ "BitTorrent",+ "StorageMode",+ "sparse",+ OptionsValidator(["sparse", "allocate"]),+ )++ def loadSettingCards(self, settingPage: "SettingPage"):+ self.bittorrentGroup = SettingCardGroup(self.tr("BitTorrent 下载"), settingPage.container)+ 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.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.sequentialDownloadCard,+ self.enableDHTCard,+ self.enableLSDCard,+ self.enableUPnPCard,+ self.enableNATPMPCard,+ self.enableWebTrackersCard,+ self.autoRefreshWebTrackersCard,+ self.webTrackerCard,+ ):+ self.bittorrentGroup.addSettingCard(card)++ settingPage.vBoxLayout.addWidget(self.bittorrentGroup)+++bittorrentConfig = BitTorrentConfig()diff --git a/features/bittorrent_pack/manifest.toml b/features/bittorrent_pack/manifest.tomlnew file mode 100644index 00000000..90158411--- /dev/null+++ b/features/bittorrent_pack/manifest.toml@@ -0,0 +1,3 @@+[pack]+entry = "pack.py"+dependencies = []diff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.pynew file mode 100644index 00000000..e82f81d4--- /dev/null+++ b/features/bittorrent_pack/pack.py@@ -0,0 +1,35 @@+from urllib.parse import urlparse++from app.bases.interfaces import FeaturePack++from .cards import BitTorrentResultCard, BitTorrentTaskCard+from .config import bittorrentConfig+from .task import BitTorrentTask, parse+++def _isTorrentUrl(url: str) -> bool:+ 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")+++class BitTorrentPack(FeaturePack):+ priority = 85+ taskType = BitTorrentTask+ config = bittorrentConfig++ def canHandle(self, url: str) -> bool:+ return _isTorrentUrl(url)++ async def parse(self, payload: dict) -> BitTorrentTask:+ return await parse(payload)++ def createTaskCard(self, task: BitTorrentTask, parent=None):+ return BitTorrentTaskCard(task, parent)++ def createResultCard(self, task: BitTorrentTask, parent=None):+ return BitTorrentResultCard(task, parent)diff --git a/features/bittorrent_pack/task.py b/features/bittorrent_pack/task.pynew file mode 100644index 00000000..782d8465--- /dev/null+++ b/features/bittorrent_pack/task.py@@ -0,0 +1,895 @@+import asyncio+import re+from base64 import b64decode, b64encode+from contextlib import suppress+from dataclasses import dataclass, field+from datetime import timedelta+from pathlib import Path, PurePosixPath+from tempfile import gettempdir+from typing import Any+from urllib.parse import urlparse, urlsplit++import libtorrent as lt+import niquests+from loguru import logger++from app.bases.interfaces import Worker+from app.bases.models import Task, TaskStage, TaskStatus+from app.supports.config import DEFAULT_HEADERS, cfg+from app.supports.utils import getProxies+from .config import bittorrentConfig, getCachedWebTrackers, refreshConfiguredWebTrackers+from .trackers import mergeTrackers+++def _storageMode(mode: str) -> int:+ if mode == "allocate":+ return lt.storage_mode_t.storage_mode_allocate+ return lt.storage_mode_t.storage_mode_sparse+++def _sanitizeName(name: str) -> str:+ cleaned = re.sub(r'[\x00-\x1f\\/:*?"<>|]+', "_", str(name or "")).strip().rstrip(".")+ return cleaned or "torrent"+++def _normalizeTorrentPath(path: str) -> str:+ return str(PurePosixPath(str(path).replace("\\", "/")))+++def _encodeBytes(data: bytes) -> str:+ return b64encode(data).decode("ascii")+++def _decodeBytes(data: str) -> bytes:+ return b64decode(data.encode("ascii"))+++def _proxyTypeForScheme(scheme: str) -> int:+ lowered = scheme.lower()+ if lowered == "http":+ return lt.proxy_type_t.http+ if lowered == "https":+ return lt.proxy_type_t.http_pw+ if lowered == "socks4":+ return lt.proxy_type_t.socks4+ if lowered == "socks5":+ return lt.proxy_type_t.socks5+ return lt.proxy_type_t.none+++def _sessionProxySettings(proxies: dict | None) -> dict[str, Any]:+ if proxies is None:+ return {}++ proxyUrl = ""+ for key in ("https", "http"):+ value = str(proxies.get(key) or "").strip()+ if value:+ proxyUrl = value+ break++ if not proxyUrl:+ return {}++ parsed = urlsplit(proxyUrl)+ if not parsed.hostname or not parsed.port:+ return {}++ return {+ "proxy_type": _proxyTypeForScheme(parsed.scheme),+ "proxy_hostname": parsed.hostname,+ "proxy_port": parsed.port,+ "proxy_username": parsed.username or "",+ "proxy_password": parsed.password or "",+ "proxy_hostnames": True,+ "proxy_peer_connections": True,+ "proxy_tracker_connections": True,+ "force_proxy": False,+ }+++def _sessionSettings(+ *,+ listenPort: int,+ connectionsLimit: int,+ downloadRateLimit: int,+ uploadRateLimit: int,+ enableDHT: bool,+ enableLSD: bool,+ enableUPnP: bool,+ enableNATPMP: bool,+ proxies: dict | None,+) -> dict[str, Any]:+ settings = {+ "user_agent": DEFAULT_HEADERS["user-agent"],+ "listen_interfaces": f"0.0.0.0:{listenPort}",+ "connections_limit": connectionsLimit,+ "download_rate_limit": downloadRateLimit,+ "upload_rate_limit": uploadRateLimit,+ "enable_dht": enableDHT,+ "enable_lsd": enableLSD,+ "enable_upnp": enableUPnP,+ "enable_natpmp": enableNATPMP,+ }+ settings.update(_sessionProxySettings(proxies))+ return settings+++def _startDiscoveryServices(+ session: lt.session,+ *,+ enableDHT: bool,+ enableLSD: bool,+ enableUPnP: bool,+ enableNATPMP: bool,+):+ if enableDHT:+ session.start_dht()+ if enableLSD:+ session.start_lsd()+ if enableUPnP:+ session.start_upnp()+ if enableNATPMP:+ session.start_natpmp()+++def _createSession(+ *,+ listenPort: int,+ connectionsLimit: int,+ downloadRateLimit: int,+ uploadRateLimit: int,+ enableDHT: bool,+ enableLSD: bool,+ enableUPnP: bool,+ enableNATPMP: bool,+ proxies: dict | None,+ extraSettings: dict[str, Any] | None = None,+) -> lt.session:+ settings = _sessionSettings(+ listenPort=listenPort,+ connectionsLimit=connectionsLimit,+ downloadRateLimit=downloadRateLimit,+ uploadRateLimit=uploadRateLimit,+ enableDHT=enableDHT,+ enableLSD=enableLSD,+ enableUPnP=enableUPnP,+ enableNATPMP=enableNATPMP,+ proxies=proxies,+ )+ if extraSettings:+ settings.update(extraSettings)++ session = lt.session(settings)+ session.set_alert_mask(int(lt.alert.category_t.all_categories))+ _startDiscoveryServices(+ session,+ enableDHT=enableDHT,+ enableLSD=enableLSD,+ enableUPnP=enableUPnP,+ enableNATPMP=enableNATPMP,+ )+ return session+++def _torrentBytesFromInfo(ti: lt.torrent_info) -> bytes:+ return lt.bencode(lt.create_torrent(ti).generate())+++def _extractTrackers(ti: lt.torrent_info) -> list[str]:+ trackers: list[str] = []+ for tracker in list(ti.trackers()):+ url = str(tracker.url).strip()+ if url and url not in trackers:+ trackers.append(url)+ return trackers+++def _isPadFile(files: lt.file_storage, index: int) -> bool:+ return bool(files.file_flags(index) & lt.file_storage.flag_pad_file)+++def _metadataTempPath() -> Path:+ return Path(gettempdir()) / "ghost_downloader_bt_metadata"+++def _forceMetadataPeerDiscovery(handle: lt.torrent_handle, *, enableDHT: bool):+ try:+ handle.force_reannounce(0, -1, lt.reannounce_flags_t.ignore_min_interval)+ except Exception:+ handle.force_reannounce()++ if enableDHT:+ try:+ handle.force_dht_announce()+ except Exception:+ pass+++def _addTrackersToHandle(handle: lt.torrent_handle, trackers: list[str], knownTrackers: set[str]) -> bool:+ added = False+ for tracker in trackers:+ if tracker in knownTrackers:+ continue+ handle.add_tracker({"url": tracker, "tier": 0})+ knownTrackers.add(tracker)+ added = True+ return added+++def _shareRatioPercent(status: lt.torrent_status) -> float:+ downloaded = int(status.all_time_download or status.total_wanted_done or status.total_done)+ if downloaded == 0:+ return 0.0+ return status.all_time_upload / downloaded * 100+++def _durationSeconds(value: int | float | timedelta) -> int:+ if isinstance(value, timedelta):+ return int(value.total_seconds())+ return int(value)+++def _seedingSeconds(status: lt.torrent_status) -> int:+ return _durationSeconds(status.seeding_duration or status.seeding_time)+++async def _resolveAdditionalTrackers() -> list[str]:+ if not bittorrentConfig.enableWebTrackers.value:+ return []++ if bittorrentConfig.autoRefreshWebTrackers.value:+ try:+ return await refreshConfiguredWebTrackers()+ except Exception as e:+ logger.opt(exception=e).warning("刷新 Web Tracker 失败,回退到缓存 {}", repr(e))++ return getCachedWebTrackers()+++@dataclass+class BitTorrentFile:+ index: int+ path: str+ size: int+ selected: bool = True+ priority: int = 4+ downloadedBytes: int = 0+ completed: bool = False++ def __post_init__(self):+ self.path = _normalizeTorrentPath(self.path)+++@dataclass+class BitTorrentTaskStage(TaskStage):+ resolvePath: str+ stateText: str = field(default="")+ peerCount: int = field(default=0)+ seedCount: int = field(default=0)+ downloadRate: int = field(default=0)+ uploadRate: int = field(default=0)+ shareRatioPercent: float = field(default=0)+ seedingTimeSeconds: int = field(default=0)+ isSeeding: bool = field(default=False)++ def reset(self, notifyTask: bool = True):+ super().reset(notifyTask=notifyTask)+ self.stateText = ""+ self.peerCount = 0+ self.seedCount = 0+ self.downloadRate = 0+ self.uploadRate = 0+ self.shareRatioPercent = 0+ self.seedingTimeSeconds = 0+ self.isSeeding = False+++@dataclass+class BitTorrentTask(Task):+ sourceType: str+ torrentData: str+ resumeData: str = field(default="")+ trackers: list[str] = field(default_factory=list)+ files: list[BitTorrentFile] = field(default_factory=list)+ proxies: dict | None = field(default_factory=getProxies)+ listenPort: int = field(default_factory=lambda: bittorrentConfig.listenPort.value)+ connectionsLimit: int = field(default_factory=lambda: bittorrentConfig.connectionsLimit.value)+ downloadRateLimit: int = field(default_factory=lambda: bittorrentConfig.downloadRateLimit.value)+ uploadRateLimit: int = field(default_factory=lambda: bittorrentConfig.uploadRateLimit.value)+ enableDHT: bool = field(default_factory=lambda: bittorrentConfig.enableDHT.value)+ enableLSD: bool = field(default_factory=lambda: bittorrentConfig.enableLSD.value)+ enableUPnP: bool = field(default_factory=lambda: bittorrentConfig.enableUPnP.value)+ enableNATPMP: bool = field(default_factory=lambda: bittorrentConfig.enableNATPMP.value)+ sequentialDownload: bool = field(default_factory=lambda: bittorrentConfig.sequentialDownload.value)+ storageMode: str = field(default_factory=lambda: bittorrentConfig.storageMode.value)+ seedRatioLimitPercent: int = field(default_factory=lambda: bittorrentConfig.seedRatioLimitPercent.value)+ seedTimeLimitMinutes: int = field(default_factory=lambda: bittorrentConfig.seedTimeLimitMinutes.value)+ fileSelectionVersion: int = field(default=0)++ def __post_init__(self):+ self.files = [+ item if isinstance(item, BitTorrentFile) else BitTorrentFile(**item)+ for item in self.files+ ]+ self.title = _sanitizeName(self.title)+ super().__post_init__()+ self._recalculateSelection()+ self.syncStagePaths()++ @property+ def resolvePath(self) -> str:+ return str(self.path / self.title)++ @property+ def stage(self) -> BitTorrentTaskStage | None:+ return self.stages[0] if self.stages else None++ @property+ def selectedFileCount(self) -> int:+ return sum(1 for file in self.files if file.selected)++ @property+ def totalFileCount(self) -> int:+ return len(self.files)++ @property+ def isSingleFileTorrent(self) -> bool:+ return len(self.files) == 1++ @property+ def hasUnselectedFiles(self) -> bool:+ return self.selectedFileCount < self.totalFileCount++ def syncStagePaths(self):+ if self.stage is not None:+ self.stage.resolvePath = self.resolvePath++ def mappedRelativePath(self, file: BitTorrentFile) -> str:+ if self.isSingleFileTorrent:+ return self.title.replace("\\", "/")++ parts = list(PurePosixPath(file.path).parts)+ parts[0] = self.title+ return str(PurePosixPath(*parts))++ def filePriorities(self) -> list[int]:+ return [file.priority if file.selected else 0 for file in self.files]++ def _recalculateSelection(self):+ self.fileSize = sum(file.size for file in self.files if file.selected)++ def updateSelectedFiles(self, selectedIndexes: set[int]):+ if not selectedIndexes:+ raise ValueError("至少需要选择一个文件")++ changed = False+ for file in self.files:+ selected = file.index in selectedIndexes+ priority = 4 if selected else 0+ if file.selected != selected or file.priority != priority:+ changed = True+ file.selected = selected+ file.priority = priority+ if not selected:+ file.downloadedBytes = 0+ file.completed = False++ if not changed:+ return++ self.fileSelectionVersion += 1+ self._recalculateSelection()++ def reopenForAdditionalFiles(self) -> bool:+ stage = self.stage+ if stage is None or stage.status != TaskStatus.COMPLETED:+ return False++ if not any(file.selected and not file.completed for file in self.files):+ return False++ stage.isSeeding = False+ stage.stateText = "已添加新的下载文件"+ stage.setStatus(TaskStatus.PAUSED)+ stage.receivedBytes = sum(file.downloadedBytes for file in self.files if file.selected)+ if self.fileSize > 0:+ stage.progress = stage.receivedBytes / self.fileSize * 100+ else:+ stage.progress = 0+ return True++ def updateFileProgress(self, progresses: list[int]):+ for file in self.files:+ if not file.selected:+ file.downloadedBytes = 0+ file.completed = False+ continue+ downloaded = int(progresses[file.index]) if file.index < len(progresses) else 0+ file.downloadedBytes = downloaded+ file.completed = file.size > 0 and downloaded >= file.size++ def applyPayloadToTask(self, payload: dict[str, Any]):+ super().applyPayloadToTask(payload)+ if "proxies" in payload:+ self.proxies = payload.get("proxies")+ self.syncStagePaths()++ def reset(self) -> TaskStatus:+ result = super().reset()+ self.resumeData = ""+ for file in self.files:+ file.downloadedBytes = 0+ file.completed = False+ return result++ def occupiesDownloadSlot(self) -> bool:+ return self.status == TaskStatus.RUNNING and not self.stage.isSeeding++ def willOccupyDownloadSlotWhenStarted(self) -> bool:+ return not self.stage.isSeeding++ async def run(self):+ stage = self.stage+ if stage is None:+ return++ try:+ if self.status != TaskStatus.RUNNING or stage.status == TaskStatus.COMPLETED:+ return+ await BitTorrentWorker(stage).run()+ except asyncio.CancelledError:+ logger.info(f"{self.title} 停止下载")+ raise+ except Exception as e:+ if not stage.error:+ stage.setError(e)+ logger.opt(exception=e).error("{} 下载失败", self.title)+ raise++ def __hash__(self):+ return hash(self.taskId)+++class BitTorrentWorker(Worker):+ def __init__(self, stage: BitTorrentTaskStage):+ super().__init__(stage)+ self.stage = stage+ self.task: BitTorrentTask = stage._task+ self.session: lt.session | None = None+ self.handle: lt.torrent_handle | None = None+ self._appliedSelectionVersion = -1++ def _applyTaskParams(self, params: lt.add_torrent_params):+ params.save_path = str(self.task.path)+ params.storage_mode = _storageMode(self.task.storageMode)+ params.file_priorities = self.task.filePriorities()+ params.download_limit = self.task.downloadRateLimit+ params.upload_limit = self.task.uploadRateLimit+ params.max_connections = self.task.connectionsLimit+ if self.task.trackers:+ params.trackers = self.task.trackers.copy()++ def _buildAddTorrentParams(self) -> lt.add_torrent_params:+ if self.task.resumeData:+ try:+ params = lt.read_resume_data(_decodeBytes(self.task.resumeData))+ except Exception as e:+ logger.opt(exception=e).warning("读取 BitTorrent resume 数据失败,改用种子元数据 {}", self.task.title)+ else:+ self._applyTaskParams(params)+ return params++ params = lt.add_torrent_params()+ params.ti = lt.torrent_info(_decodeBytes(self.task.torrentData))+ self._applyTaskParams(params)+ if self.task.sequentialDownload:+ params.flags = int(params.flags) | int(lt.torrent_flags.sequential_download)+ else:+ params.flags = int(params.flags) & ~int(lt.torrent_flags.sequential_download)+ params.flags = int(params.flags) | int(lt.torrent_flags.update_subscribe)+ return params++ def _applyRenameMapping(self):+ if self.handle is None:+ return++ for file in self.task.files:+ mappedPath = self.task.mappedRelativePath(file)+ if mappedPath == file.path:+ continue+ self.handle.rename_file(file.index, mappedPath)++ def _applyFileSelection(self):+ if self.handle is None or self._appliedSelectionVersion == self.task.fileSelectionVersion:+ return+ self.handle.prioritize_files(self.task.filePriorities())+ self.handle.set_sequential_download(self.task.sequentialDownload)+ self.handle.set_max_connections(self.task.connectionsLimit)+ self.handle.set_download_limit(self.task.downloadRateLimit)+ self.handle.set_upload_limit(self.task.uploadRateLimit)+ self._appliedSelectionVersion = self.task.fileSelectionVersion++ def _stateText(self, status: lt.torrent_status) -> str:+ mapping = {+ "checking_files": "校验已有文件",+ "checking_resume_data": "检查续传状态",+ "downloading_metadata": "获取元数据",+ "downloading": "下载中",+ "finished": "下载完成",+ "seeding": "做种中",+ "allocating": "分配文件中",+ "queued_for_checking": "等待校验",+ }+ return mapping.get(status.state.name, status.state.name)++ def _syncFromStatus(self, status: lt.torrent_status):+ wasSeeding = self.stage.isSeeding+ totalWanted = int(status.total_wanted)+ totalWantedDone = int(status.total_wanted_done)+ self.stage.stateText = self._stateText(status)+ self.stage.peerCount = int(status.num_peers)+ self.stage.seedCount = int(status.num_seeds)+ self.stage.isSeeding = bool(status.is_seeding)+ self.stage.downloadRate = int(status.download_rate)+ self.stage.uploadRate = int(status.upload_rate)+ self.stage.shareRatioPercent = _shareRatioPercent(status)+ self.stage.seedingTimeSeconds = _seedingSeconds(status)+ self.stage.speed = self.stage.downloadRate+ self.stage.receivedBytes = totalWantedDone++ if totalWanted > 0:+ self.task.fileSize = totalWanted+ self.stage.progress = totalWantedDone / totalWanted * 100+ elif self.task.fileSize > 0:+ self.stage.progress = self.stage.receivedBytes / self.task.fileSize * 100+ else:+ self.stage.progress = 0++ if wasSeeding != self.stage.isSeeding:+ from app.services.core_service import coreService++ coreService.notifyTaskSchedulingChanged()++ def _syncFileProgress(self):+ if self.handle is None:+ return+ try:+ progresses = list(self.handle.file_progress())+ except Exception:+ return+ self.task.updateFileProgress(progresses)++ def _seedPauseReason(self) -> str:+ if not self.stage.isSeeding:+ return ""++ ratioLimit = self.task.seedRatioLimitPercent+ if ratioLimit > 0 and self.stage.shareRatioPercent >= ratioLimit:+ return "分享率达到 {0:.2f}% / {1}%".format(self.stage.shareRatioPercent, ratioLimit)++ timeLimitMinutes = self.task.seedTimeLimitMinutes+ if timeLimitMinutes > 0 and self.stage.seedingTimeSeconds >= timeLimitMinutes * 60:+ return "做种时间达到 {0} / {1} 分钟".format(+ round(self.stage.seedingTimeSeconds / 60),+ timeLimitMinutes,+ )++ return ""++ def _handleAlerts(self, alerts: list[lt.alert], *, raiseOnError: bool = True):+ for alert in alerts:+ if isinstance(alert, lt.file_completed_alert):+ for file in self.task.files:+ if file.index == alert.index:+ file.completed = True+ file.downloadedBytes = file.size+ break+ continue++ if isinstance(alert, lt.fastresume_rejected_alert):+ logger.warning("BitTorrent fastresume 被拒绝 {}: {}", self.task.title, alert.message())+ self.task.resumeData = ""+ continue++ if not raiseOnError:+ continue++ if isinstance(+ alert,+ (+ lt.file_error_alert,+ lt.metadata_failed_alert,+ lt.torrent_error_alert,+ lt.hash_failed_alert,+ ),+ ):+ raise RuntimeError(alert.message())++ async def _saveResumeData(self) -> str:+ if self.handle is None or self.session is None:+ return ""++ 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.task.title)+ return ""++ deadline = asyncio.get_running_loop().time() + 10+ while asyncio.get_running_loop().time() < deadline:+ alerts = list(self.session.pop_alerts())+ for alert in alerts:+ if isinstance(alert, lt.save_resume_data_alert):+ return _encodeBytes(lt.write_resume_data_buf(alert.params))+ if isinstance(alert, lt.save_resume_data_failed_alert):+ logger.warning("保存 BitTorrent resume 数据失败 {}: {}", self.task.title, alert.message())+ return ""+ self._handleAlerts(alerts, raiseOnError=False)+ await asyncio.sleep(0.1)++ logger.warning("等待 BitTorrent resume 数据超时 {}", self.task.title)+ return ""++ async def _shutdownSession(self):+ if self.handle is None or self.session is None:+ return+ try:+ self.session.remove_torrent(self.handle)+ except Exception:+ pass++ async def run(self):+ if self.task.selectedFileCount <= 0:+ self.stage.setStatus(TaskStatus.FAILED)+ raise RuntimeError("至少需要选择一个文件")++ Path(self.task.path).mkdir(parents=True, exist_ok=True)++ self.session = _createSession(+ listenPort=self.task.listenPort,+ connectionsLimit=self.task.connectionsLimit,+ downloadRateLimit=self.task.downloadRateLimit,+ uploadRateLimit=self.task.uploadRateLimit,+ enableDHT=self.task.enableDHT,+ enableLSD=self.task.enableLSD,+ enableUPnP=self.task.enableUPnP,+ enableNATPMP=self.task.enableNATPMP,+ proxies=self.task.proxies,+ )++ try:+ params = self._buildAddTorrentParams()+ self.handle = self.session.add_torrent(params)+ self._applyRenameMapping()+ self._applyFileSelection()+ self.session.resume()+ self.handle.resume()++ while True:+ alerts = list(self.session.pop_alerts())+ self._handleAlerts(alerts)+ self._applyFileSelection()++ status = self.handle.status()+ self._syncFromStatus(status)+ self._syncFileProgress()++ pauseReason = self._seedPauseReason()+ if pauseReason:+ logger.info("{} 自动暂停做种: {}", self.task.title, pauseReason)+ self.task.resumeData = await self._saveResumeData()+ self.stage.isSeeding = False+ self.stage.stateText = "已自动暂停做种"+ self.stage.setStatus(TaskStatus.COMPLETED)+ self.stage.progress = 100+ self.stage.speed = 0+ return++ await asyncio.sleep(1)+ except asyncio.CancelledError:+ self.task.resumeData = await asyncio.shield(self._saveResumeData())+ wasSeeding = self.stage.isSeeding+ self.stage.stateText = "已暂停做种" if wasSeeding else "已暂停下载"+ self.stage.setStatus(TaskStatus.PAUSED)+ raise+ except Exception as e:+ self.task.resumeData = await self._saveResumeData()+ self.stage.setError(e)+ raise+ finally:+ await self._shutdownSession()+ self.handle = None+ self.session = None+++async def _fetchTorrentBytes(payload: dict) -> bytes:+ url = str(payload["url"]).strip()+ headers = payload.get("headers", DEFAULT_HEADERS)+ proxies = payload.get("proxies", getProxies())++ client = niquests.AsyncSession(headers=headers, timeout=30, happy_eyeballs=True)+ client.trust_env = False++ try:+ response = await client.get(+ url,+ proxies=proxies,+ verify=cfg.SSLVerify.value,+ allow_redirects=True,+ )+ try:+ response.raise_for_status()+ return bytes(response.content)+ finally:+ response.close()+ finally:+ await client.close()+++async def _resolveMagnetMetadata(payload: dict) -> tuple[lt.torrent_info, list[str], bytes]:+ url = str(payload["url"]).strip()+ proxies = payload.get("proxies", getProxies())+ enableDHT = bittorrentConfig.enableDHT.value+ enableWebTrackers = bittorrentConfig.enableWebTrackers.value+ initialWebTrackers = getCachedWebTrackers() if enableWebTrackers else []+ session = _createSession(+ listenPort=bittorrentConfig.listenPort.value,+ connectionsLimit=bittorrentConfig.connectionsLimit.value,+ downloadRateLimit=bittorrentConfig.downloadRateLimit.value,+ uploadRateLimit=bittorrentConfig.uploadRateLimit.value,+ enableDHT=enableDHT,+ enableLSD=bittorrentConfig.enableLSD.value,+ enableUPnP=bittorrentConfig.enableUPnP.value,+ enableNATPMP=bittorrentConfig.enableNATPMP.value,+ proxies=proxies,+ extraSettings={+ "announce_to_all_trackers": True,+ "announce_to_all_tiers": True,+ },+ )++ params = lt.parse_magnet_uri(url)+ params.trackers = mergeTrackers(params.trackers.copy(), initialWebTrackers)+ _metadataTempPath().mkdir(parents=True, exist_ok=True)+ params.save_path = str(_metadataTempPath())+ params.storage_mode = _storageMode("sparse")+ params.flags = int(params.flags) | int(lt.torrent_flags.default_dont_download)+ params.flags = int(params.flags) | int(lt.torrent_flags.update_subscribe)++ webTrackerTask: asyncio.Task[list[str]] | None = None+ if enableWebTrackers and bittorrentConfig.autoRefreshWebTrackers.value:+ webTrackerTask = asyncio.create_task(_resolveAdditionalTrackers())++ handle = session.add_torrent(params)+ session.resume()+ handle.resume()+ knownTrackers = set(params.trackers)+ appliedRefreshedTrackers = False+ _forceMetadataPeerDiscovery(handle, enableDHT=enableDHT)++ try:+ deadline = asyncio.get_running_loop().time() + bittorrentConfig.metadataTimeout.value+ while asyncio.get_running_loop().time() < deadline:+ if webTrackerTask is not None and webTrackerTask.done() and not appliedRefreshedTrackers:+ appliedRefreshedTrackers = True+ refreshedTrackers = webTrackerTask.result()+ params.trackers = mergeTrackers(params.trackers.copy(), refreshedTrackers)+ if _addTrackersToHandle(handle, refreshedTrackers, knownTrackers):+ _forceMetadataPeerDiscovery(handle, enableDHT=enableDHT)++ alerts = list(session.pop_alerts())+ for alert in alerts:+ if isinstance(alert, lt.metadata_received_alert):+ ti = handle.torrent_file()+ if ti is not None and ti.is_valid():+ return ti, params.trackers.copy(), _torrentBytesFromInfo(ti)+ if isinstance(alert, lt.metadata_failed_alert):+ raise RuntimeError(alert.message())+ if isinstance(alert, (lt.torrent_error_alert, lt.file_error_alert)):+ raise RuntimeError(alert.message())++ status = handle.status()+ if status.has_metadata:+ ti = handle.torrent_file()+ if ti is not None and ti.is_valid():+ return ti, params.trackers.copy(), _torrentBytesFromInfo(ti)++ await asyncio.sleep(0.2)++ raise TimeoutError("等待 magnet 元数据超时")+ finally:+ if webTrackerTask is not None and not webTrackerTask.done():+ webTrackerTask.cancel()+ with suppress(asyncio.CancelledError):+ await webTrackerTask+ try:+ session.remove_torrent(handle)+ except Exception:+ pass+++def buildTaskFromTorrentInfo(+ ti: lt.torrent_info,+ *,+ payload: dict,+ sourceType: str,+ sourceUrl: str,+ torrentBytes: bytes,+ trackers: list[str],+) -> BitTorrentTask:+ files = ti.files()+ entries: list[BitTorrentFile] = []+ for index in range(ti.num_files()):+ if _isPadFile(files, index):+ continue+ entries.append(+ BitTorrentFile(+ index=index,+ path=files.file_path(index),+ size=int(files.file_size(index)),+ )+ )++ if not entries:+ raise ValueError("该种子中没有可下载的普通文件")++ rootName = _sanitizeName(PurePosixPath(entries[0].path).parts[0])+ title = _sanitizeName(Path(entries[0].path).name) if len(entries) == 1 else rootName+ task = BitTorrentTask(+ title=title,+ url=sourceUrl,+ fileSize=sum(entry.size for entry in entries),+ path=Path(payload.get("path", cfg.downloadFolder.value)),+ sourceType=sourceType,+ torrentData=_encodeBytes(torrentBytes),+ trackers=trackers or _extractTrackers(ti),+ files=entries,+ proxies=payload.get("proxies", getProxies()),+ listenPort=bittorrentConfig.listenPort.value,+ connectionsLimit=bittorrentConfig.connectionsLimit.value,+ downloadRateLimit=bittorrentConfig.downloadRateLimit.value,+ uploadRateLimit=bittorrentConfig.uploadRateLimit.value,+ enableDHT=bittorrentConfig.enableDHT.value,+ enableLSD=bittorrentConfig.enableLSD.value,+ enableUPnP=bittorrentConfig.enableUPnP.value,+ enableNATPMP=bittorrentConfig.enableNATPMP.value,+ sequentialDownload=bittorrentConfig.sequentialDownload.value,+ storageMode=bittorrentConfig.storageMode.value,+ seedRatioLimitPercent=bittorrentConfig.seedRatioLimitPercent.value,+ seedTimeLimitMinutes=bittorrentConfig.seedTimeLimitMinutes.value,+ )+ task.addStage(BitTorrentTaskStage(stageIndex=1, resolvePath=task.resolvePath))+ return task+++async def parse(payload: dict) -> BitTorrentTask:+ url = str(payload["url"]).strip()+ parsedUrl = urlparse(url)++ if parsedUrl.scheme.lower() == "magnet":+ ti, trackers, torrentBytes = await _resolveMagnetMetadata(payload)+ return buildTaskFromTorrentInfo(+ ti,+ payload=payload,+ sourceType="magnet",+ sourceUrl=url,+ torrentBytes=torrentBytes,+ trackers=trackers,+ )++ torrentBytes, webTrackers = await asyncio.gather(+ _fetchTorrentBytes(payload),+ _resolveAdditionalTrackers(),+ )+ ti = lt.torrent_info(torrentBytes)+ return buildTaskFromTorrentInfo(+ ti,+ payload=payload,+ sourceType="torrent",+ sourceUrl=url,+ torrentBytes=torrentBytes,+ trackers=mergeTrackers(_extractTrackers(ti), webTrackers),+ )diff --git a/features/bittorrent_pack/trackers.py b/features/bittorrent_pack/trackers.pynew file mode 100644index 00000000..40402a08--- /dev/null+++ b/features/bittorrent_pack/trackers.py@@ -0,0 +1,75 @@+from urllib.parse import urlsplit++import niquests++from app.supports.config import DEFAULT_HEADERS, cfg+from app.supports.utils import getProxies+++_TRACKER_SCHEMES = {"http", "https", "udp", "ws", "wss"}+++def normalizeTrackerSource(source: str) -> str:+ value = str(source or "").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]:+ trackers: list[str] = []+ for raw in str(text or "").replace("\r", "\n").split():+ tracker = raw.strip()+ if not tracker:+ continue+ parsed = urlsplit(tracker)+ if parsed.scheme.lower() not in _TRACKER_SCHEMES or not parsed.netloc:+ continue+ if tracker not in trackers:+ trackers.append(tracker)+ return trackers+++def formatTrackers(trackers: list[str]) -> str:+ return "\n".join(parseTrackerText("\n".join(trackers)))+++def mergeTrackers(*trackerGroups: list[str]) -> list[str]:+ merged: list[str] = []+ for group in trackerGroups:+ for tracker in group:+ if tracker and tracker not in merged:+ merged.append(tracker)+ return merged+++async def fetchWebTrackers(sourceUrl: str) -> list[str]:+ normalizedSource = normalizeTrackerSource(sourceUrl)+ if not normalizedSource:+ raise ValueError("Web Tracker 源地址无效")++ client = niquests.AsyncSession(headers=DEFAULT_HEADERS.copy(), timeout=30, happy_eyeballs=True)+ client.trust_env = False++ try:+ response = await client.get(+ normalizedSource,+ proxies=getProxies(),+ verify=cfg.SSLVerify.value,+ allow_redirects=True,+ )+ try:+ response.raise_for_status()+ trackers = parseTrackerText(response.text)+ finally:+ response.close()+ finally:+ await client.close()++ if not trackers:+ raise ValueError("Web Tracker 源没有返回有效的 Tracker")++ return trackersdiff --git a/pyproject.toml b/pyproject.tomlindex b5859ed7..1c6c4316 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -6,6 +6,7 @@ requires-python = ">=3.11"dependencies = ["darkdetect[macos-listener]>=0.8.0","desktop-notifier>=6.2.0",+ "libtorrent>=2.0.11","loguru>=0.7.3","niquests[http3,socks,speedups]>=3.18.1","nuitka==4.0.5",@@ -13,3 +14,8 @@ dependencies = ["pyside6-fluent-widgets>=1.11.1","qrcode[png]>=8.2",]++[dependency-groups]+dev = [+ "types-libtorrent>=2.0.11.20250816",+]diff --git a/requirements.txt b/requirements.txtindex 68618b58..52c12c5e 100644--- a/requirements.txt+++ b/requirements.txt@@ -5,4 +5,5 @@ niquests[http3,socks,speedups]>=3.18.1nuitka==4.0.5pyside6>=6.10.2pyside6-fluent-widgets>=1.11.1-qrcode[png]>=8.2\ No newline at end of file+qrcode[png]>=8.2+libtorrent>=2.0.11\ No newline at end of file