Skip to content

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

fix(bootstrap-list): 订阅总条数按条目去重

XiaoYouChRe1942c076c6a
diff --git a/app/bootstrap_list.py b/app/bootstrap_list.py
index e8d68062..04ecfcb1 100644
--- a/app/bootstrap_list.py
+++ b/app/bootstrap_list.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import asyncio
import hashlib
import time
-from collections.abc import Awaitable, Callable
+from collections.abc import Awaitable, Callable, Hashable
from dataclasses import dataclass
from pathlib import Path
@@ -36,13 +36,13 @@ class BootstrapList:
folder: Path,
snapshot: Path,
sources: Callable[[], list[str]],
- count: Callable[[bytes], int],
+ parse: Callable[[bytes], list[Hashable]],
fetch: Callable[[str], Awaitable[bytes]] = fetchBytes,
):
self._folder = folder
self._snapshot = snapshot
self._sources = sources
- self._count = count
+ self._parse = parse
self._fetch = fetch
self._errors: dict[str, str] = {}
self._refreshing: asyncio.Task | None = None
@@ -72,12 +72,19 @@ class BootstrapList:
isCached = path.is_file()
statuses.append(SubscriptionStatus(
url,
- self._count(path.read_bytes()) if isCached else None,
+ len(set(self._parse(path.read_bytes()))) if isCached else None,
path.stat().st_mtime if isCached else None,
self._errors.get(url, ""),
))
return statuses
+ def entryCount(self) -> int:
+ entries = set()
+ for url in self._sources():
+ if (path := self._cachePath(url)).is_file():
+ entries.update(self._parse(path.read_bytes()))
+ return len(entries)
+
async def refresh(self) -> None:
if self._refreshing is None:
self._refreshing = asyncio.ensure_future(self._fetchAll())
@@ -93,7 +100,7 @@ class BootstrapList:
async def _fetchOne(self, url: str) -> None:
try:
data = await self._fetch(url)
- self._count(data)
+ self._parse(data)
path = self._cachePath(url)
path.parent.mkdir(parents=True, exist_ok=True)
partPath = path.with_suffix(".part")
diff --git a/app/view/components/bootstrap_list.py b/app/view/components/bootstrap_list.py
index 87a12a77..9c066b09 100644
--- a/app/view/components/bootstrap_list.py
+++ b/app/view/components/bootstrap_list.py
@@ -92,7 +92,7 @@ class BootstrapListCard(SettingCard):
self._startRefresh()
else:
self._refreshContent()
- self._probeNetwork()
+ self.probeNetwork()
def _initLayout(self):
self.hBoxLayout.addWidget(self.manageButton, 0)
@@ -110,22 +110,23 @@ class BootstrapListCard(SettingCard):
return
statuses = self._list.statuses()
cached = [s for s in statuses if s.count is not None]
+ hasError = any(s.error for s in statuses)
parts = [self.tr("{0} 个订阅").format(len(statuses))]
if cached:
newest = max(s.updatedAt for s in cached)
- parts.append(self.tr("共 {0} 条").format(sum(s.count for s in cached)))
+ parts.append(self.tr("共 {0} 条").format(self._list.entryCount()))
parts.append(self.tr("{0}更新").format(toAgoText(time.time() - newest)))
- if any(s.error for s in statuses) and time.time() - newest > FAILURE_NOTICE_AGE:
+ if hasError and time.time() - newest > FAILURE_NOTICE_AGE:
parts.append(self.tr("更新失败"))
else:
parts.append(self.tr("使用内置列表"))
- if any(s.error for s in statuses):
+ if hasError:
parts.append(self.tr("更新失败"))
if self._networkText:
parts.append(self._networkText)
self.setContent(self.tr(",").join(parts))
- def _probeNetwork(self):
+ def probeNetwork(self):
if self._probeNetworkText is not None:
self._submit(self._probeNetworkText(), done=self._onNetworkProbed, owner=self)
@@ -141,7 +142,7 @@ class BootstrapListCard(SettingCard):
def _onRefreshed(self, _result=None):
self.refreshButton.setEnabled(True)
self._refreshContent()
- self._probeNetwork()
+ self.probeNetwork()
def _onManageClicked(self):
dialog = BootstrapListDialog(self._list, self._sourcesItem, self._customItem, self.window())
@@ -250,9 +251,9 @@ class BootstrapListDialog(MessageBoxBase):
return True
def _addRow(self, url: str):
- row = SubscriptionRow(url, toStatusText(self._statuses.get(url)), self._onRowRemoved, self.rowContainer)
- error = self._statuses[url].error if url in self._statuses else ""
- row.statusLabel.setToolTip(error)
+ status = self._statuses.get(url)
+ row = SubscriptionRow(url, toStatusText(status), self._onRowRemoved, self.rowContainer)
+ row.statusLabel.setToolTip(status.error if status is not None else "")
self.rowLayout.addWidget(row)
self._rows.append(row)
diff --git a/features/bittorrent_pack/android.py b/features/bittorrent_pack/android.py
index 6b3621c6..3bdf9693 100644
--- a/features/bittorrent_pack/android.py
+++ b/features/bittorrent_pack/android.py
@@ -46,6 +46,7 @@ async def trackerListState() -> dict:
"defaults": list(bittorrentConfig.webTrackerSources.defaultValue),
"custom": bittorrentConfig.webTrackerCustomList.value,
"statuses": [asdict(status) for status in trackerList.statuses()],
+ "entryCount": trackerList.entryCount(),
"isRefreshing": trackerList.isRefreshing,
"dhtNodes": await btSession.probeDhtNodes(),
}
diff --git a/features/bittorrent_pack/trackers.py b/features/bittorrent_pack/trackers.py
index 87886892..c63429f1 100644
--- a/features/bittorrent_pack/trackers.py
+++ b/features/bittorrent_pack/trackers.py
@@ -18,18 +18,18 @@ def parseTrackers(text: str) -> list[str]:
]
-def countTrackers(data: bytes) -> int:
- count = len(parseTrackers(data.decode("utf-8", errors="ignore")))
- if count == 0:
+def parseTrackerList(data: bytes) -> list[str]:
+ trackers = parseTrackers(data.decode("utf-8", errors="ignore"))
+ if not trackers:
raise ValueError("没有有效的 Tracker")
- return count
+ return trackers
trackerList = BootstrapList(
APP_DATA_DIR / "bt" / "trackers",
Path(__file__).parent / "lists" / "trackers.txt",
lambda: list(bittorrentConfig.webTrackerSources.value),
- countTrackers,
+ parseTrackerList,
)
diff --git a/features/ed2k_pack/lists.py b/features/ed2k_pack/lists.py
index 0fad48f2..e7a4a68e 100644
--- a/features/ed2k_pack/lists.py
+++ b/features/ed2k_pack/lists.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import struct
from pathlib import Path
from app.bootstrap_list import BootstrapList
@@ -7,30 +8,67 @@ from app.config.paths import APP_DATA_DIR
from .config import ed2kConfig
-CONTACT_SIZE = 25
+TAG_SIZES = {0x01: 16, 0x03: 4, 0x04: 4, 0x05: 1, 0x08: 2, 0x09: 1, 0x0B: 8}
+TAG_LENGTH_FORMATS = {0x02: "<H", 0x07: "<I", 0x0A: "<B"}
-def countServers(data: bytes) -> int:
- if len(data) < 5 or data[0] not in (0xE0, 0x0E):
+def parseServerList(data: bytes) -> list[bytes]:
+ if len(data) < 5 or data[0] not in (0xE0, 0x0E, 0x0F):
raise ValueError("不是有效的 server.met")
- count = int.from_bytes(data[1:5], "little")
- if count == 0:
+ (count,) = struct.unpack_from("<I", data, 1)
+ offset = 5
+ endpoints = []
+ try:
+ for _ in range(count):
+ endpoints.append(data[offset:offset + 6])
+ (tagCount,) = struct.unpack_from("<I", data, offset + 6)
+ offset += 10
+ for _ in range(tagCount):
+ head = data[offset]
+ tagType = head & 0x7F
+ offset += 2 if head & 0x80 else 3 + struct.unpack_from("<H", data, offset + 1)[0]
+ if tagType in TAG_SIZES:
+ offset += TAG_SIZES[tagType]
+ elif 0x11 <= tagType <= 0x20:
+ offset += tagType - 0x10
+ elif tagType in TAG_LENGTH_FORMATS:
+ lengthFormat = TAG_LENGTH_FORMATS[tagType]
+ offset += struct.calcsize(lengthFormat) + struct.unpack_from(lengthFormat, data, offset)[0]
+ elif tagType == 0x06:
+ offset += 3 + struct.unpack_from("<H", data, offset)[0] // 8
+ else:
+ raise ValueError(f"server.met 中有未知的标签类型 {tagType:#x}")
+ except (IndexError, struct.error):
+ raise ValueError("server.met 不完整") from None
+ if offset > len(data):
+ raise ValueError("server.met 不完整")
+ if not endpoints:
raise ValueError("server.met 中没有服务器")
- return count
+ return endpoints
-def countNodes(data: bytes) -> int:
+def parseNodeList(data: bytes) -> list[bytes]:
def readCount(offset: int) -> int:
return int.from_bytes(data[offset:offset + 4], "little")
headerSize = 4
+ contactSize = 25
count = readCount(0)
if count == 0 and len(data) >= 12:
- headerSize = 16 if readCount(4) == 3 else 12
+ version = readCount(4)
+ if version == 3:
+ headerSize = 16
+ contactSize = 25 if readCount(8) == 1 else 34
+ else:
+ headerSize = 12
+ contactSize = 34 if version == 2 else 25
count = readCount(headerSize - 4)
- if count == 0 or len(data) < headerSize + count * CONTACT_SIZE:
+ if count == 0 or len(data) < headerSize + count * contactSize:
raise ValueError("不是有效的 nodes.dat")
- return count
+ return [
+ data[offset:offset + 16]
+ for offset in range(headerSize, headerSize + count * contactSize, contactSize)
+ ]
LISTS_FOLDER = Path(__file__).parent / "lists"
@@ -39,11 +77,11 @@ serverList = BootstrapList(
APP_DATA_DIR / "ed2k" / "servers",
LISTS_FOLDER / "server.met",
lambda: list(ed2kConfig.serverListSources.value),
- countServers,
+ parseServerList,
)
nodeList = BootstrapList(
APP_DATA_DIR / "ed2k" / "nodes",
LISTS_FOLDER / "nodes.dat",
lambda: list(ed2kConfig.nodeListSources.value),
- countNodes,
+ parseNodeList,
)
diff --git a/scripts/update_bootstrap_snapshots.py b/scripts/update_bootstrap_snapshots.py
index e43cb131..c2abd3e6 100644
--- a/scripts/update_bootstrap_snapshots.py
+++ b/scripts/update_bootstrap_snapshots.py
@@ -14,7 +14,7 @@ sys.path[:0] = [str(REPO), str(REPO / "features")]
from bittorrent_pack.config import DEFAULT_TRACKER_LIST_SOURCES # noqa: E402
from bittorrent_pack.trackers import parseTrackers # noqa: E402
from ed2k_pack.config import DEFAULT_NODE_LIST_SOURCES, DEFAULT_SERVER_LIST_SOURCES # noqa: E402
-from ed2k_pack.lists import countNodes, countServers # noqa: E402
+from ed2k_pack.lists import parseNodeList, parseServerList # noqa: E402
def fetch(url: str) -> bytes:
@@ -22,11 +22,11 @@ def fetch(url: str) -> bytes:
return response.read()
-def fetchFirstValid(urls: list[str], count) -> bytes:
+def fetchFirstValid(urls: list[str], parse) -> bytes:
for url in urls:
try:
data = fetch(url)
- print(f"{url}: {count(data)}")
+ print(f"{url}: {len(parse(data))}")
return data
except Exception as e:
print(f"{url}: {e}")
@@ -48,9 +48,9 @@ def main() -> None:
"\n".join(dict.fromkeys(trackers)) + "\n", "utf-8")
(REPO / "features/ed2k_pack/lists/server.met").write_bytes(
- fetchFirstValid(DEFAULT_SERVER_LIST_SOURCES, countServers))
+ fetchFirstValid(DEFAULT_SERVER_LIST_SOURCES, parseServerList))
(REPO / "features/ed2k_pack/lists/nodes.dat").write_bytes(
- fetchFirstValid(DEFAULT_NODE_LIST_SOURCES, countNodes))
+ fetchFirstValid(DEFAULT_NODE_LIST_SOURCES, parseNodeList))
if __name__ == "__main__":
diff --git a/tests/test_bootstrap_list.py b/tests/test_bootstrap_list.py
index 78f2a49d..5ad7e514 100644
--- a/tests/test_bootstrap_list.py
+++ b/tests/test_bootstrap_list.py
@@ -7,11 +7,11 @@ import pytest
from app.bootstrap_list import BootstrapList
-def countLines(data: bytes) -> int:
+def parseLines(data: bytes) -> list[str]:
lines = data.decode().split()
if not lines:
raise ValueError("empty list")
- return len(lines)
+ return lines
def makeList(tmp_path, sources: list[str], bodies: dict[str, bytes], fetched: list[str] | None = None):
@@ -26,7 +26,7 @@ def makeList(tmp_path, sources: list[str], bodies: dict[str, bytes], fetched: li
raise OSError("unreachable")
return bodies[url]
- return BootstrapList(tmp_path / "cache", snapshot, lambda: sources, countLines, fetch)
+ return BootstrapList(tmp_path / "cache", snapshot, lambda: sources, parseLines, fetch)
def test_snapshot_is_used_until_anything_is_cached(tmp_path):
@@ -105,3 +105,15 @@ async def test_failed_refresh_is_not_retried_until_the_next_day(tmp_path):
await bootstrapList.refresh()
assert not bootstrapList.isStale()
+
+
+async def test_entries_shared_by_subscriptions_are_counted_once(tmp_path):
+ bootstrapList = makeList(tmp_path, ["https://a", "https://b"], {
+ "https://a": b"udp://a:1\nudp://shared:1\nudp://shared:1\n",
+ "https://b": b"udp://b:1\nudp://shared:1\n",
+ })
+
+ await bootstrapList.refresh()
+
+ assert [s.count for s in bootstrapList.statuses()] == [2, 2]
+ assert bootstrapList.entryCount() == 3
diff --git a/tests/test_ed2k_task.py b/tests/test_ed2k_task.py
index 8963019e..b6590d40 100644
--- a/tests/test_ed2k_task.py
+++ b/tests/test_ed2k_task.py
@@ -7,6 +7,7 @@ import pytest
from app.models.pack import VersionInfo
from app.models.task import TaskError, TaskOptions, TaskStatus
from ed2k_pack import session as session_module
+from ed2k_pack.lists import parseNodeList, parseServerList
from ed2k_pack.pack import ED2kParser
from ed2k_pack.python_ed2k import Snapshot, Transfer, TransferState
from ed2k_pack.python_ed2k.errors import Error, ErrorCode
@@ -404,28 +405,55 @@ def u32(value: int) -> bytes:
return value.to_bytes(4, "little")
+def u16(value: int) -> bytes:
+ return value.to_bytes(2, "little")
+
+
+def buildContact(nodeId: int, size: int) -> bytes:
+ return nodeId.to_bytes(16, "little") + bytes(size - 16)
+
+
@pytest.mark.parametrize("data, count", [
- (u32(2) + bytes(2 * 25), 2),
- (u32(0) + u32(2) + u32(3) + bytes(3 * 34), 3),
- (u32(0) + u32(3) + u32(1) + u32(4) + bytes(4 * 25), 4),
+ (u32(2) + buildContact(1, 25) + buildContact(2, 25), 2),
+ (u32(0) + u32(2) + u32(3) + b"".join(buildContact(i, 34) for i in range(3)), 3),
+ (u32(0) + u32(3) + u32(1) + u32(4) + b"".join(buildContact(i, 25) for i in range(4)), 4),
+ (u32(0) + u32(3) + u32(0) + u32(2) + b"".join(buildContact(i, 34) for i in range(2)), 2),
])
-def test_count_nodes_reads_every_nodes_dat_version(data, count):
- from ed2k_pack.lists import countNodes
+def test_parse_node_list_reads_every_nodes_dat_version(data, count):
+ assert len(set(parseNodeList(data))) == count
- assert countNodes(data) == count
[email protected]("data", [b"", u32(5) + bytes(25), u32(0) + u32(2) + u32(0), u32(0) + u32(2) + u32(1) + bytes(25)])
+def test_parse_node_list_rejects_broken_files(data):
+ with pytest.raises(ValueError):
+ parseNodeList(data)
[email protected]("data", [b"", u32(5) + bytes(25), u32(0) + u32(2) + u32(0)])
-def test_count_nodes_rejects_broken_files(data):
- from ed2k_pack.lists import countNodes
- with pytest.raises(ValueError):
- countNodes(data)
+def buildServer(ip: bytes, port: int) -> bytes:
+ tags = [
+ b"\x02" + u16(1) + b"\x01" + u16(4) + b"name",
+ b"\x83\x0c" + u32(50),
+ b"\x03" + u16(5) + b"users" + u32(1000),
+ b"\x89\x0e\x01",
+ b"\x94\x0b" + b"desc",
+ b"\x87\x99" + u32(2) + b"..",
+ ]
+ return ip + u16(port) + u32(len(tags)) + b"".join(tags)
+
+def test_parse_server_list_reads_every_endpoint_past_the_tags():
+ servers = [buildServer(b"\x01\x02\x03\x04", 4661), buildServer(b"\x05\x06\x07\x08", 4242)]
+ data = b"\x0e" + u32(2) + b"".join(servers)
-def test_count_servers_reads_the_header():
- from ed2k_pack.lists import countServers
+ assert parseServerList(data) == [b"\x01\x02\x03\x04" + u16(4661), b"\x05\x06\x07\x08" + u16(4242)]
- assert countServers(b"\xe0" + u32(13)) == 13
+
+ b"<html>",
+ b"\xe0" + u32(0),
+ b"\xe0" + u32(2) + buildServer(b"\x01\x02\x03\x04", 4661),
+ b"\xe0" + u32(1) + buildServer(b"\x01\x02\x03\x04", 4661)[:-1],
+])
+def test_parse_server_list_rejects_broken_files(data):
with pytest.raises(ValueError):
- countServers(b"<html>")
+ parseServerList(data)