Skip to content

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

8.3 KB
Raw Blame
from __future__ import annotations

from typing import TYPE_CHECKING

from app.config.cfg import (
    BoolValidator,
    ConfigItem,
    OptionsConfigItem,
    OptionsValidator,
    RangeConfigItem,
    RangeValidator,
    StringListValidator,
)
from app.i18n import N
from app.models.pack import PackConfig

if TYPE_CHECKING:
    from PySide6.QtWidgets import QWidget
    from app.view.components.setting_card_group import CollapsibleSettingCardGroup

DEFAULT_TRACKER_LIST_SOURCES = [
    "https://trackerslist.com/best.txt",
    "https://cdn.jsdelivr.net/gh/XIU2/TrackersListCollection/best.txt",
    "https://ngosang.github.io/trackerslist/trackers_best.txt",
    "https://newtrackon.com/api/stable",
]


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())
    shouldParseOnlineTorrent = ConfigItem("BitTorrent", "ParseOnlineTorrent", True, BoolValidator())
    saveMagnetFile = ConfigItem("BitTorrent", "SaveMagnetTorrentFile", False, BoolValidator())
    seedingRatioLimit = RangeConfigItem("BitTorrent", "SeedRatioLimitPercent", 0, RangeValidator(0, 10000))
    seedingTimeLimit = RangeConfigItem("BitTorrent", "SeedTimeLimitMinutes", 0, RangeValidator(0, 43200))
    maxConnections = RangeConfigItem("BitTorrent", "ConnectionsLimit", 500, RangeValidator(20, 2000))
    maxUploadSpeed = RangeConfigItem("BitTorrent", "UploadRateLimit", 0, RangeValidator(0, 1024 * 1024 * 100))
    listenPort = RangeConfigItem("BitTorrent", "ListenPort", 0, RangeValidator(0, 65535))
    metadataTimeout = RangeConfigItem("BitTorrent", "MetadataTimeout", 60, RangeValidator(5, 300))
    enableSequentialDownload = ConfigItem("BitTorrent", "SequentialDownload", False, BoolValidator())
    storageMode = OptionsConfigItem(
        "BitTorrent", "StorageMode", "sparse", OptionsValidator(["sparse", "allocate"]),
    )
    associateFileTypes = ConfigItem("BitTorrent", "AssociateFileTypes", False, BoolValidator())
    associateUriSchemes = ConfigItem("BitTorrent", "AssociateUriSchemes", False, BoolValidator())
    webTrackerSources = ConfigItem(
        "BitTorrent", "WebTrackerSources", DEFAULT_TRACKER_LIST_SOURCES, StringListValidator(),
    )
    webTrackerCustomList = ConfigItem("BitTorrent", "WebTrackerCustomList", "")

    def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:
        from qfluentwidgets import ComboBoxSettingCard, FluentIcon, PushSettingCard, RangeSettingCard, SwitchSettingCard
        from app.view.components.setting_card_group import CollapsibleSettingCardGroup
        from app.view.components.setting_cards import SpinBoxSettingCard
        from app.view.components.bootstrap_list import BootstrapListCard
        from .session import SessionState, btSession
        from .trackers import trackerList

        btGroup = CollapsibleSettingCardGroup(self.tr("BitTorrent 下载"), "bittorrent", parent)

        stopCard = PushSettingCard(self.tr("停止"), FluentIcon.CLOSE, self.tr("停止 BitTorrent 会话"), self.tr("未运行"), btGroup)
        stopContent = {
            SessionState.STOPPED: self.tr("未运行"),
            SessionState.BUSY: self.tr("有 BT 任务正在下载或做种,结束后才能停止"),
            SessionState.IDLE: self.tr("空闲 5 分钟后自动停止,开始任务时会自动启动"),
        }

        def refreshStopCard() -> None:
            stopCard.button.setEnabled(btSession.state == SessionState.IDLE)
            stopCard.setContent(stopContent[btSession.state])

        stopCard.clicked.connect(lambda: self.submit(btSession.stop()))
        btSession.stateChanged.connect(refreshStopCard, owner=stopCard)
        refreshStopCard()

        trackerListCard = BootstrapListCard(
            FluentIcon.GLOBE, self.tr("Tracker 列表"), trackerList,
            self.webTrackerSources, self.submit, btGroup,
            customItem=self.webTrackerCustomList, probeNetworkText=self._probeDhtText,
        )
        btSession.stateChanged.connect(trackerListCard.probeNetwork, owner=trackerListCard)

        cards = [
            stopCard,
            SpinBoxSettingCard(FluentIcon.GLOBE, self.tr("监听端口"),
                self.tr("0 表示交给系统自动分配可用端口"), "", self.listenPort, btGroup, 1),
            SpinBoxSettingCard(FluentIcon.HISTORY, self.tr("元数据超时"),
                self.tr("解析 magnet 链接时等待元数据的最长时间"), " s", self.metadataTimeout, btGroup, 5),
            RangeSettingCard(self.maxConnections, FluentIcon.PEOPLE, self.tr("连接数上限"),
                self.tr("单个 BT 任务对应 session 的最大连接数"), btGroup),
            SpinBoxSettingCard(FluentIcon.SHARE, self.tr("上传限速"),
                self.tr("0 表示不限速,单位为 session 级别的 KB/s"), " KB/s",
                self.maxUploadSpeed, btGroup, 64, 1 / 1024),
            SpinBoxSettingCard(FluentIcon.SHARE, self.tr("自动停止做种分享率"),
                self.tr("0 表示不按分享率自动停止,100% 表示分享率 1.0"), " %",
                self.seedingRatioLimit, btGroup, 50),
            SpinBoxSettingCard(FluentIcon.STOP_WATCH, self.tr("自动停止做种时长"),
                self.tr("0 表示不按做种时长自动停止"), " min",
                self.seedingTimeLimit, btGroup, 10),
            ComboBoxSettingCard(self.storageMode, FluentIcon.SAVE, self.tr("文件分配模式"),
                self.tr("稀疏分配更省磁盘写入,预分配更容易提前暴露空间不足"),
                texts=[self.tr("稀疏分配"), self.tr("预分配")], parent=btGroup),
            SwitchSettingCard(FluentIcon.LINK, self.tr("解析在线种子链接"),
                self.tr("HTTP 链接指向 .torrent 文件时解析为 BT 任务,关闭时仅下载 .torrent 文件"),
                self.shouldParseOnlineTorrent, btGroup),
            SwitchSettingCard(FluentIcon.SAVE, self.tr("保存 Magnet 种子文件"),
                self.tr("下载 magnet 链接或在线种子时额外保存 .torrent 文件"), self.saveMagnetFile, btGroup),
            SwitchSettingCard(FluentIcon.LIBRARY, self.tr("顺序下载"),
                self.tr("按文件顺序下载,适合边下边看但通常会影响整体效率"),
                self.enableSequentialDownload, btGroup),
            SwitchSettingCard(FluentIcon.GLOBE, self.tr("启用 DHT"),
                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),
            SwitchSettingCard(FluentIcon.SYNC, self.tr("自动更新订阅"),
                self.tr("每天在后台更新一次 Tracker 列表"),
                self.autoRefreshWebTrackers, btGroup),
            trackerListCard,
        ]
        btGroup.addSettingCards(cards)
        return [btGroup]

    async def _probeDhtText(self) -> tuple[str, dict]:
        from .session import btSession
        nodes = await btSession.probeDhtNodes()
        return ("", {}) if nodes is None else (N("BootstrapList", "DHT 节点 {nodes}"), {"nodes": nodes})


bittorrentConfig = BitTorrentConfig()