Skip to content

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

fix(bt): 修复多文件 BT 完成后追加勾选新文件不下载的问题

XiaoYouChRaa5b375e7476
diff --git a/dist/packs/bittorrent_pack.zip b/dist/packs/bittorrent_pack.zip
index afb069ba..72f8963b 100644
Binary files a/dist/packs/bittorrent_pack.zip and b/dist/packs/bittorrent_pack.zip differ
diff --git a/features/bittorrent_pack/lists/trackers.txt b/features/bittorrent_pack/lists/trackers.txt
index 5e4c5a85..dfde5c3f 100644
--- a/features/bittorrent_pack/lists/trackers.txt
+++ b/features/bittorrent_pack/lists/trackers.txt
@@ -1,7 +1,6 @@
http://1337.abcvg.info:80/announce
http://bt1.archive.org:6969/announce
http://bt2.archive.org:6969/announce
-http://ipv4announce.sktorrent.eu:6969/announce
http://nyaa.tracker.wf:7777/announce
http://torrentsmd.com:8080/announce
http://tracker.dhitechnical.com:6969/announce
@@ -9,8 +8,10 @@ http://tracker.dler.com:6969/announce
http://tracker.internetwarriors.net:1337/announce
http://tracker.mywaifu.best:6969/announce
http://tracker.renfei.net:8080/announce
+http://tracker.skyts.net:6969/announce
http://tracker.waaa.moe:6969/announce
http://www.wareztorrent.com:80/announce
+https://004430.xyz:443/announce
https://1.tracker.eu.org:443/announce
https://1337.abcvg.info:443/announce
https://t.213891.xyz:443/announce
@@ -20,56 +21,59 @@ https://tr.burnabyhighstar.com:443/announce
https://tracker.7471.top:443/announce
https://tracker.foreverpirates.co:443/announce
https://tracker.kuroy.me:443/announce
-https://tracker.midnightprogrammer.net:443/announce
https://tracker.nekomi.cn:443/announce
https://tracker.pmman.tech:443/announce
https://tracker.qingwapt.org:443/announce
+https://tracker.yume-hatsuyuki.moe:443/announce
https://tracker1.520.jp:443/announce
-udp://bittorrent-tracker.e-n-c-r-y-p-t.net:1337/announce
+udp://discover.curiousfacts.blog:6969/announce
udp://evan.im:6969/announce
udp://exodus.desync.com:6969/announce
udp://explodie.org:6969/announce
udp://kolankoalastree.newtrackon.co.nz:1337/announce
udp://mail.segso.net:6969/announce
udp://martin-gebhardt.eu:25/announce
+udp://ns575949.ip-51-222-82.net:6969/announce
udp://open.demonii.com:1337/announce
udp://open.ftorrent.com:443/announce
udp://open.stealth.si:80/announce
+udp://open.tracker.cl:1337/announce
udp://open.tracker.ink:6969/announce
udp://opentor.org:2710/announce
-udp://opentracker.lain.moscow:6969/announce
udp://p4p.arenabg.com:1337/announce
udp://retracker.hotplug.ru:2710/announce
udp://retracker01-msk-virt.corbina.net:80/announce
udp://torrent.tracker.durukanbal.com:6969/announce
-udp://tr.btube3.com:2010/announce
udp://tr4ck3r.duckdns.org:6969/announce
udp://tracker-udp.gbitt.info:80/announce
-udp://tracker.aruku.ovh:8081/announce
+udp://tracker.alt.cx:6969/announce
udp://tracker.bittor.pw:1337/announce
udp://tracker.cn.nyaa.net:6969/announce
udp://tracker.corpscorp.online:80/announce
udp://tracker.dler.com:6969/announce
udp://tracker.dler.org:6969/announce
udp://tracker.ducks.party:1984/announce
+udp://tracker.evergarden.uk:1914/announce
+udp://tracker.gmi.gd:6969/announce
udp://tracker.ilibr.org:6969/announce
udp://tracker.nyaa.net:6969/announce
udp://tracker.nyaa.vc:6969/announce
+udp://tracker.okade.pro:1337/announce
udp://tracker.opentrackr.com:6969/announce
udp://tracker.opentrackr.org:1337/announce
udp://tracker.peerfect.org:6969/announce
udp://tracker.qu.ax:6969/announce
-udp://tracker.skynetcloud.site:6969/announce
udp://tracker.skyts.net:6969/announce
udp://tracker.theoks.net:6969/announce
udp://tracker.torrent.eu.org:451/announce
+udp://tracker.torrents.observer:80/announce
+udp://tracker.transfur.org:6969/announce
udp://tracker.wildkat.net:6969/announce
udp://tracker.willy.pro:6969/announce
-udp://tracker.yume-hatsuyuki.moe:6969/announce
udp://tracker2.dler.org:80/announce
udp://v2.iperson.xyz:6969/announce
wss://tracker.openwebtorrent.com:443/announce
-http://tracker.ipv6tracker.ru:80/announce
http://wegkxfcivgx.ydns.eu:80/announce
-http://echostar.ddnsfree.com:8080/announce
-https://004430.xyz:443/announce
+http://tracker.ipv6tracker.ru:80/announce
+http://taciturn-shadow.spb.ru:6969/announce
+http://tracker.beeimg.com:6969/announce
diff --git a/features/bittorrent_pack/manifest.toml b/features/bittorrent_pack/manifest.toml
index 488af0e0..2617576d 100644
--- a/features/bittorrent_pack/manifest.toml
+++ b/features/bittorrent_pack/manifest.toml
@@ -2,5 +2,5 @@
entry = "pack.py"
class = "BitTorrentPack"
dependencies = []
-version = "1.4.0"
+version = "1.4.1"
gdMinVersion = "4.5.0"
diff --git a/features/bittorrent_pack/session.py b/features/bittorrent_pack/session.py
index ebd69e84..9c2c5f9c 100644
--- a/features/bittorrent_pack/session.py
+++ b/features/bittorrent_pack/session.py
@@ -157,13 +157,17 @@ def isSeedingLimitReached(shareRatioPercent: float, seedingTimeSeconds: int) ->
)
+def toFilePriorities(selectedIndexes: set[int], fileCount: int) -> list[int]:
+ return [4 if i in selectedIndexes else 0 for i in range(fileCount)]
+
+
@dataclass(frozen=True)
class TorrentParams:
torrentData: bytes
savePath: str
resumeData: bytes = b""
trackers: list[str] = field(default_factory=list)
- filePriorities: list[int] = field(default_factory=list)
+ selectedIndexes: set[int] | None = None
fileRenames: dict[int, str] = field(default_factory=dict)
seedingTimeSeconds: int = 0
@@ -196,7 +200,7 @@ class ActiveTorrent:
seedStart: int | None = None
pollCount: int = 0
resumeWaiter: asyncio.Future | None = None
- pendingPriorities: list[int] | None = None
+ pendingSelection: set[int] | None = None
def seedingElapsed(self, isSeeding: bool, sessionSeconds: int) -> int:
if isSeeding:
@@ -337,10 +341,10 @@ class BTSession:
except TimeoutError:
return None
- def updatePriorities(self, taskId: str, priorities: list[int]) -> None:
+ def setSelection(self, taskId: str, selectedIndexes: set[int]) -> None:
entry = self._active.get(taskId)
if entry is not None:
- entry.pendingPriorities = priorities
+ entry.pendingSelection = selectedIndexes
def lastResumeData(self, taskId: str) -> bytes | None:
return self._resumeCache.pop(taskId, None)
@@ -463,7 +467,10 @@ class BTSession:
if bittorrentConfig.storageMode.value == "allocate"
else lt.storage_mode_t.storage_mode_sparse
)
- ltParams.file_priorities = params.filePriorities
+ if params.selectedIndexes is not None:
+ # resumeData 携带旧的 piece_priorities,不清空会覆盖新的 file_priorities
+ ltParams.piece_priorities = []
+ ltParams.file_priorities = toFilePriorities(params.selectedIndexes, ltParams.ti.num_files())
ltParams.renamed_files = params.fileRenames
if bittorrentConfig.enableSequentialDownload.value:
ltParams.flags |= lt.torrent_flags.sequential_download
@@ -580,6 +587,12 @@ class BTSession:
return
def _updateEntry(self, entry: ActiveTorrent) -> None:
+ if entry.pendingSelection is not None:
+ fileCount = entry.handle.torrent_file().num_files()
+ entry.handle.prioritize_files(toFilePriorities(entry.pendingSelection, fileCount))
+ entry.pendingSelection = None
+ return
+
status = entry.handle.status()
isSeeding = status.is_seeding
@@ -612,10 +625,6 @@ class BTSession:
if entry.onProgress is not None:
entry.onProgress(torrentProgress)
- if entry.pendingPriorities is not None:
- entry.handle.prioritize_files(entry.pendingPriorities)
- entry.pendingPriorities = None
-
if not entry.done.done() and entry.isDone(torrentProgress):
entry.done.set_result(None)
diff --git a/features/bittorrent_pack/task.py b/features/bittorrent_pack/task.py
index e2853e07..b17754d7 100644
--- a/features/bittorrent_pack/task.py
+++ b/features/bittorrent_pack/task.py
@@ -16,7 +16,6 @@ if TYPE_CHECKING:
@dataclass(kw_only=True)
class BTFile(TaskFile):
- priority: int = 4
def __post_init__(self) -> None:
self.relativePath = toPosixPath(self.relativePath)
@@ -67,20 +66,15 @@ class BTTask(Task):
return self.name
return toPosixPath(Path(self.name, *PurePosixPath(file.relativePath).parts[1:]))
- def priorities(self) -> list[int]:
- return [f.priority if f.selected else 0 for f in self.files]
-
def setSelection(self, selectedIndexes: set[int]) -> None:
if not selectedIndexes:
raise ValueError("至少需要选择一个文件")
changed = False
for f in self.files:
selected = f.index in selectedIndexes
- priority = 4 if selected else 0
- if f.selected != selected or f.priority != priority:
+ if f.selected != selected:
changed = True
f.selected = selected
- f.priority = priority
if not selected:
f.downloadedBytes = 0
f.completed = False
@@ -90,7 +84,7 @@ class BTTask(Task):
self.fileSize = sum(f.size for f in self.files if f.selected)
from .session import btSession
- btSession.updatePriorities(self.taskId, self.priorities())
+ btSession.setSelection(self.taskId, self.selectedIndexes)
if self.step.status == TaskStatus.COMPLETED and any(f.selected and not f.completed for f in self.files):
self.step.status = TaskStatus.WAITING
@@ -128,7 +122,7 @@ class BTTask(Task):
savePath=str(self.outputFolder),
resumeData=b64decode(self.resumeData) if self.resumeData else b"",
trackers=self.trackers.copy(),
- filePriorities=self.priorities(),
+ selectedIndexes=self.selectedIndexes,
fileRenames=fileRenames,
seedingTimeSeconds=self.seedingTimeSeconds,
)
@@ -190,7 +184,7 @@ class BTTaskStep(TaskStep):
continue
dl = p.fileProgress[f.index] if f.index < len(p.fileProgress) else 0
f.downloadedBytes = dl
- f.completed = f.size > 0 and dl >= f.size
+ f.completed = dl >= f.size
selectionVersion = None
while selectionVersion != task.selectionVersion:
diff --git a/tests/bittorrent_pack/test_session.py b/tests/bittorrent_pack/test_session.py
index 9415a990..14c0e540 100644
--- a/tests/bittorrent_pack/test_session.py
+++ b/tests/bittorrent_pack/test_session.py
@@ -2,8 +2,10 @@ from __future__ import annotations
import asyncio
import hashlib
+import socket
from pathlib import Path
+from aiohttp import web
import libtorrent as lt
import pytest
@@ -154,3 +156,140 @@ async def test_cancel_run_closes_session_after_idle(config, tmp_path):
assert session.state == SessionState.STOPPED
finally:
await session.close()
+
+
+def buildMultiFileTorrent(tmpPath: Path, files: dict[str, bytes]) -> tuple[bytes, dict[str, int]]:
+ sourceRoot = tmpPath / "source"
+ torrentDir = sourceRoot / "pack"
+ torrentDir.mkdir(parents=True)
+ for name, content in files.items():
+ (torrentDir / name).write_bytes(content)
+
+ fs = lt.list_files(str(torrentDir))
+ ct = lt.create_torrent(fs, piece_size=16384)
+ lt.set_piece_hashes(ct, str(sourceRoot))
+ torrentData = lt.bencode(ct.generate())
+
+ layout = lt.load_torrent_buffer(torrentData).ti.layout()
+ indexByName = {
+ Path(layout.file_path(i)).name: i
+ for i in range(layout.num_files())
+ if not (layout.file_flags(i) & lt.file_storage.flag_pad_file)
+ }
+ return torrentData, indexByName
+
+
+async def startLocalSeeder(
+ sourceRoot: Path, torrentData: bytes, startServer, *, uploadRateLimit: int = 0,
+) -> tuple[lt.session, lt.torrent_handle, str]:
+ seeder = lt.session({
+ "listen_interfaces": "127.0.0.1:0",
+ "enable_dht": False,
+ "enable_lsd": False,
+ "enable_upnp": False,
+ "enable_natpmp": False,
+ "upload_rate_limit": uploadRateLimit,
+ "ignore_limits_on_local_network": uploadRateLimit == 0,
+ })
+ params = lt.load_torrent_buffer(torrentData)
+ params.save_path = str(sourceRoot)
+ handle = seeder.add_torrent(params)
+ handle.resume()
+ async with asyncio.timeout(5):
+ while not handle.status().is_seeding:
+ await asyncio.sleep(0.05)
+ peer = socket.inet_aton("127.0.0.1") + seeder.listen_port().to_bytes(2, "big")
+ body = lt.bencode({b"interval": 60, b"peers": peer})
+
+ async def announce(_):
+ return web.Response(body=body)
+
+ trackerUrl = (await startServer(announce)).removesuffix("/file") + "/announce"
+ return seeder, handle, trackerUrl
+
+
+async def test_run_downloads_newly_selected_file_after_resume(config, startServer, tmp_path):
+ payloads = {"a.bin": b"A" * 20000, "b.bin": b"B" * 20000, "c.bin": b"C" * 20000}
+ torrentData, indexByName = buildMultiFileTorrent(tmp_path, payloads)
+ seeder, seederHandle, trackerUrl = await startLocalSeeder(tmp_path / "source", torrentData, startServer)
+
+ cfg.set(bittorrentConfig.enableDht, False)
+ cfg.set(bittorrentConfig.enableLsd, False)
+
+ saveDir = tmp_path / "downloads"
+ session = BTSession()
+ try:
+ async with asyncio.timeout(10):
+ resumeData = await session.run(
+ "t1",
+ TorrentParams(
+ torrentData=torrentData,
+ savePath=str(saveDir),
+ trackers=[trackerUrl],
+ selectedIndexes={indexByName["a.bin"]},
+ ),
+ )
+
+ assert (saveDir / "pack" / "a.bin").read_bytes() == payloads["a.bin"]
+ assert not (saveDir / "pack" / "b.bin").exists()
+ assert not (saveDir / "pack" / "c.bin").exists()
+
+ async with asyncio.timeout(10):
+ await session.run(
+ "t1",
+ TorrentParams(
+ torrentData=torrentData,
+ savePath=str(saveDir),
+ resumeData=resumeData,
+ trackers=[trackerUrl],
+ selectedIndexes={indexByName["a.bin"], indexByName["b.bin"]},
+ ),
+ )
+
+ assert (saveDir / "pack" / "a.bin").read_bytes() == payloads["a.bin"]
+ assert (saveDir / "pack" / "b.bin").read_bytes() == payloads["b.bin"]
+ assert not (saveDir / "pack" / "c.bin").exists()
+ finally:
+ await session.close()
+ seeder.remove_torrent(seederHandle)
+
+
+async def test_set_selection_downloads_newly_selected_file(config, startServer, tmp_path):
+ payloads = {"a.bin": b"A" * 20000, "b.bin": b"B" * 20000, "c.bin": b"C" * 20000}
+ torrentData, indexByName = buildMultiFileTorrent(tmp_path, payloads)
+ seeder, seederHandle, trackerUrl = await startLocalSeeder(
+ tmp_path / "source", torrentData, startServer, uploadRateLimit=16384,
+ )
+
+ cfg.set(bittorrentConfig.enableDht, False)
+ cfg.set(bittorrentConfig.enableLsd, False)
+
+ saveDir = tmp_path / "downloads"
+ session = BTSession()
+ didSelect = False
+
+ def onProgress(_):
+ nonlocal didSelect
+ if not didSelect:
+ didSelect = True
+ session.setSelection("t1", {indexByName["a.bin"], indexByName["b.bin"]})
+
+ try:
+ async with asyncio.timeout(10):
+ await session.run(
+ "t1",
+ TorrentParams(
+ torrentData=torrentData,
+ savePath=str(saveDir),
+ trackers=[trackerUrl],
+ selectedIndexes={indexByName["a.bin"]},
+ ),
+ onProgress=onProgress,
+ )
+
+ assert (saveDir / "pack" / "a.bin").read_bytes() == payloads["a.bin"]
+ assert (saveDir / "pack" / "b.bin").read_bytes() == payloads["b.bin"]
+ assert not (saveDir / "pack" / "c.bin").exists()
+ finally:
+ await session.close()
+ seeder.remove_torrent(seederHandle)
diff --git a/tests/bittorrent_pack/test_task.py b/tests/bittorrent_pack/test_task.py
index 5ce28a16..3d6bc701 100644
--- a/tests/bittorrent_pack/test_task.py
+++ b/tests/bittorrent_pack/test_task.py
@@ -11,12 +11,12 @@ from app.models.task import TaskStatus
class FakeSession:
def __init__(self, onRun=None, progresses: tuple[TorrentProgress, ...] = ()):
- self.runPriorities: list[list[int]] = []
+ self.runSelections: list[set[int]] = []
self.onRun = onRun
self.progresses = progresses
async def run(self, taskId, params, onProgress=None) -> bytes:
- self.runPriorities.append(list(params.filePriorities))
+ self.runSelections.append(set(params.selectedIndexes))
for progress in self.progresses:
onProgress(progress)
if self.onRun is not None:
@@ -24,7 +24,7 @@ class FakeSession:
onRun()
return b"resume"
- def updatePriorities(self, taskId, priorities):
+ def setSelection(self, taskId, selectedIndexes):
pass
def lastResumeData(self, taskId):
@@ -36,7 +36,7 @@ def buildTask(tmp_path: Path) -> BTTask:
name="pack", url="x.torrent", outputFolder=tmp_path,
steps=[BTTaskStep(stepIndex=1)], torrentData=b64encode(b"x").decode(),
files=[BTFile(index=0, relativePath="pack/a", size=1),
- BTFile(index=1, relativePath="pack/b", size=1, selected=False, priority=0)],
+ BTFile(index=1, relativePath="pack/b", size=1, selected=False)],
)
task.setStatus(TaskStatus.RUNNING)
return task
@@ -71,7 +71,28 @@ def test_run_downloads_file_selected_near_the_end(monkeypatch, tmp_path):
asyncio.run(task.run(lambda _: None, noLimit))
- assert fake.runPriorities == [[4, 0], [4, 4]]
+ assert fake.runSelections == [{0}, {0, 1}]
+ assert task.status == TaskStatus.COMPLETED
+
+
+def test_set_selection_keeps_completed_with_empty_file(monkeypatch, tmp_path):
+ task = BTTask(
+ name="pack", url="x.torrent", outputFolder=tmp_path,
+ steps=[BTTaskStep(stepIndex=1)], torrentData=b64encode(b"x").decode(),
+ files=[BTFile(index=0, relativePath="pack/a", size=10),
+ BTFile(index=1, relativePath="pack/empty", size=0)],
+ )
+ task.setStatus(TaskStatus.RUNNING)
+ progress = TorrentProgress(
+ stateText="finished", peerCount=1, totalPeerCount=1, seedCount=1, isSeeding=False, isFinished=True,
+ downloadRate=0, uploadRate=0, shareRatioPercent=0, seedingTimeSeconds=0, progress=100,
+ receivedBytes=10, totalWanted=10, fileProgress=[10, 0],
+ )
+ monkeypatch.setattr(session_module, "btSession", FakeSession(progresses=(progress,)))
+
+ asyncio.run(task.run(lambda _: None, noLimit))
+ task.setSelection({1})
+
assert task.status == TaskStatus.COMPLETED
diff --git a/versions.json b/versions.json
index 70834416..69c79864 100644
--- a/versions.json
+++ b/versions.json
@@ -58,9 +58,9 @@
"gdMinVersion": "4.5.0"
},
"bittorrent_pack": {
- "version": "1.4.0",
+ "version": "1.4.1",
"file": "bittorrent_pack.zip",
- "sha256": "cb934b70849b97f3efa37a629c536778881fa1f437b90c842ab7571c9b8b01b3",
+ "sha256": "34ddaef956fb5692bf8969282a492a771c0eb0cd8f66928934028ee99a50c7fe",
"gdMinVersion": "4.5.0"
},
"ed2k_pack": {
@@ -130,4 +130,4 @@
"gdMinVersion": "4.5.0"
}
}
-}
\ No newline at end of file
+}