Skip to content

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

feat(packs): Tracker 列表和 eD2k 节点列表改由应用拉取

XiaoYouChRa50fa8a22861
diff --git a/CONTEXT.md b/CONTEXT.md
index d9bd1a8c..755bb924 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -89,6 +89,11 @@ _Avoid_: execution、session
用户可随时开关;到达上限或用户关掉后不再自动恢复,否则随应用启动恢复。
_Avoid_: 与 Seed(Pack 同步)混淆;sharing;第六个 Task 状态
+**Bootstrap List**:
+Pack 从订阅地址拉取、用来发现对等方的列表:BT 的 Tracker 列表,eD2k 的服务器列表和 KAD 节点列表。
+由应用拉取并缓存,Pack 自带内置快照,任何时候都有一份可用;刷新只在后台进行,Task 从不等它。
+_Avoid_: Source(指更新分发)、节点源、mirror
+
**Task Step**:
Task 内的一个可执行步骤。一个 Task 可能有一个或多个 Step。
_Avoid_: stage、phase、action
diff --git a/app/bootstrap_list.py b/app/bootstrap_list.py
new file mode 100644
index 00000000..e8d68062
--- /dev/null
+++ b/app/bootstrap_list.py
@@ -0,0 +1,107 @@
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import time
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass
+from pathlib import Path
+
+MAX_AGE = 86400
+
+
+@dataclass(frozen=True)
+class SubscriptionStatus:
+ url: str
+ count: int | None
+ updatedAt: float | None
+ error: str = ""
+
+
+async def fetchBytes(url: str) -> bytes:
+ from app.client import buildClient
+
+ client = buildClient(readTimeout=30)
+ try:
+ response = await client.get(url)
+ response.raise_for_status()
+ return await response.bytes()
+ finally:
+ client.close()
+
+
+class BootstrapList:
+ def __init__(
+ self,
+ folder: Path,
+ snapshot: Path,
+ sources: Callable[[], list[str]],
+ count: Callable[[bytes], int],
+ fetch: Callable[[str], Awaitable[bytes]] = fetchBytes,
+ ):
+ self._folder = folder
+ self._snapshot = snapshot
+ self._sources = sources
+ self._count = count
+ self._fetch = fetch
+ self._errors: dict[str, str] = {}
+ self._refreshing: asyncio.Task | None = None
+ self._lastRefreshAt = 0.0
+
+ @property
+ def isRefreshing(self) -> bool:
+ return self._refreshing is not None
+
+ def paths(self) -> list[Path]:
+ cached = [path for url in self._sources() if (path := self._cachePath(url)).is_file()]
+ return cached or [self._snapshot]
+
+ def isStale(self) -> bool:
+ now = time.time()
+ if now - self._lastRefreshAt < MAX_AGE:
+ return False
+ return any(
+ not path.is_file() or now - path.stat().st_mtime > MAX_AGE
+ for path in map(self._cachePath, self._sources())
+ )
+
+ def statuses(self) -> list[SubscriptionStatus]:
+ statuses = []
+ for url in self._sources():
+ path = self._cachePath(url)
+ isCached = path.is_file()
+ statuses.append(SubscriptionStatus(
+ url,
+ self._count(path.read_bytes()) if isCached else None,
+ path.stat().st_mtime if isCached else None,
+ self._errors.get(url, ""),
+ ))
+ return statuses
+
+ async def refresh(self) -> None:
+ if self._refreshing is None:
+ self._refreshing = asyncio.ensure_future(self._fetchAll())
+ await asyncio.shield(self._refreshing)
+
+ async def _fetchAll(self) -> None:
+ try:
+ self._lastRefreshAt = time.time()
+ await asyncio.gather(*map(self._fetchOne, self._sources()))
+ finally:
+ self._refreshing = None
+
+ async def _fetchOne(self, url: str) -> None:
+ try:
+ data = await self._fetch(url)
+ self._count(data)
+ path = self._cachePath(url)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ partPath = path.with_suffix(".part")
+ partPath.write_bytes(data)
+ partPath.replace(path)
+ self._errors.pop(url, None)
+ except Exception as e:
+ self._errors[url] = str(e) or type(e).__name__
+
+ def _cachePath(self, url: str) -> Path:
+ return self._folder / hashlib.sha1(url.encode()).hexdigest()[:16]
diff --git a/app/view/components/bootstrap_list.py b/app/view/components/bootstrap_list.py
new file mode 100644
index 00000000..c4b989da
--- /dev/null
+++ b/app/view/components/bootstrap_list.py
@@ -0,0 +1,266 @@
+from __future__ import annotations
+
+import time
+from collections.abc import Awaitable, Callable
+from urllib.parse import urlsplit
+
+from PySide6.QtCore import QCoreApplication
+from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget
+from qfluentwidgets import (
+ BodyLabel,
+ FluentIcon,
+ InfoBar,
+ LineEdit,
+ MessageBoxBase,
+ PrimaryPushButton,
+ PushButton,
+ SettingCard,
+ SubtitleLabel,
+ ToolButton,
+ ToolTipFilter,
+ TransparentToolButton,
+)
+
+from app.bootstrap_list import BootstrapList, SubscriptionStatus
+from app.config.cfg import ConfigItem, cfg
+from app.view.components.editors import AutoSizingEdit
+
+FAILURE_NOTICE_AGE = 7 * 86400
+
+
+def tr(text: str) -> str:
+ return QCoreApplication.translate("BootstrapList", text)
+
+
+def toAgoText(seconds: float) -> str:
+ if seconds < 60:
+ return tr("刚刚")
+ if seconds < 3600:
+ return tr("{0} 分钟前").format(int(seconds // 60))
+ if seconds < 86400:
+ return tr("{0} 小时前").format(int(seconds // 3600))
+ return tr("{0} 天前").format(int(seconds // 86400))
+
+
+def toStatusText(status: SubscriptionStatus | None) -> str:
+ if status is None or status.count is None:
+ return tr("更新失败") if status is not None and status.error else tr("未拉取")
+ parts = [tr("{0} 条").format(status.count), tr("{0}更新").format(toAgoText(time.time() - status.updatedAt))]
+ if status.error:
+ parts.append(tr("更新失败"))
+ return tr(",").join(parts)
+
+
+def isSubscriptionUrl(url: str) -> bool:
+ parts = urlsplit(url)
+ return parts.scheme in {"http", "https"} and bool(parts.netloc)
+
+
+class BootstrapListCard(SettingCard):
+ def __init__(
+ self,
+ icon: FluentIcon,
+ title: str,
+ bootstrapList: BootstrapList,
+ sourcesItem: ConfigItem,
+ submit: Callable[..., str],
+ parent=None,
+ *,
+ customItem: ConfigItem | None = None,
+ probeNetworkText: Callable[[], Awaitable[str]] | None = None,
+ ):
+ super().__init__(icon, title, "", parent)
+ self._list = bootstrapList
+ self._sourcesItem = sourcesItem
+ self._customItem = customItem
+ self._submit = submit
+ self._probeNetworkText = probeNetworkText
+ self._networkText = ""
+ self.manageButton = PrimaryPushButton(self.tr("管理"), self)
+ self.refreshButton = ToolButton(FluentIcon.SYNC, self)
+
+ self._initWidget()
+ self._initLayout()
+ self._bind()
+
+ def _initWidget(self):
+ self.refreshButton.setToolTip(self.tr("立即更新"))
+ self.refreshButton.installEventFilter(ToolTipFilter(self.refreshButton))
+ if self._list.isRefreshing:
+ self._startRefresh()
+ else:
+ self._refreshContent()
+ self._probeNetwork()
+
+ def _initLayout(self):
+ self.hBoxLayout.addWidget(self.manageButton, 0)
+ self.hBoxLayout.addSpacing(8)
+ self.hBoxLayout.addWidget(self.refreshButton, 0)
+ self.hBoxLayout.addSpacing(16)
+
+ def _bind(self):
+ self.manageButton.clicked.connect(self._onManageClicked)
+ self.refreshButton.clicked.connect(self._startRefresh)
+
+ def _refreshContent(self):
+ if self._list.isRefreshing:
+ self.setContent(self.tr("正在更新…"))
+ return
+ statuses = self._list.statuses()
+ cached = [s for s in statuses if s.count is not None]
+ 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(toAgoText(time.time() - newest)))
+ if any(s.error for s in statuses) and time.time() - newest > FAILURE_NOTICE_AGE:
+ parts.append(self.tr("更新失败"))
+ else:
+ parts.append(self.tr("使用内置列表"))
+ if any(s.error for s in statuses):
+ parts.append(self.tr("更新失败"))
+ if self._networkText:
+ parts.append(self._networkText)
+ self.setContent(self.tr(",").join(parts))
+
+ def _probeNetwork(self):
+ if self._probeNetworkText is not None:
+ self._submit(self._probeNetworkText(), done=self._onNetworkProbed, owner=self)
+
+ def _onNetworkProbed(self, text: str):
+ self._networkText = text
+ self._refreshContent()
+
+ def _startRefresh(self):
+ self.refreshButton.setEnabled(False)
+ self._submit(self._list.refresh(), done=self._onRefreshed, failed=self._onRefreshed, owner=self)
+ self._refreshContent()
+
+ def _onRefreshed(self, _result=None):
+ self.refreshButton.setEnabled(True)
+ self._refreshContent()
+ self._probeNetwork()
+
+ def _onManageClicked(self):
+ dialog = BootstrapListDialog(self._list, self._sourcesItem, self._customItem, self.window())
+ try:
+ if dialog.exec():
+ self._startRefresh()
+ finally:
+ dialog.deleteLater()
+
+
+class SubscriptionRow(QWidget):
+ def __init__(self, url: str, statusText: str, onRemoved: Callable[[SubscriptionRow], None], parent=None):
+ super().__init__(parent)
+ self.urlEdit = LineEdit(self)
+ self.statusLabel = BodyLabel(statusText, self)
+ self.deleteButton = TransparentToolButton(FluentIcon.CLOSE, self)
+ self.hBoxLayout = QHBoxLayout(self)
+ self._onRemoved = onRemoved
+
+ self._initWidget(url)
+ self._initLayout()
+ self._bind()
+
+ @property
+ def url(self) -> str:
+ return self.urlEdit.text().strip()
+
+ def _initWidget(self, url: str):
+ self.urlEdit.setText(url)
+ self.urlEdit.setPlaceholderText("https://")
+
+ def _initLayout(self):
+ self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
+ self.hBoxLayout.setSpacing(8)
+ self.hBoxLayout.addWidget(self.urlEdit, 1)
+ self.hBoxLayout.addWidget(self.statusLabel)
+ self.hBoxLayout.addWidget(self.deleteButton)
+
+ def _bind(self):
+ self.deleteButton.clicked.connect(lambda: self._onRemoved(self))
+
+
+class BootstrapListDialog(MessageBoxBase):
+ def __init__(self, bootstrapList: BootstrapList, sourcesItem: ConfigItem,
+ customItem: ConfigItem | None, parent=None):
+ super().__init__(parent)
+ self._sourcesItem = sourcesItem
+ self._customItem = customItem
+ self._statuses = {s.url: s for s in bootstrapList.statuses()}
+ self._rows: list[SubscriptionRow] = []
+ self.sourceHeaderLabel = SubtitleLabel(self.tr("订阅地址"), self.widget)
+ self.restoreButton = PushButton(self.tr("恢复默认"), self.widget)
+ self.addButton = PrimaryPushButton(FluentIcon.ADD, self.tr("添加"), self.widget)
+ self.rowContainer = QWidget(self.widget)
+ self.customLabel = SubtitleLabel(self.tr("自定义条目"), self.widget)
+ self.customEdit = AutoSizingEdit(self.widget)
+ self.sourceHeaderLayout = QHBoxLayout()
+ self.rowLayout = QVBoxLayout(self.rowContainer)
+
+ self._initWidget()
+ self._initLayout()
+ self._bind()
+
+ def _initWidget(self):
+ self.widget.setMinimumWidth(720)
+ self.yesButton.setText(self.tr("保存并更新"))
+ self.cancelButton.setText(self.tr("取消"))
+ for url in self._sourcesItem.value:
+ self._addRow(url)
+ self.customLabel.setVisible(self._customItem is not None)
+ self.customEdit.setVisible(self._customItem is not None)
+ if self._customItem is not None:
+ self.customEdit.setPlaceholderText(self.tr("每行一个,不会被订阅更新覆盖"))
+ self.customEdit.setPlainText(self._customItem.value)
+
+ def _initLayout(self):
+ self.sourceHeaderLayout.setContentsMargins(0, 0, 0, 0)
+ self.sourceHeaderLayout.addWidget(self.sourceHeaderLabel)
+ self.sourceHeaderLayout.addStretch(1)
+ self.sourceHeaderLayout.addWidget(self.restoreButton)
+ self.sourceHeaderLayout.addWidget(self.addButton)
+
+ self.rowLayout.setContentsMargins(0, 0, 0, 0)
+ self.rowLayout.setSpacing(8)
+
+ self.viewLayout.addLayout(self.sourceHeaderLayout)
+ self.viewLayout.addWidget(self.rowContainer)
+ self.viewLayout.addSpacing(8)
+ self.viewLayout.addWidget(self.customLabel)
+ self.viewLayout.addWidget(self.customEdit)
+
+ def _bind(self):
+ self.addButton.clicked.connect(lambda: self._addRow(""))
+ self.restoreButton.clicked.connect(self._onRestoreClicked)
+
+ def validate(self) -> bool:
+ for row in self._rows:
+ if not isSubscriptionUrl(row.url):
+ InfoBar.error(self.tr("订阅地址无效"), self.tr("请输入有效的 HTTP/HTTPS 地址"), parent=self)
+ row.urlEdit.setFocus()
+ return False
+ cfg.set(self._sourcesItem, list(dict.fromkeys(row.url for row in self._rows)))
+ if self._customItem is not None:
+ lines = (line.strip() for line in self.customEdit.toPlainText().splitlines())
+ cfg.set(self._customItem, "\n".join(line for line in lines if line))
+ 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)
+ self.rowLayout.addWidget(row)
+ self._rows.append(row)
+
+ def _onRowRemoved(self, row: SubscriptionRow):
+ self._rows.remove(row)
+ self.rowLayout.removeWidget(row)
+ row.deleteLater()
+
+ def _onRestoreClicked(self):
+ for row in list(self._rows):
+ self._onRowRemoved(row)
+ for url in self._sourcesItem.defaultValue:
+ self._addRow(url)
diff --git a/docs/adr/0016-app-fetches-bootstrap-lists.md b/docs/adr/0016-app-fetches-bootstrap-lists.md
new file mode 100644
index 00000000..6081b6ad
--- /dev/null
+++ b/docs/adr/0016-app-fetches-bootstrap-lists.md
@@ -0,0 +1,20 @@
+# Bootstrap List 由应用拉取,Pack 自带快照
+
+BT 的 Tracker 列表和 eD2k 的 `server.met`、`nodes.dat` 都由应用经全局代理拉取,按订阅地址缓存为磁盘文件,
+引擎只加载本地文件。每个 Pack 自带一份内置快照,没有缓存时使用。刷新在 Pack 激活后于后台进行,过期时间一天,
+新建 Task 和启动引擎都只用当前已有的列表,从不等待拉取。
+
+## Considered Options
+
+- **交给 goed2kd 在启动时自己下载**(本 ADR 前 eD2k 的做法):不走代理、没有缓存,下载失败或一个服务器都连不上就让
+ goed2kd 启动失败,所有 eD2k Task 随之报错;界面也拿不到任何状态。
+- **首次使用时等第一次拉取完成**:离线、首次启动、所有订阅都失败时仍然没有列表可用,且新建 Task 被网络拖慢。
+- **缓存存进配置文件**(本 ADR 前 BT 的做法):配置文件变成数据仓库,二进制文件要 base64,更新时间和条数要另存,
+ 容易与内容不一致。
+
+## Consequences
+
+- 更新时间取缓存文件的修改时间,条数在加载时计算;失败原因只在本次运行中保留,不弹 Notice。
+- 内置快照需要在发版前用脚本更新。
+- DHT 引导节点不是 Bootstrap List,保持为代码常量。
+- 应用交给 goed2kd 多个本地 `server.met` 路径,需要 goed2kd 0.3.0 及以上;`ED2kRuntime` 在启动前按版本检查。
diff --git a/features/bittorrent_pack/android.py b/features/bittorrent_pack/android.py
index 964c6e79..6b3621c6 100644
--- a/features/bittorrent_pack/android.py
+++ b/features/bittorrent_pack/android.py
@@ -35,15 +35,32 @@ def taskFields(task) -> dict:
}
-def setWebTrackerSources(sources: str):
+async def trackerListState() -> dict:
+ from dataclasses import asdict
+ from .config import bittorrentConfig
+ from .session import btSession
+ from .trackers import trackerList
+
+ return {
+ "sources": list(bittorrentConfig.webTrackerSources.value),
+ "defaults": list(bittorrentConfig.webTrackerSources.defaultValue),
+ "custom": bittorrentConfig.webTrackerCustomList.value,
+ "statuses": [asdict(status) for status in trackerList.statuses()],
+ "isRefreshing": trackerList.isRefreshing,
+ "dhtNodes": await btSession.probeDhtNodes(),
+ }
+
+
+def setTrackerList(sources: str, custom: str):
from app.config.cfg import cfg
from .config import bittorrentConfig
- urls = list(dict.fromkeys(u.strip() for u in sources.split("\n") if u.strip()))
- cfg.set(bittorrentConfig.webTrackerSources, urls)
+ cfg.set(bittorrentConfig.webTrackerSources, list(dict.fromkeys(sources.split())))
+ cfg.set(bittorrentConfig.webTrackerCustomList, custom)
-async def refreshWebTrackers():
- from .web_tracker.service import trackerService
+async def refreshTrackerList() -> dict:
+ from .trackers import trackerList
- await trackerService.refresh()
+ await trackerList.refresh()
+ return await trackerListState()
diff --git a/features/bittorrent_pack/config.py b/features/bittorrent_pack/config.py
index 4808ccdd..4a312172 100644
--- a/features/bittorrent_pack/config.py
+++ b/features/bittorrent_pack/config.py
@@ -10,11 +10,12 @@ from app.config.cfg import (
)
from app.models.pack import PackConfig
-from .web_tracker.schema import (
- DEFAULT_WEB_TRACKER_SOURCES,
- SourceCacheSerializer,
- SourceCacheValidator,
-)
+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 StringListValidator:
@@ -46,10 +47,7 @@ class BitTorrentConfig(PackConfig):
associateFileTypes = ConfigItem("BitTorrent", "AssociateFileTypes", False, BoolValidator())
associateUriSchemes = ConfigItem("BitTorrent", "AssociateUriSchemes", False, BoolValidator())
webTrackerSources = ConfigItem(
- "BitTorrent", "WebTrackerSources", DEFAULT_WEB_TRACKER_SOURCES, StringListValidator(),
- )
- webTrackerSourceCache = ConfigItem(
- "BitTorrent", "WebTrackerSourceCache", {}, SourceCacheValidator(), SourceCacheSerializer(),
+ "BitTorrent", "WebTrackerSources", DEFAULT_TRACKER_LIST_SOURCES, StringListValidator(),
)
webTrackerCustomList = ConfigItem("BitTorrent", "WebTrackerCustomList", "")
@@ -58,7 +56,8 @@ class BitTorrentConfig(PackConfig):
from qfluentwidgets import ComboBoxSettingCard, FluentIcon, RangeSettingCard, SwitchSettingCard
from app.view.components.setting_card_group import CollapsibleSettingCardGroup
from app.view.components.setting_cards import SpinBoxSettingCard
- from .web_tracker.card import WebTrackerCard
+ from app.view.components.bootstrap_list import BootstrapListCard
+ from .trackers import trackerList
btGroup = CollapsibleSettingCardGroup(self.tr("BitTorrent 下载"), "bittorrent", parent)
@@ -90,16 +89,23 @@ class BitTorrentConfig(PackConfig):
self.tr("允许通过 DHT 网络发现 peers"), self.enableDht, btGroup),
SwitchSettingCard(FluentIcon.HOME, self.tr("启用 LSD"),
self.tr("在局域网中广播并发现同一 torrent 的 peers"), self.enableLsd, btGroup),
- SwitchSettingCard(FluentIcon.LINK, self.tr("启用 Web Tracker"),
- self.tr("把配置好的额外 Trackers 合并到新建 BT 任务中"),
+ SwitchSettingCard(FluentIcon.LINK, self.tr("附加 Tracker 列表"),
+ self.tr("把 Tracker 列表合并到新建的 BT 任务中"),
self.enableWebTrackers, btGroup),
- SwitchSettingCard(FluentIcon.SYNC, self.tr("新建任务时刷新 Web Tracker"),
- self.tr("创建新的 BT 任务时先从源地址拉取最新 Tracker"),
+ SwitchSettingCard(FluentIcon.SYNC, self.tr("自动更新订阅"),
+ self.tr("每天在后台更新一次 Tracker 列表"),
self.autoRefreshWebTrackers, btGroup),
- WebTrackerCard(self.submit, btGroup),
+ BootstrapListCard(FluentIcon.GLOBE, self.tr("Tracker 列表"), trackerList,
+ self.webTrackerSources, self.submit, btGroup,
+ customItem=self.webTrackerCustomList, probeNetworkText=self._probeDhtText),
]
btGroup.addSettingCards(cards)
return [btGroup]
+ async def _probeDhtText(self) -> str:
+ from .session import btSession
+ nodes = await btSession.probeDhtNodes()
+ return "" if nodes is None else self.tr("DHT 节点 {0}").format(nodes)
+
bittorrentConfig = BitTorrentConfig()
diff --git a/features/bittorrent_pack/lists/trackers.txt b/features/bittorrent_pack/lists/trackers.txt
new file mode 100644
index 00000000..c5909f9b
--- /dev/null
+++ b/features/bittorrent_pack/lists/trackers.txt
@@ -0,0 +1,78 @@
+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
+http://tracker.dler.com:6969/announce
+http://tracker.mywaifu.best:6969/announce
+http://tracker.renfei.net:8080/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
+https://tr.abiir.top:443/announce
+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.nekomi.cn:443/announce
+https://tracker.pmman.tech:443/announce
+https://tracker.qingwapt.org:443/announce
+https://tracker1.520.jp:443/announce
+udp://anime-tracker.aruku.kro.kr:8081/announce
+udp://bittorrent-tracker.e-n-c-r-y-p-t.net:1337/announce
+udp://evan.im:6969/announce
+udp://explodie.org:6969/announce
+udp://ipv6.govt.hu:6969/announce
+udp://mail.segso.net:6969/announce
+udp://martin-gebhardt.eu:25/announce
+udp://open.demonii.com:1337/announce
+udp://open.ftorrent.com:443/announce
+udp://open.stealth.si:80/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://t.overflow.biz:6969/announce
+udp://torrent.tracker.durukanbal.com:6969/announce
+udp://tr4ck3r.duckdns.org:6969/announce
+udp://tracker-udp.gbitt.info:80/announce
+udp://tracker.aruku.ovh:8081/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.farted.net:6969/announce
+udp://tracker.gmi.gd:6969/announce
+udp://tracker.ilibr.org:6969/announce
+udp://tracker.k.vu:6969/announce
+udp://tracker.nyaa.net:6969/announce
+udp://tracker.nyaa.vc:6969/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.teambelgium.net:6969/announce
+udp://tracker.theoks.net:6969/announce
+udp://tracker.torrent.eu.org:451/announce
+udp://tracker.torrents.observer:80/announce
+udp://tracker.tryhackx.org:6969/announce
+udp://tracker.willy.pro:6969/announce
+udp://tracker2.dler.org:80/announce
+wss://tracker.openwebtorrent.com:443/announce
+http://tracker.dler.org:6969/announce
+udp://exodus.desync.com:6969/announce
+http://wegkxfcivgx.ydns.eu:80/announce
+http://tracker.ipv6tracker.ru:80/announce
+http://echostar.ddnsfree.com:8080/announce
+udp://v6.vito-tracker.space:6969/announce
diff --git a/features/bittorrent_pack/pack.py b/features/bittorrent_pack/pack.py
index 1719eab4..729a6285 100644
--- a/features/bittorrent_pack/pack.py
+++ b/features/bittorrent_pack/pack.py
@@ -6,7 +6,6 @@ from pathlib import Path, PurePosixPath
from urllib.parse import urlparse
import libtorrent as lt
-from loguru import logger
from app.i18n import N
@@ -17,7 +16,12 @@ from app.platform.filesystem import localFilePath, toSafeFilename
from .config import bittorrentConfig
from .session import btSession
from .task import BTFile, BTTask, BTTaskStep, BTTorrentFileStep
-from .web_tracker.service import trackerService
+from .trackers import mergedTrackers, trackerList
+
+
+def refreshTrackerListIfStale() -> None:
+ if bittorrentConfig.autoRefreshWebTrackers.value and trackerList.isStale():
+ asyncio.ensure_future(trackerList.refresh())
class TorrentParser(TaskParser):
@@ -33,15 +37,8 @@ class TorrentParser(TaskParser):
url = options.url.strip()
outputFolder = options.outputFolder
- if bittorrentConfig.enableWebTrackers.value:
- if bittorrentConfig.autoRefreshWebTrackers.value and trackerService.isStale():
- try:
- await trackerService.refresh()
- except Exception as e:
- logger.opt(exception=e).warning("刷新 Web Tracker 失败,使用缓存")
- webTrackers = trackerService.mergedTrackers()
- else:
- webTrackers = []
+ refreshTrackerListIfStale()
+ webTrackers = mergedTrackers() if bittorrentConfig.enableWebTrackers.value else []
localPath = localFilePath(url, {".torrent"})
if localPath is not None:
@@ -135,6 +132,7 @@ class BitTorrentPack(FeaturePack):
async def activate(self):
btSession.open()
+ refreshTrackerListIfStale()
async def deactivate(self):
await btSession.close()
diff --git a/features/bittorrent_pack/session.py b/features/bittorrent_pack/session.py
index cc34d535..6f017735 100644
--- a/features/bittorrent_pack/session.py
+++ b/features/bittorrent_pack/session.py
@@ -21,8 +21,8 @@ if TYPE_CHECKING:
pass
DHT_BOOTSTRAP_NODES = (
- "router.bittorrent.com:6881, router.utorrent.com:6881, "
- "dht.transmissionbt.com:6881, dht.libtorrent.org:25401"
+ "dht.transmissionbt.com:6881, router.bt.ouinet.work:6881, dht.libtorrent.org:25401, "
+ "router.bittorrent.com:6881, router.utorrent.com:6881"
)
ALERT_MASK = (
@@ -122,6 +122,7 @@ class BTSession:
self._active: dict[str, ActiveTorrent] = {}
self._metadataWaiters: dict[int, tuple[lt.torrent_handle, asyncio.Future]] = {}
self._resumeCache: dict[str, bytes] = {}
+ self._statsWaiter: asyncio.Future | None = None
for item in (
bittorrentConfig.maxUploadSpeed,
bittorrentConfig.maxConnections,
@@ -224,6 +225,17 @@ class BTSession:
except Exception:
pass
+ async def probeDhtNodes(self) -> int | None:
+ if self._session is None or not self._session.is_dht_running():
+ return None
+ if self._statsWaiter is None or self._statsWaiter.done():
+ self._statsWaiter = asyncio.get_running_loop().create_future()
+ self._session.post_session_stats()
+ try:
+ return await asyncio.wait_for(asyncio.shield(self._statsWaiter), timeout=5)
+ except TimeoutError:
+ return None
+
def updatePriorities(self, taskId: str, priorities: list[int]) -> None:
entry = self._active.get(taskId)
if entry is None:
@@ -422,6 +434,11 @@ class BTSession:
await asyncio.sleep(1)
def _routeAlert(self, alert) -> None:
+ if isinstance(alert, lt.session_stats_alert):
+ if self._statsWaiter is not None and not self._statsWaiter.done():
+ self._statsWaiter.set_result(alert.values["dht.dht_nodes"])
+ return
+
if isinstance(alert, lt.performance_alert):
logger.warning("BitTorrent 性能警告: {}", alert.message())
return
diff --git a/features/bittorrent_pack/trackers.py b/features/bittorrent_pack/trackers.py
new file mode 100644
index 00000000..87886892
--- /dev/null
+++ b/features/bittorrent_pack/trackers.py
@@ -0,0 +1,39 @@
+from __future__ import annotations
+
+from pathlib import Path
+from urllib.parse import urlsplit
+
+from app.bootstrap_list import BootstrapList
+from app.config.paths import APP_DATA_DIR
+
+from .config import bittorrentConfig
+
+TRACKER_SCHEMES = {"http", "https", "udp", "ws", "wss"}
+
+
+def parseTrackers(text: str) -> list[str]:
+ return [
+ tracker for tracker in text.split()
+ if (parts := urlsplit(tracker)).scheme.lower() in TRACKER_SCHEMES and parts.netloc
+ ]
+
+
+def countTrackers(data: bytes) -> int:
+ count = len(parseTrackers(data.decode("utf-8", errors="ignore")))
+ if count == 0:
+ raise ValueError("没有有效的 Tracker")
+ return count
+
+
+trackerList = BootstrapList(
+ APP_DATA_DIR / "bt" / "trackers",
+ Path(__file__).parent / "lists" / "trackers.txt",
+ lambda: list(bittorrentConfig.webTrackerSources.value),
+ countTrackers,
+)
+
+
+def mergedTrackers() -> list[str]:
+ texts = [path.read_text("utf-8", errors="ignore") for path in trackerList.paths()]
+ texts.append(bittorrentConfig.webTrackerCustomList.value)
+ return list(dict.fromkeys(tracker for text in texts for tracker in parseTrackers(text)))
diff --git a/features/bittorrent_pack/web_tracker/card.py b/features/bittorrent_pack/web_tracker/card.py
deleted file mode 100644
index 271af0b4..00000000
--- a/features/bittorrent_pack/web_tracker/card.py
+++ /dev/null
@@ -1,93 +0,0 @@
-from qfluentwidgets import (
- FluentIcon,
- PrimaryPushButton,
- SettingCard,
- StateToolTip,
- ToolButton,
- ToolTipFilter,
-)
-
-from ..config import bittorrentConfig
-from .service import trackerService
-
-
-class WebTrackerCard(SettingCard):
- def __init__(self, submit, parent=None):
- super().__init__(FluentIcon.GLOBE, self.tr("Web Tracker"), "", parent)
- self._submit = submit
- self.manageButton = PrimaryPushButton(self.tr("管理"), self)
- self.refreshButton = ToolButton(FluentIcon.SYNC, self)
- self._stateToolTip: StateToolTip | None = None
-
- self._initWidget()
- self._initLayout()
- self._bind()
-
- def _initWidget(self):
- self.refreshButton.setToolTip(self.tr("刷新缓存"))
- self.refreshButton.installEventFilter(ToolTipFilter(self.refreshButton))
- self.refreshContent()
-
- def _initLayout(self):
- self.hBoxLayout.addWidget(self.manageButton, 0)
- self.hBoxLayout.addSpacing(8)
- self.hBoxLayout.addWidget(self.refreshButton, 0)
- self.hBoxLayout.addSpacing(16)
-
- def _bind(self):
- self.manageButton.clicked.connect(self._onManageClicked)
- self.refreshButton.clicked.connect(self._onRefreshClicked)
-
- def refreshContent(self):
- sourceCount = len(list(bittorrentConfig.webTrackerSources.value))
- cachedTotal = len(trackerService.mergedTrackers())
- self.setContent(self.tr("{0} 个源 · 共 {1} 条缓存").format(sourceCount, cachedTotal))
-
- def _onManageClicked(self):
- from .dialog import WebTrackerDialog
- dialog = WebTrackerDialog(self.window())
- try:
- if dialog.exec():
- self._onRefreshClicked()
- finally:
- dialog.deleteLater()
-
- def _onRefreshClicked(self):
- urls = list(bittorrentConfig.webTrackerSources.value)
- if not urls:
- return
- self.refreshButton.setEnabled(False)
- self._stateToolTip = StateToolTip(
- self.tr("正在刷新 Web Tracker"),
- self.tr("正在拉取 {0} 个源...").format(len(urls)),
- self.window(),
- )
- self._stateToolTip.move(self._stateToolTip.getSuitablePos())
- self._stateToolTip.show()
-
- self._submit(
- trackerService.refresh(),
- done=self._onRefreshDone, failed=self._onRefreshFailed,
- owner=self,
- )
-
- def _onRefreshDone(self, result):
- self.refreshButton.setEnabled(True)
- if self._stateToolTip is None:
- return
- success, total = result
- cachedTotal = len(trackerService.mergedTrackers())
- self._stateToolTip.setContent(
- self.tr("已刷新 {0}/{1} 个源,共 {2} 条 Tracker").format(success, total, cachedTotal)
- )
- self._stateToolTip.setState(True)
- self._stateToolTip = None
- self.refreshContent()
-
- def _onRefreshFailed(self, error):
- self.refreshButton.setEnabled(True)
- if self._stateToolTip is None:
- return
- self._stateToolTip.setContent(self.tr("刷新失败: {0}").format(str(error)))
- self._stateToolTip.setState(True)
- self._stateToolTip = None
diff --git a/features/bittorrent_pack/web_tracker/dialog.py b/features/bittorrent_pack/web_tracker/dialog.py
deleted file mode 100644
index 10bf050d..00000000
--- a/features/bittorrent_pack/web_tracker/dialog.py
+++ /dev/null
@@ -1,154 +0,0 @@
-from urllib.parse import urlsplit
-
-from PySide6.QtCore import Signal
-from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget
-from qfluentwidgets import (
- BodyLabel,
- FluentIcon,
- InfoBar,
- LineEdit,
- MessageBoxBase,
- PrimaryPushButton,
- SubtitleLabel,
- TransparentToolButton,
-)
-
-from app.config.cfg import cfg
-from app.view.components.editors import AutoSizingEdit
-from ..config import bittorrentConfig
-from .schema import DEFAULT_WEB_TRACKER_SOURCES
-
-
-TRACKER_SCHEMES = {"http", "https", "udp", "ws", "wss"}
-
-
-class WebTrackerSourceCard(QWidget):
- removed = Signal(object)
-
- def __init__(self, url: str = "", cachedCount: int | None = None, parent=None):
- super().__init__(parent)
- self.urlEdit = LineEdit(self)
- self.statusLabel = BodyLabel(self)
- self.deleteButton = TransparentToolButton(FluentIcon.CLOSE, self)
- self.hBoxLayout = QHBoxLayout(self)
-
- self._initWidget(url, cachedCount)
- self._initLayout()
- self._bind()
-
- @property
- def url(self) -> str:
- value = self.urlEdit.text().strip()
- if not value:
- return ""
- parsed = urlsplit(value)
- if parsed.scheme not in {"http", "https"} or not parsed.netloc:
- return ""
- return value
-
- def setCachedCount(self, count: int | None):
- if count is None:
- self.statusLabel.setText(self.tr("未拉取"))
- else:
- self.statusLabel.setText(self.tr("{0} 条").format(count))
-
- def _initWidget(self, url: str, cachedCount: int | None):
- self.urlEdit.setText(url)
- self.urlEdit.setPlaceholderText(DEFAULT_WEB_TRACKER_SOURCES[0])
- self.setCachedCount(cachedCount)
-
- def _initLayout(self):
- self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
- self.hBoxLayout.setSpacing(8)
- self.hBoxLayout.addWidget(self.urlEdit, 1)
- self.hBoxLayout.addWidget(self.statusLabel)
- self.hBoxLayout.addWidget(self.deleteButton)
-
- def _bind(self):
- self.deleteButton.clicked.connect(lambda: self.removed.emit(self))
-
-
-class WebTrackerDialog(MessageBoxBase):
- def __init__(self, parent=None):
- super().__init__(parent)
- self.sourceHeaderLabel = SubtitleLabel(self.tr("Tracker 源"), self.widget)
- self.addSourceButton = PrimaryPushButton(FluentIcon.ADD, self.tr("添加"), self.widget)
- self.sourceContainer = QWidget(self.widget)
- self.customLabel = SubtitleLabel(self.tr("自定义 Tracker"), self.widget)
- self.customEdit = AutoSizingEdit(self.widget)
- self.sourceHeaderLayout = QHBoxLayout()
- self.sourceLayout = QVBoxLayout(self.sourceContainer)
- self._sourceCards: list[WebTrackerSourceCard] = []
-
- self._initWidget()
- self._initLayout()
- self._bind()
-
- def _initWidget(self):
- self.widget.setMinimumWidth(720)
- self.yesButton.setText(self.tr("保存并刷新"))
- self.cancelButton.setText(self.tr("取消"))
- customText = bittorrentConfig.webTrackerCustomList.value
- customTrackers = [
- t for t in customText.split()
- if urlsplit(t).scheme.lower() in TRACKER_SCHEMES and urlsplit(t).netloc
- ]
- self.customEdit.setPlaceholderText(self.tr("每行一个 tracker URL,不会被源刷新覆盖"))
- self.customEdit.setPlainText("\n".join(customTrackers))
- for url in list(bittorrentConfig.webTrackerSources.value):
- self._addSourceCard(url)
-
- def _initLayout(self):
- self.sourceHeaderLayout.setContentsMargins(0, 0, 0, 0)
- self.sourceHeaderLayout.addWidget(self.sourceHeaderLabel)
- self.sourceHeaderLayout.addStretch(1)
- self.sourceHeaderLayout.addWidget(self.addSourceButton)
-
- self.sourceLayout.setContentsMargins(0, 0, 0, 0)
- self.sourceLayout.setSpacing(8)
-
- self.viewLayout.addLayout(self.sourceHeaderLayout)
- self.viewLayout.addWidget(self.sourceContainer)
- self.viewLayout.addSpacing(8)
- self.viewLayout.addWidget(self.customLabel)
- self.viewLayout.addWidget(self.customEdit)
-
- def _bind(self):
- self.addSourceButton.clicked.connect(lambda: self._addSourceCard())
-
- def validate(self) -> bool:
- urls: list[str] = []
- for card in self._sourceCards:
- normalized = card.url
- if not normalized:
- InfoBar.error(
- self.tr("源地址无效"),
- self.tr("请输入有效的 HTTP/HTTPS 地址"),
- parent=self,
- )
- card.urlEdit.setFocus()
- return False
- urls.append(normalized)
-
- uniqueUrls = list(dict.fromkeys(urls))
- cfg.set(bittorrentConfig.webTrackerSources, uniqueUrls)
-
- customTrackers = [
- t for t in self.customEdit.toPlainText().split()
- if urlsplit(t).scheme.lower() in TRACKER_SCHEMES and urlsplit(t).netloc
- ]
- cfg.set(bittorrentConfig.webTrackerCustomList, "\n".join(customTrackers))
- return True
-
- def _addSourceCard(self, url: str = ""):
- cache = dict(bittorrentConfig.webTrackerSourceCache.value)
- cachedCount = len(cache[url]) if url in cache else None
- card = WebTrackerSourceCard(url, cachedCount, self.sourceContainer)
- card.removed.connect(self._onSourceRemoved)
- self.sourceLayout.addWidget(card)
- self._sourceCards.append(card)
-
- def _onSourceRemoved(self, card: WebTrackerSourceCard):
- self._sourceCards.remove(card)
- self.sourceLayout.removeWidget(card)
- card.deleteLater()
diff --git a/features/bittorrent_pack/web_tracker/schema.py b/features/bittorrent_pack/web_tracker/schema.py
deleted file mode 100644
index 0139d711..00000000
--- a/features/bittorrent_pack/web_tracker/schema.py
+++ /dev/null
@@ -1,40 +0,0 @@
-import json
-
-from app.config.cfg import ConfigSerializer, ConfigValidator
-
-DEFAULT_WEB_TRACKER_SOURCES = [
- "https://cf.trackerslist.com/best.txt",
- "https://cdn.jsdelivr.net/gh/XIU2/TrackersListCollection/best.txt",
-]
-
-
-class SourceCacheValidator(ConfigValidator):
- def validate(self, value) -> bool:
- if not isinstance(value, dict):
- return False
- return all(
- isinstance(url, str) and isinstance(trackers, list)
- and all(isinstance(t, str) for t in trackers)
- for url, trackers in value.items()
- )
-
- def correct(self, value) -> dict:
- return value if self.validate(value) else {}
-
-
-class SourceCacheSerializer(ConfigSerializer):
- def serialize(self, value: dict[str, list[str]]) -> str:
- return json.dumps(value, ensure_ascii=False)
-
- def deserialize(self, value: str) -> dict[str, list[str]]:
- try:
- result = json.loads(value)
- except (ValueError, TypeError):
- return {}
- if not isinstance(result, dict):
- return {}
- return {
- url: list(trackers)
- for url, trackers in result.items()
- if isinstance(url, str) and isinstance(trackers, list)
- }
diff --git a/features/bittorrent_pack/web_tracker/service.py b/features/bittorrent_pack/web_tracker/service.py
deleted file mode 100644
index eb036fd2..00000000
--- a/features/bittorrent_pack/web_tracker/service.py
+++ /dev/null
@@ -1,93 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-from time import time
-from urllib.parse import urlsplit
-
-from app.client import buildClient
-from app.config.cfg import cfg
-
-from ..config import bittorrentConfig
-
-TRACKER_SCHEMES = {"http", "https", "udp", "ws", "wss"}
-
-_REFRESH_TTL = 3600
-
-
-class TrackerService:
- def __init__(self):
- self._lastRefreshTime: float = 0
- self._refreshing = False
-
- def isStale(self) -> bool:
- return time() - self._lastRefreshTime > _REFRESH_TTL
-
- def mergedTrackers(self) -> list[str]:
- cache = dict(bittorrentConfig.webTrackerSourceCache.value)
- customText = bittorrentConfig.webTrackerCustomList.value
- customTrackers = [
- t for t in customText.split()
- if (p := urlsplit(t)).scheme.lower() in TRACKER_SCHEMES and p.netloc
- ]
- return list(dict.fromkeys(
- tracker
- for source in (*cache.values(), customTrackers)
- for tracker in source
- if tracker
- ))
-
- async def refresh(self) -> tuple[int, int]:
- self._refreshing = True
- try:
- return await self._doRefresh()
- finally:
- self._refreshing = False
-
- async def _doRefresh(self) -> tuple[int, int]:
- urls = list(bittorrentConfig.webTrackerSources.value)
- if not urls:
- return 0, 0
-
- async def fetchOne(sourceUrl: str) -> list[str]:
- normalized = sourceUrl.strip()
- parsed = urlsplit(normalized)
- if parsed.scheme not in {"http", "https"} or not parsed.netloc:
- raise ValueError("Web Tracker 源地址无效")
- client = buildClient()
- try:
- response = await client.get(normalized)
- response.raise_for_status()
- text = await response.text()
- finally:
- client.close()
- trackers = [
- t for t in text.split()
- if (p := urlsplit(t)).scheme.lower() in TRACKER_SCHEMES and p.netloc
- ]
- if not trackers:
- raise ValueError("Web Tracker 源没有返回有效的 Tracker")
- return trackers
-
- results = await asyncio.gather(
- *(fetchOne(url) for url in urls),
- return_exceptions=True,
- )
-
- oldCache = dict(bittorrentConfig.webTrackerSourceCache.value)
- newCache: dict[str, list[str]] = {}
- successCount = 0
- for url, result in zip(urls, results):
- if isinstance(result, Exception):
- if url in oldCache:
- newCache[url] = oldCache[url]
- else:
- newCache[url] = result
- successCount += 1
-
- cfg.set(bittorrentConfig.webTrackerSourceCache, newCache)
- if successCount > 0:
- self._lastRefreshTime = time()
- return successCount, len(urls)
-
-
-trackerService = TrackerService()
diff --git a/features/ed2k_pack/android.py b/features/ed2k_pack/android.py
index 5f4c8423..1be4d923 100644
--- a/features/ed2k_pack/android.py
+++ b/features/ed2k_pack/android.py
@@ -19,3 +19,42 @@ def taskFields(task) -> dict:
"uploadSpeed": task.uploadRate,
},
}
+
+
+def bootstrapListByName(name: str):
+ from .lists import nodeList, serverList
+
+ return {"servers": serverList, "nodes": nodeList}[name]
+
+
+def sourcesItemByName(name: str):
+ from .config import ed2kConfig
+
+ return {"servers": ed2kConfig.serverListSources, "nodes": ed2kConfig.nodeListSources}[name]
+
+
+async def bootstrapListState(name: str) -> dict:
+ from dataclasses import asdict
+ from .session import ed2kSession
+
+ bootstrapList = bootstrapListByName(name)
+ network = await ed2kSession.probeNetwork()
+ return {
+ "sources": list(sourcesItemByName(name).value),
+ "defaults": list(sourcesItemByName(name).defaultValue),
+ "statuses": [asdict(status) for status in bootstrapList.statuses()],
+ "isRefreshing": bootstrapList.isRefreshing,
+ "serverConnected": None if network is None else network.isServerConnected,
+ "kadNodes": None if network is None else network.kadNodes,
+ }
+
+
+def setBootstrapListSources(name: str, sources: str):
+ from app.config.cfg import cfg
+
+ cfg.set(sourcesItemByName(name), list(dict.fromkeys(sources.split())))
+
+
+async def refreshBootstrapList(name: str) -> dict:
+ await bootstrapListByName(name).refresh()
+ return await bootstrapListState(name)
diff --git a/features/ed2k_pack/config.py b/features/ed2k_pack/config.py
index 52fee0ff..0607c14f 100644
--- a/features/ed2k_pack/config.py
+++ b/features/ed2k_pack/config.py
@@ -4,7 +4,9 @@ import platform
import sys
from pathlib import Path
-from app.config.cfg import BoolValidator, ConfigItem, RangeConfigItem, RangeValidator
+from app.config.cfg import (
+ BoolValidator, ConfigItem, RangeConfigItem, RangeValidator, StringListValidator,
+)
from app.i18n import N
from app.config.paths import APP_DATA_DIR
@@ -14,6 +16,12 @@ from app.platform.filesystem import findExecutable
from app.sources import Repo, fetchLatestRelease, fetchReleaseAsset
ED2K_REPO = Repo("XiaoYouChR/Python-eD2k", mirrors={"gitcode": "XiaoYouChR/Python-eD2k"})
+DEFAULT_SERVER_LIST_SOURCES = [
+ "https://upd.emule-security.org/server.met",
+ "https://shortypower.org/server.met",
+ "http://www.gruk.org/server.met",
+]
+DEFAULT_NODE_LIST_SOURCES = ["https://upd.emule-security.org/nodes.dat"]
class ED2kConfig(PackConfig):
@@ -22,17 +30,22 @@ class ED2kConfig(PackConfig):
enableDht = ConfigItem("ED2k", "EnableDHT", True, BoolValidator(), restart=True)
enableUpnp = ConfigItem("ED2k", "EnableUPnP", True, BoolValidator(), restart=True)
listenPort = RangeConfigItem("ED2k", "ListenPort", 0, RangeValidator(0, 65535), restart=True)
- serverMetSource = ConfigItem("ED2k", "ServerMetSource", "http://upd.emule-security.org/server.met")
- nodesDatSource = ConfigItem("ED2k", "NodesDatSource", "http://upd.emule-security.org/nodes.dat")
+ serverListSources = ConfigItem(
+ "ED2k", "ServerListSources", DEFAULT_SERVER_LIST_SOURCES, StringListValidator(), restart=True,
+ )
+ nodeListSources = ConfigItem(
+ "ED2k", "NodeListSources", DEFAULT_NODE_LIST_SOURCES, StringListValidator(), restart=True,
+ )
+ shouldRefreshLists = ConfigItem("ED2k", "ShouldRefreshLists", True, BoolValidator())
seedingRatioLimit = RangeConfigItem("ED2k", "SeedRatioLimitPercent", 0, RangeValidator(0, 10000))
seedingTimeLimit = RangeConfigItem("ED2k", "SharingTimeLimitMinutes", 0, RangeValidator(0, 43200))
def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:
from qfluentwidgets import FluentIcon, SwitchSettingCard
+ from app.view.components.bootstrap_list import BootstrapListCard
from app.view.components.setting_card_group import CollapsibleSettingCardGroup
- from app.view.components.setting_cards import (
- LineEditSettingCard, SelectFolderSettingCard, SpinBoxSettingCard,
- )
+ from app.view.components.setting_cards import SelectFolderSettingCard, SpinBoxSettingCard
+ from .lists import nodeList, serverList
group = CollapsibleSettingCardGroup(self.tr("eD2k 下载"), "ed2k", parent)
installFolderCard = SelectFolderSettingCard(
@@ -46,15 +59,20 @@ class ED2kConfig(PackConfig):
group.addSettingCards([
installFolderCard,
runtimeCard,
- LineEditSettingCard(
- FluentIcon.GLOBE, self.tr("服务器列表源"),
- self.tr("eD2k server.met 文件的 URL,留空则不引导"),
- self.serverMetSource, group,
+ SwitchSettingCard(
+ FluentIcon.SYNC, self.tr("自动更新订阅"),
+ self.tr("每天在后台更新一次服务器列表和 KAD 节点列表"),
+ self.shouldRefreshLists, group,
),
- LineEditSettingCard(
- FluentIcon.GLOBE, self.tr("DHT 节点源"),
- self.tr("KAD nodes.dat 文件的 URL,留空则不引导"),
- self.nodesDatSource, group,
+ BootstrapListCard(
+ FluentIcon.GLOBE, self.tr("服务器列表"), serverList,
+ self.serverListSources, self.submit, group,
+ probeNetworkText=self._probeServerText,
+ ),
+ BootstrapListCard(
+ FluentIcon.GLOBE, self.tr("KAD 节点列表"), nodeList,
+ self.nodeListSources, self.submit, group,
+ probeNetworkText=self._probeKadText,
),
SwitchSettingCard(
FluentIcon.WIFI, self.tr("启用 DHT"),
@@ -85,6 +103,18 @@ class ED2kConfig(PackConfig):
runtimeCard.refreshStatus()
return [group]
+ async def _probeServerText(self) -> str:
+ from .session import ed2kSession
+ network = await ed2kSession.probeNetwork()
+ if network is None:
+ return ""
+ return self.tr("已连接服务器") if network.isServerConnected else self.tr("未连接服务器")
+
+ async def _probeKadText(self) -> str:
+ from .session import ed2kSession
+ network = await ed2kSession.probeNetwork()
+ return "" if network is None else self.tr("KAD 节点 {0}").format(network.kadNodes)
+
ed2kConfig = ED2kConfig()
diff --git a/features/ed2k_pack/lists.py b/features/ed2k_pack/lists.py
new file mode 100644
index 00000000..0fad48f2
--- /dev/null
+++ b/features/ed2k_pack/lists.py
@@ -0,0 +1,49 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from app.bootstrap_list import BootstrapList
+from app.config.paths import APP_DATA_DIR
+
+from .config import ed2kConfig
+
+CONTACT_SIZE = 25
+
+
+def countServers(data: bytes) -> int:
+ if len(data) < 5 or data[0] not in (0xE0, 0x0E):
+ raise ValueError("不是有效的 server.met")
+ count = int.from_bytes(data[1:5], "little")
+ if count == 0:
+ raise ValueError("server.met 中没有服务器")
+ return count
+
+
+def countNodes(data: bytes) -> int:
+ def readCount(offset: int) -> int:
+ return int.from_bytes(data[offset:offset + 4], "little")
+
+ headerSize = 4
+ count = readCount(0)
+ if count == 0 and len(data) >= 12:
+ headerSize = 16 if readCount(4) == 3 else 12
+ count = readCount(headerSize - 4)
+ if count == 0 or len(data) < headerSize + count * CONTACT_SIZE:
+ raise ValueError("不是有效的 nodes.dat")
+ return count
+
+
+LISTS_FOLDER = Path(__file__).parent / "lists"
+
+serverList = BootstrapList(
+ APP_DATA_DIR / "ed2k" / "servers",
+ LISTS_FOLDER / "server.met",
+ lambda: list(ed2kConfig.serverListSources.value),
+ countServers,
+)
+nodeList = BootstrapList(
+ APP_DATA_DIR / "ed2k" / "nodes",
+ LISTS_FOLDER / "nodes.dat",
+ lambda: list(ed2kConfig.nodeListSources.value),
+ countNodes,
+)
diff --git a/features/ed2k_pack/lists/nodes.dat b/features/ed2k_pack/lists/nodes.dat
new file mode 100644
index 00000000..48ab16f0
Binary files /dev/null and b/features/ed2k_pack/lists/nodes.dat differ
diff --git a/features/ed2k_pack/lists/server.met b/features/ed2k_pack/lists/server.met
new file mode 100644
index 00000000..8244e2b3
Binary files /dev/null and b/features/ed2k_pack/lists/server.met differ
diff --git a/features/ed2k_pack/pack.py b/features/ed2k_pack/pack.py
index 14deb956..e8195d21 100644
--- a/features/ed2k_pack/pack.py
+++ b/features/ed2k_pack/pack.py
@@ -1,9 +1,12 @@
from __future__ import annotations
+import asyncio
+
from app.models.pack import FeaturePack, TaskParser, UriScheme
from app.models.task import Task, TaskError, TaskOptions
from app.platform.filesystem import toSafeFilename
from .config import ed2kConfig, ed2kRuntime
+from .lists import nodeList, serverList
from .session import parseEd2kLink
from .task import ED2kTask, ED2kTaskStep
@@ -51,6 +54,10 @@ class ED2kPack(FeaturePack):
async def activate(self):
from .session import ed2kSession
ed2kSession.submit = self.submit
+ if ed2kConfig.shouldRefreshLists.value:
+ for bootstrapList in (serverList, nodeList):
+ if bootstrapList.isStale():
+ asyncio.ensure_future(bootstrapList.refresh())
async def deactivate(self):
from .session import ed2kSession
diff --git a/features/ed2k_pack/session.py b/features/ed2k_pack/session.py
index ba884cb3..3729dcef 100644
--- a/features/ed2k_pack/session.py
+++ b/features/ed2k_pack/session.py
@@ -12,6 +12,7 @@ from app.config.paths import APP_DATA_DIR
from app.models.task import TaskError
from app.update import parseVersion
from .config import ed2kConfig, ed2kRuntime
+from .lists import nodeList, serverList
from .python_ed2k import Client, Settings, Transfer, TransferState
from .python_ed2k.errors import ErrorCode, Error
@@ -19,6 +20,12 @@ from .python_ed2k.errors import ErrorCode, Error
MIN_GOED2KD_VERSION = (0, 2, 4)
+@dataclass(frozen=True)
+class NetworkStatus:
+ isServerConnected: bool
+ kadNodes: int
+
+
@dataclass(frozen=True)
class RunResult:
fileHash: str
@@ -158,6 +165,13 @@ class ED2kSession:
finally:
self._activeTransfers.discard(identity)
+ async def probeNetwork(self) -> NetworkStatus | None:
+ client = self._client
+ if client is None or not client.isRunning:
+ return None
+ snapshot = await client.snapshot()
+ return NetworkStatus(snapshot.serverConnected, snapshot.kadNodes)
+
def remove(self, fileHash: str) -> None:
if self.submit is None:
return
@@ -194,8 +208,8 @@ class ED2kSession:
enableDht=ed2kConfig.enableDht.value,
enableUpnp=ed2kConfig.enableUpnp.value,
listenPort=ed2kConfig.listenPort.value,
- serverMetSource=ed2kConfig.serverMetSource.value or None,
- nodesDatSource=ed2kConfig.nodesDatSource.value or None,
+ serverMetSource=",".join(map(str, serverList.paths())),
+ nodesDatSource=",".join(map(str, nodeList.paths())),
))
self._client = client
diff --git a/scripts/update_bootstrap_snapshots.py b/scripts/update_bootstrap_snapshots.py
new file mode 100644
index 00000000..e43cb131
--- /dev/null
+++ b/scripts/update_bootstrap_snapshots.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python3
+"""Refresh the Bootstrap List snapshots bundled with the BT and eD2k packs.
+
+Run before a release:
+ python scripts/update_bootstrap_snapshots.py
+"""
+import sys
+from pathlib import Path
+from urllib.request import Request, urlopen
+
+REPO = Path(__file__).resolve().parent.parent
+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
+
+
+def fetch(url: str) -> bytes:
+ with urlopen(Request(url, headers={"User-Agent": "Mozilla/5.0"}), timeout=30) as response:
+ return response.read()
+
+
+def fetchFirstValid(urls: list[str], count) -> bytes:
+ for url in urls:
+ try:
+ data = fetch(url)
+ print(f"{url}: {count(data)}")
+ return data
+ except Exception as e:
+ print(f"{url}: {e}")
+ sys.exit("No source returned a valid list")
+
+
+def main() -> None:
+ trackers: list[str] = []
+ for url in DEFAULT_TRACKER_LIST_SOURCES:
+ try:
+ fetched = parseTrackers(fetch(url).decode("utf-8", errors="ignore"))
+ print(f"{url}: {len(fetched)}")
+ trackers += fetched
+ except Exception as e:
+ print(f"{url}: {e}")
+ if not trackers:
+ sys.exit("No tracker source returned a valid list")
+ (REPO / "features/bittorrent_pack/lists/trackers.txt").write_text(
+ "\n".join(dict.fromkeys(trackers)) + "\n", "utf-8")
+
+ (REPO / "features/ed2k_pack/lists/server.met").write_bytes(
+ fetchFirstValid(DEFAULT_SERVER_LIST_SOURCES, countServers))
+ (REPO / "features/ed2k_pack/lists/nodes.dat").write_bytes(
+ fetchFirstValid(DEFAULT_NODE_LIST_SOURCES, countNodes))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_bootstrap_list.py b/tests/test_bootstrap_list.py
new file mode 100644
index 00000000..78f2a49d
--- /dev/null
+++ b/tests/test_bootstrap_list.py
@@ -0,0 +1,107 @@
+import asyncio
+import os
+import time
+
+import pytest
+
+from app.bootstrap_list import BootstrapList
+
+
+def countLines(data: bytes) -> int:
+ lines = data.decode().split()
+ if not lines:
+ raise ValueError("empty list")
+ return len(lines)
+
+
+def makeList(tmp_path, sources: list[str], bodies: dict[str, bytes], fetched: list[str] | None = None):
+ snapshot = tmp_path / "snapshot.txt"
+ snapshot.write_bytes(b"udp://snapshot:1\n")
+
+ async def fetch(url: str) -> bytes:
+ if fetched is not None:
+ fetched.append(url)
+ await asyncio.sleep(0)
+ if url not in bodies:
+ raise OSError("unreachable")
+ return bodies[url]
+
+ return BootstrapList(tmp_path / "cache", snapshot, lambda: sources, countLines, fetch)
+
+
+def test_snapshot_is_used_until_anything_is_cached(tmp_path):
+ bootstrapList = makeList(tmp_path, ["https://a"], {})
+
+ assert bootstrapList.paths() == [tmp_path / "snapshot.txt"]
+
+
+async def test_refresh_caches_every_source_in_order(tmp_path):
+ bootstrapList = makeList(tmp_path, ["https://a", "https://b"], {
+ "https://a": b"udp://a:1\nudp://a:2\n",
+ "https://b": b"udp://b:1\n",
+ })
+
+ await bootstrapList.refresh()
+
+ paths = bootstrapList.paths()
+ assert [p.read_bytes() for p in paths] == [b"udp://a:1\nudp://a:2\n", b"udp://b:1\n"]
+ statuses = bootstrapList.statuses()
+ assert [(s.url, s.count, s.error) for s in statuses] == [("https://a", 2, ""), ("https://b", 1, "")]
+ assert all(s.updatedAt is not None for s in statuses)
+
+
+async def test_failed_source_keeps_its_cache_and_reports_why(tmp_path):
+ bodies = {"https://a": b"udp://a:1\n", "https://b": b"udp://b:1\n"}
+ bootstrapList = makeList(tmp_path, ["https://a", "https://b"], bodies)
+ await bootstrapList.refresh()
+
+ del bodies["https://a"]
+ await bootstrapList.refresh()
+
+ assert bootstrapList.paths()[0].read_bytes() == b"udp://a:1\n"
+ status = bootstrapList.statuses()[0]
+ assert status.count == 1
+ assert "unreachable" in status.error
+
+
+async def test_invalid_content_never_replaces_the_cache(tmp_path):
+ bodies = {"https://a": b"udp://a:1\n"}
+ bootstrapList = makeList(tmp_path, ["https://a"], bodies)
+ await bootstrapList.refresh()
+
+ bodies["https://a"] = b" "
+ await bootstrapList.refresh()
+
+ assert bootstrapList.paths()[0].read_bytes() == b"udp://a:1\n"
+ assert "empty list" in bootstrapList.statuses()[0].error
+
+
+async def test_concurrent_refreshes_fetch_once(tmp_path):
+ fetched: list[str] = []
+ bootstrapList = makeList(tmp_path, ["https://a"], {"https://a": b"udp://a:1\n"}, fetched)
+
+ await asyncio.gather(bootstrapList.refresh(), bootstrapList.refresh())
+
+ assert fetched == ["https://a"]
+ assert not bootstrapList.isRefreshing
+
+
+async def test_list_is_stale_only_when_a_source_is_missing_or_old(tmp_path):
+ bodies = {"https://a": b"udp://a:1\n"}
+ assert makeList(tmp_path, ["https://a"], bodies).isStale()
+
+ await makeList(tmp_path, ["https://a"], bodies).refresh()
+ assert not makeList(tmp_path, ["https://a"], bodies).isStale()
+
+ cached = makeList(tmp_path, ["https://a"], bodies).paths()[0]
+ old = time.time() - 2 * 86400
+ os.utime(cached, (old, old))
+ assert makeList(tmp_path, ["https://a"], bodies).isStale()
+
+
+async def test_failed_refresh_is_not_retried_until_the_next_day(tmp_path):
+ bootstrapList = makeList(tmp_path, ["https://a"], {})
+
+ await bootstrapList.refresh()
+
+ assert not bootstrapList.isStale()
diff --git a/tests/test_ed2k_task.py b/tests/test_ed2k_task.py
index 1630aba8..8963019e 100644
--- a/tests/test_ed2k_task.py
+++ b/tests/test_ed2k_task.py
@@ -398,3 +398,34 @@ async def test_open_rejects_an_outdated_goed2kd(monkeypatch, version, isAccepted
with pytest.raises(TaskError):
await session._open()
assert session._client is None
+
+
+def u32(value: int) -> bytes:
+ return value.to_bytes(4, "little")
+
+
[email protected]("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),
+])
+def test_count_nodes_reads_every_nodes_dat_version(data, count):
+ from ed2k_pack.lists import countNodes
+
+ assert countNodes(data) == count
+
+
[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 test_count_servers_reads_the_header():
+ from ed2k_pack.lists import countServers
+
+ assert countServers(b"\xe0" + u32(13)) == 13
+ with pytest.raises(ValueError):
+ countServers(b"<html>")