Skip to content

The only downloader you need. 下载器的集大成者。

refactor(desktop): BitTorrent 收敛为单 session 架构

XiaoYouChR5641128d5997
diff --git a/Ghost-Downloader-3.py b/Ghost-Downloader-3.py
index 75fc6bc4..47a89598 100644
--- a/Ghost-Downloader-3.py
+++ b/Ghost-Downloader-3.py
@@ -80,6 +80,7 @@ mainWindow.updateThemeColor()
if not isSilently:
mainWindow.splashScreen.finish()
+application.aboutToQuit.connect(featureService.shutdown)
application.aboutToQuit.connect(coreService.stop)
application.aboutToQuit.connect(taskService.flushNow)
diff --git a/android/main.py b/android/main.py
index 43ee6501..7d08bed7 100644
--- a/android/main.py
+++ b/android/main.py
@@ -135,6 +135,7 @@ def _onApplicationStateChanged(state: Qt.ApplicationState) -> None:
application.applicationStateChanged.connect(_onApplicationStateChanged)
+application.aboutToQuit.connect(featureService.shutdown)
application.aboutToQuit.connect(coreService.stop)
application.aboutToQuit.connect(taskService.flushNow)
diff --git a/app/bases/interfaces.py b/app/bases/interfaces.py
index 056dace9..ece04abb 100644
--- a/app/bases/interfaces.py
+++ b/app/bases/interfaces.py
@@ -53,5 +53,9 @@ class FeaturePack:
def setup(self, mainWindow: "MainWindow"):
pass
+ def shutdown(self):
+ """app 退出时释放本 pack 的长生命周期资源。Core 保证在事件循环停止前调用。"""
+ pass
+
def tr(self, text: str) -> str:
return QCoreApplication.translate(self.__class__.__name__, text)
diff --git a/app/services/core_service.py b/app/services/core_service.py
index 9636e3a2..60545ca2 100644
--- a/app/services/core_service.py
+++ b/app/services/core_service.py
@@ -86,6 +86,13 @@ class CoreService(QThread):
return ""
+ def runBlocking(self, coroutine: Coroutine, timeout: float | None = None):
+ """从其它线程把协程丢到核心事件循环上跑并阻塞等结果(app 退出前收尾用)。"""
+ if not self.loop.is_running():
+ coroutine.close()
+ return None
+ return asyncio.run_coroutine_threadsafe(coroutine, self.loop).result(timeout)
+
async def _runCoroutine(self, coroutine: Coroutine, callbackId):
try:
result = await coroutine
diff --git a/app/services/feature_service.py b/app/services/feature_service.py
index aa9c1200..65a9ad1c 100644
--- a/app/services/feature_service.py
+++ b/app/services/feature_service.py
@@ -309,5 +309,12 @@ class FeatureService:
logger.warning("FeaturePack 加载完成: {}/{} 个成功加载", loadedCount, len(featurePacks))
+ def shutdown(self):
+ for packName, packInstance in self._packs.items():
+ try:
+ packInstance.shutdown()
+ except Exception as e:
+ logger.opt(exception=e).error("FeaturePack.shutdown 失败 {}", packName)
+
featureService = FeatureService()
diff --git a/features/bittorrent_pack/loaders.py b/features/bittorrent_pack/loaders.py
index addc0441..ada2d7fe 100644
--- a/features/bittorrent_pack/loaders.py
+++ b/features/bittorrent_pack/loaders.py
@@ -1,8 +1,6 @@
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
@@ -15,10 +13,10 @@ from app.bases.models import TaskStage
from app.supports.config import cfg, defaultHeaders
from app.supports.utils import getProxies, splitCookies, toSafeFilename
from .config import bittorrentConfig
+from .session import btSessionService
from .task import BTFile, BTTask
from .trackers import mergeTrackers
from .web_tracker.service import webTrackerService
-from .worker import createSession
def loadLocalTorrent(source: str) -> Path | None:
@@ -71,72 +69,12 @@ async def _loadFromUrl(payload: dict) -> tuple[bytes, lt.torrent_info]:
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)
+ return await btSessionService.fetchMetadata(url, webTrackers)
def _buildTask(
@@ -175,7 +113,6 @@ def _buildTask(
torrentData=b64encode(torrentBytes).decode(),
trackers=trackers,
files=entries,
- proxies=payload.get("proxies", getProxies()),
)
diff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.py
index 3675a4bb..29112e51 100644
--- a/features/bittorrent_pack/pack.py
+++ b/features/bittorrent_pack/pack.py
@@ -9,6 +9,7 @@ from app.supports import file_association
from .cards import BitTorrentResultCard, BTTaskCard
from .config import bittorrentConfig
from .loaders import loadLocalTorrent, resolve as _btResolve
+from .session import btSessionService
from .web_tracker.service import webTrackerService
@@ -40,6 +41,9 @@ class BitTorrentPack(FeaturePack):
coreService.runCoroutine(webTrackerService.refresh(), self._onTrackersLoaded)
+ def shutdown(self):
+ btSessionService.shutdown()
+
def _onAssociationToggled(self, enabled: bool):
if enabled:
file_association.register(self.fileTypes())
diff --git a/features/bittorrent_pack/session.py b/features/bittorrent_pack/session.py
new file mode 100644
index 00000000..6a169e66
--- /dev/null
+++ b/features/bittorrent_pack/session.py
@@ -0,0 +1,468 @@
+"""全 app 唯一的 libtorrent session。
+
+主流 BT 客户端(qBittorrent/Deluge)都是一个进程一个 session,所有 torrent 加进同一个
+session,由它统一持有监听端口 / DHT / 限速器 / 连接池,并用一条 alert 泵驱动全部 torrent。
+本模块就是这个角色:Pack 拥有 session 这台机器,Core 只负责调度(占不占 slot)。
+
+每个 BTTask 通过 `lease()` 把自己的 torrent 登记进来、挂起等终态;泵循环直接把
+`torrent_status` 写回各 task 字段,并在做种到限额时 resolve 对应 Future 让 worker 收尾。
+"""
+
+import asyncio
+from base64 import b64decode, b64encode
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import gettempdir
+from urllib.parse import urlsplit
+
+import libtorrent as lt
+from loguru import logger
+
+from app.services.core_service import coreService
+from app.supports.config import VERSION
+from app.supports.utils import getProxies
+from .config import bittorrentConfig
+from .task import BTTask
+from .trackers import mergeTrackers
+
+USER_AGENT = f"GhostDownloader/{VERSION} libtorrent/{lt.__version__}"
+
+# torrent_status.state.name → 展示文案
+_STATE_TEXT = {
+ "checking_files": "校验已有文件",
+ "checking_resume_data": "检查续传状态",
+ "downloading_metadata": "获取元数据",
+ "downloading": "下载中",
+ "finished": "下载完成",
+ "seeding": "做种中",
+ "allocating": "分配文件中",
+ "queued_for_checking": "等待校验",
+}
+
+_ERROR_ALERTS = (
+ lt.file_error_alert,
+ lt.metadata_failed_alert,
+ lt.torrent_error_alert,
+ lt.hash_failed_alert,
+)
+
+
+@dataclass(eq=False)
+class _ActiveTorrent:
+ """session 视角下的一条在跑 torrent:把 task、handle 与做种计时记在一处。"""
+
+ task: BTTask
+ handle: lt.torrent_handle
+ done: asyncio.Future
+ resumeWaiter: asyncio.Future | None = None
+ appliedSelectionVersion: int = -1
+ _seedBase: int = field(init=False)
+ _seedStart: int | None = field(default=None, init=False)
+
+ def __post_init__(self):
+ self._seedBase = self.task.seedingTimeSeconds
+
+ def seedingElapsed(self, isSeeding: bool, sessionSeconds: int) -> int:
+ if isSeeding:
+ if self._seedStart is None:
+ self._seedStart = sessionSeconds
+ return self._seedBase + max(0, sessionSeconds - self._seedStart)
+ if self._seedStart is not None:
+ self._seedBase += max(0, sessionSeconds - self._seedStart)
+ self._seedStart = None
+ return self._seedBase
+
+
+class BTSessionService:
+ def __init__(self):
+ self._session: lt.session | None = None
+ self._pump: asyncio.Task | None = None
+ self._active: dict[str, _ActiveTorrent] = {}
+ self._pendingMetadata: list[tuple[lt.torrent_handle, asyncio.Future]] = []
+ for item in (
+ bittorrentConfig.downloadRateLimit,
+ bittorrentConfig.uploadRateLimit,
+ bittorrentConfig.connectionsLimit,
+ ):
+ item.valueChanged.connect(self._onLimitsChanged)
+
+ # ── 对 worker:登记一条 torrent,挂起到终态 ──────────────────────────────
+ async def lease(self, task: BTTask):
+ if task.countSelected <= 0:
+ raise RuntimeError("至少需要选择一个文件")
+
+ self._prepareTarget(task)
+ self._saveMagnetFile(task)
+ self._open()
+
+ handle = self._addTorrent(task)
+ handle.resume()
+ handle.force_reannounce(0, -1, lt.reannounce_flags_t.ignore_min_interval)
+ if bittorrentConfig.enableDHT.value:
+ handle.force_dht_announce()
+
+ active = _ActiveTorrent(task, handle, asyncio.get_running_loop().create_future())
+ self._active[task.taskId] = active
+ try:
+ await active.done
+ finally:
+ await asyncio.shield(self._removeTorrent(active))
+
+ # ── 对 loaders:磁力取元数据,复用共享 session 的热 DHT ─────────────────
+ async def fetchMetadata(
+ self, magnetUri: str, webTrackers: list[str]
+ ) -> tuple[bytes, lt.torrent_info, list[str]]:
+ self._open()
+
+ params = lt.parse_magnet_uri(magnetUri)
+ params.trackers = mergeTrackers(params.trackers, webTrackers)
+ tempDir = Path(gettempdir()) / "ghost_downloader_bt_metadata"
+ tempDir.mkdir(parents=True, exist_ok=True)
+ params.save_path = str(tempDir)
+ params.storage_mode = lt.storage_mode_t.storage_mode_sparse
+ params.flags |= lt.torrent_flags.default_dont_download | lt.torrent_flags.update_subscribe
+
+ handle = self._session.add_torrent(params)
+ handle.force_reannounce(0, -1, lt.reannounce_flags_t.ignore_min_interval)
+ if bittorrentConfig.enableDHT.value:
+ handle.force_dht_announce()
+
+ waiter = asyncio.get_running_loop().create_future()
+ self._pendingMetadata.append((handle, waiter))
+ try:
+ ti = await asyncio.wait_for(waiter, timeout=bittorrentConfig.metadataTimeout.value)
+ torrentBytes = lt.bencode(lt.create_torrent(ti).generate())
+ except asyncio.TimeoutError:
+ raise TimeoutError("等待 magnet 元数据超时")
+ finally:
+ self._pendingMetadata.remove((handle, waiter))
+ try:
+ self._session.remove_torrent(handle)
+ except Exception:
+ pass
+
+ return torrentBytes, ti, params.trackers.copy()
+
+ # ── 对 Core:app 退出前优雅关闭(必须在事件循环停止前完成)─────────────
+ def shutdown(self):
+ if self._session is None:
+ return
+ try:
+ coreService.runBlocking(self._shutdown(), timeout=15)
+ except Exception as e:
+ logger.opt(exception=e).warning("BitTorrent session 关闭异常")
+
+ async def _shutdown(self):
+ actives = list(self._active.values())
+ if actives:
+ await asyncio.gather(
+ *(self._saveResume(active) for active in actives),
+ return_exceptions=True,
+ )
+
+ if self._pump is not None:
+ self._pump.cancel()
+ try:
+ await self._pump
+ except asyncio.CancelledError:
+ pass
+ self._pump = None
+
+ session, self._session = self._session, None
+ if session is not None:
+ for active in actives:
+ try:
+ session.remove_torrent(active.handle)
+ except Exception:
+ pass
+ self._active.clear()
+
+ # ── session / 泵 的拉起 ────────────────────────────────────────────────
+ def _open(self):
+ if self._session is None:
+ self._session = lt.session(self._sessionSettings())
+ if self._pump is None or self._pump.done():
+ self._pump = asyncio.get_running_loop().create_task(self._pumpLoop())
+
+ def _sessionSettings(self) -> dict:
+ settings = {
+ "user_agent": USER_AGENT,
+ "listen_interfaces": f"0.0.0.0:{bittorrentConfig.listenPort.value}",
+ "connections_limit": bittorrentConfig.connectionsLimit.value,
+ "download_rate_limit": bittorrentConfig.downloadRateLimit.value,
+ "upload_rate_limit": bittorrentConfig.uploadRateLimit.value,
+ "enable_dht": bittorrentConfig.enableDHT.value,
+ "enable_lsd": bittorrentConfig.enableLSD.value,
+ "enable_upnp": bittorrentConfig.enableUPnP.value,
+ "enable_natpmp": bittorrentConfig.enableNATPMP.value,
+ "announce_to_all_trackers": True,
+ "announce_to_all_tiers": True,
+ "alert_mask": lt.alert.category_t.all_categories,
+ }
+ settings.update(self._proxySettings(getProxies()))
+ return settings
+
+ def _proxySettings(self, proxies: dict | None) -> dict:
+ if not proxies:
+ return {}
+ proxyUrl = str(proxies.get("https") or proxies.get("http") or "").strip()
+ if not proxyUrl:
+ return {}
+ parsed = urlsplit(proxyUrl)
+ # 只接受 SOCKS5: HTTP/HTTPS/SOCKS4 不支持 UDP, 配上反而会拖垮 DHT 与 UDP tracker
+ if parsed.scheme.lower() != "socks5" or not parsed.hostname or not parsed.port:
+ return {}
+ hasCredentials = bool(parsed.username or parsed.password)
+ return {
+ "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,
+ }
+
+ def _onLimitsChanged(self, _=None):
+ if self._session is None:
+ return
+ self._session.apply_settings({
+ "download_rate_limit": bittorrentConfig.downloadRateLimit.value,
+ "upload_rate_limit": bittorrentConfig.uploadRateLimit.value,
+ "connections_limit": bittorrentConfig.connectionsLimit.value,
+ })
+
+ # ── 把一条 torrent 加进 session ───────────────────────────────────────
+ def _addTorrent(self, task: BTTask) -> lt.torrent_handle:
+ params = None
+ if task.resumeData:
+ try:
+ params = lt.read_resume_data(b64decode(task.resumeData))
+ except Exception as e:
+ logger.opt(exception=e).warning("读取 BitTorrent resume 数据失败,改用种子元数据 {}", task.title)
+
+ if params is None:
+ params = lt.add_torrent_params()
+ params.ti = lt.torrent_info(b64decode(task.torrentData))
+ params.flags |= lt.torrent_flags.update_subscribe
+
+ params.save_path = str(task.path)
+ params.storage_mode = (
+ lt.storage_mode_t.storage_mode_allocate
+ if bittorrentConfig.storageMode.value == "allocate"
+ else lt.storage_mode_t.storage_mode_sparse
+ )
+ params.file_priorities = task.priorities()
+ if bittorrentConfig.sequentialDownload.value:
+ params.flags |= lt.torrent_flags.sequential_download
+ else:
+ params.flags &= ~lt.torrent_flags.sequential_download
+ if task.trackers:
+ params.trackers = task.trackers.copy()
+
+ handle = self._session.add_torrent(params)
+ for file in task.files:
+ mappedPath = task.mapPath(file)
+ if mappedPath != file.path:
+ handle.rename_file(file.index, mappedPath)
+ return handle
+
+ def _prepareTarget(self, task: BTTask):
+ target = Path(task.outputFolder)
+ if target.exists():
+ return
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.touch() if task.isSingleFile else target.mkdir()
+
+ def _saveMagnetFile(self, task: BTTask):
+ if task.sourceType != "magnet" or not bittorrentConfig.saveMagnetTorrentFile.value:
+ return
+ torrentPath = task.magnetTorrentPath
+ if torrentPath is None:
+ return
+ try:
+ torrentPath.write_bytes(b64decode(task.torrentData))
+ except Exception as e:
+ logger.opt(exception=e).warning("保存 magnet 种子文件失败 {}", task.title)
+
+ # ── 摘除 / 存 resume ──────────────────────────────────────────────────
+ async def _removeTorrent(self, active: _ActiveTorrent):
+ # 先存 resume(此刻仍在 _active 中, 泵才能把 alert 回填)再摘除
+ await self._saveResume(active)
+ self._active.pop(active.task.taskId, None)
+ if self._session is not None:
+ try:
+ self._session.remove_torrent(active.handle)
+ except Exception:
+ pass
+
+ async def _saveResume(self, active: _ActiveTorrent):
+ if self._session is None:
+ active.task.resumeData = ""
+ return
+
+ try:
+ active.handle.save_resume_data(
+ lt.save_resume_flags_t.flush_disk_cache | lt.save_resume_flags_t.save_info_dict
+ )
+ except Exception as e:
+ logger.opt(exception=e).warning("保存 BitTorrent resume 数据失败 {}", active.task.title)
+ active.task.resumeData = ""
+ return
+
+ active.resumeWaiter = asyncio.get_running_loop().create_future()
+ try:
+ await asyncio.wait_for(active.resumeWaiter, timeout=10)
+ except asyncio.TimeoutError:
+ logger.warning("等待 BitTorrent resume 数据超时 {}", active.task.title)
+ active.task.resumeData = ""
+ finally:
+ active.resumeWaiter = None
+
+ # ── 泵:一条循环驱动所有 torrent ──────────────────────────────────────
+ async def _pumpLoop(self):
+ # 一条循环驱动全部 torrent: 单个 torrent 的瞬时错误不该掀翻整条泵
+ while self._session is not None:
+ try:
+ for alert in self._session.pop_alerts():
+ self._handleAlert(alert)
+ for active in list(self._active.values()):
+ self._applyStatus(active)
+ except Exception as e:
+ logger.opt(exception=e).error("BitTorrent 泵循环异常")
+ await asyncio.sleep(1)
+
+ def _applyStatus(self, active: _ActiveTorrent):
+ task = active.task
+ status = active.handle.status()
+ wasSeeding = task.isSeeding
+
+ task.stateText = _STATE_TEXT.get(status.state.name, status.state.name)
+ task.peerCount = status.num_peers
+ task.seedCount = status.num_seeds
+ task.isSeeding = status.is_seeding
+ task.downloadRate = status.download_rate
+ task.uploadRate = status.upload_rate
+ task._updateSlot()
+
+ downloaded = status.all_time_download or status.total_wanted_done or status.total_done
+ task.shareRatioPercent = (status.all_time_upload / downloaded * 100) if downloaded > 0 else 0.0
+ task.seedingTimeSeconds = active.seedingElapsed(
+ task.isSeeding, int(status.seeding_duration.total_seconds())
+ )
+
+ task.stage.speed = status.download_rate
+ task.stage.receivedBytes = status.total_wanted_done
+ if status.total_wanted > 0:
+ task.fileSize = status.total_wanted
+ task.stage.progress = status.total_wanted_done / status.total_wanted * 100
+ elif task.fileSize > 0:
+ task.stage.progress = task.stage.receivedBytes / task.fileSize * 100
+ else:
+ task.stage.progress = 0
+
+ task.updateProgress(active.handle.file_progress())
+
+ if active.appliedSelectionVersion != task.fileSelectionVersion:
+ active.handle.prioritize_files(task.priorities())
+ active.appliedSelectionVersion = task.fileSelectionVersion
+
+ if wasSeeding != task.isSeeding:
+ coreService.rebalance()
+
+ if self._shouldStopSeeding(task) and not active.done.done():
+ active.done.set_result(None)
+
+ def _shouldStopSeeding(self, task: BTTask) -> bool:
+ if not task.isSeeding:
+ return False
+
+ ratioLimit = bittorrentConfig.seedRatioLimitPercent.value
+ if ratioLimit > 0 and task.shareRatioPercent >= ratioLimit:
+ logger.info(
+ "{} 自动暂停做种: 分享率达到 {:.2f}% / {}%",
+ task.title, task.shareRatioPercent, ratioLimit,
+ )
+ return True
+
+ timeLimitMinutes = bittorrentConfig.seedTimeLimitMinutes.value
+ if timeLimitMinutes > 0 and task.seedingTimeSeconds >= timeLimitMinutes * 60:
+ logger.info(
+ "{} 自动暂停做种: 做种时间达到 {} / {} 分钟",
+ task.title, round(task.seedingTimeSeconds / 60), timeLimitMinutes,
+ )
+ return True
+
+ return False
+
+ def _handleAlert(self, alert: lt.alert):
+ if isinstance(alert, lt.metadata_received_alert):
+ self._resolveMetadata(alert)
+ return
+
+ if isinstance(alert, lt.save_resume_data_alert):
+ active = self._activeOf(alert.handle)
+ if active is not None and active.resumeWaiter is not None and not active.resumeWaiter.done():
+ active.task.resumeData = b64encode(lt.write_resume_data_buf(alert.params)).decode()
+ active.resumeWaiter.set_result(True)
+ return
+
+ if isinstance(alert, lt.save_resume_data_failed_alert):
+ active = self._activeOf(alert.handle)
+ if active is not None and active.resumeWaiter is not None and not active.resumeWaiter.done():
+ logger.warning("保存 BitTorrent resume 数据失败 {}: {}", active.task.title, alert.message())
+ active.task.resumeData = ""
+ active.resumeWaiter.set_result(False)
+ return
+
+ if isinstance(alert, lt.file_completed_alert):
+ active = self._activeOf(alert.handle)
+ if active is not None:
+ for file in active.task.files:
+ if file.index == alert.index:
+ file.completed = True
+ file.downloadedBytes = file.size
+ break
+ return
+
+ if isinstance(alert, lt.fastresume_rejected_alert):
+ active = self._activeOf(alert.handle)
+ if active is not None:
+ active.task.resumeData = ""
+ logger.warning("BitTorrent fastresume 被拒绝: {}", alert.message())
+ return
+
+ if isinstance(alert, _ERROR_ALERTS):
+ self._failTorrent(alert)
+
+ def _resolveMetadata(self, alert: lt.metadata_received_alert):
+ for handle, waiter in self._pendingMetadata:
+ if handle == alert.handle and not waiter.done():
+ ti = handle.torrent_file()
+ if ti is not None and ti.is_valid():
+ waiter.set_result(ti)
+ else:
+ waiter.set_exception(RuntimeError("magnet 元数据无效"))
+ return
+
+ def _failTorrent(self, alert: lt.alert):
+ active = self._activeOf(alert.handle)
+ if active is not None:
+ if not active.done.done():
+ active.done.set_exception(RuntimeError(alert.message()))
+ return
+ for handle, waiter in self._pendingMetadata:
+ if handle == alert.handle and not waiter.done():
+ waiter.set_exception(RuntimeError(alert.message()))
+ return
+
+ def _activeOf(self, handle: lt.torrent_handle) -> _ActiveTorrent | None:
+ for active in self._active.values():
+ if active.handle == handle:
+ return active
+ return None
+
+
+btSessionService = BTSessionService()
diff --git a/features/bittorrent_pack/task.py b/features/bittorrent_pack/task.py
index 1a33d0e2..14d68b22 100644
--- a/features/bittorrent_pack/task.py
+++ b/features/bittorrent_pack/task.py
@@ -1,13 +1,11 @@
import asyncio
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
-from typing import Any
from loguru import logger
from app.bases.models import Task, TaskStage, TaskStatus
-from app.supports.utils import getProxies, removePath, toSafeFilename
-from .config import bittorrentConfig
+from app.supports.utils import removePath, toSafeFilename
@dataclass
@@ -32,20 +30,6 @@ class BTTask(Task):
resumeData: str = ""
trackers: list[str] = field(default_factory=list)
files: list[BTFile] = field(default_factory=list)
- proxies: dict | None = field(default_factory=getProxies)
- listenPort: int = field(default_factory=lambda: bittorrentConfig.listenPort.value)
- connectionsLimit: int = field(default_factory=lambda: bittorrentConfig.connectionsLimit.value)
- downloadRateLimit: int = field(default_factory=lambda: bittorrentConfig.downloadRateLimit.value)
- uploadRateLimit: int = field(default_factory=lambda: bittorrentConfig.uploadRateLimit.value)
- enableDHT: bool = field(default_factory=lambda: bittorrentConfig.enableDHT.value)
- enableLSD: bool = field(default_factory=lambda: bittorrentConfig.enableLSD.value)
- enableUPnP: bool = field(default_factory=lambda: bittorrentConfig.enableUPnP.value)
- enableNATPMP: bool = field(default_factory=lambda: bittorrentConfig.enableNATPMP.value)
- sequentialDownload: bool = field(default_factory=lambda: bittorrentConfig.sequentialDownload.value)
- storageMode: str = field(default_factory=lambda: bittorrentConfig.storageMode.value)
- seedRatioLimitPercent: int = field(default_factory=lambda: bittorrentConfig.seedRatioLimitPercent.value)
- seedTimeLimitMinutes: int = field(default_factory=lambda: bittorrentConfig.seedTimeLimitMinutes.value)
- saveMagnetTorrentFile: bool = field(default_factory=lambda: bittorrentConfig.saveMagnetTorrentFile.value)
shareRatioPercent: float = 0
seedingTimeSeconds: int = 0
isSeeding: bool = False
@@ -72,7 +56,7 @@ class BTTask(Task):
@property
def magnetTorrentPath(self) -> Path | None:
- if self.sourceType != "magnet" or not self.saveMagnetTorrentFile:
+ if self.sourceType != "magnet":
return None
return self.path / f"{self.title}.torrent"
@@ -155,11 +139,6 @@ class BTTask(Task):
file.downloadedBytes = downloaded
file.completed = file.size > 0 and downloaded >= file.size
- def applySettings(self, payload: dict[str, Any]):
- super().applySettings(payload)
- if "proxies" in payload:
- self.proxies = payload.get("proxies")
-
def reset(self) -> TaskStatus:
result = super().reset()
self.resumeData = ""
@@ -181,19 +160,29 @@ class BTTask(Task):
self.usesSlot = not self.isSeeding
async def run(self):
- from .worker import BTWorker
+ from .session import btSessionService
try:
- for stage in self.pendingStages():
- await BTWorker(stage).run()
+ await btSessionService.lease(self)
except asyncio.CancelledError:
- logger.info(f"{self.title} 停止下载")
+ self.stateText = "已暂停做种" if self.isSeeding else "已暂停下载"
+ self.isSeeding = False
+ self._updateSlot()
+ self.stage.setStatus(TaskStatus.PAUSED)
+ logger.info("{} 停止下载", self.title)
raise
except Exception as e:
if not self.stage.error:
self.stage.setError(e)
logger.opt(exception=e).error("{} 下载失败", self.title)
raise
+ else:
+ self.isSeeding = False
+ self._updateSlot()
+ self.stateText = "已自动暂停做种"
+ self.stage.setStatus(TaskStatus.COMPLETED)
+ self.stage.progress = 100
+ self.stage.speed = 0
def __hash__(self):
return hash(self.taskId)
diff --git a/features/bittorrent_pack/worker.py b/features/bittorrent_pack/worker.py
deleted file mode 100644
index 32cc5427..00000000
--- a/features/bittorrent_pack/worker.py
+++ /dev/null
@@ -1,354 +0,0 @@
-import asyncio
-from base64 import b64decode, b64encode
-from pathlib import Path
-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("至少需要选择一个文件")
-
- target = Path(self.task.outputFolder)
- if not target.exists():
- target.parent.mkdir(parents=True, exist_ok=True)
- target.touch() if self.task.isSingleFile else target.mkdir()
- 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()
- self.handle.force_reannounce(0, -1, lt.reannounce_flags_t.ignore_min_interval)
- if self.task.enableDHT:
- self.handle.force_dht_announce()
-
- 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