The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(BitTorrent): 新增 uTP 与协议加密设置 #1064
XiaoYouChR327f06aba557
diff --git a/features/bittorrent_pack/config.py b/features/bittorrent_pack/config.pyindex 4a67f740..1afe3e88 100644--- a/features/bittorrent_pack/config.py+++ b/features/bittorrent_pack/config.py@@ -29,6 +29,10 @@ DEFAULT_TRACKER_LIST_SOURCES = [class BitTorrentConfig(PackConfig):enableDht = ConfigItem("BitTorrent", "EnableDHT", True, BoolValidator())enableLsd = ConfigItem("BitTorrent", "EnableLSD", True, BoolValidator())+ enableUtp = ConfigItem("BitTorrent", "EnableUTP", True, BoolValidator())+ encryptionMode = OptionsConfigItem(+ "BitTorrent", "EncryptionMode", "enabled", OptionsValidator(["enabled", "forced", "disabled"]),+ )enableWebTrackers = ConfigItem("BitTorrent", "EnableWebTrackers", True, BoolValidator())autoRefreshWebTrackers = ConfigItem("BitTorrent", "AutoRefreshWebTrackers", True, BoolValidator())saveMagnetFile = ConfigItem("BitTorrent", "SaveMagnetTorrentFile", False, BoolValidator())@@ -50,7 +54,6 @@ class BitTorrentConfig(PackConfig):webTrackerCustomList = ConfigItem("BitTorrent", "WebTrackerCustomList", "")def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:- import sysfrom qfluentwidgets import ComboBoxSettingCard, FluentIcon, RangeSettingCard, SwitchSettingCardfrom app.view.components.setting_card_group import CollapsibleSettingCardGroupfrom app.view.components.setting_cards import SpinBoxSettingCard@@ -87,6 +90,11 @@ class BitTorrentConfig(PackConfig):self.tr("允许通过 DHT 网络发现 peers"), self.enableDht, btGroup),SwitchSettingCard(FluentIcon.HOME, self.tr("启用 LSD"),self.tr("在局域网中广播并发现同一 torrent 的 peers"), self.enableLsd, btGroup),+ SwitchSettingCard(FluentIcon.SPEED_HIGH, self.tr("启用 uTP"),+ self.tr("使用 uTP 传输协议控制拥塞,关闭后仅使用 TCP"), self.enableUtp, btGroup),+ ComboBoxSettingCard(self.encryptionMode, FluentIcon.VPN, self.tr("协议加密"),+ self.tr("混淆对等连接流量特征,减少被运营商识别和限速"),+ texts=[self.tr("允许加密"), self.tr("强制加密"), self.tr("禁用加密")], parent=btGroup),SwitchSettingCard(FluentIcon.LINK, self.tr("附加 Tracker 列表"),self.tr("把 Tracker 列表合并到新建的 BT 任务中"),self.enableWebTrackers, btGroup),diff --git a/features/bittorrent_pack/session.py b/features/bittorrent_pack/session.pyindex 7e6e9710..e4990eb1 100644--- a/features/bittorrent_pack/session.py+++ b/features/bittorrent_pack/session.py@@ -1,26 +1,24 @@from __future__ import annotationsimport asyncio-from base64 import b64decode, b64encode+from collections.abc import Callable+from contextlib import suppressfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom tempfile import gettempdir-from collections.abc import Callable-from typing import TYPE_CHECKINGfrom urllib.parse import urlsplitimport libtorrent as ltfrom loguru import loggerfrom app.config.cfg import cfg, proxy+from app.config.constants import VERSION+from app.config.paths import APP_DATA_DIRfrom app.models.task import TaskErrorfrom .config import bittorrentConfigfrom .swarm import PeerInfo, SwarmInfo, TrackerInfo, toPeers, toSourceTrackers, toSwarmInfo, toTracker-if TYPE_CHECKING:- pass-DHT_BOOTSTRAP_NODES = ("dht.transmissionbt.com:6881, router.bt.ouinet.work:6881, dht.libtorrent.org:25401, ""router.bittorrent.com:6881, router.utorrent.com:6881"@@ -48,6 +46,107 @@ ERROR_ALERTS = (RESUME_SAVE_INTERVAL = 30+LIVE_SETTINGS = (+ bittorrentConfig.listenPort,+ bittorrentConfig.maxConnections,+ bittorrentConfig.maxUploadSpeed,+ bittorrentConfig.enableDht,+ bittorrentConfig.enableLsd,+ bittorrentConfig.enableUtp,+ bittorrentConfig.encryptionMode,+ cfg.isSpeedLimitEnabled,+ cfg.speedLimitation,+ cfg.proxyServer,+)++ENCRYPTION_MODES = {+ "enabled": (lt.enc_policy.enabled, lt.enc_level.both, True),+ "forced": (lt.enc_policy.forced, lt.enc_level.rc4, True),+ "disabled": (lt.enc_policy.disabled, lt.enc_level.both, False),+}+++def buildProxySettings() -> dict:+ url = proxy(PROXY_SCHEMES)+ parsed = urlsplit(url) if url else None+ if not parsed or not parsed.hostname or not parsed.port:+ return {"proxy_type": lt.proxy_type_t.none}+ 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 buildSettings() -> dict:+ port = bittorrentConfig.listenPort.value+ enableUtp = bittorrentConfig.enableUtp.value+ encPolicy, encLevel, preferRc4 = ENCRYPTION_MODES[bittorrentConfig.encryptionMode.value]+ return {+ "user_agent": f"GhostDownloader/{VERSION} libtorrent/{lt.__version__}",+ "listen_interfaces": f"0.0.0.0:{port},[::]:{port}",+ "connections_limit": bittorrentConfig.maxConnections.value,+ # libtorrent high_performance_seed 预设值,默认 500 会把单个 peer 限制在约 2.7 MB/s+ "max_out_request_queue": 1500,+ "download_rate_limit": int(cfg.speedLimitation.value) if cfg.isSpeedLimitEnabled.value else 0,+ "upload_rate_limit": int(bittorrentConfig.maxUploadSpeed.value),+ "enable_dht": bittorrentConfig.enableDht.value,+ "enable_lsd": bittorrentConfig.enableLsd.value,+ "enable_incoming_utp": enableUtp,+ "enable_outgoing_utp": enableUtp,+ "in_enc_policy": encPolicy,+ "out_enc_policy": encPolicy,+ "allowed_enc_level": encLevel,+ "prefer_rc4": preferRc4,+ "dht_bootstrap_nodes": DHT_BOOTSTRAP_NODES,+ "announce_to_all_trackers": True,+ "announce_to_all_tiers": True,+ "active_downloads": -1,+ "active_seeds": -1,+ "active_limit": -1,+ "active_checking": -1,+ "mixed_mode_algorithm": lt.bandwidth_mixed_algo_t.prefer_tcp,+ "enable_upnp": True,+ "enable_natpmp": True,+ "alert_mask": ALERT_MASK,+ **buildProxySettings(),+ }+++def loadDhtState() -> lt.session_params:+ path = APP_DATA_DIR / DHT_STATE_FILE+ if path.exists():+ try:+ return lt.read_session_params(path.read_bytes(), lt.save_state_flags_t.save_dht_state)+ except Exception as e:+ logger.warning("加载 DHT 状态失败: {}", e)+ return lt.session_params()+++def saveDhtState(session: lt.session) -> None:+ try:+ state = session.session_state(lt.save_state_flags_t.save_dht_state)+ (APP_DATA_DIR / DHT_STATE_FILE).write_bytes(+ lt.write_session_params_buf(state, lt.save_state_flags_t.save_dht_state)+ )+ except Exception as e:+ logger.warning("保存 DHT 状态失败: {}", e)+++def isSeedingLimitReached(shareRatioPercent: float, seedingTimeSeconds: int) -> bool:+ ratioLimit = bittorrentConfig.seedingRatioLimit.value+ timeLimit = bittorrentConfig.seedingTimeLimit.value+ return (ratioLimit > 0 and shareRatioPercent >= ratioLimit) or (+ timeLimit > 0 and seedingTimeSeconds >= timeLimit * 60+ )+@dataclass(frozen=True)class TorrentParams:@@ -110,19 +209,18 @@ class BTSession:self._metadataWaiters: dict[int, tuple[lt.torrent_handle, asyncio.Future]] = {}self._resumeCache: dict[str, bytes] = {}self._statsWaiter: asyncio.Future | None = None- for item in (- bittorrentConfig.maxUploadSpeed,- bittorrentConfig.maxConnections,- cfg.isSpeedLimitEnabled,- cfg.speedLimitation,- ):- item.valueChanged.connect(self._onLimitChanged)- cfg.proxyServer.valueChanged.connect(self._onProxyChanged)# ── public interface ──def open(self) -> None:- self._ensureSession()+ if self._session is not None:+ return+ params = loadDhtState()+ params.settings = buildSettings()+ self._session = lt.session(params)+ self._poller = asyncio.get_running_loop().create_task(self._supervise())+ for item in LIVE_SETTINGS:+ item.valueChanged.connect(self._onSettingsChanged)async def run(self, taskId: str, params: TorrentParams,onProgress: Callable[[TorrentProgress], None] | None = None) -> bytes:@@ -131,14 +229,13 @@ class BTSession:async def runSeeding(self, taskId: str, params: TorrentParams, isManual: bool,onProgress: Callable[[TorrentProgress], None] | None = None) -> bytes:def isDone(p: TorrentProgress) -> bool:- return not isManual and p.isSeeding and self._isSeedingLimitReached(+ return not isManual and p.isSeeding and isSeedingLimitReached(p.shareRatioPercent, p.seedingTimeSeconds)return await self._run(taskId, params, onProgress, isDone)async def _run(self, taskId: str, params: TorrentParams,onProgress: Callable[[TorrentProgress], None] | None,isDone: Callable[[TorrentProgress], bool]) -> bytes:- self._ensureSession()handle = self._addTorrent(params)handle.resume()@@ -162,20 +259,16 @@ class BTSession:finally:if cancelled:self._active.pop(taskId, None)- try:- if self._session is not None:+ if self._session is not None:+ with suppress(Exception):self._session.remove_torrent(handle)- except Exception:- passelse:- await self._saveResumeAndRemove(entry, taskId)+ await self._saveResumeAndRemove(entry)self._active.pop(taskId, None)return self._resumeCache.pop(taskId, b"")async def fetchMetadata(self, magnetUri: str, trackers: list[str]) -> bytes:- self._ensureSession()-params = lt.parse_magnet_uri(magnetUri)magnetTrackers = list(params.trackers)params.trackers = list(dict.fromkeys(@@ -211,10 +304,8 @@ class BTSession:raise TimeoutError("等待 magnet 元数据超时")finally:self._metadataWaiters.pop(id(handle), None)- try:+ with suppress(Exception):self._session.remove_torrent(handle)- except Exception:- passasync def probeDhtNodes(self) -> int | None:if self._session is None or not self._session.is_dht_running():@@ -229,9 +320,8 @@ class BTSession:def updatePriorities(self, taskId: str, priorities: list[int]) -> None:entry = self._active.get(taskId)- if entry is None:- return- entry.pendingPriorities = priorities+ if entry is not None:+ entry.pendingPriorities = prioritiesdef lastResumeData(self, taskId: str) -> bytes | None:return self._resumeCache.pop(taskId, None)@@ -255,17 +345,19 @@ class BTSession:return (*sourceTrackers, *(toTracker(raw) for raw in entry.handle.trackers()))async def close(self) -> None:- self._saveDhtState()+ if self._session is None:+ return+ for item in LIVE_SETTINGS:+ item.valueChanged.disconnect(self._onSettingsChanged)+ saveDhtState(self._session)waiters = []for entry in list(self._active.values()):- try:+ with suppress(Exception):entry.handle.save_resume_data(lt.save_resume_flags_t.flush_disk_cache | lt.save_resume_flags_t.save_info_dict)entry.resumeWaiter = asyncio.get_running_loop().create_future()waiters.append(entry.resumeWaiter)- except Exception:- passif waiters:await asyncio.wait(waiters, timeout=5)@@ -273,92 +365,24 @@ class BTSession:for entry in list(self._active.values()):if not entry.done.done():entry.done.cancel()- try:+ with suppress(Exception):self._session.remove_torrent(entry.handle)- except Exception:- passself._active.clear()for _key, (handle, waiter) in list(self._metadataWaiters.items()):if not waiter.done():waiter.cancel()- try:+ with suppress(Exception):self._session.remove_torrent(handle)- except Exception:- passself._metadataWaiters.clear()if self._poller is not None:self._poller.cancel()- try:+ with suppress(asyncio.CancelledError):await self._poller- except asyncio.CancelledError:- passself._poller = Noneself._session = None- # ── session lifecycle ──-- def _ensureSession(self) -> None:- if self._session is None:- from app.config.constants import VERSION- params = self._loadDhtState()- params.settings = {- "user_agent": f"GhostDownloader/{VERSION} libtorrent/{lt.__version__}",- "listen_interfaces": (- f"0.0.0.0:{bittorrentConfig.listenPort.value},"- f"[::]:{bittorrentConfig.listenPort.value}"- ),- "connections_limit": bittorrentConfig.maxConnections.value,- # libtorrent high_performance_seed 预设值,默认 500 会把单个 peer 限制在约 2.7 MB/s- "max_out_request_queue": 1500,- "download_rate_limit": self._downloadLimit(),- "upload_rate_limit": int(bittorrentConfig.maxUploadSpeed.value),- "enable_dht": bittorrentConfig.enableDht.value,- "enable_lsd": bittorrentConfig.enableLsd.value,- "dht_bootstrap_nodes": DHT_BOOTSTRAP_NODES,- "announce_to_all_trackers": True,- "announce_to_all_tiers": True,- "active_downloads": -1,- "active_seeds": -1,- "active_limit": -1,- "active_checking": -1,- "mixed_mode_algorithm": int(lt.bandwidth_mixed_algo_t.prefer_tcp),- "enable_upnp": True,- "enable_natpmp": True,- "alert_mask": ALERT_MASK,- **self.buildProxySettings(),- }- self._session = lt.session(params)- if self._poller is None or self._poller.done():- self._poller = asyncio.get_running_loop().create_task(self._supervise())-- def _loadDhtState(self) -> lt.session_params:- from app.config.paths import APP_DATA_DIR- path = APP_DATA_DIR / DHT_STATE_FILE- if path.exists():- try:- return lt.read_session_params(- path.read_bytes(), lt.save_state_flags_t.save_dht_state- )- except Exception as e:- logger.warning("加载 DHT 状态失败: {}", e)- return lt.session_params()-- def _saveDhtState(self) -> None:- if self._session is None:- return- from app.config.paths import APP_DATA_DIR- try:- state = self._session.session_state(- lt.save_state_flags_t.save_dht_state- )- (APP_DATA_DIR / DHT_STATE_FILE).write_bytes(- lt.write_session_params_buf(state, lt.save_state_flags_t.save_dht_state)- )- except Exception as e:- logger.warning("保存 DHT 状态失败: {}", e)-# ── torrent management ──def _addTorrent(self, params: TorrentParams) -> lt.torrent_handle:@@ -404,16 +428,14 @@ class BTSession:return self._session.add_torrent(ltParams)- async def _saveResumeAndRemove(self, entry: ActiveTorrent, taskId: str) -> None:+ async def _saveResumeAndRemove(self, entry: ActiveTorrent) -> None:try:entry.handle.save_resume_data(lt.save_resume_flags_t.flush_disk_cache | lt.save_resume_flags_t.save_info_dict)except Exception:- try:+ with suppress(Exception):self._session.remove_torrent(entry.handle)- except Exception:- passreturnentry.resumeWaiter = asyncio.get_running_loop().create_future()@@ -423,10 +445,8 @@ class BTSession:logger.warning("等待 BitTorrent resume 数据超时")finally:entry.resumeWaiter = None- try:+ with suppress(Exception):self._session.remove_torrent(entry.handle)- except Exception:- pass# ── poll loop ──@@ -502,11 +522,7 @@ class BTSession:def _updateEntry(self, entry: ActiveTorrent) -> None:status = entry.handle.status()- stateText = status.state.nameisSeeding = status.is_seeding- downloadRate = status.download_rate- uploadRate = status.upload_rate-downloaded = status.all_time_download or status.total_wanted_done or status.total_doneshareRatioPercent = (status.all_time_upload / downloaded * 100) if downloaded > 0 else 0.0seedingTimeSeconds = entry.seedingElapsed(@@ -518,14 +534,14 @@ class BTSession:progress = (receivedBytes / totalWanted * 100) if totalWanted > 0 else 0torrentProgress = TorrentProgress(- stateText=stateText,+ stateText=status.state.name,peerCount=status.num_peers,totalPeerCount=max(status.num_peers, status.list_peers),seedCount=status.num_seeds,isSeeding=isSeeding,isFinished=status.is_finished,- downloadRate=downloadRate,- uploadRate=uploadRate,+ downloadRate=status.download_rate,+ uploadRate=status.upload_rate,shareRatioPercent=shareRatioPercent,seedingTimeSeconds=seedingTimeSeconds,progress=progress,@@ -545,65 +561,16 @@ class BTSession:entry.pollCount += 1if entry.pollCount % RESUME_SAVE_INTERVAL == 0:- try:+ with suppress(Exception):entry.handle.save_resume_data(lt.save_resume_flags_t.flush_disk_cache | lt.save_resume_flags_t.save_info_dict)- except Exception:- pass-- def _isSeedingLimitReached(self, shareRatioPercent: float, seedingTimeSeconds: int) -> bool:- ratioLimit = bittorrentConfig.seedingRatioLimit.value- if ratioLimit > 0 and shareRatioPercent >= ratioLimit:- return True- timeLimitMinutes = bittorrentConfig.seedingTimeLimit.value- if timeLimitMinutes > 0 and seedingTimeSeconds >= timeLimitMinutes * 60:- return True- return False# ── config handlers ──- def _onLimitChanged(self, _value=None) -> None:- if self._session is None:- return- self._session.apply_settings({- "download_rate_limit": self._downloadLimit(),- "upload_rate_limit": int(bittorrentConfig.maxUploadSpeed.value),- "connections_limit": bittorrentConfig.maxConnections.value,- })-- def _onProxyChanged(self, _value=None) -> None:- if self._session is None:- return- settings = self.buildProxySettings()- self._session.apply_settings(- settings or {"proxy_type": lt.proxy_type_t.none}- )-- def _downloadLimit(self) -> int:- if not cfg.isSpeedLimitEnabled.value:- return 0- return int(cfg.speedLimitation.value)-- def buildProxySettings(self) -> dict:- url = proxy(PROXY_SCHEMES)- if not url:- return {}- parsed = urlsplit(url)- if 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 _onSettingsChanged(self, *_) -> None:+ if self._session is not None:+ self._session.apply_settings(buildSettings())btSession = BTSession()diff --git a/tests/bittorrent_pack/test_session.py b/tests/bittorrent_pack/test_session.pyindex ed2d2b4c..786372a7 100644--- a/tests/bittorrent_pack/test_session.py+++ b/tests/bittorrent_pack/test_session.py@@ -4,36 +4,77 @@ import libtorrent as ltimport pytestfrom app.config.cfg import cfg-from features.bittorrent_pack.session import BTSession+from features.bittorrent_pack.config import bittorrentConfig+from features.bittorrent_pack.session import BTSession, buildSettings@pytest.fixture()-def buildSettings():- saved = cfg.proxyServer.value-+def settingsForProxy(monkeypatch):def build(url):- cfg.proxyServer.value = url or "Off"+ monkeypatch.setattr(cfg.proxyServer, "value", url or "Off")assert cfg.proxyServer.value == (url or "Off")- return BTSession().buildProxySettings()- yield build- cfg.proxyServer.value = saved+ return buildSettings()+ return build@pytest.mark.parametrize("url", [None, "http://127.0.0.1:7890", "https://127.0.0.1:7890", "socks4://127.0.0.1:1080"])-def test_build_direct_for_non_socks5_proxy(buildSettings, url):- assert buildSettings(url) == {}+def test_build_direct_for_non_socks5_proxy(settingsForProxy, url):+ assert settingsForProxy(url)["proxy_type"] == lt.proxy_type_t.none-def test_build_socks5_for_all_traffic(buildSettings):- settings = buildSettings("socks5://127.0.0.1:7890")+def test_build_socks5_for_all_traffic(settingsForProxy):+ settings = settingsForProxy("socks5://127.0.0.1:7890")assert settings["proxy_type"] == lt.proxy_type_t.socks5assert (settings["proxy_hostname"], settings["proxy_port"]) == ("127.0.0.1", 7890)assert settings["proxy_peer_connections"] and settings["proxy_tracker_connections"]-def test_build_socks5_with_password(buildSettings):- settings = buildSettings("socks5h://user:[email protected]:1080")+def test_build_socks5_with_password(settingsForProxy):+ settings = settingsForProxy("socks5h://user:[email protected]:1080")assert settings["proxy_type"] == lt.proxy_type_t.socks5_pwassert (settings["proxy_username"], settings["proxy_password"]) == ("user", "pass")++[email protected]("isEnabled", [True, False])+def test_build_utp_for_both_directions(monkeypatch, isEnabled):+ monkeypatch.setattr(bittorrentConfig.enableUtp, "value", isEnabled)++ settings = buildSettings()++ assert (settings["enable_incoming_utp"], settings["enable_outgoing_utp"]) == (isEnabled, isEnabled)+++ ("mode", "policy", "level", "preferRc4"),+ [+ ("enabled", lt.enc_policy.enabled, lt.enc_level.both, True),+ ("forced", lt.enc_policy.forced, lt.enc_level.rc4, True),+ ("disabled", lt.enc_policy.disabled, lt.enc_level.both, False),+ ],+)+def test_build_encryption_mode(monkeypatch, mode, policy, level, preferRc4):+ monkeypatch.setattr(bittorrentConfig.encryptionMode, "value", mode)++ settings = buildSettings()++ assert (+ settings["in_enc_policy"],+ settings["out_enc_policy"],+ settings["allowed_enc_level"],+ settings["prefer_rc4"],+ ) == (policy, policy, level, preferRc4)+++async def test_set_config_updates_open_session(config):+ session = BTSession()+ session.open()+ try:+ cfg.set(bittorrentConfig.enableUtp, False)+ cfg.set(bittorrentConfig.encryptionMode, "forced")+ cfg.set(bittorrentConfig.enableDht, False)++ assert await session.probeDhtNodes() is None+ finally:+ await session.close()