Skip to content

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

feat(bittorrent): 移除 libtorrent 废弃接口 #1023

XiaoYouChRbcf13c59f47c
diff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.py
index 1af34e5c..69579380 100644
--- a/features/bittorrent_pack/pack.py
+++ b/features/bittorrent_pack/pack.py
@@ -71,7 +71,6 @@ class TorrentParser(TaskParser):
sourceType, sourceUrl = "torrent", str(localPath.resolve())
elif urlparse(url).scheme.lower() == "magnet":
- magnetTrackers = list(lt.parse_magnet_uri(url).trackers)
torrentBytes = await btSession.fetchMetadata(url, webTrackers)
sourceType, sourceUrl = "magnet", url
@@ -82,23 +81,23 @@ class TorrentParser(TaskParser):
raise ValueError("种子文件为空")
try:
- ti = lt.torrent_info(torrentBytes)
+ params = lt.load_torrent_buffer(torrentBytes)
except Exception as e:
raise ValueError(f"无效的 BitTorrent 种子文件:{e}") from e
- torrentTrackers = [str(t.url).strip() for t in ti.trackers()]
- allSources = (magnetTrackers, torrentTrackers, webTrackers) if sourceType == "magnet" else (torrentTrackers, webTrackers)
- trackers = list(dict.fromkeys(t for g in allSources for t in g if t))
+ trackers = list(dict.fromkeys(
+ t.strip() for g in (params.trackers, webTrackers) for t in g if t.strip()
+ ))
- fileStorage = ti.files()
+ layout = params.ti.layout()
entries: list[BTFile] = [
BTFile(
index=i,
- relativePath=fileStorage.file_path(i),
- size=fileStorage.file_size(i),
+ relativePath=layout.file_path(i),
+ size=layout.file_size(i),
)
- for i in range(ti.num_files())
- if not (fileStorage.file_flags(i) & lt.file_storage.flag_pad_file)
+ for i in range(layout.num_files())
+ if not (layout.file_flags(i) & lt.file_storage.flag_pad_file)
]
if not entries:
diff --git a/features/bittorrent_pack/session.py b/features/bittorrent_pack/session.py
index 9ac90601..7e6e9710 100644
--- a/features/bittorrent_pack/session.py
+++ b/features/bittorrent_pack/session.py
@@ -177,14 +177,15 @@ class BTSession:
self._ensureSession()
params = lt.parse_magnet_uri(magnetUri)
+ magnetTrackers = list(params.trackers)
params.trackers = list(dict.fromkeys(
- t for g in (params.trackers, trackers) for t in g if t
+ t for g in (magnetTrackers, trackers) for t in g if t
))
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
+ params.flags |= lt.torrent_flags.default_dont_download
hashes = params.info_hashes if params.ti is None else params.ti.info_hashes()
if hashes.has_v1() and self._session.find_torrent(hashes.v1).is_valid():
@@ -202,7 +203,10 @@ class BTSession:
try:
ti = await asyncio.wait_for(waiter, timeout=bittorrentConfig.metadataTimeout.value)
- return lt.bencode(lt.create_torrent(ti).generate())
+ torrent = lt.add_torrent_params()
+ torrent.ti = ti
+ torrent.trackers = magnetTrackers
+ return lt.bencode(lt.write_torrent_file(torrent, lt.write_flags.allow_missing_piece_layer))
except asyncio.TimeoutError:
raise TimeoutError("等待 magnet 元数据超时")
finally:
@@ -346,11 +350,11 @@ class BTSession:
return
from app.config.paths import APP_DATA_DIR
try:
- state = self._session.save_state(
+ state = self._session.session_state(
lt.save_state_flags_t.save_dht_state
)
(APP_DATA_DIR / DHT_STATE_FILE).write_bytes(
- lt.bencode(state)
+ lt.write_session_params_buf(state, lt.save_state_flags_t.save_dht_state)
)
except Exception as e:
logger.warning("保存 DHT 状态失败: {}", e)
@@ -365,10 +369,11 @@ class BTSession:
except Exception as e:
logger.opt(exception=e).warning("读取 BitTorrent resume 数据失败")
+ torrentParams = lt.load_torrent_buffer(params.torrentData)
if ltParams is None:
- ltParams = lt.add_torrent_params()
- ltParams.ti = lt.torrent_info(params.torrentData)
- ltParams.flags |= lt.torrent_flags.update_subscribe
+ ltParams = torrentParams
+ elif ltParams.ti is None:
+ ltParams.ti = torrentParams.ti
ltParams.save_path = params.savePath
ltParams.storage_mode = (
@@ -377,6 +382,7 @@ class BTSession:
else lt.storage_mode_t.storage_mode_sparse
)
ltParams.file_priorities = params.filePriorities
+ ltParams.renamed_files = params.fileRenames
if bittorrentConfig.enableSequentialDownload.value:
ltParams.flags |= lt.torrent_flags.sequential_download
else:
@@ -396,12 +402,7 @@ class BTSession:
raise TaskError("该种子已在下载中")
self._session.remove_torrent(stale)
- handle = self._session.add_torrent(ltParams)
-
- for index, newPath in params.fileRenames.items():
- handle.rename_file(index, newPath)
-
- return handle
+ return self._session.add_torrent(ltParams)
async def _saveResumeAndRemove(self, entry: ActiveTorrent, taskId: str) -> None:
try:
diff --git a/features/bittorrent_pack/swarm.py b/features/bittorrent_pack/swarm.py
index 26c9f7d6..0ec822ef 100644
--- a/features/bittorrent_pack/swarm.py
+++ b/features/bittorrent_pack/swarm.py
@@ -59,14 +59,15 @@ class TrackerInfo:
def toTorrentMeta(torrentData: bytes) -> TorrentMeta:
- info = lt.torrent_info(torrentData)
+ params = lt.load_torrent_buffer(torrentData)
+ info = params.ti
hashes = info.info_hashes()
return TorrentMeta(
infoHashV1=str(hashes.v1) if hashes.has_v1() else "",
infoHashV2=str(hashes.v2) if hashes.has_v2() else "",
- comment=info.comment(),
- creator=info.creator(),
- createdAt=info.creation_date(),
+ comment=params.comment,
+ creator=params.created_by,
+ createdAt=params.creation_date,
pieceCount=info.num_pieces(),
pieceSize=info.piece_length(),
isPrivate=info.priv(),
diff --git a/tests/bittorrent_pack/test_task_parser.py b/tests/bittorrent_pack/test_task_parser.py
index 9fdbe3d3..746dfec0 100644
--- a/tests/bittorrent_pack/test_task_parser.py
+++ b/tests/bittorrent_pack/test_task_parser.py
@@ -46,7 +46,6 @@ def buildNamedHandler(content: bytes, name: str):
return handler
[email protected]("ignore::DeprecationWarning:bittorrent_pack.pack")
async def test_parse_online_torrent_adds_its_files(features, startServer, tmp_path):
url = await startServer(buildNamedHandler(buildTorrent(tmp_path), "movie.torrent"))
@@ -66,7 +65,6 @@ async def test_parse_invalid_online_torrent_adds_plain_file(features, startServe
assert task.name == "movie.torrent"
[email protected]("ignore::DeprecationWarning:bittorrent_pack.pack")
async def test_relink_torrent_to_http_task_rejects(engine, features, startServer, tmp_path):
task = await features.parse(TaskOptions(url=await startServer(buildRangeHandler(b"x" * 100))))
btTask = await features.parse(TaskOptions(url=await startServer(buildNamedHandler(buildTorrent(tmp_path), "movie.torrent"))))
@@ -85,7 +83,6 @@ def test_match_rejects_text_that_is_not_info_hash(features, text):
assert not features.match(text)
[email protected]("ignore::DeprecationWarning:bittorrent_pack.pack")
async def test_parse_bare_info_hash_as_magnet_link(features, monkeypatch, tmp_path):
infoHash = "AB" * 20
torrentBytes = buildTorrent(tmp_path)