The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor: 简化 BT 功能包
XiaoYouChRc59e068c40b4
diff --git a/features/bittorrent_pack/cards.py b/features/bittorrent_pack/cards.pyindex c5046c77..084b7fd7 100644--- a/features/bittorrent_pack/cards.py+++ b/features/bittorrent_pack/cards.py@@ -138,30 +138,30 @@ class BTTaskCard(UniversalTaskCard):def _metaText(self) -> str:parts: list[str] = []- if self.task.stage.stateText and self.task.stage.stateText not in {"下载中", "做种中"}:- parts.append(self.task.stage.stateText)+ if self.task.stateText and self.task.stateText not in {"下载中", "做种中"}:+ parts.append(self.task.stateText)if self.task.isSeeding and self.task.shareRatioPercent > 0:parts.append(self.tr("分享率 {0:.2f}%").format(self.task.shareRatioPercent))if self.task.isSeeding and self.task.seedingTimeSeconds > 0:parts.append(self.tr("做种 {0}").format(getReadableTime(self.task.seedingTimeSeconds)))- if self.task.stage.peerCount or self.task.stage.seedCount:+ if self.task.peerCount or self.task.seedCount:parts.append(self.tr("Peers {0} / Seeds {1}").format(- self.task.stage.peerCount,- self.task.stage.seedCount,+ self.task.peerCount,+ self.task.seedCount,))return " · ".join(parts)def _refreshInfoLayout(self):if self.task.status == TaskStatus.RUNNING:- self.speedLabel.setText(f"{getReadableSize(self.task.stage.downloadRate)}/s")- self.uploadRateLabel.setText(f"{getReadableSize(self.task.stage.uploadRate)}/s")+ self.speedLabel.setText(f"{getReadableSize(self.task.downloadRate)}/s")+ self.uploadRateLabel.setText(f"{getReadableSize(self.task.uploadRate)}/s")if self.task.isSeeding:self.leftTimeLabel.hide()- elif self.task.fileSize > 0 and self.task.stage.downloadRate > 0:+ elif self.task.fileSize > 0 and self.task.downloadRate > 0:remainingBytes = self.task.fileSize - self.task.stage.receivedBytes- self.leftTimeLabel.setText(getReadableTime(int(remainingBytes / self.task.stage.downloadRate)))+ self.leftTimeLabel.setText(getReadableTime(int(remainingBytes / self.task.downloadRate)))self.leftTimeLabel.show()else:self.leftTimeLabel.setText("--")diff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.pyindex 2890750b..25b10c8c 100644--- a/features/bittorrent_pack/pack.py+++ b/features/bittorrent_pack/pack.py@@ -8,7 +8,7 @@ from app.services.core_service import coreServicefrom .cards import BitTorrentResultCard, BTTaskCardfrom .config import bittorrentConfig, getCachedWebTrackers, refreshConfiguredWebTrackers-from .task import BTTask, parse, resolveLocalTorrentPath+from .task import BTTask, resolve as _btResolve, resolveLocalTorrentPathdef _isTorrentUrl(url: str) -> bool:@@ -42,10 +42,10 @@ class BitTorrentPack(FeaturePack):return _isTorrentUrl(url)async def resolve(self, payload: dict) -> dict:- return payload+ return {"_task": await _btResolve(payload)}def build(self, payload: dict) -> Task:- raise NotImplementedError("Use resolve() for BitTorrent tasks")+ return payload["_task"]def taskCard(self, task, parent=None):return BTTaskCard(task, parent)diff --git a/features/bittorrent_pack/task.py b/features/bittorrent_pack/task.pyindex 125d9bf9..3b5ea20d 100644--- a/features/bittorrent_pack/task.py+++ b/features/bittorrent_pack/task.py@@ -1,6 +1,5 @@import asynciofrom base64 import b64decode, b64encode-from contextlib import suppressfrom dataclasses import dataclass, fieldfrom datetime import timedeltafrom pathlib import Path, PurePosixPath@@ -22,6 +21,24 @@ from .trackers import mergeTrackersBITTORRENT_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 resolveLocalTorrentPath(source: str) -> Path | None:text = str(source).strip()@@ -41,52 +58,7 @@ def resolveLocalTorrentPath(source: str) -> Path | None:return path if path.suffix.lower() == ".torrent" else None--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(+def _createSession(*,listenPort: int,connectionsLimit: int,@@ -97,8 +69,9 @@ def _sessionSettings(enableUPnP: bool,enableNATPMP: bool,proxies: dict | None,-) -> dict[str, Any]:- settings = {+ 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,@@ -109,99 +82,38 @@ def _sessionSettings("enable_upnp": enableUPnP,"enable_natpmp": enableNATPMP,}- settings.update(_sessionProxySettings(proxies))- return settings+ 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,+ })-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 sessiondef _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 _forcePeerDiscovery(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-+ 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]:@@ -231,28 +143,9 @@ class BTFile:self.path = str(PurePosixPath(str(self.path).replace("\\", "/")))-@dataclass-class BTStage(TaskStage):- outputFile: str-- def __post_init__(self):- self.stateText = ""- self.peerCount = 0- self.seedCount = 0- self.downloadRate = 0- self.uploadRate = 0-- def reset(self, sync: bool = True):- super().reset(sync=sync)- self.stateText = ""- self.peerCount = 0- self.seedCount = 0- self.downloadRate = 0- self.uploadRate = 0--@dataclass(kw_only=True)class BTTask(Task):+ packId: str = field(default="bt")sourceType: strtorrentData: strresumeData: str = field(default="")@@ -275,6 +168,11 @@ class BTTask(Task):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)def __post_init__(self):self.files = [@@ -284,11 +182,10 @@ class BTTask(Task):self.fileSelectionVersion = 0self.title = sanitizeFilename(self.title, fallback="torrent")super().__post_init__()- self._recalculateSelection()- self.syncStagePaths()+ self.fileSize = sum(file.size for file in self.files if file.selected)@property- def stage(self) -> BTStage:+ def stage(self) -> TaskStage:return self.stages[0]@property@@ -313,23 +210,14 @@ class BTTask(Task):def hasUnselected(self) -> bool:return self.countSelected < self.countAll- def syncStagePaths(self):- self.stage.outputFile = self.outputFolder-def mapPath(self, file: BTFile) -> str:if self.isSingleFile:- return self.title.replace("\\", "/")-- parts = list(PurePosixPath(file.path).parts)- parts[0] = self.title- return str(PurePosixPath(*parts))+ return self.title+ return str(PurePosixPath(self.title, *PurePosixPath(file.path).parts[1:]))def priorities(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 setSelection(self, selectedIndexes: set[int]):if not selectedIndexes:raise ValueError("至少需要选择一个文件")@@ -350,7 +238,7 @@ class BTTask(Task):returnself.fileSelectionVersion += 1- self._recalculateSelection()+ self.fileSize = sum(file.size for file in self.files if file.selected)def reopen(self) -> bool:if self.stage.status != TaskStatus.COMPLETED:@@ -361,7 +249,7 @@ class BTTask(Task):self.isSeeding = Falseself._updateSlot()- self.stage.stateText = "已添加新的下载文件"+ self.stateText = "已添加新的下载文件"self.stage.setStatus(TaskStatus.PAUSED)self.stage.receivedBytes = sum(file.downloadedBytes for file in self.files if file.selected)if self.fileSize > 0:@@ -370,13 +258,13 @@ class BTTask(Task):self.stage.progress = 0return True- def setProgress(self, progresses: list[int]):+ def updateProgress(self, fileBytes: list[int]):for file in self.files:if not file.selected:file.downloadedBytes = 0file.completed = Falsecontinue- downloaded = int(progresses[file.index]) if file.index < len(progresses) else 0+ downloaded = int(fileBytes[file.index]) if file.index < len(fileBytes) else 0file.downloadedBytes = downloadedfile.completed = file.size > 0 and downloaded >= file.size@@ -384,7 +272,6 @@ class BTTask(Task):super().applySettings(payload)if "proxies" in payload:self.proxies = payload.get("proxies")- self.syncStagePaths()def reset(self) -> TaskStatus:result = super().reset()@@ -393,6 +280,11 @@ class BTTask(Task):self.seedingTimeSeconds = 0self.isSeeding = Falseself._updateSlot()+ self.stateText = ""+ self.peerCount = 0+ self.seedCount = 0+ self.downloadRate = 0+ self.uploadRate = 0for file in self.files:file.downloadedBytes = 0file.completed = False@@ -419,17 +311,37 @@ class BTTask(Task):class BTWorker(Worker):- def __init__(self, stage: BTStage):+ def __init__(self, stage: TaskStage):super().__init__(stage)self.stage = stageself.task: BTTask = stage._taskself.session: lt.session | None = Noneself.handle: lt.torrent_handle | None = None- self._appliedSelectionVersion = -1+ self._appliedSettingsVersion = -1self._seedingTimeBaseSeconds = self.task.seedingTimeSecondsself._sessionSeedingStartSeconds: int | None = None- def _applyParams(self, params: lt.add_torrent_params):+ def _buildParams(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_sparseparams.file_priorities = self.task.priorities()@@ -438,82 +350,51 @@ class BTWorker(Worker):params.max_connections = self.task.connectionsLimitif self.task.trackers:params.trackers = self.task.trackers.copy()-- def _buildParams(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)- else:- self._applyParams(params)- return params-- params = lt.add_torrent_params()- params.ti = lt.torrent_info(b64decode(self.task.torrentData.encode("ascii")))- self._applyParams(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 _renameFiles(self):+ def _mapFiles(self):if self.handle is None:return-for file in self.task.files:mappedPath = self.task.mapPath(file)if mappedPath == file.path:continueself.handle.rename_file(file.index, mappedPath)- def _syncSelection(self):- if self.handle is None or self._appliedSelectionVersion == self.task.fileSelectionVersion:+ def _updateSettings(self):+ if self.handle is None or self._appliedSettingsVersion == self.task.fileSelectionVersion:returnself.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._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 _syncStatus(self, status: lt.torrent_status):+ self._appliedSettingsVersion = self.task.fileSelectionVersion++ def _updateStatus(self, status: lt.torrent_status):wasSeeding = self.task.isSeedingtotalWanted = 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.stage.stateText = self._stateText(status)- self.stage.peerCount = int(status.num_peers)- self.stage.seedCount = int(status.num_seeds)++ 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 = isSeedingself.task._updateSlot()- self.stage.downloadRate = int(status.download_rate)- self.stage.uploadRate = int(status.upload_rate)+ 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.seedingTimeSecondsself._sessionSeedingStartSeconds = sessionSeedingSecondselif self._sessionSeedingStartSeconds is None:self._sessionSeedingStartSeconds = sessionSeedingSeconds-self.task.seedingTimeSeconds = self._seedingTimeBaseSeconds + max(0,sessionSeedingSeconds - self._sessionSeedingStartSeconds,@@ -521,7 +402,8 @@ class BTWorker(Worker):elif wasSeeding:self._seedingTimeBaseSeconds = self.task.seedingTimeSecondsself._sessionSeedingStartSeconds = None- self.stage.speed = self.stage.downloadRate++ self.stage.speed = self.task.downloadRateself.stage.receivedBytes = totalWantedDoneif totalWanted > 0:@@ -534,36 +416,40 @@ class BTWorker(Worker):if wasSeeding != self.task.isSeeding:from app.services.core_service import coreService-coreService.notifyTaskSchedulingChanged()- def _syncFiles(self):+ def _updateFiles(self):if self.handle is None:returntry:- progresses = list(self.handle.file_progress())+ fileBytes = list(self.handle.file_progress())except Exception:return- self.task.setProgress(progresses)+ self.task.updateProgress(fileBytes)- def _seedStopReason(self) -> str:+ def _shouldStopSeding(self) -> bool:if not self.task.isSeeding:- return ""+ return FalseratioLimit = self.task.seedRatioLimitPercentif ratioLimit > 0 and self.task.shareRatioPercent >= ratioLimit:- return "分享率达到 {0:.2f}% / {1}%".format(self.task.shareRatioPercent, ratioLimit)+ logger.info(+ "{} 自动暂停做种: 分享率达到 {:.2f}% / {}%",+ self.task.title, self.task.shareRatioPercent, ratioLimit,+ )+ return TruetimeLimitMinutes = self.task.seedTimeLimitMinutesif timeLimitMinutes > 0 and self.task.seedingTimeSeconds >= timeLimitMinutes * 60:- return "做种时间达到 {0} / {1} 分钟".format(- round(self.task.seedingTimeSeconds / 60),- timeLimitMinutes,+ logger.info(+ "{} 自动暂停做种: 做种时间达到 {} / {} 分钟",+ self.task.title, round(self.task.seedingTimeSeconds / 60), timeLimitMinutes,)+ return True- return ""+ return False- def _processAlerts(self, alerts: list[lt.alert], *, raiseOnError: bool = True):+ 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:@@ -592,9 +478,10 @@ class BTWorker(Worker):):raise RuntimeError(alert.message())- async def _saveResume(self) -> str:+ async def _saveResume(self):if self.handle is None or self.session is None:- return ""+ self.task.resumeData = ""+ returntry:self.handle.save_resume_data(@@ -602,43 +489,37 @@ class BTWorker(Worker):)except Exception as e:logger.opt(exception=e).warning("保存 BitTorrent resume 数据失败 {}", self.task.title)- return ""+ self.task.resumeData = ""+ returndeadline = asyncio.get_running_loop().time() + 10while 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 b64encode(lt.write_resume_data_buf(alert.params)).decode("ascii")+ self.task.resumeData = b64encode(lt.write_resume_data_buf(alert.params)).decode("ascii")+ returnif isinstance(alert, lt.save_resume_data_failed_alert):logger.warning("保存 BitTorrent resume 数据失败 {}: {}", self.task.title, alert.message())- return ""- self._processAlerts(alerts, raiseOnError=False)+ self.task.resumeData = ""+ return+ self._handleAlerts(alerts, raiseOnError=False)await asyncio.sleep(0.1)logger.warning("等待 BitTorrent resume 数据超时 {}", self.task.title)- return ""-- async def _shutdown(self):- if self.handle is None or self.session is None:- return- try:- self.session.remove_torrent(self.handle)- except Exception:- pass+ self.task.resumeData = ""def _saveMagnetFile(self):torrentPath = self.task.magnetTorrentPathif 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.selectedFileCount <= 0:+ if self.task.countSelected <= 0:self.stage.setStatus(TaskStatus.FAILED)raise RuntimeError("至少需要选择一个文件")@@ -660,26 +541,24 @@ class BTWorker(Worker):try:params = self._buildParams()self.handle = self.session.add_torrent(params)- self._renameFiles()- self._syncSelection()+ self._mapFiles()+ self._updateSettings()self.session.resume()self.handle.resume()while True:alerts = list(self.session.pop_alerts())- self._processAlerts(alerts)- self._syncSelection()+ self._handleAlerts(alerts)+ self._updateSettings()status = self.handle.status()- self._syncStatus(status)- self._syncFiles()+ self._updateStatus(status)+ self._updateFiles()- pauseReason = self._seedStopReason()- if pauseReason:- logger.info("{} 自动暂停做种: {}", self.task.title, pauseReason)- self.task.resumeData = await self._saveResume()+ if self._shouldStopSeding():+ await self._saveResume()self.task.isSeeding = False- self.stage.stateText = "已自动暂停做种"+ self.task.stateText = "已自动暂停做种"self.stage.setStatus(TaskStatus.COMPLETED)self.stage.progress = 100self.stage.speed = 0@@ -687,30 +566,45 @@ class BTWorker(Worker):await asyncio.sleep(1)except asyncio.CancelledError:- self.task.resumeData = await asyncio.shield(self._saveResume())+ await asyncio.shield(self._saveResume())wasSeeding = self.task.isSeeding- self.stage.stateText = "已暂停做种" if wasSeeding else "已暂停下载"+ self.task.stateText = "已暂停做种" if wasSeeding else "已暂停下载"self.stage.setStatus(TaskStatus.PAUSED)raiseexcept Exception as e:- self.task.resumeData = await self._saveResume()+ await self._saveResume()self.stage.setError(e)raisefinally:- await self._shutdown()+ if self.session is not None and self.handle is not None:+ try:+ self.session.remove_torrent(self.handle)+ except Exception:+ passself.handle = Noneself.session = None-async def _fetchTorrent(payload: dict) -> bytes:++async def _loadFromFile(source: str, webTrackers: list[str]) -> tuple[bytes, lt.torrent_info, list[str]]:+ torrentPath = resolveLocalTorrentPath(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 = splitRequestHeadersAndCookies(headers if isinstance(headers, dict) else DEFAULT_HEADERS)+ requestHeaders, requestCookies = splitRequestHeadersAndCookies(+ headers if isinstance(headers, dict) else DEFAULT_HEADERS+ )client = niquests.AsyncSession(timeout=30, happy_eyeballs=True)client.trust_env = False-try:response = await client.get(url,@@ -722,46 +616,32 @@ async def _fetchTorrent(payload: dict) -> bytes:)try:response.raise_for_status()- return bytes(response.content)+ torrentBytes = bytes(response.content)finally:- response.close()+ await response.close()finally:await client.close()--def _readLocalTorrent(source: str) -> bytes:- torrentPath = resolveLocalTorrentPath(source)- if torrentPath is None:- raise ValueError("不是有效的本地 .torrent 文件路径")- return torrentPath.resolve().read_bytes()+ ti = lt.torrent_info(torrentBytes)+ return torrentBytes, ti, mergeTrackers(_extractTrackers(ti), webTrackers)-def _resolveMagnetSync(+def _loadFromMagnetBlocking(url: str,- *,proxies: dict | None,- enableDHT: bool,- enableLSD: bool,- enableUPnP: bool,- enableNATPMP: bool,- listenPort: int,- connectionsLimit: int,- downloadRateLimit: int,- uploadRateLimit: int,- metadataTimeout: int,webTrackers: list[str],-) -> tuple[lt.torrent_info, list[str], bytes]:+) -> tuple[bytes, lt.torrent_info, list[str]]:import timesession = _createSession(- listenPort=listenPort,- connectionsLimit=connectionsLimit,- downloadRateLimit=downloadRateLimit,- uploadRateLimit=uploadRateLimit,- enableDHT=enableDHT,- enableLSD=enableLSD,- enableUPnP=enableUPnP,- enableNATPMP=enableNATPMP,+ 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,@@ -771,8 +651,9 @@ def _resolveMagnetSync(params = lt.parse_magnet_uri(url)params.trackers = mergeTrackers(params.trackers.copy(), webTrackers)- Path(gettempdir()) / "ghost_downloader_bt_metadata".mkdir(parents=True, exist_ok=True)- params.save_path = str(Path(gettempdir()) / "ghost_downloader_bt_metadata")+ 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_sparseparams.flags = int(params.flags) | int(lt.torrent_flags.default_dont_download)params.flags = int(params.flags) | int(lt.torrent_flags.update_subscribe)@@ -780,8 +661,18 @@ def _resolveMagnetSync(handle = session.add_torrent(params)session.resume()handle.resume()- _forcePeerDiscovery(handle, enableDHT=enableDHT)+ 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.valuetry:deadline = time.monotonic() + metadataTimeoutwhile time.monotonic() < deadline:@@ -790,7 +681,8 @@ def _resolveMagnetSync(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(), lt.bencode(lt.create_torrent(ti).generate())+ 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)):@@ -800,7 +692,8 @@ def _resolveMagnetSync(if status.has_metadata:ti = handle.torrent_file()if ti is not None and ti.is_valid():- return ti, params.trackers.copy(), lt.bencode(lt.create_torrent(ti).generate())+ ti_bytes = lt.bencode(lt.create_torrent(ti).generate())+ return ti_bytes, ti, params.trackers.copy()time.sleep(0.2)@@ -812,29 +705,16 @@ def _resolveMagnetSync(pass-async def _resolveMagnet(payload: dict) -> tuple[lt.torrent_info, list[str], bytes]:+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())- enableDHT = bittorrentConfig.enableDHT.value- webTrackers = await _fetchTrackers()- return await asyncio.to_thread(- _resolveMagnetSync,- url,- proxies=proxies,- enableDHT=enableDHT,- enableLSD=bittorrentConfig.enableLSD.value,- enableUPnP=bittorrentConfig.enableUPnP.value,- enableNATPMP=bittorrentConfig.enableNATPMP.value,- listenPort=bittorrentConfig.listenPort.value,- connectionsLimit=bittorrentConfig.connectionsLimit.value,- downloadRateLimit=bittorrentConfig.downloadRateLimit.value,- uploadRateLimit=bittorrentConfig.uploadRateLimit.value,- metadataTimeout=bittorrentConfig.metadataTimeout.value,- webTrackers=webTrackers,- )+ return await asyncio.to_thread(_loadFromMagnetBlocking, url, proxies, webTrackers)-def buildTask(+def _buildTask(ti: lt.torrent_info,*,payload: dict,@@ -844,74 +724,56 @@ def buildTask(trackers: list[str],) -> BTTask:files = ti.files()- entries: list[BTFile] = []- for index in range(ti.num_files()):- if bool(files.file_flags(index) & lt.file_storage.flag_pad_file):- continue- entries.append(- BTFile(- index=index,- path=files.file_path(index),- size=int(files.file_size(index)),- )+ 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 = sanitizeFilename(PurePosixPath(entries[0].path).parts[0], fallback="torrent")title = sanitizeFilename(Path(entries[0].path).name, fallback="torrent") if len(entries) == 1 else rootName- task = BTTask(++ return BTTask(title=title,url=sourceUrl,fileSize=sum(entry.size for entry in entries),path=Path(payload.get("path", cfg.downloadFolder.value)),- stages=[BTStage(stageIndex=1, outputFile="")],+ stages=[TaskStage(stageIndex=1)],sourceType=sourceType,torrentData=b64encode(torrentBytes).decode("ascii"),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,- saveMagnetTorrentFile=bittorrentConfig.saveMagnetTorrentFile.value,)- return task-async def parse(payload: dict) -> BTTask:+async def resolve(payload: dict) -> BTTask:url = str(payload["url"]).strip()+ webTrackers = await _fetchTrackers()+localTorrentPath = resolveLocalTorrentPath(url)if localTorrentPath is not None:- torrentBytes, webTrackers = await asyncio.gather(- asyncio.to_thread(_readLocalTorrent, url),- _fetchTrackers(),- )- ti = lt.torrent_info(torrentBytes)- return buildTask(+ torrentBytes, ti, trackers = await _loadFromFile(url, webTrackers)+ return _buildTask(ti,payload=payload,sourceType="torrent",sourceUrl=str(localTorrentPath.resolve()),torrentBytes=torrentBytes,- trackers=mergeTrackers(_extractTrackers(ti), webTrackers),+ trackers=trackers,)parsedUrl = urlparse(url)-if parsedUrl.scheme.lower() == "magnet":- ti, trackers, torrentBytes = await _resolveMagnet(payload)- return buildTask(+ torrentBytes, ti, trackers = await _loadFromMagnet(payload, webTrackers)+ return _buildTask(ti,payload=payload,sourceType="magnet",@@ -920,16 +782,12 @@ async def parse(payload: dict) -> BTTask:trackers=trackers,)- torrentBytes, webTrackers = await asyncio.gather(- _fetchTorrent(payload),- _fetchTrackers(),- )- ti = lt.torrent_info(torrentBytes)- return buildTask(+ torrentBytes, ti, trackers = await _loadFromUrl(payload, webTrackers)+ return _buildTask(ti,payload=payload,sourceType="torrent",sourceUrl=url,torrentBytes=torrentBytes,- trackers=mergeTrackers(_extractTrackers(ti), webTrackers),+ trackers=trackers,)