The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor: Bittorrent Pack
XiaoYouChRb4ce60dfa723
diff --git a/app/view/components/tree_view.py b/app/view/components/tree_view.pyindex 3b83dc64..3f0bea7f 100644--- a/app/view/components/tree_view.py+++ b/app/view/components/tree_view.py@@ -40,7 +40,7 @@ class AutoSizingTreeView(TreeView):return hreturn self.fontMetrics().height() + 4- def _viewChromeHeight(self) -> int:+ def _viewFrameHeight(self) -> int:margins = self.contentsMargins()viewportMargins = self.viewportMargins()header = self.header()@@ -55,7 +55,7 @@ class AutoSizingTreeView(TreeView):)def _sizeHintForRowCount(self, rowCount: int) -> QSize:- height = self._viewChromeHeight() + self._rowHeight() * rowCount+ height = self._viewFrameHeight() + self._rowHeight() * rowCountreturn QSize(super().sizeHint().width(), height)def minimumSizeHint(self) -> QSize:diff --git a/features/bittorrent_pack/cards.py b/features/bittorrent_pack/cards.pyindex d4ed19a5..5baaf5aa 100644--- a/features/bittorrent_pack/cards.py+++ b/features/bittorrent_pack/cards.py@@ -63,17 +63,19 @@ class TorrentFileSelectDialog(FileSelectDialog):class BitTorrentResultCard(ResultCard):def __init__(self, task: BTTask, parent: QWidget = None):super().__init__(task, parent)-- self.mainLayout = QHBoxLayout(self)- self.textLayout = QVBoxLayout()+ # instant widgetself.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()@@ -82,7 +84,6 @@ class BitTorrentResultCard(ResultCard):self.iconLabel.setFixedSize(20, 20)icon = QFileIconProvider.IconType.File if self.task.isSingleFile else QFileIconProvider.IconType.Folderself.iconLabel.setIcon(QFileIconProvider().icon(icon))- self.selectFilesButton.clicked.connect(self._onSelectFilesClicked)def _initLayout(self):self.mainLayout.setContentsMargins(10, 6, 10, 6)@@ -99,6 +100,9 @@ class BitTorrentResultCard(ResultCard):self.mainLayout.addWidget(self.categoryButton)self.mainLayout.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)@@ -173,8 +177,6 @@ class BTTaskCard(UniversalTaskCard):self.speedLabel.show()self.uploadRateLabel.show()self.progressLabel.show()- if not metaText:- self.metaInfoLabel.hide()self.infoLabel.hide()returndiff --git a/features/bittorrent_pack/config.py b/features/bittorrent_pack/config.pyindex 5b783b9b..993a71f9 100644--- a/features/bittorrent_pack/config.py+++ b/features/bittorrent_pack/config.py@@ -1,188 +1,33 @@from typing import TYPE_CHECKINGfrom qfluentwidgets import (- BodyLabel,BoolValidator,ComboBoxSettingCard,ConfigItem,- ConfigValidator,FluentIcon,- InfoBar,- LineEdit,- MessageBoxBase,OptionsConfigItem,OptionsValidator,- PrimaryPushButton,RangeConfigItem,RangeSettingCard,RangeValidator,- SettingCard,SwitchSettingCard,- ToolButton,- ToolTipFilter,)from app.bases.models import PackConfig-from app.services.core_service import coreService-from app.supports.config import cfg+from app.supports.config import StringListValidatorfrom app.view.components.setting_card_group import CollapsibleSettingCardGroup-from app.view.components.editors import AutoSizingEditfrom app.view.components.setting_cards import SpinBoxSettingCard-from .trackers import fetchWebTrackers, formatTrackers, toTrackers, parseTrackerText++from .web_tracker.schema import (+ DEFAULT_WEB_TRACKER_SOURCE,+ SourceCacheSerializer,+ SourceCacheValidator,+)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(toTrackers(str(value or "")))-- def correct(self, value) -> str:- source = toTrackers(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 = toTrackers(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.setMinimumWidth(720)- self.sourceLabel = BodyLabel(self.tr("Tracker 源地址"), self.widget)- self.sourceEdit = LineEdit(self.widget)- self.trackersLabel = BodyLabel(self.tr("当前 Tracker 列表"), self.widget)- self.trackersEdit = AutoSizingEdit(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 = toTrackers(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 = toTrackers(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"),- self.tr("来源: {0}\n当前缓存: {1} 条 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))@@ -209,13 +54,20 @@ class BitTorrentConfig(PackConfig):saveMagnetTorrentFile = ConfigItem("BitTorrent", "SaveMagnetTorrentFile", False, BoolValidator())enableWebTrackers = ConfigItem("BitTorrent", "EnableWebTrackers", True, BoolValidator())autoRefreshWebTrackers = ConfigItem("BitTorrent", "AutoRefreshWebTrackers", True, BoolValidator())- webTrackerSource = ConfigItem(+ webTrackerSources = ConfigItem(+ "BitTorrent",+ "WebTrackerSources",+ [DEFAULT_WEB_TRACKER_SOURCE],+ StringListValidator(),+ )+ webTrackerSourceCache = ConfigItem("BitTorrent",- "WebTrackerSource",- DEFAULT_WEB_TRACKER_SOURCE,- WebTrackerSourceValidator(),+ "WebTrackerSourceCache",+ {},+ SourceCacheValidator(),+ SourceCacheSerializer(),)- webTrackerList = ConfigItem("BitTorrent", "WebTrackerList", "", WebTrackerListValidator())+ webTrackerCustomList = ConfigItem("BitTorrent", "WebTrackerCustomList", "")storageMode = OptionsConfigItem("BitTorrent","StorageMode",@@ -224,6 +76,8 @@ class BitTorrentConfig(PackConfig):)def setupSettings(self, settingPage: "SettingPage"):+ from .web_tracker.card import WebTrackerCard+self.bittorrentGroup = CollapsibleSettingCardGroup(self.tr("BitTorrent 下载"), "bittorrent", settingPage.container)self.listenPortCard = SpinBoxSettingCard(FluentIcon.GLOBE,@@ -253,7 +107,7 @@ class BitTorrentConfig(PackConfig):self.downloadRateLimitCard = SpinBoxSettingCard(FluentIcon.DOWNLOAD,self.tr("下载限速"),- self.tr("0 表示不限速,单位为 session 级别的 KB/s"),+ self.tr("0 表示不限速,单位为 session 级别的 KB/s")," KB/s",self.downloadRateLimit,self.bittorrentGroup,@@ -263,7 +117,7 @@ class BitTorrentConfig(PackConfig):self.uploadRateLimitCard = SpinBoxSettingCard(FluentIcon.SHARE,self.tr("上传限速"),- self.tr("0 表示不限速,单位为 session 级别的 KB/s"),+ self.tr("0 表示不限速,单位为 session 级别的 KB/s")," KB/s",self.uploadRateLimit,self.bittorrentGroup,@@ -273,7 +127,7 @@ class BitTorrentConfig(PackConfig):self.seedRatioLimitCard = SpinBoxSettingCard(FluentIcon.SHARE,self.tr("自动暂停做种分享率"),- self.tr("下载完成后继续做种;0 表示不按分享率自动暂停,100% 表示分享率 1.0"),+ self.tr("下载完成后继续做种;0 表示不按分享率自动暂停,100% 表示分享率 1.0")," %",self.seedRatioLimitPercent,self.bittorrentGroup,@@ -282,7 +136,7 @@ class BitTorrentConfig(PackConfig):self.seedTimeLimitCard = SpinBoxSettingCard(FluentIcon.STOP_WATCH,self.tr("自动暂停做种时长"),- self.tr("下载完成后继续做种;0 表示不按做种时长自动暂停"),+ self.tr("下载完成后继续做种;0 表示不按做种时长自动暂停")," min",self.seedTimeLimitMinutes,self.bittorrentGroup,@@ -292,21 +146,21 @@ class BitTorrentConfig(PackConfig):self.storageMode,FluentIcon.SAVE,self.tr("文件分配模式"),- 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.tr("下载 magnet 链接时,在下载目录额外保存解析得到的 .torrent 文件"),self.saveMagnetTorrentFile,self.bittorrentGroup,)self.sequentialDownloadCard = SwitchSettingCard(FluentIcon.LIBRARY,self.tr("顺序下载"),- self.tr("按文件顺序下载内容,适合边下边看但通常会影响整体效率"),+ self.tr("按文件顺序下载内容,适合边下边看但通常会影响整体效率"),self.sequentialDownload,self.bittorrentGroup,)@@ -348,7 +202,7 @@ class BitTorrentConfig(PackConfig):self.autoRefreshWebTrackersCard = SwitchSettingCard(FluentIcon.SYNC,self.tr("新建任务时刷新 Web Tracker"),- self.tr("创建新的 BT 任务时,先从源地址拉取最新 Tracker;失败时回退到缓存"),+ self.tr("创建新的 BT 任务时,先从源地址拉取最新 Tracker;失败时回退到缓存"),self.autoRefreshWebTrackers,self.bittorrentGroup,)diff --git a/features/bittorrent_pack/loaders.py b/features/bittorrent_pack/loaders.pynew file mode 100644index 00000000..764dbf7a--- /dev/null+++ b/features/bittorrent_pack/loaders.py@@ -0,0 +1,218 @@+import asyncio+import time+from base64 import b64encode+from pathlib import Path, PurePosixPath+from tempfile import gettempdir+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 DEFAULT_HEADERS, cfg+from app.supports.utils import getProxies, splitCookies, toSafeFilename++from .config import bittorrentConfig+from .task import BTFile, BTTask+from .trackers import mergeTrackers+from .web_tracker.service import webTrackerService+from .worker import createSession+++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", DEFAULT_HEADERS)+ proxies = payload.get("proxies", getProxies())+ requestHeaders, requestCookies = splitCookies(+ headers if isinstance(headers, dict) else DEFAULT_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,+ )+ response.raise_for_status()+ torrentBytes = cast(bytes, response.content)++ return torrentBytes, lt.torrent_info(torrentBytes)+++def _loadFromMagnetBlocking(+ url: str,+ proxies: dict | None,+ webTrackers: list[str],+) -> tuple[bytes, lt.torrent_info, list[str]]:+ session = createSession(+ 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,+ proxies=proxies,+ extraSettings={+ "announce_to_all_trackers": True,+ "announce_to_all_tiers": True,+ },+ )++ params = cast(lt.add_torrent_params, lt.parse_magnet_uri(url))+ 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++ handle = session.add_torrent(params)+ session.resume()+ handle.resume()++ handle.force_reannounce(0, -1, lt.reannounce_flags_t.ignore_min_interval)+ if bittorrentConfig.enableDHT.value:+ handle.force_dht_announce()++ deadline = time.monotonic() + bittorrentConfig.metadataTimeout.value+ try:+ while True:+ remainingMs = int(max(0.0, deadline - time.monotonic()) * 1000)+ if remainingMs <= 0:+ raise TimeoutError("等待 magnet 元数据超时")+ session.wait_for_alert(remainingMs)+ for alert in session.pop_alerts():+ if isinstance(alert, lt.metadata_received_alert):+ ti = handle.torrent_file()+ if ti is not None and ti.is_valid():+ torrentBytes = lt.bencode(lt.create_torrent(ti).generate())+ return torrentBytes, ti, params.trackers.copy()+ if isinstance(alert, (lt.metadata_failed_alert, lt.torrent_error_alert, lt.file_error_alert)):+ raise RuntimeError(alert.message())+ finally:+ try:+ session.remove_torrent(handle)+ except Exception:+ pass+++async def _loadFromMagnet(+ payload: dict,+ webTrackers: list[str],+) -> tuple[bytes, lt.torrent_info, list[str]]:+ url = str(payload["url"]).strip()+ proxies = payload.get("proxies", getProxies())+ return await asyncio.to_thread(_loadFromMagnetBlocking, url, proxies, 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,+ proxies=payload.get("proxies", getProxies()),+ )+++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/pack.py b/features/bittorrent_pack/pack.pyindex 16a5c03d..ab77a1b5 100644--- a/features/bittorrent_pack/pack.py+++ b/features/bittorrent_pack/pack.py@@ -7,8 +7,9 @@ from app.bases.models import Taskfrom app.services.core_service import coreServicefrom .cards import BitTorrentResultCard, BTTaskCard-from .config import bittorrentConfig, getCachedWebTrackers, refreshConfiguredWebTrackers-from .task import resolve as _btResolve, loadLocalTorrent+from .config import bittorrentConfig+from .loaders import loadLocalTorrent, resolve as _btResolve+from .web_tracker.service import webTrackerServicedef _isTorrentUrl(url: str) -> bool:@@ -30,13 +31,10 @@ class BitTorrentPack(FeaturePack):config = bittorrentConfigdef setup(self, mainWindow):- if getCachedWebTrackers():+ if webTrackerService.mergedTrackers():return- coreService.runCoroutine(- refreshConfiguredWebTrackers(),- self._onTrackersLoaded,- )+ coreService.runCoroutine(webTrackerService.refresh(), self._onTrackersLoaded)def matches(self, url: str) -> bool:return _isTorrentUrl(url)@@ -55,5 +53,10 @@ class BitTorrentPack(FeaturePack):logger.warning("初始化 Web Tracker 失败: {}", error)return- logger.info("已自动初始化 {} 条 Web Tracker", len(result or []))- bittorrentConfig.webTrackerCard.refreshContent()+ success, total = result+ logger.info(+ "已自动初始化 {} 条 Web Tracker (成功 {}/{} 个源)",+ len(webTrackerService.mergedTrackers()),+ success,+ total,+ )diff --git a/features/bittorrent_pack/task.py b/features/bittorrent_pack/task.pyindex 38b7c441..d6a1b195 100644--- a/features/bittorrent_pack/task.py+++ b/features/bittorrent_pack/task.py@@ -1,132 +1,14 @@import asyncio-from base64 import b64decode, b64encodefrom dataclasses import dataclass, field-from datetime import timedeltafrom pathlib import Path, PurePosixPath-from tempfile import gettempdirfrom typing import Any-from urllib.parse import unquote, urlparse, urlsplit-from urllib.request import url2pathname-import libtorrent as lt-import niquestsfrom loguru import logger-from app.bases.interfaces import Workerfrom app.bases.models import Task, TaskStage, TaskStatus-from app.supports.config import DEFAULT_HEADERS, VERSION, cfg-from app.supports.utils import getProxies, toSafeFilename, splitCookies-from .config import bittorrentConfig, getCachedWebTrackers, refreshConfiguredWebTrackers-from .trackers import mergeTrackers+from app.supports.utils import getProxies, toSafeFilename-BITTORRENT_USER_AGENT = f"GhostDownloader/{VERSION} libtorrent/{lt.__version__}"--_PROXY_TYPE_MAP = {- "http": lt.proxy_type_t.http,- "https": lt.proxy_type_t.http_pw,- "socks4": lt.proxy_type_t.socks4,- "socks5": lt.proxy_type_t.socks5,-}--_STATE_TEXT_MAP = {- "checking_files": "校验已有文件",- "checking_resume_data": "检查续传状态",- "downloading_metadata": "获取元数据",- "downloading": "下载中",- "finished": "下载完成",- "seeding": "做种中",- "allocating": "分配文件中",- "queued_for_checking": "等待校验",-}---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---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: dict[str, Any] = {- "user_agent": BITTORRENT_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,- }-- if proxies:- proxyUrl = str(proxies.get("https") or proxies.get("http") or "").strip()- if proxyUrl:- parsed = urlsplit(proxyUrl)- if parsed.hostname and parsed.port:- settings.update({- "proxy_type": _PROXY_TYPE_MAP.get(parsed.scheme.lower(), lt.proxy_type_t.none),- "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,- })-- if extraSettings:- settings.update(extraSettings)-- session = lt.session(settings)- session.set_alert_mask(int(lt.alert.category_t.all_categories))- return session---def _extractTrackers(ti: lt.torrent_info) -> list[str]:- seen: set[str] = set()- return [- url for tracker in ti.trackers()- if (url := str(tracker.url).strip()) and url not in seen and not seen.add(url)- ]---async def _fetchTrackers() -> 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()+from .config import bittorrentConfig@dataclass@@ -145,10 +27,10 @@ class BTFile:@dataclass(kw_only=True, eq=False)class BTTask(Task):- packId: str = field(default="bt")+ packId: str = "bt"sourceType: strtorrentData: str- resumeData: str = field(default="")+ resumeData: str = ""trackers: list[str] = field(default_factory=list)files: list[BTFile] = field(default_factory=list)proxies: dict | None = field(default_factory=getProxies)@@ -165,14 +47,14 @@ class BTTask(Task):seedRatioLimitPercent: int = field(default_factory=lambda: bittorrentConfig.seedRatioLimitPercent.value)seedTimeLimitMinutes: int = field(default_factory=lambda: bittorrentConfig.seedTimeLimitMinutes.value)saveMagnetTorrentFile: bool = field(default_factory=lambda: bittorrentConfig.saveMagnetTorrentFile.value)- shareRatioPercent: float = field(default=0)- seedingTimeSeconds: int = field(default=0)- isSeeding: bool = field(default=False)- 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 = 0+ seedingTimeSeconds: int = 0+ isSeeding: bool = False+ stateText: str = ""+ peerCount: int = 0+ seedCount: int = 0+ downloadRate: int = 0+ uploadRate: int = 0def __post_init__(self):self.files = [@@ -209,7 +91,7 @@ class BTTask(Task):@propertydef hasUnselected(self) -> bool:- return self.countSelected < self.countAll+ return not all(file.selected for file in self.files)def mapPath(self, file: BTFile) -> str:if self.isSingleFile:@@ -265,7 +147,7 @@ class BTTask(Task):file.downloadedBytes = 0file.completed = Falsecontinue- downloaded = int(fileBytes[file.index]) if file.index < len(fileBytes) else 0+ downloaded = fileBytes[file.index] if file.index < len(fileBytes) else 0file.downloadedBytes = downloadedfile.completed = file.size > 0 and downloaded >= file.size@@ -295,6 +177,8 @@ class BTTask(Task):self.usesSlot = not self.isSeedingasync def run(self):+ from .worker import BTWorker+try:for stage in self.pendingStages():await BTWorker(stage).run()@@ -309,484 +193,3 @@ class BTTask(Task):def __hash__(self):return hash(self.taskId)---class BTWorker(Worker):- def __init__(self, stage: TaskStage):- super().__init__(stage)- self.stage = stage- self.task: BTTask = stage._task- self.session: lt.session | None = None- self.handle: lt.torrent_handle | None = None- self._appliedSettingsVersion = -1- self._seedingTimeBaseSeconds = self.task.seedingTimeSeconds- self._sessionSeedingStartSeconds: int | None = None-- def _buildArgs(self) -> lt.add_torrent_params:- if self.task.resumeData:- try:- params = lt.read_resume_data(b64decode(self.task.resumeData.encode("ascii")))- except Exception as e:- logger.opt(exception=e).warning("读取 BitTorrent resume 数据失败,改用种子元数据 {}", self.task.title)- params = None- else:- params = None-- if params is None:- params = lt.add_torrent_params()- params.ti = lt.torrent_info(b64decode(self.task.torrentData.encode("ascii")))- flags = int(params.flags)- if self.task.sequentialDownload:- flags |= int(lt.torrent_flags.sequential_download)- else:- flags &= ~int(lt.torrent_flags.sequential_download)- params.flags = flags | int(lt.torrent_flags.update_subscribe)-- # 即使从 resume 恢复也要覆盖参数,确保用户修改的设置生效- params.save_path = str(self.task.path)- params.storage_mode = lt.storage_mode_t.storage_mode_allocate if self.task.storageMode == "allocate" else lt.storage_mode_t.storage_mode_sparse- params.file_priorities = self.task.priorities()- 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()- return params-- def _mapFiles(self):- if self.handle is None:- return- for file in self.task.files:- mappedPath = self.task.mapPath(file)- if mappedPath == file.path:- continue- self.handle.rename_file(file.index, mappedPath)-- def _updateSettings(self):- if self.handle is None or self._appliedSettingsVersion == self.task.fileSelectionVersion:- return- self.handle.prioritize_files(self.task.priorities())- 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._appliedSettingsVersion = self.task.fileSelectionVersion-- def _updateStatus(self, status: lt.torrent_status):- wasSeeding = self.task.isSeeding- totalWanted = int(status.total_wanted)- totalWantedDone = int(status.total_wanted_done)- isSeeding = bool(status.is_seeding)- sessionSeedingSeconds = int((status.seeding_duration or status.seeding_time).total_seconds() if isinstance(status.seeding_duration or status.seeding_time, timedelta) else int(status.seeding_duration or status.seeding_time))-- self.task.stateText = _STATE_TEXT_MAP.get(status.state.name, status.state.name)- self.task.peerCount = int(status.num_peers)- self.task.seedCount = int(status.num_seeds)- self.task.isSeeding = isSeeding- self.task._updateSlot()- self.task.downloadRate = int(status.download_rate)- self.task.uploadRate = int(status.upload_rate)-- downloaded = int(status.all_time_download or status.total_wanted_done or status.total_done)- self.task.shareRatioPercent = (status.all_time_upload / downloaded * 100) if downloaded > 0 else 0.0-- if isSeeding:- if not wasSeeding:- self._seedingTimeBaseSeconds = self.task.seedingTimeSeconds- self._sessionSeedingStartSeconds = sessionSeedingSeconds- elif self._sessionSeedingStartSeconds is None:- self._sessionSeedingStartSeconds = sessionSeedingSeconds- self.task.seedingTimeSeconds = self._seedingTimeBaseSeconds + max(- 0,- sessionSeedingSeconds - self._sessionSeedingStartSeconds,- )- elif wasSeeding:- self._seedingTimeBaseSeconds = self.task.seedingTimeSeconds- self._sessionSeedingStartSeconds = None-- self.stage.speed = self.task.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.task.isSeeding:- from app.services.core_service import coreService- coreService.rebalance()-- def _updateFiles(self):- if self.handle is None:- return- try:- fileBytes = list(self.handle.file_progress())- except Exception:- return- self.task.updateProgress(fileBytes)-- def _shouldStopSeding(self) -> bool:- if not self.task.isSeeding:- return False-- ratioLimit = self.task.seedRatioLimitPercent- if ratioLimit > 0 and self.task.shareRatioPercent >= ratioLimit:- logger.info(- "{} 自动暂停做种: 分享率达到 {:.2f}% / {}%",- self.task.title, self.task.shareRatioPercent, ratioLimit,- )- return True-- timeLimitMinutes = self.task.seedTimeLimitMinutes- if timeLimitMinutes > 0 and self.task.seedingTimeSeconds >= timeLimitMinutes * 60:- logger.info(- "{} 自动暂停做种: 做种时间达到 {} / {} 分钟",- self.task.title, round(self.task.seedingTimeSeconds / 60), timeLimitMinutes,- )- return True-- return False-- 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 _saveResume(self):- if self.handle is None or self.session is None:- self.task.resumeData = ""- 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)- self.task.resumeData = ""- 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):- self.task.resumeData = b64encode(lt.write_resume_data_buf(alert.params)).decode("ascii")- return- if isinstance(alert, lt.save_resume_data_failed_alert):- logger.warning("保存 BitTorrent resume 数据失败 {}: {}", self.task.title, alert.message())- self.task.resumeData = ""- return- self._handleAlerts(alerts, raiseOnError=False)- await asyncio.sleep(0.1)-- logger.warning("等待 BitTorrent resume 数据超时 {}", self.task.title)- self.task.resumeData = ""-- def _saveMagnetFile(self):- torrentPath = self.task.magnetTorrentPath- if torrentPath is None:- return- try:- torrentPath.write_bytes(b64decode(self.task.torrentData.encode("ascii")))- except Exception as e:- logger.opt(exception=e).warning("保存 magnet 种子文件失败 {}", self.task.title)-- async def run(self):- if self.task.countSelected <= 0:- self.stage.setStatus(TaskStatus.FAILED)- raise RuntimeError("至少需要选择一个文件")-- Path(self.task.path).mkdir(parents=True, exist_ok=True)- self._saveMagnetFile()-- 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._buildArgs()- self.handle = self.session.add_torrent(params)- self._mapFiles()- self._updateSettings()- self.session.resume()- self.handle.resume()-- while True:- alerts = list(self.session.pop_alerts())- self._handleAlerts(alerts)- self._updateSettings()-- status = self.handle.status()- self._updateStatus(status)- self._updateFiles()-- if self._shouldStopSeding():- await self._saveResume()- self.task.isSeeding = False- self.task.stateText = "已自动暂停做种"- self.stage.setStatus(TaskStatus.COMPLETED)- self.stage.progress = 100- self.stage.speed = 0- return-- await asyncio.sleep(1)- except asyncio.CancelledError:- await asyncio.shield(self._saveResume())- wasSeeding = self.task.isSeeding- self.task.stateText = "已暂停做种" if wasSeeding else "已暂停下载"- self.stage.setStatus(TaskStatus.PAUSED)- raise- except Exception as e:- await self._saveResume()- self.stage.setError(e)- raise- finally:- if self.session is not None and self.handle is not None:- try:- self.session.remove_torrent(self.handle)- except Exception:- pass- self.handle = None- self.session = None----async def _loadFromFile(source: str, webTrackers: list[str]) -> tuple[bytes, lt.torrent_info, list[str]]:- torrentPath = loadLocalTorrent(source)- if torrentPath is None:- raise ValueError("不是有效的本地 .torrent 文件路径")- torrentBytes = await asyncio.to_thread(lambda: torrentPath.resolve().read_bytes())- ti = lt.torrent_info(torrentBytes)- return torrentBytes, ti, mergeTrackers(_extractTrackers(ti), webTrackers)---async def _loadFromUrl(payload: dict, webTrackers: list[str]) -> tuple[bytes, lt.torrent_info, list[str]]:- url = str(payload["url"]).strip()- headers = payload.get("headers", DEFAULT_HEADERS)- proxies = payload.get("proxies", getProxies())- requestHeaders, requestCookies = splitCookies(- headers if isinstance(headers, dict) else DEFAULT_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,- )- response.raise_for_status()- torrentBytes = bytes(response.content)-- ti = lt.torrent_info(torrentBytes)- return torrentBytes, ti, mergeTrackers(_extractTrackers(ti), webTrackers)---def _loadFromMagnetBlocking(- url: str,- proxies: dict | None,- webTrackers: list[str],-) -> tuple[bytes, lt.torrent_info, list[str]]:- import time-- session = _createSession(- 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,- 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(), 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 = int(params.flags) | int(lt.torrent_flags.default_dont_download)- params.flags = int(params.flags) | int(lt.torrent_flags.update_subscribe)-- handle = session.add_torrent(params)- session.resume()- handle.resume()-- try:- handle.force_reannounce(0, -1, lt.reannounce_flags_t.ignore_min_interval)- except Exception:- handle.force_reannounce()- if bittorrentConfig.enableDHT.value:- try:- handle.force_dht_announce()- except Exception:- pass-- metadataTimeout = bittorrentConfig.metadataTimeout.value- try:- deadline = time.monotonic() + metadataTimeout- while time.monotonic() < deadline:- 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():- ti_bytes = lt.bencode(lt.create_torrent(ti).generate())- return ti_bytes, ti, params.trackers.copy()- 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():- ti_bytes = lt.bencode(lt.create_torrent(ti).generate())- return ti_bytes, ti, params.trackers.copy()-- time.sleep(0.2)-- raise TimeoutError("等待 magnet 元数据超时")- finally:- try:- session.remove_torrent(handle)- except Exception:- pass---async def _loadFromMagnet(- payload: dict,- webTrackers: list[str],-) -> tuple[bytes, lt.torrent_info, list[str]]:- url = str(payload["url"]).strip()- proxies = payload.get("proxies", getProxies())- return await asyncio.to_thread(_loadFromMagnetBlocking, url, proxies, 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=int(files.file_size(index)),- )- for index in range(ti.num_files())- if not bool(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("ascii"),- trackers=trackers or _extractTrackers(ti),- files=entries,- proxies=payload.get("proxies", getProxies()),- )---async def resolve(payload: dict) -> BTTask:- url = str(payload["url"]).strip()- webTrackers = await _fetchTrackers()-- # Fixes https://github.com/XiaoYouChR/Ghost-Downloader-3/issues/448- localTorrentPath = loadLocalTorrent(url)- if localTorrentPath is not None:- torrentBytes, ti, trackers = await _loadFromFile(url, webTrackers)- return await asyncio.to_thread(- _buildTask,- ti,- payload=payload,- sourceType="torrent",- sourceUrl=str(localTorrentPath.resolve()),- torrentBytes=torrentBytes,- trackers=trackers,- )-- parsedUrl = urlparse(url)- if parsedUrl.scheme.lower() == "magnet":- torrentBytes, ti, trackers = await _loadFromMagnet(payload, webTrackers)- return await asyncio.to_thread(- _buildTask,- ti,- payload=payload,- sourceType="magnet",- sourceUrl=url,- torrentBytes=torrentBytes,- trackers=trackers,- )-- torrentBytes, ti, trackers = await _loadFromUrl(payload, webTrackers)- return await asyncio.to_thread(- _buildTask,- ti,- payload=payload,- sourceType="torrent",- sourceUrl=url,- torrentBytes=torrentBytes,- trackers=trackers,- )diff --git a/features/bittorrent_pack/trackers.py b/features/bittorrent_pack/trackers.pyindex 6ac06c0c..68eb86ab 100644--- a/features/bittorrent_pack/trackers.py+++ b/features/bittorrent_pack/trackers.py@@ -1,5 +1,7 @@+from collections.abc import Iterablefrom urllib.parse import urlsplit+import libtorrent as ltimport niquestsfrom app.supports.config import DEFAULT_HEADERS, cfg@@ -10,7 +12,7 @@ _TRACKER_SCHEMES = {"http", "https", "udp", "ws", "wss"}def toTrackers(source: str) -> str:- value = str(source or "").strip()+ value = source.strip()if not value:return ""parsed = urlsplit(value)@@ -20,30 +22,24 @@ def toTrackers(source: str) -> str: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+ 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]:diff --git a/features/bittorrent_pack/web_tracker/card.py b/features/bittorrent_pack/web_tracker/card.pynew file mode 100644index 00000000..83a99526--- /dev/null+++ b/features/bittorrent_pack/web_tracker/card.py@@ -0,0 +1,97 @@+from qfluentwidgets import (+ FluentIcon,+ PrimaryPushButton,+ SettingCard,+ StateToolTip,+ ToolButton,+ ToolTipFilter,+)++from app.services.core_service import coreService++from .dialog import WebTrackerDialog+from .service import webTrackerService+++class WebTrackerCard(SettingCard):++ def __init__(self, parent=None):+ super().__init__(+ FluentIcon.GLOBE,+ self.tr("Web Tracker"),+ "",+ parent,+ )+ # instant widget+ self.manageButton = PrimaryPushButton(self.tr("管理"), self)+ self.refreshButton = ToolButton(FluentIcon.SYNC, self)++ self._stateToolTip: StateToolTip | None = None++ self._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:+ self.refreshButton.setToolTip(self.tr("刷新缓存"))+ self.refreshButton.installEventFilter(ToolTipFilter(self.refreshButton))+ self.refreshContent()++ def _initLayout(self) -> None:+ self.hBoxLayout.addWidget(self.manageButton, 0)+ self.hBoxLayout.addSpacing(8)+ self.hBoxLayout.addWidget(self.refreshButton, 0)+ self.hBoxLayout.addSpacing(16)++ def _bind(self) -> None:+ self.manageButton.clicked.connect(self._onManageClicked)+ self.refreshButton.clicked.connect(self._refresh)+ webTrackerService.trackersChanged.connect(self.refreshContent)++ def _onManageClicked(self) -> None:+ dialog = WebTrackerDialog(self.window())+ try:+ if dialog.exec():+ self._refresh()+ finally:+ dialog.deleteLater()++ def _refresh(self) -> None:+ urls = webTrackerService.sourceUrls()+ if not urls:+ return++ self.refreshButton.setEnabled(False)+ self._stateToolTip = StateToolTip(+ self.tr("正在刷新 Web Tracker"),+ self.tr("正在拉取 {0} 个源...").format(len(urls)),+ self.window(),+ )+ self._stateToolTip.move(self._stateToolTip.getSuitablePos())+ self._stateToolTip.show()+ coreService.runCoroutine(webTrackerService.refresh(), self._onRefreshFinished)++ def _onRefreshFinished(self, result, error: str | None) -> None:+ self.refreshButton.setEnabled(True)+ if self._stateToolTip is None:+ return++ 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+ )+ )+ self._stateToolTip.setState(True)+ self._stateToolTip = Nonediff --git a/features/bittorrent_pack/web_tracker/dialog.py b/features/bittorrent_pack/web_tracker/dialog.pynew file mode 100644index 00000000..2c643934--- /dev/null+++ b/features/bittorrent_pack/web_tracker/dialog.py@@ -0,0 +1,147 @@+from PySide6.QtCore import Signal+from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget+from qfluentwidgets import (+ BodyLabel,+ CaptionLabel,+ FluentIcon,+ InfoBar,+ LineEdit,+ MessageBoxBase,+ TransparentToolButton, PrimaryToolButton, SubtitleLabel, PrimaryPushButton,+)++from app.view.components.editors import AutoSizingEdit++from ..trackers import parseTrackerText, toTrackers+from .schema import DEFAULT_WEB_TRACKER_SOURCE+from .service import webTrackerService+++class WebTrackerSourceCard(QWidget):+ removed = Signal(object)++ def __init__(self, url: str = "", cachedCount: int | None = None, parent=None):+ super().__init__(parent)+ # instant widget+ self.urlEdit = LineEdit(self)+ self.statusLabel = BodyLabel(self)+ self.deleteButton = TransparentToolButton(FluentIcon.CLOSE, self)+ # instant layout+ self.hBoxLayout = QHBoxLayout(self)++ self._initWidget(url, cachedCount)+ self._initLayout()+ self._bind()++ def url(self) -> str:+ return toTrackers(self.urlEdit.text())++ def setCachedCount(self, count: int | None) -> 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:+ self.urlEdit.setText(url)+ self.urlEdit.setPlaceholderText(DEFAULT_WEB_TRACKER_SOURCE)+ self.setCachedCount(cachedCount)++ def _initLayout(self) -> None:+ 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)+++class WebTrackerDialog(MessageBoxBase):++ def __init__(self, parent=None):+ super().__init__(parent)+ # instant widget+ self.sourceHeaderLabel = SubtitleLabel(self.tr("Tracker 源"), self.widget)+ self.addSourceButton = PrimaryPushButton(FluentIcon.ADD, "添加", self.widget)+ self.sourceContainer = QWidget(self.widget)+ self.customLabel = SubtitleLabel(self.tr("自定义 Tracker"), self.widget)+ self.customEdit = AutoSizingEdit(self.widget)+ # instant layout+ self.sourceHeaderLayout = QHBoxLayout()+ self.sourceLayout = QVBoxLayout(self.sourceContainer)+ self._sourceRows: list[WebTrackerSourceCard] = []++ self._initWidget()+ self._initLayout()+ self._bind()++ def _initWidget(self) -> None:+ 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:+ self.sourceHeaderLayout.setContentsMargins(0, 0, 0, 0)+ self.sourceHeaderLayout.addWidget(self.sourceHeaderLabel)+ self.sourceHeaderLayout.addStretch(1)+ self.sourceHeaderLayout.addWidget(self.addSourceButton)++ self.sourceLayout.setContentsMargins(0, 0, 0, 0)+ self.sourceLayout.setSpacing(8)++ self.viewLayout.addLayout(self.sourceHeaderLayout)+ self.viewLayout.addWidget(self.sourceContainer)+ self.viewLayout.addSpacing(8)+ self.viewLayout.addWidget(self.customLabel)+ self.viewLayout.addWidget(self.customEdit)++ def _bind(self) -> None:+ self.addSourceButton.clicked.connect(self._onAddSourceClicked)++ def validate(self) -> bool:+ urls: list[str] = []+ for row in self._sourceRows:+ normalized = row.url()+ if not normalized:+ InfoBar.error(+ self.tr("源地址无效"),+ self.tr("请输入有效的 HTTP/HTTPS 地址"),+ parent=self,+ )+ row.urlEdit.setFocus()+ return False+ urls.append(normalized)++ uniqueUrls = list(dict.fromkeys(urls))+ webTrackerService.setSourceUrls(uniqueUrls)+ webTrackerService.setCustomTrackers(parseTrackerText(self.customEdit.toPlainText()))+ return True++ 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()++ def _onSourceRemoved(self, row: WebTrackerSourceCard) -> None:+ self._sourceRows.remove(row)+ self.sourceLayout.removeWidget(row)+ row.deleteLater()diff --git a/features/bittorrent_pack/web_tracker/schema.py b/features/bittorrent_pack/web_tracker/schema.pynew file mode 100644index 00000000..0a6c30b5--- /dev/null+++ b/features/bittorrent_pack/web_tracker/schema.py@@ -0,0 +1,38 @@+from orjson import dumps, loads+from qfluentwidgets import ConfigSerializer, ConfigValidator+++DEFAULT_WEB_TRACKER_SOURCE = "https://cf.trackerslist.com/best.txt"+++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++ def correct(self, value) -> dict:+ return value if self.validate(value) else {}+++class SourceCacheSerializer(ConfigSerializer):+ def serialize(self, value: dict[str, list[str]]) -> str:+ return dumps(value).decode("utf-8")++ def deserialize(self, value: str) -> dict[str, list[str]]:+ try:+ result = loads(value)+ except (ValueError, TypeError):+ return {}+ if not isinstance(result, dict):+ return {}+ return {+ url: list(trackers)+ for url, trackers in result.items()+ if isinstance(url, str) and isinstance(trackers, list)+ }diff --git a/features/bittorrent_pack/web_tracker/service.py b/features/bittorrent_pack/web_tracker/service.pynew file mode 100644index 00000000..50dd6b2f--- /dev/null+++ b/features/bittorrent_pack/web_tracker/service.py@@ -0,0 +1,76 @@+import asyncio++from PySide6.QtCore import QObject, Signal++from app.supports.config import cfg++from ..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)++ def cachedCount(self, url: str) -> int | None:+ cache = self._sourceCache()+ if url not in cache:+ return None+ return len(cache[url])++ 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()++ async def refresh(self) -> tuple[int, int]:+ urls = self.sourceUrls()+ if not urls:+ self.trackersChanged.emit()+ return 0, 0++ results = await asyncio.gather(+ *(fetchWebTrackers(url) for url in urls),+ return_exceptions=True,+ )++ oldCache = self._sourceCache()+ newCache: dict[str, list[str]] = {}+ successCount = 0+ for url, result in zip(urls, results):+ if isinstance(result, Exception):+ if url in oldCache:+ newCache[url] = oldCache[url]+ else:+ newCache[url] = result+ successCount += 1++ cfg.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()diff --git a/features/bittorrent_pack/worker.py b/features/bittorrent_pack/worker.pynew file mode 100644index 00000000..4d3b83eb--- /dev/null+++ b/features/bittorrent_pack/worker.py@@ -0,0 +1,349 @@+import asyncio+from base64 import b64decode, b64encode+from typing import Any+from urllib.parse import urlsplit++import libtorrent as lt+from loguru import logger++from app.bases.interfaces import Worker+from app.bases.models import TaskStage, TaskStatus+from app.services.core_service import coreService+from app.supports.config import VERSION++from .task import BTTask+++BITTORRENT_USER_AGENT = f"GhostDownloader/{VERSION} libtorrent/{lt.__version__}"++_STATE_TEXT_MAP = {+ "checking_files": "校验已有文件",+ "checking_resume_data": "检查续传状态",+ "downloading_metadata": "获取元数据",+ "downloading": "下载中",+ "finished": "下载完成",+ "seeding": "做种中",+ "allocating": "分配文件中",+ "queued_for_checking": "等待校验",+}+++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: dict[str, Any] = {+ "user_agent": BITTORRENT_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,+ "alert_mask": lt.alert.category_t.all_categories,+ }++ if proxies:+ proxyUrl = str(proxies.get("https") or proxies.get("http") or "").strip()+ if proxyUrl:+ parsed = urlsplit(proxyUrl)+ scheme = parsed.scheme.lower()+ # 只接受 SOCKS5: HTTP/HTTPS/SOCKS4 不支持 UDP, 配上反而会拖垮 DHT 与 UDP tracker+ if scheme == "socks5" and parsed.hostname and parsed.port:+ hasCredentials = bool(parsed.username or parsed.password)+ settings.update({+ "proxy_type": lt.proxy_type_t.socks5_pw if hasCredentials else lt.proxy_type_t.socks5,+ "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,+ })++ if extraSettings:+ settings.update(extraSettings)++ return lt.session(settings)+++class BTWorker(Worker):+ def __init__(self, stage: TaskStage):+ super().__init__(stage)+ self.stage = stage+ self.task: BTTask = stage._task+ self.session: lt.session | None = None+ self.handle: lt.torrent_handle | None = None+ self._appliedSettingsVersion = -1+ self._seedingTimeBaseSeconds = self.task.seedingTimeSeconds+ self._sessionSeedingStartSeconds: int | None = None++ def _buildArgs(self) -> lt.add_torrent_params:+ if self.task.resumeData:+ try:+ params = lt.read_resume_data(b64decode(self.task.resumeData))+ except Exception as e:+ logger.opt(exception=e).warning("读取 BitTorrent resume 数据失败,改用种子元数据 {}", self.task.title)+ params = None+ else:+ params = None++ if params is None:+ params = lt.add_torrent_params()+ params.ti = lt.torrent_info(b64decode(self.task.torrentData))+ if self.task.sequentialDownload:+ params.flags |= lt.torrent_flags.sequential_download+ else:+ params.flags &= ~lt.torrent_flags.sequential_download+ params.flags |= lt.torrent_flags.update_subscribe++ # 即使从 resume 恢复也要覆盖参数,确保用户修改的设置生效+ params.save_path = str(self.task.path)+ params.storage_mode = lt.storage_mode_t.storage_mode_allocate if self.task.storageMode == "allocate" else lt.storage_mode_t.storage_mode_sparse+ params.file_priorities = self.task.priorities()+ 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()+ return params++ def _mapFiles(self):+ if self.handle is None:+ return+ for file in self.task.files:+ mappedPath = self.task.mapPath(file)+ if mappedPath == file.path:+ continue+ self.handle.rename_file(file.index, mappedPath)++ def _updateSettings(self):+ if self.handle is None or self._appliedSettingsVersion == self.task.fileSelectionVersion:+ return+ self.handle.prioritize_files(self.task.priorities())+ 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._appliedSettingsVersion = self.task.fileSelectionVersion++ def _updateStatus(self, status: lt.torrent_status):+ wasSeeding = self.task.isSeeding+ totalWanted = status.total_wanted+ totalWantedDone = status.total_wanted_done+ isSeeding = status.is_seeding+ sessionSeedingSeconds = int(status.seeding_duration.total_seconds())++ self.task.stateText = _STATE_TEXT_MAP.get(status.state.name, status.state.name)+ self.task.peerCount = status.num_peers+ self.task.seedCount = status.num_seeds+ self.task.isSeeding = isSeeding+ self.task._updateSlot()+ self.task.downloadRate = status.download_rate+ self.task.uploadRate = status.upload_rate++ downloaded = status.all_time_download or status.total_wanted_done or status.total_done+ self.task.shareRatioPercent = (status.all_time_upload / downloaded * 100) if downloaded > 0 else 0.0++ if isSeeding:+ if not wasSeeding:+ self._seedingTimeBaseSeconds = self.task.seedingTimeSeconds+ self._sessionSeedingStartSeconds = sessionSeedingSeconds+ elif self._sessionSeedingStartSeconds is None:+ self._sessionSeedingStartSeconds = sessionSeedingSeconds+ self.task.seedingTimeSeconds = self._seedingTimeBaseSeconds + max(+ 0,+ sessionSeedingSeconds - self._sessionSeedingStartSeconds,+ )+ elif wasSeeding:+ self._seedingTimeBaseSeconds = self.task.seedingTimeSeconds+ self._sessionSeedingStartSeconds = None++ self.stage.speed = self.task.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.task.isSeeding:+ coreService.rebalance()++ def _updateFiles(self):+ if self.handle is None:+ return+ self.task.updateProgress(self.handle.file_progress())++ def _shouldStopSeeding(self) -> bool:+ if not self.task.isSeeding:+ return False++ ratioLimit = self.task.seedRatioLimitPercent+ if ratioLimit > 0 and self.task.shareRatioPercent >= ratioLimit:+ logger.info(+ "{} 自动暂停做种: 分享率达到 {:.2f}% / {}%",+ self.task.title, self.task.shareRatioPercent, ratioLimit,+ )+ return True++ timeLimitMinutes = self.task.seedTimeLimitMinutes+ if timeLimitMinutes > 0 and self.task.seedingTimeSeconds >= timeLimitMinutes * 60:+ logger.info(+ "{} 自动暂停做种: 做种时间达到 {} / {} 分钟",+ self.task.title, round(self.task.seedingTimeSeconds / 60), timeLimitMinutes,+ )+ return True++ return False++ 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 _saveResume(self):+ if self.handle is None or self.session is None:+ self.task.resumeData = ""+ 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)+ self.task.resumeData = ""+ 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):+ self.task.resumeData = b64encode(lt.write_resume_data_buf(alert.params)).decode()+ return+ if isinstance(alert, lt.save_resume_data_failed_alert):+ logger.warning("保存 BitTorrent resume 数据失败 {}: {}", self.task.title, alert.message())+ self.task.resumeData = ""+ return+ self._handleAlerts(alerts, raiseOnError=False)+ await asyncio.sleep(0.1)++ logger.warning("等待 BitTorrent resume 数据超时 {}", self.task.title)+ self.task.resumeData = ""++ def _saveMagnetFile(self):+ torrentPath = self.task.magnetTorrentPath+ if torrentPath is None:+ return+ try:+ torrentPath.write_bytes(b64decode(self.task.torrentData))+ except Exception as e:+ logger.opt(exception=e).warning("保存 magnet 种子文件失败 {}", self.task.title)++ async def run(self):+ if self.task.countSelected <= 0:+ self.stage.setStatus(TaskStatus.FAILED)+ raise RuntimeError("至少需要选择一个文件")++ self.task.path.mkdir(parents=True, exist_ok=True)+ self._saveMagnetFile()++ 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._buildArgs()+ self.handle = self.session.add_torrent(params)+ self._mapFiles()+ self._updateSettings()+ self.session.resume()+ self.handle.resume()++ while True:+ alerts = list(self.session.pop_alerts())+ self._handleAlerts(alerts)+ self._updateSettings()++ status = self.handle.status()+ self._updateStatus(status)+ self._updateFiles()++ if self._shouldStopSeeding():+ await self._saveResume()+ self.task.isSeeding = False+ self.task.stateText = "已自动暂停做种"+ self.stage.setStatus(TaskStatus.COMPLETED)+ self.stage.progress = 100+ self.stage.speed = 0+ return++ await asyncio.sleep(1)+ except asyncio.CancelledError:+ await asyncio.shield(self._saveResume())+ wasSeeding = self.task.isSeeding+ self.task.stateText = "已暂停做种" if wasSeeding else "已暂停下载"+ self.stage.setStatus(TaskStatus.PAUSED)+ raise+ except Exception as e:+ await self._saveResume()+ self.stage.setError(e)+ raise+ finally:+ if self.session is not None and self.handle is not None:+ try:+ self.session.remove_torrent(self.handle)+ except Exception:+ pass+ self.handle = None+ self.session = None