Skip to content

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

feat(bittorrent): 完善BitTorrent功能实现

XiaoYouChR11da49c30f63
diff --git a/app/view/components/add_task_dialog.py b/app/view/components/add_task_dialog.py
index dd09f60d..f0120d25 100644
--- a/app/view/components/add_task_dialog.py
+++ b/app/view/components/add_task_dialog.py
@@ -3,9 +3,9 @@ from difflib import SequenceMatcher
from pathlib import Path
from typing import Any, Self
-from PySide6.QtCore import QEvent, Qt, QPoint, QTimer, Signal, QSize
+from PySide6.QtCore import QEvent, Qt, QPoint, QTimer, Signal
from PySide6.QtGui import QTextOption
-from PySide6.QtWidgets import QDialog, QFileDialog, QSizePolicy
+from PySide6.QtWidgets import QDialog, QFileDialog
from loguru import logger
from qfluentwidgets import (
MessageBoxBase,
@@ -13,7 +13,6 @@ from qfluentwidgets import (
LineEdit,
Action,
FluentIcon,
- PlainTextEdit,
InfoBar,
InfoBarPosition,
)
@@ -28,6 +27,7 @@ from app.view.components.card_widgets import (
ParseSettingHeaderCardWidget,
)
from app.view.components.cards import ParseSettingCard, ResultCard
+from app.view.components.editors import AutoSizingEdit
class SelectFolderCard(ParseSettingCard):
@@ -76,44 +76,6 @@ class _AcceptedPendingParse:
payload: dict[str, Any]
-class AutoSizingEdit(PlainTextEdit):
- def __init__(self, parent=None, minimumVisibleLines: int = 5):
- super().__init__(parent)
- self._minimumVisibleLines = minimumVisibleLines
- self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum)
- self.document().blockCountChanged.connect(self.updateGeometry)
-
- def _lineHeight(self) -> int:
- return self.fontMetrics().lineSpacing()
-
- def _editorChromeHeight(self) -> int:
- margins = self.contentsMargins()
- viewportMargins = self.viewportMargins()
- documentMargin = round(self.document().documentMargin() * 2)
- return (
- margins.top()
- + margins.bottom()
- + viewportMargins.top()
- + viewportMargins.bottom()
- + self.frameWidth() * 2
- + documentMargin
- )
-
- def _sizeHintForLineCount(self, lineCount: int) -> QSize:
- size = super().sizeHint()
- height = self._editorChromeHeight() + self._lineHeight() * lineCount
- return QSize(size.width(), height)
-
- def minimumSizeHint(self) -> QSize:
- return self._sizeHintForLineCount(min(self._minimumVisibleLines, self.document().blockCount()))
-
- def maximumSizeHint(self) -> QSize:
- return self._sizeHintForLineCount(self.document().blockCount())
-
- def sizeHint(self) -> QSize:
- return self.maximumSizeHint().expandedTo(self.minimumSizeHint())
-
-
class AddTaskDialog(MessageBoxBase):
taskConfirmed = Signal(object)
diff --git a/app/view/components/editors.py b/app/view/components/editors.py
new file mode 100644
index 00000000..4f6bacf7
--- /dev/null
+++ b/app/view/components/editors.py
@@ -0,0 +1,41 @@
+from PySide6.QtCore import QSize
+from PySide6.QtWidgets import QSizePolicy
+from qfluentwidgets import PlainTextEdit
+
+
+class AutoSizingEdit(PlainTextEdit):
+ def __init__(self, parent=None, minimumVisibleLines: int = 5):
+ super().__init__(parent)
+ self._minimumVisibleLines = minimumVisibleLines
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum)
+ self.document().blockCountChanged.connect(self.updateGeometry)
+
+ def _lineHeight(self) -> int:
+ return self.fontMetrics().lineSpacing()
+
+ def _editorChromeHeight(self) -> int:
+ margins = self.contentsMargins()
+ viewportMargins = self.viewportMargins()
+ documentMargin = round(self.document().documentMargin() * 2)
+ return (
+ margins.top()
+ + margins.bottom()
+ + viewportMargins.top()
+ + viewportMargins.bottom()
+ + self.frameWidth() * 2
+ + documentMargin
+ )
+
+ def _sizeHintForLineCount(self, lineCount: int) -> QSize:
+ size = super().sizeHint()
+ height = self._editorChromeHeight() + self._lineHeight() * lineCount
+ return QSize(size.width(), height)
+
+ def minimumSizeHint(self) -> QSize:
+ return self._sizeHintForLineCount(min(self._minimumVisibleLines, self.document().blockCount()))
+
+ def maximumSizeHint(self) -> QSize:
+ return self._sizeHintForLineCount(self.document().blockCount())
+
+ def sizeHint(self) -> QSize:
+ return self.maximumSizeHint().expandedTo(self.minimumSizeHint())
diff --git a/app/view/components/labels.py b/app/view/components/labels.py
index 9240b412..77917681 100644
--- a/app/view/components/labels.py
+++ b/app/view/components/labels.py
@@ -14,10 +14,14 @@ class IconBodyLabel(BodyLabel):
super().__init__(parent)
self.size = size
self.setText(text)
- self.icon = icon
self.setContentsMargins(size + 4, 0, 0, 2) # 给 Icon 和 Text 之间留出 4px 的间距
self.setMinimumHeight(size)
+ self.setIcon(icon)
+
+ def setIcon(self, icon: "FluentIconBase"):
+ self.icon = icon
self.cachedIconKey = self.preCacheIcon()
+ self.update()
def preCacheIcon(self):
"""预缓存图标并返回缓存键"""
diff --git a/features/bittorrent_pack/cards.py b/features/bittorrent_pack/cards.py
index f1f8c331..20ecb971 100644
--- a/features/bittorrent_pack/cards.py
+++ b/features/bittorrent_pack/cards.py
@@ -5,22 +5,26 @@ from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
QHeaderView,
QHBoxLayout,
- QTreeWidget,
QTreeWidgetItem,
QVBoxLayout,
QWidget,
)
from qfluentwidgets import (
+ Action,
BodyLabel,
CaptionLabel,
+ DropDownPushButton,
FluentIcon,
ImageLabel,
InfoBar,
MessageBoxBase,
PrimaryPushButton,
PushButton,
+ RoundMenu,
StrongBodyLabel,
ToolButton,
+ SubtitleLabel,
+ TreeWidget
)
from app.bases.models import TaskStatus
@@ -30,6 +34,41 @@ from app.view.components.labels import IconBodyLabel
from .task import BitTorrentFile, BitTorrentTask
+_TORRENT_FILE_TYPE_RULES = (
+ ("video", "视频", FluentIcon.VIDEO, {
+ ".avi", ".flv", ".m2ts", ".m4v", ".mkv", ".mov", ".mp4", ".mpeg", ".mpg", ".rmvb", ".ts", ".webm", ".wmv",
+ }),
+ ("audio", "音频", FluentIcon.MUSIC, {
+ ".aac", ".ape", ".flac", ".m4a", ".mp3", ".ogg", ".opus", ".wav", ".wma",
+ }),
+ ("image", "图片", FluentIcon.PHOTO, {
+ ".avif", ".bmp", ".gif", ".jpeg", ".jpg", ".png", ".svg", ".tif", ".tiff", ".webp",
+ }),
+ ("subtitle", "字幕", FluentIcon.CHAT, {
+ ".ass", ".idx", ".lrc", ".psb", ".smi", ".srt", ".ssa", ".sub", ".sup", ".vtt",
+ }),
+ ("document", "文档", FluentIcon.DOCUMENT, {
+ ".chm", ".csv", ".doc", ".docx", ".epub", ".md", ".nfo", ".odt", ".pdf", ".ppt", ".pptx", ".rtf",
+ ".txt", ".xls", ".xlsx",
+ }),
+ ("archive", "压缩包", FluentIcon.ZIP_FOLDER, {
+ ".001", ".7z", ".bz2", ".cab", ".gz", ".iso", ".rar", ".tar", ".tbz2", ".tgz", ".xz", ".zip", ".zst",
+ ".tar.bz2", ".tar.gz", ".tar.xz", ".tar.zst",
+ }),
+ ("application", "程序", FluentIcon.APPLICATION, {
+ ".apk", ".appimage", ".bat", ".com", ".deb", ".dmg", ".exe", ".iso", ".jar", ".msi", ".pkg", ".rpm", ".sh",
+ }),
+)
+
+_TORRENT_FILE_TYPE_META = {
+ key: (label, icon)
+ for key, label, icon, _ in _TORRENT_FILE_TYPE_RULES
+}
+_TORRENT_FILE_TYPE_SUFFIXES = {
+ key: suffixes
+ for key, _, _, suffixes in _TORRENT_FILE_TYPE_RULES
+}
+
def _removePath(path: Path):
if not path.exists():
@@ -52,10 +91,25 @@ def _openFileSelection(task: BitTorrentTask, parent) -> set[int] | None:
dialog.deleteLater()
-def _setIcon(label: IconBodyLabel, icon: FluentIcon):
- label.icon = icon
- label.cachedIconKey = label.preCacheIcon()
- label.update()
+def _torrentFileSuffix(path: str) -> str:
+ suffixes = [suffix.lower() for suffix in PurePosixPath(path).suffixes]
+ if not suffixes:
+ return ""
+
+ if len(suffixes) > 1:
+ combined = "".join(suffixes[-2:])
+ if combined in _TORRENT_FILE_TYPE_SUFFIXES["archive"]:
+ return combined
+
+ return suffixes[-1]
+
+
+def _torrentFileType(path: str) -> str:
+ suffix = _torrentFileSuffix(path)
+ for key, _, _, suffixes in _TORRENT_FILE_TYPE_RULES:
+ if suffix in suffixes:
+ return key
+ return "other"
class TorrentFileSelectDialog(MessageBoxBase):
@@ -66,13 +120,16 @@ class TorrentFileSelectDialog(MessageBoxBase):
self._updatingChecks = False
self.widget.setMinimumSize(720, 520)
- self.titleLabel = StrongBodyLabel(self.tr("选择下载文件"), self.widget)
- self.summaryLabel = CaptionLabel("", self.widget)
- self.treeWidget = QTreeWidget(self.widget)
+ self.titleLabel = SubtitleLabel(self.tr("选择下载文件"), self.widget)
+ self.summaryLabel = BodyLabel("", self.widget)
+ self.treeWidget = TreeWidget(self.widget)
self.actionsWidget = QWidget(self.widget)
self.actionsLayout = QHBoxLayout(self.actionsWidget)
- self.selectAllButton = PushButton(self.tr("全选"), self.actionsWidget)
+ self.selectAllButton = PrimaryPushButton(self.tr("全选"), self.actionsWidget)
self.clearButton = PushButton(self.tr("全不选"), self.actionsWidget)
+ self.invertButton = PushButton(self.tr("反选"), self.actionsWidget)
+ self.selectByTypeButton = DropDownPushButton(self.tr("按类型选择"), self.actionsWidget)
+ self.selectByTypeMenu = RoundMenu(parent=self)
self.yesButton.setText(self.tr("应用"))
self.cancelButton.setText(self.tr("取消"))
@@ -92,10 +149,14 @@ class TorrentFileSelectDialog(MessageBoxBase):
self.actionsLayout.setSpacing(8)
self.actionsLayout.addWidget(self.selectAllButton)
self.actionsLayout.addWidget(self.clearButton)
+ self.actionsLayout.addWidget(self.invertButton)
+ self.actionsLayout.addWidget(self.selectByTypeButton)
self.actionsLayout.addStretch(1)
self.selectAllButton.clicked.connect(self._selectAll)
self.clearButton.clicked.connect(self._clearAll)
+ self.invertButton.clicked.connect(self._invertSelection)
+ self._initTypeMenu()
self.viewLayout.addWidget(self.titleLabel)
self.viewLayout.addWidget(self.summaryLabel)
@@ -135,6 +196,23 @@ class TorrentFileSelectDialog(MessageBoxBase):
finally:
self._updatingChecks = False
+ def _initTypeMenu(self):
+ for typeKey, count in self._availableFileTypes().items():
+ label, icon = _TORRENT_FILE_TYPE_META.get(typeKey, (self.tr("其他"), FluentIcon.FOLDER))
+ action = Action(icon, self.tr("仅选{0} ({1})").format(self.tr(label), count), self)
+ action.triggered.connect(lambda _, key=typeKey: self._selectOnlyFileType(key))
+ self.selectByTypeMenu.addAction(action)
+
+ self.selectByTypeButton.setMenu(self.selectByTypeMenu)
+ self.selectByTypeButton.setEnabled(bool(self.selectByTypeMenu.actions()))
+
+ def _availableFileTypes(self) -> dict[str, int]:
+ counts: dict[str, int] = {}
+ for file in self.task.files:
+ typeKey = _torrentFileType(file.path)
+ counts[typeKey] = counts.get(typeKey, 0) + 1
+ return counts
+
def _refreshParentCheckStates(self):
root = self.treeWidget.invisibleRootItem()
for i in range(root.childCount()):
@@ -169,6 +247,17 @@ class TorrentFileSelectDialog(MessageBoxBase):
if item.checkState(0) == Qt.CheckState.Checked
}
+ def _setSelectedIndexes(self, selectedIndexes: set[int]):
+ self._updatingChecks = True
+ try:
+ for item, file in self._itemToFile.items():
+ state = Qt.CheckState.Checked if file.index in selectedIndexes else Qt.CheckState.Unchecked
+ item.setCheckState(0, state)
+ self._refreshParentCheckStates()
+ self._updateSummary()
+ finally:
+ self._updatingChecks = False
+
def _updateSummary(self):
selectedIndexes = self._collectSelectedIndexes()
selectedFiles = [file for file in self.task.files if file.index in selectedIndexes]
@@ -196,17 +285,10 @@ class TorrentFileSelectDialog(MessageBoxBase):
self._updatingChecks = False
def _setRootCheckState(self, state: Qt.CheckState):
- self._updatingChecks = True
- try:
- root = self.treeWidget.invisibleRootItem()
- for i in range(root.childCount()):
- item = root.child(i)
- item.setCheckState(0, state)
- self._setChildrenState(item, state)
- self._refreshParentCheckStates()
- self._updateSummary()
- finally:
- self._updatingChecks = False
+ if state == Qt.CheckState.Checked:
+ self._setSelectedIndexes({file.index for file in self.task.files})
+ return
+ self._setSelectedIndexes(set())
def _selectAll(self):
self._setRootCheckState(Qt.CheckState.Checked)
@@ -214,6 +296,21 @@ class TorrentFileSelectDialog(MessageBoxBase):
def _clearAll(self):
self._setRootCheckState(Qt.CheckState.Unchecked)
+ def _invertSelection(self):
+ currentSelected = self._collectSelectedIndexes()
+ self._setSelectedIndexes({
+ file.index
+ for file in self.task.files
+ if file.index not in currentSelected
+ })
+
+ def _selectOnlyFileType(self, typeKey: str):
+ self._setSelectedIndexes({
+ file.index
+ for file in self.task.files
+ if _torrentFileType(file.path) == typeKey
+ })
+
def validate(self) -> bool:
if self._collectSelectedIndexes():
return True
@@ -293,56 +390,60 @@ class BitTorrentResultCard(ResultCard):
class BitTorrentTaskCard(UniversalTaskCard):
def __init__(self, task: BitTorrentTask, parent=None):
- self.metaInfoLabel = None
- self.selectFilesButton = None
super().__init__(task, parent)
self.task: BitTorrentTask = task
- _setIcon(self.speedLabel, FluentIcon.DOWNLOAD)
- _setIcon(self.leftTimeLabel, FluentIcon.SHARE)
+ self.speedLabel.setIcon(FluentIcon.DOWNLOAD)
+ self.uploadRateLabel = IconBodyLabel("", FluentIcon.SHARE, self)
+ self.infoLayout.insertWidget(self.infoLayout.indexOf(self.leftTimeLabel), self.uploadRateLabel)
self.metaInfoLabel = IconBodyLabel("", FluentIcon.INFO, self)
- self.infoLayout.insertWidget(self.infoLayout.count() - 2, self.metaInfoLabel)
+ self.infoLayout.insertWidget(self.infoLayout.indexOf(self.infoLabel), self.metaInfoLabel)
self.selectFilesButton = ToolButton(FluentIcon.LIBRARY, self)
- self.hBoxLayout.insertWidget(self.hBoxLayout.count() - 3, self.selectFilesButton)
+ self.hBoxLayout.insertWidget(self.hBoxLayout.indexOf(self.verifyHashButton), self.selectFilesButton)
self.selectFilesButton.clicked.connect(self._onSelectFilesClicked)
self._refreshInfoLayout()
def _metaText(self) -> str:
- stage = self.task.stage
- if stage is None:
- return ""
-
parts: list[str] = []
- if stage.stateText and stage.stateText not in {"下载中", "做种中"}:
- parts.append(stage.stateText)
- if stage.isSeeding and stage.shareRatioPercent > 0:
- parts.append(self.tr("分享率 {0:.2f}%").format(stage.shareRatioPercent))
- if stage.isSeeding and stage.seedingTimeSeconds > 0:
- parts.append(self.tr("做种 {0}").format(getReadableTime(stage.seedingTimeSeconds)))
- if stage.peerCount or stage.seedCount:
+ if self.task.stage.stateText and self.task.stage.stateText not in {"下载中", "做种中"}:
+ parts.append(self.task.stage.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:
parts.append(
self.tr("Peers {0} / Seeds {1}").format(
- stage.peerCount,
- stage.seedCount,
+ self.task.stage.peerCount,
+ self.task.stage.seedCount,
)
)
return " · ".join(parts)
def _refreshInfoLayout(self):
- stage = self.task.stage
- if self.task.status == TaskStatus.RUNNING and stage is not None:
- self.speedLabel.setText(f"{getReadableSize(stage.downloadRate)}/s")
- self.leftTimeLabel.setText(f"{getReadableSize(stage.uploadRate)}/s")
+ 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")
+ if self.task.isSeeding:
+ self.leftTimeLabel.hide()
+ elif self.task.fileSize > 0 and self.task.stage.downloadRate > 0:
+ remainingBytes = self.task.fileSize - self.task.stage.receivedBytes
+ self.leftTimeLabel.setText(getReadableTime(int(remainingBytes / self.task.stage.downloadRate)))
+ self.leftTimeLabel.show()
+ else:
+ self.leftTimeLabel.setText("--")
+ self.leftTimeLabel.show()
metaText = self._metaText()
self.metaInfoLabel.setText(metaText)
self.metaInfoLabel.setVisible(bool(metaText))
self.speedLabel.show()
- self.leftTimeLabel.show()
+ self.uploadRateLabel.show()
self.progressLabel.show()
if not metaText:
self.metaInfoLabel.hide()
self.infoLabel.hide()
return
+ self.uploadRateLabel.hide()
self.metaInfoLabel.hide()
def _onSelectFilesClicked(self):
@@ -358,6 +459,7 @@ class BitTorrentTaskCard(UniversalTaskCard):
def refresh(self):
super().refresh()
self._refreshInfoLayout()
+ self.progressBar.setVisible(self.task.status != TaskStatus.COMPLETED and not self.task.isSeeding)
self.verifyHashButton.setVisible(
self.task.isSingleFileTorrent
and self.task.status == TaskStatus.COMPLETED
diff --git a/features/bittorrent_pack/config.py b/features/bittorrent_pack/config.py
index 7989945e..d9c95469 100644
--- a/features/bittorrent_pack/config.py
+++ b/features/bittorrent_pack/config.py
@@ -27,6 +27,7 @@ from qfluentwidgets import (
from app.bases.models import PackConfig
from app.services.core_service import coreService
from app.supports.config import cfg
+from app.view.components.editors import AutoSizingEdit
from app.view.components.setting_cards import SpinBoxSettingCard
from .trackers import fetchWebTrackers, formatTrackers, normalizeTrackerSource, parseTrackerText
@@ -75,11 +76,11 @@ async def refreshConfiguredWebTrackers(sourceUrl: str | None = None) -> list[str
class WebTrackerDialog(MessageBoxBase):
def __init__(self, parent=None):
super().__init__(parent)
- self.widget.setMinimumSize(720, 560)
+ self.widget.setMinimumWidth(720)
self.sourceLabel = BodyLabel(self.tr("Tracker 源地址"), self.widget)
self.sourceEdit = LineEdit(self.widget)
self.trackersLabel = BodyLabel(self.tr("当前 Tracker 列表"), self.widget)
- self.trackersEdit = PlainTextEdit(self.widget)
+ self.trackersEdit = AutoSizingEdit(self.widget)
self.refreshButton = PrimaryPushButton(self.tr("从源刷新"), self.widget)
self.yesButton.setText(self.tr("保存"))
@@ -134,7 +135,7 @@ class WebTrackerCard(SettingCard):
super().__init__(
FluentIcon.GLOBE,
self.tr("Web Tracker"),
- "",
+ self.tr("来源: {0}\n当前缓存: {1} 条 Tracker"),
parent,
)
self.manageButton = PrimaryPushButton(self.tr("管理"), self)
diff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.py
index e82f81d4..97a473a7 100644
--- a/features/bittorrent_pack/pack.py
+++ b/features/bittorrent_pack/pack.py
@@ -4,10 +4,13 @@ from app.bases.interfaces import FeaturePack
from .cards import BitTorrentResultCard, BitTorrentTaskCard
from .config import bittorrentConfig
-from .task import BitTorrentTask, parse
+from .task import BitTorrentTask, parse, resolveLocalTorrentPath
def _isTorrentUrl(url: str) -> bool:
+ if resolveLocalTorrentPath(url) is not None:
+ return True
+
parsedUrl = urlparse(url)
scheme = parsedUrl.scheme.lower()
if scheme == "magnet":
diff --git a/features/bittorrent_pack/task.py b/features/bittorrent_pack/task.py
index 782d8465..e899bee7 100644
--- a/features/bittorrent_pack/task.py
+++ b/features/bittorrent_pack/task.py
@@ -7,7 +7,8 @@ from datetime import timedelta
from pathlib import Path, PurePosixPath
from tempfile import gettempdir
from typing import Any
-from urllib.parse import urlparse, urlsplit
+from urllib.parse import unquote, urlparse, urlsplit
+from urllib.request import url2pathname
import libtorrent as lt
import niquests
@@ -15,11 +16,13 @@ from loguru import logger
from app.bases.interfaces import Worker
from app.bases.models import Task, TaskStage, TaskStatus
-from app.supports.config import DEFAULT_HEADERS, cfg
+from app.supports.config import DEFAULT_HEADERS, VERSION, cfg
from app.supports.utils import getProxies
from .config import bittorrentConfig, getCachedWebTrackers, refreshConfiguredWebTrackers
from .trackers import mergeTrackers
+BITTORRENT_USER_AGENT = f"GhostDownloader/{VERSION} libtorrent/{lt.__version__}"
+
def _storageMode(mode: str) -> int:
if mode == "allocate":
@@ -36,6 +39,24 @@ def _normalizeTorrentPath(path: str) -> str:
return str(PurePosixPath(str(path).replace("\\", "/")))
+def resolveLocalTorrentPath(source: str) -> Path | None:
+ text = str(source).strip()
+ if not text:
+ return None
+
+ parsed = urlparse(text)
+ if parsed.scheme.lower() == "file":
+ location = f"//{parsed.netloc}{parsed.path}" if parsed.netloc else parsed.path
+ path = Path(url2pathname(unquote(location))).expanduser()
+ return path if path.suffix.lower() == ".torrent" else None
+
+ if "://" in text or parsed.scheme.lower() == "magnet":
+ return None
+
+ path = Path(text).expanduser()
+ return path if path.suffix.lower() == ".torrent" else None
+
+
def _encodeBytes(data: bytes) -> str:
return b64encode(data).decode("ascii")
@@ -101,7 +122,7 @@ def _sessionSettings(
proxies: dict | None,
) -> dict[str, Any]:
settings = {
- "user_agent": DEFAULT_HEADERS["user-agent"],
+ "user_agent": BITTORRENT_USER_AGENT,
"listen_interfaces": f"0.0.0.0:{listenPort}",
"connections_limit": connectionsLimit,
"download_rate_limit": downloadRateLimit,
@@ -264,14 +285,13 @@ class BitTorrentFile:
@dataclass
class BitTorrentTaskStage(TaskStage):
resolvePath: str
- stateText: str = field(default="")
- peerCount: int = field(default=0)
- seedCount: int = field(default=0)
- downloadRate: int = field(default=0)
- uploadRate: int = field(default=0)
- shareRatioPercent: float = field(default=0)
- seedingTimeSeconds: int = field(default=0)
- isSeeding: bool = field(default=False)
+
+ def __post_init__(self):
+ self.stateText = ""
+ self.peerCount = 0
+ self.seedCount = 0
+ self.downloadRate = 0
+ self.uploadRate = 0
def reset(self, notifyTask: bool = True):
super().reset(notifyTask=notifyTask)
@@ -280,9 +300,6 @@ class BitTorrentTaskStage(TaskStage):
self.seedCount = 0
self.downloadRate = 0
self.uploadRate = 0
- self.shareRatioPercent = 0
- self.seedingTimeSeconds = 0
- self.isSeeding = False
@dataclass
@@ -305,13 +322,16 @@ class BitTorrentTask(Task):
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)
- fileSelectionVersion: int = field(default=0)
+ shareRatioPercent: float = field(default=0)
+ seedingTimeSeconds: int = field(default=0)
+ isSeeding: bool = field(default=False)
def __post_init__(self):
self.files = [
item if isinstance(item, BitTorrentFile) else BitTorrentFile(**item)
for item in self.files
]
+ self.fileSelectionVersion = 0
self.title = _sanitizeName(self.title)
super().__post_init__()
self._recalculateSelection()
@@ -322,8 +342,8 @@ class BitTorrentTask(Task):
return str(self.path / self.title)
@property
- def stage(self) -> BitTorrentTaskStage | None:
- return self.stages[0] if self.stages else None
+ def stage(self) -> BitTorrentTaskStage:
+ return self.stages[0]
@property
def selectedFileCount(self) -> int:
@@ -342,8 +362,7 @@ class BitTorrentTask(Task):
return self.selectedFileCount < self.totalFileCount
def syncStagePaths(self):
- if self.stage is not None:
- self.stage.resolvePath = self.resolvePath
+ self.stage.resolvePath = self.resolvePath
def mappedRelativePath(self, file: BitTorrentFile) -> str:
if self.isSingleFileTorrent:
@@ -382,21 +401,20 @@ class BitTorrentTask(Task):
self._recalculateSelection()
def reopenForAdditionalFiles(self) -> bool:
- stage = self.stage
- if stage is None or stage.status != TaskStatus.COMPLETED:
+ if self.stage.status != TaskStatus.COMPLETED:
return False
if not any(file.selected and not file.completed for file in self.files):
return False
- stage.isSeeding = False
- stage.stateText = "已添加新的下载文件"
- stage.setStatus(TaskStatus.PAUSED)
- stage.receivedBytes = sum(file.downloadedBytes for file in self.files if file.selected)
+ self.isSeeding = False
+ self.stage.stateText = "已添加新的下载文件"
+ self.stage.setStatus(TaskStatus.PAUSED)
+ self.stage.receivedBytes = sum(file.downloadedBytes for file in self.files if file.selected)
if self.fileSize > 0:
- stage.progress = stage.receivedBytes / self.fileSize * 100
+ self.stage.progress = self.stage.receivedBytes / self.fileSize * 100
else:
- stage.progress = 0
+ self.stage.progress = 0
return True
def updateFileProgress(self, progresses: list[int]):
@@ -418,32 +436,31 @@ class BitTorrentTask(Task):
def reset(self) -> TaskStatus:
result = super().reset()
self.resumeData = ""
+ self.shareRatioPercent = 0
+ self.seedingTimeSeconds = 0
+ self.isSeeding = False
for file in self.files:
file.downloadedBytes = 0
file.completed = False
return result
def occupiesDownloadSlot(self) -> bool:
- return self.status == TaskStatus.RUNNING and not self.stage.isSeeding
+ return self.status == TaskStatus.RUNNING and not self.isSeeding
def willOccupyDownloadSlotWhenStarted(self) -> bool:
- return not self.stage.isSeeding
+ return not self.isSeeding
async def run(self):
- stage = self.stage
- if stage is None:
- return
-
try:
- if self.status != TaskStatus.RUNNING or stage.status == TaskStatus.COMPLETED:
+ if self.status != TaskStatus.RUNNING or self.stage.status == TaskStatus.COMPLETED:
return
- await BitTorrentWorker(stage).run()
+ await BitTorrentWorker(self.stage).run()
except asyncio.CancelledError:
logger.info(f"{self.title} 停止下载")
raise
except Exception as e:
- if not stage.error:
- stage.setError(e)
+ if not self.stage.error:
+ self.stage.setError(e)
logger.opt(exception=e).error("{} 下载失败", self.title)
raise
@@ -459,6 +476,8 @@ class BitTorrentWorker(Worker):
self.session: lt.session | None = None
self.handle: lt.torrent_handle | None = None
self._appliedSelectionVersion = -1
+ self._seedingTimeBaseSeconds = self.task.seedingTimeSeconds
+ self._sessionSeedingStartSeconds: int | None = None
def _applyTaskParams(self, params: lt.add_torrent_params):
params.save_path = str(self.task.path)
@@ -524,17 +543,32 @@ class BitTorrentWorker(Worker):
return mapping.get(status.state.name, status.state.name)
def _syncFromStatus(self, status: lt.torrent_status):
- wasSeeding = self.stage.isSeeding
+ wasSeeding = self.task.isSeeding
totalWanted = int(status.total_wanted)
totalWantedDone = int(status.total_wanted_done)
+ isSeeding = bool(status.is_seeding)
+ sessionSeedingSeconds = _seedingSeconds(status)
self.stage.stateText = self._stateText(status)
self.stage.peerCount = int(status.num_peers)
self.stage.seedCount = int(status.num_seeds)
- self.stage.isSeeding = bool(status.is_seeding)
+ self.task.isSeeding = isSeeding
self.stage.downloadRate = int(status.download_rate)
self.stage.uploadRate = int(status.upload_rate)
- self.stage.shareRatioPercent = _shareRatioPercent(status)
- self.stage.seedingTimeSeconds = _seedingSeconds(status)
+ self.task.shareRatioPercent = _shareRatioPercent(status)
+ 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.stage.downloadRate
self.stage.receivedBytes = totalWantedDone
@@ -546,7 +580,7 @@ class BitTorrentWorker(Worker):
else:
self.stage.progress = 0
- if wasSeeding != self.stage.isSeeding:
+ if wasSeeding != self.task.isSeeding:
from app.services.core_service import coreService
coreService.notifyTaskSchedulingChanged()
@@ -561,17 +595,17 @@ class BitTorrentWorker(Worker):
self.task.updateFileProgress(progresses)
def _seedPauseReason(self) -> str:
- if not self.stage.isSeeding:
+ if not self.task.isSeeding:
return ""
ratioLimit = self.task.seedRatioLimitPercent
- if ratioLimit > 0 and self.stage.shareRatioPercent >= ratioLimit:
- return "分享率达到 {0:.2f}% / {1}%".format(self.stage.shareRatioPercent, ratioLimit)
+ if ratioLimit > 0 and self.task.shareRatioPercent >= ratioLimit:
+ return "分享率达到 {0:.2f}% / {1}%".format(self.task.shareRatioPercent, ratioLimit)
timeLimitMinutes = self.task.seedTimeLimitMinutes
- if timeLimitMinutes > 0 and self.stage.seedingTimeSeconds >= timeLimitMinutes * 60:
+ if timeLimitMinutes > 0 and self.task.seedingTimeSeconds >= timeLimitMinutes * 60:
return "做种时间达到 {0} / {1} 分钟".format(
- round(self.stage.seedingTimeSeconds / 60),
+ round(self.task.seedingTimeSeconds / 60),
timeLimitMinutes,
)
@@ -681,7 +715,7 @@ class BitTorrentWorker(Worker):
if pauseReason:
logger.info("{} 自动暂停做种: {}", self.task.title, pauseReason)
self.task.resumeData = await self._saveResumeData()
- self.stage.isSeeding = False
+ self.task.isSeeding = False
self.stage.stateText = "已自动暂停做种"
self.stage.setStatus(TaskStatus.COMPLETED)
self.stage.progress = 100
@@ -691,7 +725,7 @@ class BitTorrentWorker(Worker):
await asyncio.sleep(1)
except asyncio.CancelledError:
self.task.resumeData = await asyncio.shield(self._saveResumeData())
- wasSeeding = self.stage.isSeeding
+ wasSeeding = self.task.isSeeding
self.stage.stateText = "已暂停做种" if wasSeeding else "已暂停下载"
self.stage.setStatus(TaskStatus.PAUSED)
raise
@@ -729,6 +763,13 @@ async def _fetchTorrentBytes(payload: dict) -> bytes:
await client.close()
+def _readLocalTorrentBytes(source: str) -> bytes:
+ torrentPath = resolveLocalTorrentPath(source)
+ if torrentPath is None:
+ raise ValueError("不是有效的本地 .torrent 文件路径")
+ return torrentPath.resolve().read_bytes()
+
+
async def _resolveMagnetMetadata(payload: dict) -> tuple[lt.torrent_info, list[str], bytes]:
url = str(payload["url"]).strip()
proxies = payload.get("proxies", getProxies())
@@ -843,6 +884,7 @@ def buildTaskFromTorrentInfo(
url=sourceUrl,
fileSize=sum(entry.size for entry in entries),
path=Path(payload.get("path", cfg.downloadFolder.value)),
+ stages=[BitTorrentTaskStage(stageIndex=1, resolvePath="")],
sourceType=sourceType,
torrentData=_encodeBytes(torrentBytes),
trackers=trackers or _extractTrackers(ti),
@@ -861,12 +903,27 @@ def buildTaskFromTorrentInfo(
seedRatioLimitPercent=bittorrentConfig.seedRatioLimitPercent.value,
seedTimeLimitMinutes=bittorrentConfig.seedTimeLimitMinutes.value,
)
- task.addStage(BitTorrentTaskStage(stageIndex=1, resolvePath=task.resolvePath))
return task
async def parse(payload: dict) -> BitTorrentTask:
url = str(payload["url"]).strip()
+ localTorrentPath = resolveLocalTorrentPath(url)
+ if localTorrentPath is not None:
+ torrentBytes, webTrackers = await asyncio.gather(
+ asyncio.to_thread(_readLocalTorrentBytes, url),
+ _resolveAdditionalTrackers(),
+ )
+ ti = lt.torrent_info(torrentBytes)
+ return buildTaskFromTorrentInfo(
+ ti,
+ payload=payload,
+ sourceType="torrent",
+ sourceUrl=str(localTorrentPath.resolve()),
+ torrentBytes=torrentBytes,
+ trackers=mergeTrackers(_extractTrackers(ti), webTrackers),
+ )
+
parsedUrl = urlparse(url)
if parsedUrl.scheme.lower() == "magnet":