Skip to content

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

feat(ed2k): 换用 Kelpie 引擎

XiaoYouChR330ed625acbb
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index d061be01..8ed9f962 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -726,7 +726,7 @@ jobs:
name: wreq-arm64-v8a
path: android/build-scripts/dist/wreq-*.whl
- android-goed2kd:
+ android-kelpie:
if: ${{ github.event.inputs.build_target == 'android' || github.event.inputs.build_target == 'all' }}
runs-on: ubuntu-24.04
steps:
@@ -740,23 +740,23 @@ jobs:
- uses: actions/checkout@v7
with:
- repository: XiaoYouChR/Python-eD2k
- path: Python-eD2k
+ repository: XiaoYouChR/Kelpie
+ path: Kelpie
- uses: actions/setup-go@v7
with:
- go-version-file: Python-eD2k/go.mod
+ go-version-file: Kelpie/go.mod
- - name: Build goed2kd
+ - name: Build Kelpie
working-directory: android/build-scripts
env:
- GOED2K_SRC: ${{ github.workspace }}/Python-eD2k
- run: ./build_goed2kd.sh
+ KELPIE_SRC: ${{ github.workspace }}/Kelpie
+ run: ./build_kelpie.sh
- uses: actions/upload-artifact@v7
with:
- name: goed2kd-arm64-v8a
- path: android/app/src/main/jniLibs/arm64-v8a/libgoed2kd.so
+ name: kelpie-arm64-v8a
+ path: android/app/src/main/jniLibs/arm64-v8a/libkelpie.so
android-native-libs:
if: ${{ github.event.inputs.build_target == 'android' || github.event.inputs.build_target == 'all' }}
@@ -780,7 +780,7 @@ jobs:
path: android/app/src/main/jniLibs/arm64-v8a
build-android:
- needs: [prepare, android-libtorrent, android-wreq, android-goed2kd, android-native-libs]
+ needs: [prepare, android-libtorrent, android-wreq, android-kelpie, android-native-libs]
if: ${{ github.event.inputs.build_target == 'android' || github.event.inputs.build_target == 'all' }}
runs-on: ubuntu-24.04
timeout-minutes: 120
@@ -816,7 +816,7 @@ jobs:
- uses: actions/download-artifact@v8
with:
- name: goed2kd-arm64-v8a
+ name: kelpie-arm64-v8a
path: android/app/src/main/jniLibs/arm64-v8a
- uses: actions/download-artifact@v8
diff --git a/README.md b/README.md
index c2b9325f..22e30c91 100644
--- a/README.md
+++ b/README.md
@@ -155,7 +155,7 @@ Copyright © 2024-2026 XiaoYouChR.
* [cat-catch](https://github.com/xifangczy/cat-catch) Browser Resource Sniffing Extension
* [desktop-notifier](https://github.com/samschott/desktop-notifier) Python library for cross-platform desktop notifications
* [FFmpeg](https://ffmpeg.org/) A complete, cross-platform solution to record, convert and stream audio and video
-* [goed2k](https://github.com/monkeyWie/goed2k) The eD2k download daemon behind Ghost Downloader's eD2k support
+* [Kelpie](https://github.com/XiaoYouChR/Kelpie) The eD2k download engine behind Ghost Downloader's eD2k support
* [libtorrent](https://github.com/arvidn/libtorrent) An efficient feature complete C++ bittorrent implementation
* [loguru](https://github.com/Delgan/loguru) A library which aims to bring enjoyable logging in Python
* [m3u8](https://github.com/globocom/m3u8) Python m3u8 parser
diff --git a/README_zh.md b/README_zh.md
index f767994d..9d3764f0 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -156,7 +156,7 @@ Copyright © 2024-2026 XiaoYouChR.
* [cat-catch](https://github.com/xifangczy/cat-catch) 猫抓 浏览器资源嗅探扩展
* [desktop-notifier](https://github.com/samschott/desktop-notifier) Python library for cross-platform desktop notifications
* [FFmpeg](https://ffmpeg.org/) A complete, cross-platform solution to record, convert and stream audio and video
-* [goed2k](https://github.com/monkeyWie/goed2k) The eD2k download daemon behind Ghost Downloader's eD2k support
+* [Kelpie](https://github.com/XiaoYouChR/Kelpie) Ghost Downloader 的 eD2k 下载引擎
* [libtorrent](https://github.com/arvidn/libtorrent) An efficient feature complete C++ bittorrent implementation
* [loguru](https://github.com/Delgan/loguru) A library which aims to bring enjoyable logging in Python
* [m3u8](https://github.com/globocom/m3u8) Python m3u8 parser
diff --git a/features/ed2k_pack/android.py b/features/ed2k_pack/android.py
index 1be4d923..d63a9f89 100644
--- a/features/ed2k_pack/android.py
+++ b/features/ed2k_pack/android.py
@@ -1,57 +1,72 @@
"""Android View adapter for ED2kPack."""
+import time
+from dataclasses import asdict
+
+from app.config.cfg import cfg
from app.i18n import N
+from .config import ed2kConfig
+from .lists import nodeList, serverList
+from .session import ed2kSession, toHeldMinutes
UI_CLASS = "com.xychr.ghostdownloader.features.ed2k_pack.Ed2kUi"
+def init(pack) -> dict:
+ return {"network": ed2kSession.networkChanged, "isIdle": ed2kSession.runsChanged}
+
+
+def network() -> dict | None:
+ network = ed2kSession.network
+ return None if network is None else asdict(network)
+
+
+def isIdle() -> bool:
+ return ed2kSession.isIdle
+
+
+async def stop() -> None:
+ await ed2kSession.stop()
+
+
def taskFields(task) -> dict:
- active = task.activePeerCount
+ progress = ed2kSession.progressOf(task)
+ heldMinutes = toHeldMinutes(progress, int(time.time() * 1000))
+ uploadRate = progress.uploadRate if progress is not None else 0
return {
"progressMode": "hidden" if task.isSeeding else "determinate",
"statusText": N("TaskState", "做种中") if task.isSeeding else "",
- "secondarySpeed": task.uploadRate,
+ "secondarySpeed": uploadRate,
"packFields": {
- "peers": None if active is None else {
- "active": active, "total": max(active, task.totalPeerCount),
- },
+ "peers": None if progress is None else {"active": progress.activePeers, "total": progress.peers},
+ "held": None if heldMinutes is None else {"sources": progress.heldSources, "minutes": heldMinutes},
"shareRatio": task.shareRatioPercent,
"seedingSeconds": task.seedingTimeSeconds,
- "uploadSpeed": task.uploadRate,
+ "uploadSpeed": 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()
+ sourcesItem = sourcesItemByName(name)
return {
- "sources": list(sourcesItemByName(name).value),
- "defaults": list(sourcesItemByName(name).defaultValue),
+ "sources": list(sourcesItem.value),
+ "defaults": list(sourcesItem.defaultValue),
"statuses": [asdict(status) for status in bootstrapList.statuses()],
+ "entryCount": bootstrapList.entryCount(),
"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())))
diff --git a/features/ed2k_pack/cards.py b/features/ed2k_pack/cards.py
index cb1ab640..0a46e2c4 100644
--- a/features/ed2k_pack/cards.py
+++ b/features/ed2k_pack/cards.py
@@ -1,23 +1,50 @@
+import time
+
from PySide6.QtCore import QCoreApplication
+from PySide6.QtGui import QColor
from qfluentwidgets import FluentIcon
from app.format import toReadableSize, toReadableTime
from app.models.task import TaskStatus
from app.view.cards.task_cards import ETA_FIELD, SIZE_FIELD, SPEED_FIELD, FieldSpec, TaskCard
+from .kelpie import Progress
+from .session import ed2kSession, toHeldMinutes
from .task import ED2kTask
+def toWaitText(minutes: int) -> str:
+ if minutes == 0:
+ return QCoreApplication.translate("ED2kTaskCard", "不到 1 分钟")
+ return QCoreApplication.translate("ED2kTaskCard", "约 {0} 分钟").format(minutes)
+
+
+def toHeldText(progress: Progress | None, now: int) -> str | None:
+ minutes = toHeldMinutes(progress, now)
+ if minutes is None:
+ return None
+ return QCoreApplication.translate(
+ "ED2kTaskCard", "为免被对方判为请求过频而封禁,{0} 个来源{1}后再请求",
+ ).format(progress.heldSources, toWaitText(minutes))
+
+
+def toShortHeldText(progress: Progress | None, now: int) -> str | None:
+ minutes = toHeldMinutes(progress, now)
+ if minutes is None:
+ return None
+ return QCoreApplication.translate("ED2kTaskCard", "{0} 个来源{1}后恢复").format(
+ progress.heldSources, toWaitText(minutes))
+
+
def toPeerText(task: ED2kTask, _speed: int, _received: int) -> str | None:
- if task.activePeerCount is None:
+ progress = ed2kSession.progressOf(task)
+ if progress is None:
return None
- total = max(task.activePeerCount, task.totalPeerCount)
- return QCoreApplication.translate("TaskCard", "{0}/{1} Peers").format(
- task.activePeerCount, total
- )
+ return QCoreApplication.translate("ED2kTaskCard", "{0}/{1} 来源").format(progress.activePeers, progress.peers)
def toUploadText(task: ED2kTask, _speed: int, _received: int) -> str:
- return f"{toReadableSize(task.uploadRate)}/s"
+ progress = ed2kSession.progressOf(task)
+ return f"{toReadableSize(progress.uploadRate if progress is not None else 0)}/s"
ED2K_UPLOAD_FIELD = FieldSpec("upload", FluentIcon.SHARE, {
@@ -38,12 +65,19 @@ class ED2kTaskCard(TaskCard):
def _refreshForStatus(self, task: ED2kTask):
super()._refreshForStatus(task)
- if task.isSeeding and not self._isFileMissing:
- self._setStatus(self.tr(",").join([self.tr("做种中"), *self._toSeedingParts(task)]))
- elif task.status != TaskStatus.RUNNING:
- parts = self._toSeedingParts(task)
- if parts and not self._isFileMissing:
- self.statusLabel.setText(self.tr(",").join(parts))
+ if self._isFileMissing:
+ return
+ progress, now = ed2kSession.progressOf(task), int(time.time() * 1000)
+ shortHeldText = toShortHeldText(progress, now)
+ if task.status == TaskStatus.RUNNING and shortHeldText is not None:
+ self._setStatus(shortHeldText)
+ self.statusLabel.setTextColor(QColor(200, 160, 80), QColor(200, 170, 100))
+ return
+ parts = self._toSeedingParts(task)
+ if task.isSeeding:
+ self._setStatus(self.tr(",").join([self.tr("做种中"), *parts]))
+ elif task.status != TaskStatus.RUNNING and parts:
+ self.statusLabel.setText(self.tr(",").join(parts))
def _toSeedingParts(self, task: ED2kTask) -> list[str]:
parts = []
diff --git a/features/ed2k_pack/config.py b/features/ed2k_pack/config.py
index 0607c14f..8064fa65 100644
--- a/features/ed2k_pack/config.py
+++ b/features/ed2k_pack/config.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import platform
import sys
from pathlib import Path
+from typing import TYPE_CHECKING
from app.config.cfg import (
BoolValidator, ConfigItem, RangeConfigItem, RangeValidator, StringListValidator,
@@ -12,10 +13,16 @@ from app.i18n import N
from app.config.paths import APP_DATA_DIR
from app.models.pack import BinaryRuntime, PackConfig
from app.platform.android import IS_ANDROID, nativeLibraryDir
+from app.install import installFile
from app.platform.filesystem import findExecutable
from app.sources import Repo, fetchLatestRelease, fetchReleaseAsset
-ED2K_REPO = Repo("XiaoYouChR/Python-eD2k", mirrors={"gitcode": "XiaoYouChR/Python-eD2k"})
+if TYPE_CHECKING:
+ from PySide6.QtWidgets import QWidget
+
+ from app.view.components.setting_card_group import CollapsibleSettingCardGroup
+
+KELPIE_REPO = Repo("XiaoYouChR/Kelpie", mirrors={"gitcode": "XiaoYouChR/Kelpie"})
DEFAULT_SERVER_LIST_SOURCES = [
"https://upd.emule-security.org/server.met",
"https://shortypower.org/server.met",
@@ -26,10 +33,11 @@ DEFAULT_NODE_LIST_SOURCES = ["https://upd.emule-security.org/nodes.dat"]
class ED2kConfig(PackConfig):
associateUriSchemes = ConfigItem("ED2k", "AssociateUriSchemes", False, BoolValidator())
- installFolder = ConfigItem("ED2k", "InstallFolder", f"{APP_DATA_DIR}/goed2kd")
- enableDht = ConfigItem("ED2k", "EnableDHT", True, BoolValidator(), restart=True)
- enableUpnp = ConfigItem("ED2k", "EnableUPnP", True, BoolValidator(), restart=True)
+ installFolder = ConfigItem("ED2k", "InstallFolder", f"{APP_DATA_DIR}/kelpie")
+ enableKad = ConfigItem("ED2k", "EnableKad", True, BoolValidator())
+ enableUpnp = ConfigItem("ED2k", "EnableUPnP", True, BoolValidator())
listenPort = RangeConfigItem("ED2k", "ListenPort", 0, RangeValidator(0, 65535), restart=True)
+ uploadRateLimit = RangeConfigItem("ED2k", "UploadRateLimit", 0, RangeValidator(0, 1024 * 1024 * 100))
serverListSources = ConfigItem(
"ED2k", "ServerListSources", DEFAULT_SERVER_LIST_SOURCES, StringListValidator(), restart=True,
)
@@ -41,21 +49,54 @@ class ED2kConfig(PackConfig):
seedingTimeLimit = RangeConfigItem("ED2k", "SharingTimeLimitMinutes", 0, RangeValidator(0, 43200))
def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:
- from qfluentwidgets import FluentIcon, SwitchSettingCard
+ from qfluentwidgets import FluentIcon, PushSettingCard, 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 SelectFolderSettingCard, SpinBoxSettingCard
from .lists import nodeList, serverList
+ from .session import ed2kSession
group = CollapsibleSettingCardGroup(self.tr("eD2k 下载"), "ed2k", parent)
installFolderCard = SelectFolderSettingCard(
- ed2kConfig.installFolder, f"{APP_DATA_DIR}/goed2kd",
- self.tr("goed2kd 安装目录"),
+ self.installFolder, self.installFolder.defaultValue,
+ self.tr("Kelpie 安装目录"),
group,
)
- runtimeCard = self.createRuntimeCard(ed2kRuntime, group)
+ runtimeCard = self.createRuntimeCard(kelpieRuntime, group)
installFolderCard.pathChanged.connect(runtimeCard._onInstallFolderChanged)
+
+ def toStopCardContent() -> str:
+ if ed2kSession.network is None:
+ return self.tr("未运行")
+ if not ed2kSession.isIdle:
+ return self.tr("有 eD2k 任务正在下载或做种,结束后才能终止")
+ return self.tr("开始 eD2k 任务时会自动重新启动")
+
+ stopCard = PushSettingCard(
+ self.tr("终止"), FluentIcon.CLOSE, self.tr("终止 Kelpie 进程"), toStopCardContent(), group,
+ )
+
+ def refreshStopCard():
+ stopCard.button.setEnabled(ed2kSession.network is not None and ed2kSession.isIdle)
+ stopCard.setContent(toStopCardContent())
+
+ stopCard.clicked.connect(lambda: self.submit(ed2kSession.stop()))
+ ed2kSession.networkChanged.connect(refreshStopCard, owner=stopCard)
+ ed2kSession.runsChanged.connect(refreshStopCard, owner=stopCard)
+ refreshStopCard()
+
+ serverListCard = BootstrapListCard(
+ FluentIcon.GLOBE, self.tr("服务器列表"), serverList,
+ self.serverListSources, self.submit, group, probeNetworkText=self._probeServerText,
+ )
+ nodeListCard = BootstrapListCard(
+ FluentIcon.GLOBE, self.tr("KAD 节点列表"), nodeList,
+ self.nodeListSources, self.submit, group, probeNetworkText=self._probeKadText,
+ )
+ for card in (serverListCard, nodeListCard):
+ ed2kSession.networkChanged.connect(card.probeNetwork, owner=card)
+
group.addSettingCards([
installFolderCard,
runtimeCard,
@@ -64,20 +105,13 @@ class ED2kConfig(PackConfig):
self.tr("每天在后台更新一次服务器列表和 KAD 节点列表"),
self.shouldRefreshLists, 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,
- ),
+ serverListCard,
+ nodeListCard,
+ stopCard,
SwitchSettingCard(
- FluentIcon.WIFI, self.tr("启用 DHT"),
- self.tr("通过分布式哈希表查找节点,关闭后仅使用 eD2k 服务器"),
- self.enableDht, group,
+ FluentIcon.WIFI, self.tr("启用 KAD"),
+ self.tr("通过 KAD 网络查找来源,关闭后仅使用 eD2k 服务器"),
+ self.enableKad, group,
),
SwitchSettingCard(
FluentIcon.GLOBE, self.tr("启用 UPnP"),
@@ -89,6 +123,11 @@ class ED2kConfig(PackConfig):
self.tr("0 表示交给系统自动分配可用端口"), "",
self.listenPort, group, 1,
),
+ SpinBoxSettingCard(
+ FluentIcon.SHARE, self.tr("上传限速"),
+ self.tr("0 表示不限速。上传越多积分越高,在别人的队列里排得越靠前,自己下载也越快"), " KB/s",
+ self.uploadRateLimit, group, 64, 1 / 1024,
+ ),
SpinBoxSettingCard(
FluentIcon.SHARE, self.tr("自动停止做种分享率"),
self.tr("0 表示不按分享率自动停止,100% 表示分享率 1.0"), " %",
@@ -105,22 +144,34 @@ class ED2kConfig(PackConfig):
async def _probeServerText(self) -> str:
from .session import ed2kSession
- network = await ed2kSession.probeNetwork()
+ network = ed2kSession.network
if network is None:
- return ""
- return self.tr("已连接服务器") if network.isServerConnected else self.tr("未连接服务器")
+ return self.tr("未运行")
+ if not network.isServerConnected:
+ return self.tr("未连接服务器")
+ if network.isHighId:
+ return self.tr("已连接服务器(HighID)")
+ if network.isBehindCarrierNat:
+ return self.tr("已连接服务器(LowID,运营商 NAT,无法获得 HighID)")
+ return self.tr("已连接服务器(LowID,开启 UPnP 或在路由器转发监听端口可获得 HighID)")
async def _probeKadText(self) -> str:
+ if not self.enableKad.value:
+ return self.tr("KAD 已关闭")
from .session import ed2kSession
- network = await ed2kSession.probeNetwork()
- return "" if network is None else self.tr("KAD 节点 {0}").format(network.kadNodes)
+ network = ed2kSession.network
+ if network is None:
+ return self.tr("未运行")
+ if network.isKadFirewalled:
+ return self.tr("KAD 节点 {0}(处于防火墙后)").format(network.kadNodes)
+ return self.tr("KAD 节点 {0}").format(network.kadNodes)
ed2kConfig = ED2kConfig()
-class ED2kRuntime(BinaryRuntime):
- name = "goed2kd"
+class KelpieRuntime(BinaryRuntime):
+ name = "Kelpie"
canInstall = not IS_ANDROID
title = N("BinaryRuntime", "eD2k / eMule")
description = N("BinaryRuntime", "支持电驴协议,适合下载经典资源")
@@ -134,33 +185,37 @@ class ED2kRuntime(BinaryRuntime):
nativeDir = nativeLibraryDir()
if not nativeDir:
return ""
- binary = Path(nativeDir) / "libgoed2kd.so"
+ binary = Path(nativeDir) / "libkelpie.so"
return str(binary) if binary.exists() else ""
- return findExecutable(self.installFolder(), "goed2kd")
+ return findExecutable(self.installFolder(), "kelpie")
async def fetchLatestVersion(self) -> str:
- return (await fetchLatestRelease(ED2K_REPO)).version
+ return (await fetchLatestRelease(KELPIE_REPO)).version
def installedPaths(self) -> list[Path]:
- return [self.installFolder() / ("goed2kd.exe" if sys.platform == "win32" else "goed2kd")]
+ return [self.installFolder() / ("kelpie.exe" if sys.platform == "win32" else "kelpie")]
async def install(self, version: str, onProgress) -> None:
- tag = version or (await fetchLatestRelease(ED2K_REPO)).version
- binaryPath = self.installedPaths()[0]
- await fetchReleaseAsset(ED2K_REPO, tag, _assetName(), binaryPath, onProgress)
- if sys.platform != "win32":
- binaryPath.chmod(binaryPath.stat().st_mode | 0o755)
-
-
-def _assetName() -> str:
+ tag = version or await self.fetchLatestVersion()
+ binary = self.installedPaths()[0]
+ downloadPath = binary.with_name(f"{binary.name}.download")
+ try:
+ await fetchReleaseAsset(KELPIE_REPO, tag, buildAssetName(), downloadPath, onProgress)
+ downloadPath.chmod(0o755)
+ installFile(downloadPath, binary)
+ finally:
+ downloadPath.unlink(missing_ok=True)
+
+
+def buildAssetName() -> str:
machine = platform.machine().lower()
arch = "arm64" if machine in {"arm64", "aarch64"} else "amd64"
if sys.platform == "win32":
- return f"goed2kd-windows-{arch}.exe"
+ return f"kelpie-windows-{arch}.exe"
elif sys.platform == "darwin":
- return f"goed2kd-darwin-{arch}"
+ return f"kelpie-darwin-{arch}"
else:
- return f"goed2kd-linux-{arch}"
+ return f"kelpie-linux-{arch}"
-ed2kRuntime = ED2kRuntime()
+kelpieRuntime = KelpieRuntime()
diff --git a/features/ed2k_pack/detail_cards.py b/features/ed2k_pack/detail_cards.py
new file mode 100644
index 00000000..9ee030f5
--- /dev/null
+++ b/features/ed2k_pack/detail_cards.py
@@ -0,0 +1,130 @@
+from __future__ import annotations
+
+import time
+from typing import TYPE_CHECKING
+
+from PySide6.QtCore import QCoreApplication
+from qfluentwidgets import CaptionLabel
+
+from app.format import toDockSpeed, toReadableSize, toReadableTime
+from app.view.dialogs.task_drawer import DetailCard, DetailTable, InfoRow
+from .cards import toHeldText
+from .kelpie import Link, Source
+from .session import ed2kSession
+
+if TYPE_CHECKING:
+ from .task import ED2kTask
+
+PART_SIZE = 9728000
+
+
+def toPartCount(size: int) -> int:
+ return -(-size // PART_SIZE)
+
+
+def toAichHash(url: str) -> str:
+ for field in url.split("|"):
+ if field.startswith("h="):
+ return field[2:]
+ return ""
+
+
+def toSourceStatusText(source: Source) -> str:
+ match source.status:
+ case "transferring":
+ return QCoreApplication.translate("ED2kSourceCard", "传输中")
+ case "queued" if source.rank > 0:
+ return QCoreApplication.translate("ED2kSourceCard", "排队 #{0}").format(source.rank)
+ case "queued":
+ return QCoreApplication.translate("ED2kSourceCard", "排队")
+ case "connecting":
+ return QCoreApplication.translate("ED2kSourceCard", "连接中")
+ case "held":
+ return QCoreApplication.translate("ED2kSourceCard", "暂缓")
+ case _:
+ return source.status
+
+
+def toChannelText(channel: str) -> str:
+ match channel:
+ case "link":
+ return QCoreApplication.translate("ED2kSourceCard", "链接")
+ case "server":
+ return QCoreApplication.translate("ED2kSourceCard", "服务器")
+ case "kad":
+ return "KAD"
+ case "exchange":
+ return QCoreApplication.translate("ED2kSourceCard", "来源交换")
+ case "incoming":
+ return QCoreApplication.translate("ED2kSourceCard", "对方连入")
+ case _:
+ return channel
+
+
+class ED2kCard(DetailCard):
+ def __init__(self, task: ED2kTask, parent=None):
+ super().__init__(self.tr("eD2k"), parent)
+ self._task = task
+ self.hashRow = InfoRow(self.tr("文件哈希"), self.card)
+ self.aichRow = InfoRow(self.tr("AICH 根哈希"), self.card)
+ self.partsRow = InfoRow(self.tr("分块"), self.card)
+ self.speedRow = InfoRow(self.tr("速度"), self.card)
+ self.peersRow = InfoRow(self.tr("来源"), self.card)
+ self.heldRow = InfoRow(self.tr("暂缓"), self.card)
+ self.uploadedRow = InfoRow(self.tr("已上传"), self.card)
+ self.ratioRow = InfoRow(self.tr("分享率"), self.card)
+ self._initWidget()
+ self._initLayout()
+
+ def _initWidget(self) -> None:
+ self.hashRow.addCopyButton()
+ self.hashRow.setValue(Link.parse(self._task.url).hash)
+ self.aichRow.addCopyButton()
+ self.aichRow.setValue(toAichHash(self._task.url))
+ self.aichRow.setVisible(bool(self.aichRow.valueText.text()))
+ self.partsRow.setValue(f"{toPartCount(self._task.fileSize)} × {toReadableSize(PART_SIZE)}")
+
+ def _initLayout(self) -> None:
+ for row in (self.hashRow, self.aichRow, self.partsRow, self.speedRow, self.peersRow, self.heldRow,
+ self.uploadedRow, self.ratioRow):
+ self.bodyLayout.addWidget(row)
+
+ def refresh(self) -> None:
+ task = self._task
+ progress = ed2kSession.progressOf(task)
+ for row in (self.speedRow, self.peersRow):
+ row.setVisible(progress is not None)
+ if progress is not None:
+ self.speedRow.setValue(self.tr("下载 {0},上传 {1}").format(
+ toDockSpeed(progress.downloadRate), toDockSpeed(progress.uploadRate)))
+ self.peersRow.setValue(self.tr("传输中 {0},共 {1}").format(progress.activePeers, progress.peers))
+ heldText = toHeldText(progress, int(time.time() * 1000))
+ self.heldRow.setVisible(heldText is not None)
+ if heldText is not None:
+ self.heldRow.setValue(heldText)
+ self.uploadedRow.setValue(toReadableSize(task.uploadedBytes))
+ self.ratioRow.setValue(self.tr("{0},已做种 {1}").format(
+ f"{task.shareRatioPercent / 100:.2f}", toReadableTime(task.seedingTimeSeconds)))
+
+
+class ED2kSourceCard(DetailCard):
+ def __init__(self, task: ED2kTask, parent=None):
+ super().__init__(self.tr("来源"), parent)
+ self._task = task
+ self.table = DetailTable(
+ [self.tr("地址"), self.tr("客户端"), self.tr("状态"), self.tr("下载"), self.tr("渠道")],
+ stretchColumns=(1,), parent=self.card)
+ self.idleLabel = CaptionLabel(self.tr("任务运行时显示"), self.card)
+ self.bodyLayout.addWidget(self.table)
+ self.bodyLayout.addWidget(self.idleLabel)
+
+ def refresh(self) -> None:
+ progress = ed2kSession.progressOf(self._task)
+ sources = progress.sources if progress is not None else ()
+ self.table.setVisible(bool(sources))
+ self.idleLabel.setVisible(not sources)
+ self.table.setRows([
+ (source.address, source.software, toSourceStatusText(source),
+ toDockSpeed(source.downloadRate) if source.downloadRate > 0 else "", toChannelText(source.channel))
+ for source in sources
+ ])
diff --git a/features/ed2k_pack/i18n.py b/features/ed2k_pack/i18n.py
index df2127e0..0fe492b5 100644
--- a/features/ed2k_pack/i18n.py
+++ b/features/ed2k_pack/i18n.py
@@ -3,4 +3,9 @@ from app.i18n import N
N("TaskErrors", "ED2k 错误:{detail}")
N("TaskErrors", "该 eD2k 链接已在下载中")
N("TaskErrors", "不是有效的 eD2k 链接")
-N("TaskErrors", "不支持的 eD2k 链接格式")
+N("TaskErrors", "目标文件已被占用")
+N("TaskErrors", "磁盘空间不足")
+N("TaskErrors", "无法读写文件:{detail}")
+N("TaskErrors", "{name} 版本过旧,请在设置中更新")
+N("TaskErrors", "{name} 启动失败:{detail}")
+N("TaskErrors", "{name} 意外退出:{detail}")
diff --git a/features/ed2k_pack/kelpie/__init__.py b/features/ed2k_pack/kelpie/__init__.py
new file mode 100644
index 00000000..bc38ede3
--- /dev/null
+++ b/features/ed2k_pack/kelpie/__init__.py
@@ -0,0 +1,15 @@
+from .errors import Error, ErrorCode
+from .kelpie import Kelpie, Run
+from .models import Link, Network, Progress, Settings, Source
+
+__all__ = [
+ "Error",
+ "ErrorCode",
+ "Kelpie",
+ "Link",
+ "Network",
+ "Progress",
+ "Run",
+ "Settings",
+ "Source",
+]
diff --git a/features/ed2k_pack/kelpie/errors.py b/features/ed2k_pack/kelpie/errors.py
new file mode 100644
index 00000000..5e24ab22
--- /dev/null
+++ b/features/ed2k_pack/kelpie/errors.py
@@ -0,0 +1,20 @@
+from enum import StrEnum
+
+
+class ErrorCode(StrEnum):
+ INVALID_LINK = "INVALID_LINK"
+ OUTPUT_EXISTS = "OUTPUT_EXISTS"
+ TRANSFER_BUSY = "TRANSFER_BUSY"
+ DISK_FULL = "DISK_FULL"
+ FILE_ERROR = "FILE_ERROR"
+ OUTDATED = "OUTDATED"
+ START_FAILED = "START_FAILED"
+ ENGINE_EXITED = "ENGINE_EXITED"
+ INTERNAL = "INTERNAL"
+
+
+class Error(Exception):
+ def __init__(self, code: ErrorCode, message: str) -> None:
+ super().__init__(f"{code}: {message}")
+ self.code = code
+ self.message = message
diff --git a/features/ed2k_pack/kelpie/kelpie.py b/features/ed2k_pack/kelpie/kelpie.py
new file mode 100644
index 00000000..44ca7866
--- /dev/null
+++ b/features/ed2k_pack/kelpie/kelpie.py
@@ -0,0 +1,386 @@
+import asyncio
+import json
+import logging
+import re
+from collections.abc import AsyncIterator, Callable
+from contextlib import AbstractAsyncContextManager, asynccontextmanager, suppress
+from dataclasses import dataclass, field
+from itertools import count
+from pathlib import Path
+from typing import Any
+
+from .errors import Error, ErrorCode
+from .models import Link, Network, Progress, Settings, Source
+
+PROTOCOL = 1
+MIN_ENGINE_VERSION = (0, 1, 0)
+CLOSE_TIMEOUT = 15
+HANDSHAKE_TIMEOUT = 30
+STREAM_LIMIT = 4 * 1024 * 1024
+VERSION_PATTERN = re.compile(r"v?(\d+)\.(\d+)\.(\d+)")
+
+logger = logging.getLogger(__name__)
+
+
+class Run:
+ def __init__(self, id: int) -> None:
+ self._id = id
+ # Only the newest Progress: a slow consumer skips the stale ones.
+ self._progress: Progress | None = None
+ # Kept apart from _error, because a normal end has no error.
+ self._isEnded = False
+ self._error: BaseException | None = None
+ # An Event, not a queue: repeated set() calls collapse into one wake-up.
+ self._changed = asyncio.Event()
+
+ async def __aiter__(self) -> AsyncIterator[Progress]:
+ while True:
+ await self._changed.wait()
+ self._changed.clear()
+ progress, self._progress = self._progress, None
+ if progress is not None:
+ yield progress
+ if self._isEnded:
+ if self._error is not None:
+ raise self._error
+ return
+
+ def _setProgress(self, progress: Progress) -> None:
+ if self._isEnded:
+ return
+ self._progress = progress
+ self._changed.set()
+
+ def _setEnded(self, error: BaseException | None) -> None:
+ if self._isEnded:
+ return
+ self._isEnded = True
+ self._error = error
+ self._changed.set()
+
+ def _cancel(self) -> None:
+ # Ended by someone other than its caller: a normal end would read as a
+ # finished download, so the caller sees a cancellation instead.
+ if not self._isEnded:
+ self._progress = None
+ self._setEnded(asyncio.CancelledError())
+
+
+@dataclass
+class EngineProcess:
+ process: asyncio.subprocess.Process
+ # The Runs this process still owes an `ended`, by run id because a stopped
+ # download must not end the seed that follows it. Whoever pops a Run ends
+ # it, and the `ended` that follows finds no route.
+ routes: dict[int, Run] = field(default_factory=dict)
+
+
+class Kelpie:
+ def __init__(
+ self,
+ executable: Callable[[], Path],
+ dataFolder: Path,
+ settings: Callable[[], Settings],
+ onNetwork: Callable[[Network | None], None] = lambda _: None,
+ ) -> None:
+ self._executable = executable
+ self._dataFolder = dataFolder
+ self._settings = settings
+ self._onNetwork = onNetwork
+ # None again once the process exits: only the next call starts another.
+ self._engine: EngineProcess | None = None
+ # Callers that arrive during a start wait for it instead of starting
+ # a second Engine Process.
+ self._starting: asyncio.Task[None] | None = None
+ # By hash and across Engine Process restarts: a Transfer has one open
+ # Run even while no Engine Process runs.
+ self._runs: dict[str, Run] = {}
+ # Never reused, so an id stays unique within every Engine Process.
+ self._runIds = count(1)
+ # The event loop keeps only weak references to tasks, and close() waits
+ # for them.
+ self._tasks: set[asyncio.Task[None]] = set()
+
+ def runDownload(self, link: Link, file: Path) -> AbstractAsyncContextManager[Run]:
+ return self._run("download", link, file)
+
+ def runSeed(self, link: Link, file: Path) -> AbstractAsyncContextManager[Run]:
+ return self._run("seed", link, file)
+
+ def update(self) -> None:
+ if self._engine is not None:
+ send(self._engine.process, {"type": "update", **toMessageFields(self._settings())})
+
+ def isActive(self, hash: str) -> bool:
+ return hash in self._runs
+
+ async def remove(self, hash: str) -> None:
+ run = self._runs.get(hash)
+ engine = self._engine
+ if run is not None and engine is not None and engine.routes.pop(run._id, None) is not None:
+ run._cancel()
+ await self._start()
+ if self._engine is not None:
+ send(self._engine.process, {"type": "remove", "hash": hash})
+
+ async def close(self) -> None:
+ if self._starting is not None:
+ with suppress(Error):
+ await asyncio.shield(self._starting)
+ engine = self._engine
+ if engine is None:
+ return
+ self._engine = None
+ for run in engine.routes.values():
+ run._cancel()
+ process = engine.process
+ process.stdin.close()
+ try:
+ async with asyncio.timeout(CLOSE_TIMEOUT):
+ await process.wait()
+ except TimeoutError:
+ process.kill()
+ await process.wait()
+ await asyncio.gather(*self._tasks)
+
+ @asynccontextmanager
+ async def _run(self, mode: str, link: Link, file: Path) -> AsyncIterator[Run]:
+ if link.hash in self._runs:
+ raise Error(ErrorCode.TRANSFER_BUSY, f"a Run is already open for {link.hash}")
+ run = Run(next(self._runIds))
+ self._runs[link.hash] = run
+ try:
+ try:
+ await self._start()
+ except Error as error:
+ run._setEnded(error)
+ else:
+ if self._engine is None:
+ run._setEnded(Error(ErrorCode.ENGINE_EXITED, "Engine Process exited"))
+ else:
+ self._engine.routes[run._id] = run
+ send(
+ self._engine.process,
+ {
+ "type": "run",
+ "run": run._id,
+ "mode": mode,
+ "link": str(link),
+ "file": str(file),
+ },
+ )
+ yield run
+ finally:
+ del self._runs[link.hash]
+ engine = self._engine
+ if engine is not None and engine.routes.pop(run._id, None) is not None:
+ send(engine.process, {"type": "stop", "run": run._id})
+
+ async def _start(self) -> None:
+ if self._engine is not None:
+ return
+ if self._starting is None:
+ self._starting = asyncio.create_task(self._createProcess())
+ await asyncio.shield(self._starting)
+
+ async def _createProcess(self) -> None:
+ try:
+ executable = self._executable()
+ settings = self._settings()
+ try:
+ process = await asyncio.create_subprocess_exec(
+ executable,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ limit=STREAM_LIMIT,
+ )
+ except OSError as error:
+ raise Error(
+ ErrorCode.START_FAILED, f"cannot start {executable}: {error}"
+ ) from error
+ send(process, buildHello(self._dataFolder, settings))
+ ready: asyncio.Future[None] = asyncio.get_running_loop().create_future()
+ task = asyncio.create_task(self._supervise(process, ready))
+ self._tasks.add(task)
+ task.add_done_callback(self._tasks.discard)
+ await ready
+ # An update() during the handshake found no Engine Process.
+ if self._settings() != settings:
+ self.update()
+ finally:
+ self._starting = None
+
+ async def _supervise(
+ self, process: asyncio.subprocess.Process, ready: asyncio.Future[None]
+ ) -> None:
+ lastStderrLine = asyncio.create_task(parseLastLine(process.stderr))
+ try:
+ isReady = await runHandshake(process)
+ except Error as error:
+ process.stdin.close()
+ await lastStderrLine
+ await process.wait()
+ ready.set_exception(error)
+ return
+ engine = EngineProcess(process)
+ if isReady:
+ self._engine = engine
+ ready.set_result(None)
+ while line := await process.stdout.readline():
+ network = onMessage(engine, line)
+ # After close() the old process may still report until it
+ # exits, and a new one may already run.
+ if network is not None and self._engine is engine:
+ self._onNetwork(network)
+ lastLine = await lastStderrLine
+ exitCode = await process.wait()
+ reason = lastLine if lastLine is not None else f"exit code {exitCode}"
+ if not isReady:
+ ready.set_exception(
+ Error(ErrorCode.START_FAILED, f"Engine Process exited during startup: {reason}")
+ )
+ return
+ # Unless a newer Engine Process already runs, none does now.
+ if self._engine is engine or self._engine is None:
+ self._engine = None
+ self._onNetwork(None)
+ exited = Error(ErrorCode.ENGINE_EXITED, reason)
+ for run in engine.routes.values():
+ run._setEnded(exited)
+
+
+def onMessage(engine: EngineProcess, line: bytes) -> Network | None:
+ try:
+ message = json.loads(line)
+ match message.get("type"):
+ case "progress":
+ run = engine.routes.get(message["run"])
+ if run is not None:
+ run._setProgress(parseProgress(message))
+ case "ended":
+ run = engine.routes.pop(message["run"], None)
+ if run is not None:
+ run._setEnded(parseError(message["error"]))
+ case "network":
+ return parseNetwork(message)
+ except (ValueError, KeyError, TypeError, AttributeError) as error:
+ logger.warning("ignored invalid Engine Process message %r: %s", line, error)
+ return None
+
+
+def send(process: asyncio.subprocess.Process, message: dict[str, Any]) -> None:
+ process.stdin.write(json.dumps(message, separators=(",", ":")).encode() + b"\n")
+
+
+def buildHello(dataFolder: Path, settings: Settings) -> dict[str, Any]:
+ return {
+ "type": "hello",
+ "protocol": PROTOCOL,
+ "dataFolder": str(dataFolder),
+ **toMessageFields(settings),
+ }
+
+
+def toMessageFields(settings: Settings) -> dict[str, Any]:
+ return {
+ "settings": {
+ "port": settings.port,
+ "enableKad": settings.enableKad,
+ "enableUpnp": settings.enableUpnp,
+ "serverLists": [str(path) for path in settings.serverLists],
+ "nodeLists": [str(path) for path in settings.nodeLists],
+ "traceFile": str(settings.traceFile) if settings.traceFile is not None else "",
+ },
+ "rateLimits": {"download": settings.downloadRateLimit, "upload": settings.uploadRateLimit},
+ }
+
+
+async def runHandshake(process: asyncio.subprocess.Process) -> bool:
+ try:
+ async with asyncio.timeout(HANDSHAKE_TIMEOUT):
+ line = await process.stdout.readline()
+ except TimeoutError:
+ process.kill()
+ raise Error(
+ ErrorCode.START_FAILED,
+ f"Engine Process did not answer hello within {HANDSHAKE_TIMEOUT} s",
+ ) from None
+ if not line:
+ return False
+ parseHandshake(line)
+ return True
+
+
+def parseHandshake(line: bytes) -> None:
+ try:
+ message = json.loads(line)
+ if message["type"] == "failed":
+ raise Error(ErrorCode.START_FAILED, message["error"]["message"])
+ if message["type"] != "ready":
+ raise Error(ErrorCode.START_FAILED, f"unexpected handshake: {line!r}")
+ version = message["version"]
+ except (ValueError, KeyError, TypeError) as error:
+ raise Error(ErrorCode.START_FAILED, f"invalid handshake {line!r}: {error}") from error
+ if matchOutdated(version):
+ required = ".".join(map(str, MIN_ENGINE_VERSION))
+ raise Error(ErrorCode.OUTDATED, f"Engine Process {version} is older than v{required}")
+
+
+def matchOutdated(version: str) -> bool:
+ parsed = VERSION_PATTERN.match(version)
+ return parsed is not None and tuple(map(int, parsed.groups())) < MIN_ENGINE_VERSION
+
+
+def parseProgress(message: dict[str, Any]) -> Progress:
+ return Progress(
+ hash=message["hash"],
+ size=message["size"],
+ received=message["received"],
+ downloadRate=message["downloadRate"],
+ uploadRate=message["uploadRate"],
+ uploaded=message["uploaded"],
+ peers=message["peers"],
+ activePeers=message["activePeers"],
+ heldSources=message["heldSources"],
+ heldUntil=message["heldUntil"],
+ sources=tuple(parseSource(source) for source in message["sources"]),
+ )
+
+
+def parseSource(message: dict[str, Any]) -> Source:
+ return Source(
+ address=message["address"],
+ software=message["software"],
+ status=message["status"],
+ rank=message["rank"],
+ downloadRate=message["downloadRate"],
+ channel=message["channel"],
+ )
+
+
+def parseNetwork(message: dict[str, Any]) -> Network:
+ return Network(
+ isServerConnected=message["isServerConnected"],
+ isHighId=message["isHighId"],
+ isKadFirewalled=message["isKadFirewalled"],
+ kadNodes=message["kadNodes"],
+ isBehindCarrierNat=message["isBehindCarrierNat"],
+ )
+
+
+def parseError(error: dict[str, Any] | None) -> Error | None:
+ if error is None:
+ return None
+ try:
+ code = ErrorCode(error["code"])
+ except ValueError:
+ code = ErrorCode.INTERNAL
+ return Error(code, error["message"])
+
+
+async def parseLastLine(stream: asyncio.StreamReader) -> str | None:
+ lastLine = None
+ while line := await stream.readline():
+ lastLine = line.decode(errors="replace").rstrip()
+ return lastLine
diff --git a/features/ed2k_pack/kelpie/models.py b/features/ed2k_pack/kelpie/models.py
new file mode 100644
index 00000000..b024d029
--- /dev/null
+++ b/features/ed2k_pack/kelpie/models.py
@@ -0,0 +1,93 @@
+import re
+from dataclasses import dataclass
+from pathlib import Path
+from urllib.parse import quote, unquote
+
+from .errors import Error, ErrorCode
+
+HASH_PATTERN = re.compile(r"[0-9A-Fa-f]{32}")
+SIZE_PATTERN = re.compile(r"[0-9]+")
+SCHEME = "ed2k://"
+# eMule's MAX_EMULE_FILE_SIZE
+MAX_SIZE = 256 << 30
+
+
+@dataclass(frozen=True, slots=True)
+class Link:
+ name: str
+ size: int
+ hash: str
+
+ @staticmethod
+ def parse(text: str) -> "Link":
+ text = text.strip()
+ if text[: len(SCHEME)].lower() != SCHEME:
+ raise Error(ErrorCode.INVALID_LINK, f"not an eD2k link: {text}")
+ body = text[len(SCHEME) :]
+ # Browsers may encode every separator, as aMule's TextClient.cpp:537-540
+ # repairs. Only such a link is decoded: in a plain link %7C is part of
+ # the name.
+ if body[:3].lower() == "%7c":
+ body = body.replace("%7C", "|").replace("%7c", "|")
+ fields = body.split("|")
+ if len(fields) < 5 or fields[0] != "" or fields[1].lower() != "file":
+ raise Error(ErrorCode.INVALID_LINK, f"not an eD2k file link: {text}")
+ name, size, hash = unquote(fields[2]), fields[3], fields[4]
+ if not name:
+ raise Error(ErrorCode.INVALID_LINK, f"link has no name: {text}")
+ if not SIZE_PATTERN.fullmatch(size) or not 0 < int(size) <= MAX_SIZE:
+ raise Error(ErrorCode.INVALID_LINK, f"link has an invalid size: {text}")
+ if not HASH_PATTERN.fullmatch(hash):
+ raise Error(ErrorCode.INVALID_LINK, f"link has an invalid hash: {text}")
+ return Link(name, int(size), hash.upper())
+
+ def __str__(self) -> str:
+ return f"ed2k://|file|{quote(self.name, safe='')}|{self.size}|{self.hash}|/"
+
+
+@dataclass(frozen=True, slots=True)
+class Settings:
+ port: int = 0
+ enableKad: bool = True
+ enableUpnp: bool = True
+ serverLists: tuple[Path, ...] = ()
+ nodeLists: tuple[Path, ...] = ()
+ traceFile: Path | None = None
+ downloadRateLimit: int = 0
+ uploadRateLimit: int = 0
+
+
+@dataclass(frozen=True, slots=True)
+class Source:
+ """One source in Progress.sources; docs/protocol.md "progress" describes the fields."""
+
+ address: str
+ software: str
+ status: str
+ rank: int
+ downloadRate: int
+ channel: str
+
+
+@dataclass(frozen=True, slots=True)
+class Progress:
+ hash: str
+ size: int
+ received: int
+ downloadRate: int
+ uploadRate: int
+ uploaded: int
+ peers: int
+ activePeers: int
+ heldSources: int
+ heldUntil: int
+ sources: tuple[Source, ...]
+
+
+@dataclass(frozen=True, slots=True)
+class Network:
+ isServerConnected: bool
+ isHighId: bool
+ isKadFirewalled: bool
+ kadNodes: int
+ isBehindCarrierNat: bool
diff --git a/features/ed2k_pack/pack.py b/features/ed2k_pack/pack.py
index e8195d21..4bf00c46 100644
--- a/features/ed2k_pack/pack.py
+++ b/features/ed2k_pack/pack.py
@@ -1,16 +1,24 @@
from __future__ import annotations
import asyncio
+from collections.abc import Callable
+from pathlib import Path
+from app.config.paths import APP_DATA_DIR
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 .config import ed2kConfig, kelpieRuntime
+from .kelpie import Error, Kelpie, Link, Network
from .lists import nodeList, serverList
-from .session import parseEd2kLink
+from .session import buildSettings, ed2kSession, toTaskError
from .task import ED2kTask, ED2kTaskStep
+def createKelpie(onNetwork: Callable[[Network | None], None]) -> Kelpie:
+ return Kelpie(lambda: Path(kelpieRuntime.path()), APP_DATA_DIR / "ed2k_data", buildSettings, onNetwork)
+
+
class ED2kParser(TaskParser):
priority = 45
@@ -18,20 +26,20 @@ class ED2kParser(TaskParser):
return options.url.strip().lower().startswith("ed2k://")
async def parse(self, options: TaskOptions) -> Task:
- link = options.url.strip()
- name, fileSize, fileHash = parseEd2kLink(link)
- from .session import ed2kSession
-
- if ed2kSession.hasActiveTransfer(fileHash, fileSize):
- raise TaskError("该 eD2k 链接已在下载中")
- name = toSafeFilename(name, fallback="ed2k_download")
+ url = options.url.strip()
+ try:
+ link = Link.parse(url)
+ except Error as error:
+ raise toTaskError(error) from error
task = ED2kTask(
- name=name,
- url=link,
- fileSize=fileSize,
+ name=toSafeFilename(link.name, fallback="ed2k_download"),
+ url=url,
+ fileSize=link.size,
outputFolder=options.outputFolder,
)
+ if ed2kSession.isActive(task):
+ raise TaskError("该 eD2k 链接已在下载中")
task.addStep(ED2kTaskStep(stepIndex=1))
return task
@@ -41,24 +49,29 @@ class ED2kPack(FeaturePack):
config = ed2kConfig
parsers = [ED2kParser]
+ def __init__(self, services):
+ super().__init__(services)
+ ed2kSession.open(services.coroutineRunner, createKelpie)
+
def taskCardClass(self, task: Task) -> type | None:
from .cards import ED2kTaskCard
return ED2kTaskCard
+ def detailCards(self, task, parent=None):
+ from .detail_cards import ED2kCard, ED2kSourceCard
+ return [ED2kCard(task, parent), ED2kSourceCard(task, parent)]
+
def uriSchemes(self) -> list[UriScheme]:
return [UriScheme("ed2k", "eD2k")]
def runtimes(self):
- return [ed2kRuntime]
+ return [kelpieRuntime]
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
await ed2kSession.close()
diff --git a/features/ed2k_pack/python_ed2k/__init__.py b/features/ed2k_pack/python_ed2k/__init__.py
deleted file mode 100644
index 738568e5..00000000
--- a/features/ed2k_pack/python_ed2k/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from .client import Client
-from .errors import EngineExited, Error, ErrorCode, ProtocolError
-from .models import Settings, Snapshot, Transfer, TransferState
-
-__all__ = [
- "Client",
- "EngineExited",
- "Error",
- "ErrorCode",
- "ProtocolError",
- "Settings",
- "Snapshot",
- "Transfer",
- "TransferState",
-]
diff --git a/features/ed2k_pack/python_ed2k/client.py b/features/ed2k_pack/python_ed2k/client.py
deleted file mode 100644
index 299f4075..00000000
--- a/features/ed2k_pack/python_ed2k/client.py
+++ /dev/null
@@ -1,325 +0,0 @@
-import asyncio
-import json
-from collections import deque
-from collections.abc import AsyncIterator, Mapping
-from pathlib import Path
-from typing import Any
-
-from .errors import EngineExited, Error, ErrorCode, ProtocolError
-from .models import Settings, Snapshot, Transfer, TransferState
-
-
-RPC_VERSION = 1
-STREAM_LIMIT = 4 * 1024 * 1024
-
-
-class Client:
- def __init__(self, executable: Path, dataDir: Path) -> None:
- self._executable = executable
- self._dataDir = dataDir
- self._loop: asyncio.AbstractEventLoop | None = None
- self._process: asyncio.subprocess.Process | None = None
- self._writeLock: asyncio.Lock | None = None
- self._pending: dict[int, asyncio.Future[Any]] = {}
- self._tasks: set[asyncio.Task[None]] = set()
- self._nextId = 1
- self._stderr: deque[str] = deque(maxlen=20)
- self._closing = False
- self._stopped = True
- self._latest: Snapshot | None = None
- self._snapshotVersion = 0
- self._snapshotCondition = asyncio.Condition()
- self._exitError: Error | None = None
-
- @property
- def isRunning(self) -> bool:
- process = self._process
- return process is not None and process.returncode is None and not self._stopped
-
- async def start(self, settings: Settings = Settings()) -> Snapshot:
- loop = asyncio.get_running_loop()
- if self._loop is None:
- self._loop = loop
- elif self._loop is not loop:
- raise Error(ErrorCode.INVALID_REQUEST, "Client is bound to another event loop")
- if self._process is not None and self._process.returncode is None:
- raise Error(ErrorCode.INVALID_REQUEST, "Client is already running")
-
- self._writeLock = asyncio.Lock()
- self._stderr.clear()
- self._closing = False
- self._latest = None
- self._exitError = None
- try:
- process = await asyncio.create_subprocess_exec(
- self._executable,
- stdin=asyncio.subprocess.PIPE,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- limit=STREAM_LIMIT,
- )
- except OSError as error:
- raise Error(ErrorCode.INVALID_REQUEST, f"cannot start goed2kd: {error}") from error
- self._process = process
- self._stopped = False
- for coroutine in (
- self._readStdout(process),
- self._readStderr(process),
- self._watchProcess(process),
- ):
- task = asyncio.create_task(coroutine)
- self._tasks.add(task)
- task.add_done_callback(self._tasks.discard)
-
- try:
- current = _toSnapshot(
- await self._request(
- "start",
- {
- "dataDir": str(self._dataDir),
- "settings": _toSettings(settings),
- },
- )
- )
- except asyncio.CancelledError:
- await self.terminate()
- raise
- except Exception:
- await self.terminate()
- raise
- await self._publish(current)
- return current
-
- async def snapshot(self) -> Snapshot:
- current = _toSnapshot(await self._request("snapshot"))
- await self._publish(current)
- return current
-
- async def snapshots(self) -> AsyncIterator[Snapshot]:
- version = -1
- while True:
- async with self._snapshotCondition:
- await self._snapshotCondition.wait_for(
- lambda: self._snapshotVersion != version
- or self._exitError is not None
- or self._stopped
- )
- if self._exitError is not None:
- raise self._exitError
- if self._stopped and self._snapshotVersion == version:
- return
- current = self._latest
- version = self._snapshotVersion
- if current is not None:
- yield current
-
- async def addLink(self, link: str, outputDir: Path) -> Transfer:
- return _toTransfer(
- await self._request("addLink", {"link": link, "outputDir": str(outputDir)})
- )
-
- async def pause(self, hash: str) -> Transfer:
- return _toTransfer(await self._request("pause", {"hash": hash}))
-
- async def resume(self, hash: str) -> Transfer:
- return _toTransfer(await self._request("resume", {"hash": hash}))
-
- async def remove(self, hash: str, deleteFile: bool = False) -> None:
- await self._request("remove", {"hash": hash, "deleteFile": deleteFile})
-
- async def close(self) -> None:
- process = self._process
- if process is None or process.returncode is not None:
- return
- self._closing = True
- if process.stdin is not None and self._writeLock is not None:
- requestId = self._nextId
- self._nextId += 1
- message = json.dumps(
- {"version": RPC_VERSION, "id": requestId, "method": "close", "params": {}},
- separators=(",", ":"),
- ).encode() + b"\n"
- try:
- async with self._writeLock:
- process.stdin.write(message)
- await process.stdin.drain()
- except (BrokenPipeError, ConnectionResetError):
- pass
- try:
- await asyncio.wait_for(process.wait(), timeout=15)
- except asyncio.TimeoutError:
- try:
- process.kill()
- except ProcessLookupError:
- pass
- await process.wait()
- await self._setStopped(process)
- if self._process is process:
- self._process = None
-
- async def terminate(self) -> None:
- if self._loop is not None and self._loop is not asyncio.get_running_loop():
- raise Error(ErrorCode.INVALID_REQUEST, "Client is bound to another event loop")
- process = self._process
- if process is None or process.returncode is not None:
- return
- self._closing = True
- try:
- process.kill()
- except ProcessLookupError:
- pass
- await process.wait()
- await self._setStopped(process)
- if self._process is process:
- self._process = None
-
- async def _request(self, method: str, params: Mapping[str, Any] | None = None) -> Any:
- if self._loop is not asyncio.get_running_loop():
- raise Error(ErrorCode.INVALID_REQUEST, "Client is bound to another event loop")
- process = self._process
- if process is None or process.returncode is not None or process.stdin is None:
- if self._exitError is not None:
- raise self._exitError
- raise Error(ErrorCode.NOT_RUNNING, "Client is not running")
- if self._writeLock is None:
- raise Error(ErrorCode.NOT_RUNNING, "Client is not running")
-
- requestId = self._nextId
- self._nextId += 1
- future = asyncio.get_running_loop().create_future()
- self._pending[requestId] = future
- request = {
- "version": RPC_VERSION,
- "id": requestId,
- "method": method,
- "params": params or {},
- }
- try:
- try:
- async with self._writeLock:
- process.stdin.write(
- json.dumps(request, separators=(",", ":")).encode() + b"\n"
- )
- await process.stdin.drain()
- except (BrokenPipeError, ConnectionResetError) as error:
- returnCode = process.returncode if process.returncode is not None else -1
- raise EngineExited(returnCode, tuple(self._stderr)) from error
- return await future
- finally:
- self._pending.pop(requestId, None)
-
- async def _readStdout(self, process: asyncio.subprocess.Process) -> None:
- if process.stdout is None:
- return
- while line := await process.stdout.readline():
- try:
- response = json.loads(line)
- if response.get("version") != RPC_VERSION:
- raise ProtocolError("goed2kd returned an unsupported RPC version")
- if response.get("method") == "snapshot" and "id" not in response:
- await self._publish(_toSnapshot(response["params"]))
- continue
- requestId = response["id"]
- future = self._pending.get(requestId)
- if future is None or future.done():
- continue
- if failure := response.get("error"):
- code = ErrorCode(failure["code"])
- future.set_exception(Error(code, failure["message"]))
- else:
- future.set_result(response.get("result"))
- except (KeyError, TypeError, ValueError, json.JSONDecodeError, ProtocolError) as error:
- protocolError = (
- error
- if isinstance(error, ProtocolError)
- else ProtocolError(f"invalid goed2kd response: {error}")
- )
- if self._process is process:
- self._exitError = protocolError
- self._failPending(protocolError)
- try:
- process.kill()
- except ProcessLookupError:
- pass
- return
-
- async def _readStderr(self, process: asyncio.subprocess.Process) -> None:
- if process.stderr is None:
- return
- while line := await process.stderr.readline():
- if self._process is process:
- self._stderr.append(line.decode(errors="replace").rstrip())
-
- async def _watchProcess(self, process: asyncio.subprocess.Process) -> None:
- returnCode = await process.wait()
- await self._setStopped(process, EngineExited(returnCode, tuple(self._stderr)))
-
- async def _setStopped(
- self, process: asyncio.subprocess.Process, error: EngineExited | None = None
- ) -> None:
- if self._process is not process:
- return
- if error is not None:
- self._failPending(error)
- if not self._closing and self._exitError is None:
- self._exitError = error
- self._stopped = True
- async with self._snapshotCondition:
- self._snapshotCondition.notify_all()
-
- def _failPending(self, error: Error) -> None:
- for future in self._pending.values():
- if not future.done():
- future.set_exception(error)
-
- async def _publish(self, snapshot: Snapshot) -> None:
- async with self._snapshotCondition:
- self._latest = snapshot
- self._snapshotVersion += 1
- self._snapshotCondition.notify_all()
-
-
-def _toSnapshot(value: Any) -> Snapshot:
- try:
- return Snapshot(
- transfers=tuple(_toTransfer(transfer) for transfer in value["transfers"]),
- serverConnected=value["serverConnected"],
- kadNodes=value["kadNodes"],
- )
- except (KeyError, TypeError, ValueError) as error:
- raise ProtocolError(f"invalid snapshot: {error}") from error
-
-
-def _toSettings(settings: Settings) -> dict[str, Any]:
- return {
- "servers": settings.servers,
- "serverMetSource": settings.serverMetSource or "",
- "dhtNodes": settings.dhtNodes,
- "nodesDatSource": settings.nodesDatSource or "",
- "listenPort": settings.listenPort,
- "udpPort": settings.udpPort,
- "enableDht": settings.enableDht,
- "enableUpnp": settings.enableUpnp,
- "reconnectToServer": settings.reconnectToServer,
- "enableDebugLog": settings.enableDebugLog,
- }
-
-
-def _toTransfer(value: Any) -> Transfer:
- try:
- return Transfer(
- hash=value["hash"],
- name=value["name"],
- path=Path(value["path"]),
- size=value["size"],
- state=TransferState(value["state"]),
- done=value["done"],
- received=value["received"],
- downloadRate=value["downloadRate"],
- uploadRate=value["uploadRate"],
- upload=value["upload"],
- activePeers=value["activePeers"],
- peers=value["peers"],
- )
- except (KeyError, TypeError, ValueError) as error:
- raise ProtocolError(f"invalid transfer: {error}") from error
diff --git a/features/ed2k_pack/python_ed2k/errors.py b/features/ed2k_pack/python_ed2k/errors.py
deleted file mode 100644
index edb3f797..00000000
--- a/features/ed2k_pack/python_ed2k/errors.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from enum import StrEnum
-
-
-class ErrorCode(StrEnum):
- INTERNAL = "INTERNAL"
- INVALID_LINK = "INVALID_LINK"
- INVALID_REQUEST = "INVALID_REQUEST"
- NOT_RUNNING = "NOT_RUNNING"
- OUTPUT_EXISTS = "OUTPUT_EXISTS"
- TRANSFER_EXISTS = "TRANSFER_EXISTS"
- TRANSFER_NOT_FOUND = "TRANSFER_NOT_FOUND"
-
-
-class Error(Exception):
- def __init__(self, code: ErrorCode, message: str) -> None:
- super().__init__(message)
- self.code = code
- self.message = message
-
-
-class EngineExited(Error):
- def __init__(self, returnCode: int, stderr: tuple[str, ...]) -> None:
- message = f"goed2kd exited with code {returnCode}"
- if stderr:
- message = f"{message}: {stderr[-1]}"
- super().__init__(ErrorCode.NOT_RUNNING, message)
- self.returnCode = returnCode
- self.stderr = stderr
-
-
-class ProtocolError(Error):
- def __init__(self, message: str) -> None:
- super().__init__(ErrorCode.INVALID_REQUEST, message)
diff --git a/features/ed2k_pack/python_ed2k/models.py b/features/ed2k_pack/python_ed2k/models.py
deleted file mode 100644
index 50c7b16a..00000000
--- a/features/ed2k_pack/python_ed2k/models.py
+++ /dev/null
@@ -1,48 +0,0 @@
-from dataclasses import dataclass
-from enum import StrEnum
-from pathlib import Path
-
-
-class TransferState(StrEnum):
- LOADING_RESUME_DATA = "LOADING_RESUME_DATA"
- DOWNLOADING = "DOWNLOADING"
- PAUSED = "PAUSED"
- VERIFYING = "VERIFYING"
- FINISHED = "FINISHED"
-
-
-@dataclass(frozen=True, slots=True)
-class Settings:
- servers: tuple[str, ...] = ()
- serverMetSource: str | None = None
- dhtNodes: tuple[str, ...] = ()
- nodesDatSource: str | None = None
- listenPort: int = 0
- udpPort: int = 0
- enableDht: bool = True
- enableUpnp: bool = True
- reconnectToServer: bool = True
- enableDebugLog: bool = False
-
-
-@dataclass(frozen=True, slots=True)
-class Transfer:
- hash: str
- name: str
- path: Path
- size: int
- state: TransferState
- done: int
- received: int
- downloadRate: int
- uploadRate: int
- upload: int
- activePeers: int
- peers: int
-
-
-@dataclass(frozen=True, slots=True)
-class Snapshot:
- transfers: tuple[Transfer, ...]
- serverConnected: bool
- kadNodes: int
diff --git a/features/ed2k_pack/session.py b/features/ed2k_pack/session.py
index 3729dcef..4b447bdb 100644
--- a/features/ed2k_pack/session.py
+++ b/features/ed2k_pack/session.py
@@ -1,258 +1,182 @@
from __future__ import annotations
import asyncio
-from collections.abc import Callable
-from dataclasses import dataclass
-from pathlib import Path
-from urllib.parse import quote, unquote
+import math
+from collections.abc import AsyncIterator, Callable
+from contextlib import aclosing, asynccontextmanager
+from typing import TYPE_CHECKING
-from loguru import logger
-
-from app.config.paths import APP_DATA_DIR
+from app.config.cfg import cfg
from app.models.task import TaskError
-from app.update import parseVersion
-from .config import ed2kConfig, ed2kRuntime
+from app.signal import Signal
+from .config import ed2kConfig, kelpieRuntime
+from .kelpie import Error, ErrorCode, Kelpie, Link, Network, Progress, Run, Settings
from .lists import nodeList, serverList
-from .python_ed2k import Client, Settings, Transfer, TransferState
-from .python_ed2k.errors import ErrorCode, Error
-
-MIN_GOED2KD_VERSION = (0, 2, 4)
+if TYPE_CHECKING:
+ from app.services.coroutine_runner import CoroutineRunner
+ from .task import ED2kTask
-@dataclass(frozen=True)
-class NetworkStatus:
- isServerConnected: bool
- kadNodes: int
+LIVE_SETTINGS = (
+ cfg.isSpeedLimitEnabled, cfg.speedLimitation,
+ ed2kConfig.uploadRateLimit, ed2kConfig.enableKad, ed2kConfig.enableUpnp,
+)
-@dataclass(frozen=True)
-class RunResult:
- fileHash: str
- name: str
- fileSize: int
+def buildSettings() -> Settings:
+ return Settings(
+ port=ed2kConfig.listenPort.value,
+ enableKad=ed2kConfig.enableKad.value,
+ enableUpnp=ed2kConfig.enableUpnp.value,
+ serverLists=tuple(serverList.paths()),
+ nodeLists=tuple(nodeList.paths()),
+ downloadRateLimit=cfg.speedLimitation.value if cfg.isSpeedLimitEnabled.value else 0,
+ uploadRateLimit=ed2kConfig.uploadRateLimit.value,
+ )
class ED2kSession:
+ networkChanged = Signal()
+ runsChanged = Signal()
def __init__(self):
- self._client: Client | None = None
- self._openLock = asyncio.Lock()
- self._activeTransfers: set[tuple[str, int]] = set()
- self.submit = None
-
- def hasActiveTransfer(self, fileHash: str, fileSize: int) -> bool:
- return toTransferKey(fileHash, fileSize) in self._activeTransfers
-
- async def run(
- self,
- link: str,
- fileHash: str,
- name: str,
- outputFolder: Path,
- uploadedBytes: int,
- onStarted: Callable[[RunResult], None],
- onProgress: Callable[[Transfer, int], None],
+ self._runner: CoroutineRunner | None = None
+ self._kelpie: Kelpie | None = None
+ self._progresses: dict[str, Progress] = {}
+ self._network: Network | None = None
+ self._openRunCount = 0
+ self._stopping: asyncio.Task[None] | None = None
+ self._removals: set[asyncio.Task] = set()
+
+ def open(
+ self, coroutineRunner: CoroutineRunner, createKelpie: Callable[[Callable[[Network | None], None]], Kelpie],
) -> None:
- _, linkSize, linkHash = parseEd2kLink(link)
- identity = toTransferKey(linkHash, linkSize)
- if identity in self._activeTransfers:
- raise TaskError("该 eD2k 链接已在下载中")
- self._activeTransfers.add(identity)
+ self._runner = coroutineRunner
+ self._kelpie = createKelpie(self._onNetwork)
+ for item in LIVE_SETTINGS:
+ item.valueChanged.connect(self._onSettingsChanged)
- try:
- await self._open()
- client = self._client
-
- wasCancelled = False
- if fileHash:
- transfer = await client.resume(fileHash)
- else:
- try:
- addTask = asyncio.create_task(
- client.addLink(buildEd2kLink(link, name), outputFolder)
- )
- try:
- transfer = await asyncio.shield(addTask)
- except asyncio.CancelledError:
- wasCancelled = True
- transfer = await asyncio.wait_for(addTask, timeout=15)
- except Error as e:
- if e.code == ErrorCode.TRANSFER_EXISTS:
- transfer = await client.resume(linkHash.upper())
- elif e.code == ErrorCode.OUTPUT_EXISTS:
- raise TaskError("goed2kd 版本过旧,请在设置中更新") from e
- elif wasCancelled:
- raise asyncio.CancelledError() from e
- else:
- raise TaskError("ED2k 错误:{detail}", detail=str(e)) from e
-
- fileHash = transfer.hash
- onStarted(RunResult(
- fileHash=fileHash,
- name=transfer.name or name,
- fileSize=transfer.size,
- ))
- if wasCancelled:
- raise asyncio.CancelledError()
-
- firstUpload = None
- async for snapshot in client.snapshots():
- for t in snapshot.transfers:
- if t.hash != fileHash:
- continue
- if firstUpload is None:
- firstUpload = t.upload
- onProgress(t, uploadedBytes + t.upload - firstUpload)
- if t.state == TransferState.FINISHED:
- await client.pause(fileHash)
- return
- break
- raise asyncio.CancelledError()
- except asyncio.CancelledError:
- if fileHash and self._client is not None:
- try:
- await self._client.pause(fileHash)
- except Exception as e:
- logger.opt(exception=e).warning("暂停 eD2k 传输失败")
- raise
- finally:
- self._activeTransfers.discard(identity)
-
- async def runSeeding(
- self,
- link: str,
- fileHash: str,
- seedingTimeSeconds: int,
- uploadedBytes: int,
- isManual: bool,
- onProgress: Callable[[Transfer, int, int], None],
- ) -> None:
- _, linkSize, linkHash = parseEd2kLink(link)
- identity = toTransferKey(linkHash, linkSize)
- if identity in self._activeTransfers:
- raise TaskError("该 eD2k 链接已在下载中")
- self._activeTransfers.add(identity)
+ @property
+ def network(self) -> Network | None:
+ return self._network
- try:
- await self._open()
- client = self._client
- await client.resume(fileHash)
- loop = asyncio.get_running_loop()
- seedingStart = loop.time() - seedingTimeSeconds
- firstUpload = None
- async for snapshot in client.snapshots():
- for t in snapshot.transfers:
- if t.hash != fileHash:
- continue
- if firstUpload is None:
- firstUpload = t.upload
- elapsed = int(loop.time() - seedingStart)
- uploaded = uploadedBytes + t.upload - firstUpload
- onProgress(t, elapsed, uploaded)
- if not isManual and isSeedingLimitReached(elapsed, uploaded, t.size):
- await client.pause(fileHash)
- return
- break
+ @property
+ def isIdle(self) -> bool:
+ return self._openRunCount == 0
+
+ def progressOf(self, task: ED2kTask) -> Progress | None:
+ return self._progresses.get(task.taskId)
+
+ def isActive(self, task: ED2kTask) -> bool:
+ return self._kelpie is not None and self._kelpie.isActive(Link.parse(task.url).hash)
+
+ @asynccontextmanager
+ async def run(self, task: ED2kTask, isSeed: bool) -> AsyncIterator[AsyncIterator[Progress]]:
+ if self._kelpie is None:
raise asyncio.CancelledError()
- except asyncio.CancelledError:
- if self._client is not None:
- try:
- await self._client.pause(fileHash)
- except Exception as e:
- logger.opt(exception=e).warning("暂停 eD2k 做种失败")
- raise
+ if not kelpieRuntime.path():
+ raise TaskError("{name} 未安装,请在设置中安装", name=kelpieRuntime.name)
+ start = self._kelpie.runSeed if isSeed else self._kelpie.runDownload
+ self._openRunCount += 1
+ self._runner.post(self.runsChanged.emit)
+ try:
+ if self._stopping is not None:
+ await asyncio.shield(self._stopping)
+ async with start(Link.parse(task.url), task.outputFolder / task.name) as transfer:
+ async with aclosing(self._record(task.taskId, transfer)) as recorded:
+ yield recorded
+ except Error as error:
+ raise toTaskError(error) from error
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)
+ self._progresses.pop(task.taskId, None)
+ self._openRunCount -= 1
+ self._runner.post(self.runsChanged.emit)
- def remove(self, fileHash: str) -> None:
- if self.submit is None:
+ def delete(self, task: ED2kTask) -> None:
+ if not kelpieRuntime.path():
return
- self.submit(self._remove(fileHash))
-
- async def _remove(self, fileHash: str) -> None:
- await self._open()
+ kelpie = self._kelpie
+ hash = Link.parse(task.url).hash
+
+ async def remove():
+ removal = asyncio.current_task()
+ self._removals.add(removal)
+ try:
+ if self._stopping is not None:
+ await asyncio.shield(self._stopping)
+ await kelpie.remove(hash)
+ finally:
+ self._removals.discard(removal)
+
+ self._runner.submit(remove())
+
+ async def stop(self) -> None:
+ if not self.isIdle or self._stopping is not None:
+ return
+ self._stopping = asyncio.ensure_future(self._kelpie.close())
try:
- await self._client.remove(fileHash, deleteFile=False)
- except Error as e:
- if e.code != ErrorCode.TRANSFER_NOT_FOUND:
- raise
-
- async def _open(self) -> None:
- async with self._openLock:
- if self._client is not None and self._client.isRunning:
- return
-
- # Dead client caches EngineExited; drop so the next attempt starts fresh.
- self._client = None
-
- path = ed2kRuntime.path()
- if not path:
- raise TaskError(
- "{name} 未安装,请在设置中安装", name=ed2kRuntime.name
- )
- version = parseVersion((await ed2kRuntime.probeVersion()).version)
- if version and version < MIN_GOED2KD_VERSION:
- raise TaskError(
- "{name} 版本过旧,请在设置中更新", name=ed2kRuntime.name
- )
- client = Client(Path(path), APP_DATA_DIR / "ed2k_data")
- await client.start(Settings(
- enableDht=ed2kConfig.enableDht.value,
- enableUpnp=ed2kConfig.enableUpnp.value,
- listenPort=ed2kConfig.listenPort.value,
- serverMetSource=",".join(map(str, serverList.paths())),
- nodesDatSource=",".join(map(str, nodeList.paths())),
- ))
- self._client = client
+ await self._stopping
+ finally:
+ self._stopping = None
async def close(self) -> None:
- async with self._openLock:
- client = self._client
- self._client = None
- if client is not None:
- await client.close()
+ kelpie, self._kelpie = self._kelpie, None
+ if kelpie is None:
+ return
+ for item in LIVE_SETTINGS:
+ item.valueChanged.disconnect(self._onSettingsChanged)
+ if self._removals:
+ await asyncio.wait(self._removals)
+ await kelpie.close()
+
+ async def _record(self, taskId: str, transfer: Run) -> AsyncIterator[Progress]:
+ async for progress in transfer:
+ self._progresses[taskId] = progress
+ yield progress
+
+ def _onNetwork(self, network: Network | None) -> None:
+ self._network = network
+ self._runner.post(self.networkChanged.emit)
+
+ def _onSettingsChanged(self, *_) -> None:
+ kelpie = self._kelpie
+
+ async def update():
+ kelpie.update()
+
+ self._runner.submit(update())
+ self.networkChanged.emit()
+
+
+def toHeldMinutes(progress: Progress | None, now: int) -> int | None:
+ if progress is None or progress.heldSources == 0 or progress.heldUntil <= now:
+ return None
+ remaining = progress.heldUntil - now
+ return 0 if remaining < 60_000 else math.ceil(remaining / 60_000)
+
+
+def toTaskError(error: Error) -> TaskError:
+ name = kelpieRuntime.name
+ match error.code:
+ case ErrorCode.INVALID_LINK:
+ return TaskError("不是有效的 eD2k 链接")
+ case ErrorCode.OUTPUT_EXISTS:
+ return TaskError("目标文件已被占用")
+ case ErrorCode.TRANSFER_BUSY:
+ return TaskError("该 eD2k 链接已在下载中")
+ case ErrorCode.DISK_FULL:
+ return TaskError("磁盘空间不足")
+ case ErrorCode.FILE_ERROR:
+ return TaskError("无法读写文件:{detail}", detail=error.message)
+ case ErrorCode.OUTDATED:
+ return TaskError("{name} 版本过旧,请在设置中更新", name=name)
+ case ErrorCode.START_FAILED:
+ return TaskError("{name} 启动失败:{detail}", name=name, detail=error.message)
+ case ErrorCode.ENGINE_EXITED:
+ return TaskError("{name} 意外退出:{detail}", name=name, detail=error.message)
+ case _:
+ return TaskError("ED2k 错误:{detail}", detail=error.message)
ed2kSession = ED2kSession()
-
-
-def isSeedingLimitReached(elapsed: int, uploaded: int, size: int) -> bool:
- ratioLimit = ed2kConfig.seedingRatioLimit.value
- if ratioLimit > 0 and size > 0 and uploaded * 100 >= ratioLimit * size:
- return True
- timeLimit = ed2kConfig.seedingTimeLimit.value
- return timeLimit > 0 and elapsed >= timeLimit * 60
-
-
-def toTransferKey(fileHash: str, fileSize: int) -> tuple[str, int]:
- return fileHash.upper(), fileSize
-
-
-def parseEd2kLink(link: str) -> tuple[str, int, str]:
- link = link.strip()
- if not link.lower().startswith("ed2k://"):
- raise ValueError("不是有效的 eD2k 链接")
- parts = link.strip("/").split("|")
- if len(parts) < 5 or parts[1].lower() != "file":
- raise ValueError("不支持的 eD2k 链接格式")
- name = unquote(parts[2])
- try:
- size = int(parts[3])
- except ValueError:
- size = 0
- fileHash = parts[4] if len(parts) > 4 else ""
- return name, size, fileHash
-
-
-def buildEd2kLink(link: str, name: str) -> str:
- parts = link.strip().split("|")
- parts[2] = quote(name, safe="")
- return "|".join(parts)
diff --git a/features/ed2k_pack/task.py b/features/ed2k_pack/task.py
index b6d38482..fb9d16c9 100644
--- a/features/ed2k_pack/task.py
+++ b/features/ed2k_pack/task.py
@@ -1,19 +1,17 @@
from __future__ import annotations
+import asyncio
from dataclasses import dataclass
-from app.models.task import Task, TaskError, TaskStep, TaskStatus
-from .python_ed2k import Transfer
+from app.models.task import Task, TaskStep, TaskStatus
+from .config import ed2kConfig
+from .session import ed2kSession
@dataclass(kw_only=True, eq=False)
class ED2kTask(Task):
packId: str = "ed2k"
canSeed = True
- fileHash: str = ""
- activePeerCount: int | None = None
- totalPeerCount: int = 0
- uploadRate: int = 0
uploadedBytes: int = 0
seedingTimeSeconds: int = 0
@@ -22,66 +20,42 @@ class ED2kTask(Task):
return self.uploadedBytes / self.fileSize * 100 if self.fileSize > 0 else 0.0
def reset(self) -> TaskStatus:
- self.fileHash = ""
- self.activePeerCount = None
- self.totalPeerCount = 0
- self.uploadRate = 0
+ ed2kSession.delete(self)
self.uploadedBytes = 0
self.seedingTimeSeconds = 0
return super().reset()
async def runSeeding(self, isManual: bool) -> None:
- from .session import ed2kSession
+ loop = asyncio.get_running_loop()
+ seedingStart = loop.time() - self.seedingTimeSeconds
+ async with ed2kSession.run(self, isSeed=True) as progresses:
+ async for progress in progresses:
+ self.uploadedBytes = progress.uploaded
+ self.seedingTimeSeconds = int(loop.time() - seedingStart)
+ if not isManual and isSeedingLimitReached(self.seedingTimeSeconds, progress.uploaded, progress.size):
+ return
- def onProgress(t: Transfer, elapsed: int, uploaded: int):
- self.uploadRate = t.uploadRate
- self.uploadedBytes = uploaded
- self.activePeerCount = t.activePeers
- self.totalPeerCount = t.peers
- self.seedingTimeSeconds = elapsed
-
- try:
- await ed2kSession.runSeeding(
- self.url, self.fileHash, self.seedingTimeSeconds, self.uploadedBytes,
- isManual, onProgress)
- finally:
- self.uploadRate = 0
-
- def deleteFiles(self):
- if self.fileHash:
- from .session import ed2kSession
- ed2kSession.remove(self.fileHash)
- super().deleteFiles()
+ def deletePlaceholders(self) -> None:
+ ed2kSession.delete(self)
+ super().deletePlaceholders()
@dataclass(kw_only=True)
class ED2kTaskStep(TaskStep):
async def run(self, reportSpeed, waitForSpeedLimit) -> None:
- from .session import RunResult, ed2kSession
-
task: ED2kTask = self.task
-
- def onStarted(result: RunResult):
- if result.name != task.name:
- raise TaskError("该文件已由另一个任务在下载")
- task.fileHash = result.fileHash
- if result.fileSize:
- task.fileSize = result.fileSize
-
- def onProgress(t: Transfer, uploaded: int):
- task.uploadRate = t.uploadRate
- task.uploadedBytes = uploaded
- task.activePeerCount = t.activePeers
- task.totalPeerCount = t.peers
- self.receivedBytes = t.received
- self.speed = t.downloadRate
- reportSpeed(t.downloadRate)
- if t.size > 0:
- task.fileSize = t.size
- self.progress = min(99.9, t.received / t.size * 100)
-
- await ed2kSession.run(
- task.url, task.fileHash, task.name, task.outputFolder, task.uploadedBytes,
- onStarted=onStarted,
- onProgress=onProgress,
- )
+ async with ed2kSession.run(task, isSeed=False) as progresses:
+ async for progress in progresses:
+ task.uploadedBytes = progress.uploaded
+ reportSpeed(max(0, progress.received - self.receivedBytes))
+ self.receivedBytes = progress.received
+ self.speed = progress.downloadRate
+ self.progress = min(99.9, progress.received / progress.size * 100)
+
+
+def isSeedingLimitReached(elapsed: int, uploaded: int, size: int) -> bool:
+ ratioLimit = ed2kConfig.seedingRatioLimit.value
+ if ratioLimit > 0 and size > 0 and uploaded * 100 >= ratioLimit * size:
+ return True
+ timeLimit = ed2kConfig.seedingTimeLimit.value
+ return timeLimit > 0 and elapsed >= timeLimit * 60
diff --git a/scripts/sync_python_ed2k.py b/scripts/sync_python_ed2k.py
deleted file mode 100644
index fadbe9b3..00000000
--- a/scripts/sync_python_ed2k.py
+++ /dev/null
@@ -1,23 +0,0 @@
-#!/usr/bin/env python3
-"""Copy python_ed2k from a Python-eD2k checkout into ed2k_pack, unchanged.
-
-Usage:
- python scripts/sync_python_ed2k.py ~/PycharmProjects/Python-eD2k
-"""
-import shutil
-import sys
-from pathlib import Path
-
-TARGET = Path(__file__).resolve().parent.parent / "features" / "ed2k_pack" / "python_ed2k"
-
-
-def main() -> None:
- source = Path(sys.argv[1]).expanduser() / "python_ed2k"
- if not (source / "client.py").is_file():
- sys.exit(f"Not a Python-eD2k checkout: {source.parent}")
- shutil.rmtree(TARGET)
- shutil.copytree(source, TARGET, ignore=shutil.ignore_patterns("__pycache__"))
-
-
-if __name__ == "__main__":
- main()
diff --git a/tests/test_ed2k_kelpie.py b/tests/test_ed2k_kelpie.py
new file mode 100644
index 00000000..2029fff5
--- /dev/null
+++ b/tests/test_ed2k_kelpie.py
@@ -0,0 +1,284 @@
+import asyncio
+import json
+import os
+import shutil
+import subprocess
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from dataclasses import dataclass
+
+from app.models.task import TaskStatus
+from ed2k_pack.config import ed2kConfig, kelpieRuntime
+from ed2k_pack.kelpie import Kelpie, Settings
+from ed2k_pack import pack as packModule
+from ed2k_pack.pack import ED2kPack
+from ed2k_pack.session import ed2kSession
+from ed2k_pack.task import ED2kTask, ED2kTaskStep
+
+EXECUTABLE = os.environ.get("KELPIE_EXECUTABLE", "")
+FILE_HASH = "2D2A61A79C0E0B4B4B7E6F7A4B9F1C55"
+SIZE = 1_000_000
+KELPIE_BLOCK = 180 * 1024
+
+pytestmark = pytest.mark.skipif(not EXECUTABLE, reason="设置 KELPIE_EXECUTABLE 指向本地构建的 kelpie")
+
+
+class Runner:
+ def __init__(self):
+ self.works: list[asyncio.Task] = []
+
+ def submit(self, work, done=None, failed=None, *args, owner=None, **kwargs) -> str:
+ self.works.append(asyncio.ensure_future(work))
+ return ""
+
+ def post(self, callback, *args) -> None:
+ callback(*args)
+
+
+async def engine(tmp_path, monkeypatch):
+ executable = tmp_path / "bin" / "kelpie"
+ executable.parent.mkdir()
+ shutil.copy2(EXECUTABLE, executable)
+ dataFolder = tmp_path / "ed2k_data"
+ dataFolder.mkdir()
+ monkeypatch.setattr(ed2kConfig.enableKad, "value", False)
+ monkeypatch.setattr(ed2kConfig.shouldRefreshLists, "value", False)
+ monkeypatch.setattr(kelpieRuntime, "path", lambda: str(executable))
+ kelpies: list[Kelpie] = []
+
+ def createKelpie(onNetwork):
+ kelpies.append(Kelpie(
+ lambda: executable, dataFolder,
+ lambda: Settings(enableKad=ed2kConfig.enableKad.value, enableUpnp=False), onNetwork,
+ ))
+ return kelpies[-1]
+
+ monkeypatch.setattr(packModule, "createKelpie", createKelpie)
+ runner = Runner()
+ engine = Engine(tmp_path, kelpies, ED2kPack(SimpleNamespace(coroutineRunner=runner)), runner)
+ await engine.pack.activate()
+ yield engine
+ await engine.pack.deactivate()
+ await asyncio.gather(*runner.works)
+
+
+@dataclass
+class Engine:
+ folder: Path
+ kelpies: list[Kelpie]
+ pack: ED2kPack
+ runner: Runner
+
+ @property
+ def kelpie(self) -> Kelpie:
+ return self.kelpies[-1]
+
+
+def writeGoed2kdState(dataFolder: Path, file: Path) -> None:
+ state = {
+ "version": 3,
+ "user_agent": "FD3887E9230E53F744E5CA8FAF1A6F31",
+ "transfers": [{
+ "hash": FILE_HASH,
+ "size": SIZE,
+ "create_time": 1787328879185,
+ "target_path": str(file),
+ "paused": True,
+ "resume_data": {
+ "hashes": [],
+ "pieces": [False],
+ "downloaded_blocks": [{"PieceIndex": 0, "PieceBlock": index} for index in range(3)],
+ },
+ }],
+ }
+ (dataFolder / "state.json").write_text(json.dumps(state))
+
+
+def buildTask(folder: Path) -> ED2kTask:
+ task = ED2kTask(
+ name="payload.bin", url=f"ed2k://|file|payload.bin|{SIZE}|{FILE_HASH}|/",
+ fileSize=SIZE, outputFolder=folder,
+ )
+ task.addStep(ED2kTaskStep(stepIndex=1))
+ task.setStatus(TaskStatus.RUNNING)
+ return task
+
+
+async def runUntilProgress(task: ED2kTask) -> None:
+ running = asyncio.create_task(task.run(lambda _: None, lambda: asyncio.sleep(0)))
+ async with asyncio.timeout(10):
+ while ed2kSession.progressOf(task) is None:
+ await asyncio.sleep(0.05)
+ running.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await running
+
+
+def readStateHashes(dataFolder: Path) -> set[str]:
+ return {transfer["hash"] for transfer in json.loads((dataFolder / "state.json").read_text())["transfers"]}
+
+
+def isEngineAlive(executable: Path) -> bool:
+ return subprocess.run(["pgrep", "-f", str(executable)], capture_output=True).returncode == 0
+
+
+async def test_download_resumes_from_goed2kd_state(engine):
+ file = engine.folder / "payload.bin"
+ file.write_bytes(bytes(SIZE))
+ writeGoed2kdState(engine.folder / "ed2k_data", file)
+ task = buildTask(engine.folder)
+
+ await runUntilProgress(task)
+ await engine.kelpie.close()
+
+ assert task.steps[0].receivedBytes == 3 * KELPIE_BLOCK
+
+
+async def test_delete_removes_kelpie_state(engine):
+ dataFolder = engine.folder / "ed2k_data"
+ file = engine.folder / "payload.bin"
+ file.write_bytes(bytes(SIZE))
+ writeGoed2kdState(dataFolder, file)
+ task = buildTask(engine.folder)
+ await runUntilProgress(task)
+ await engine.kelpie.close()
+ assert FILE_HASH in readStateHashes(dataFolder)
+
+ task.deletePlaceholders()
+ await asyncio.gather(*engine.runner.works)
+ await engine.kelpie.close()
+
+ assert FILE_HASH not in readStateHashes(dataFolder)
+
+
+async def test_delete_in_progress_finishes_before_deactivate_and_leaves_no_engine_process(engine):
+ executable = engine.folder / "bin" / "kelpie"
+ dataFolder = engine.folder / "ed2k_data"
+ file = engine.folder / "payload.bin"
+ file.write_bytes(bytes(SIZE))
+ writeGoed2kdState(dataFolder, file)
+
+ buildTask(engine.folder).deletePlaceholders()
+ await asyncio.sleep(0)
+ await engine.pack.deactivate()
+
+ assert FILE_HASH not in readStateHashes(dataFolder)
+ assert not isEngineAlive(executable)
+
+
+async def waitForKadFirewalled(engine: Engine, isFirewalled: bool) -> None:
+ async with asyncio.timeout(10):
+ while (network := ed2kSession.network) is None or network.isKadFirewalled != isFirewalled:
+ await asyncio.sleep(0.05)
+
+
+async def test_kad_switch_applies_to_the_running_engine(engine, monkeypatch):
+ task = buildTask(engine.folder)
+ running = asyncio.create_task(task.run(lambda _: None, lambda: asyncio.sleep(0)))
+ try:
+ await waitForKadFirewalled(engine, False)
+
+ monkeypatch.setattr(ed2kConfig.enableKad, "value", True)
+ ed2kConfig.enableKad.valueChanged.emit(True)
+ await waitForKadFirewalled(engine, True)
+
+ monkeypatch.setattr(ed2kConfig.enableKad, "value", False)
+ ed2kConfig.enableKad.valueChanged.emit(False)
+ await waitForKadFirewalled(engine, False)
+
+ assert not running.done()
+ finally:
+ await engine.pack.deactivate()
+ with pytest.raises(asyncio.CancelledError):
+ await running
+
+
+async def test_deactivate_leaves_no_engine_process(engine):
+ executable = engine.folder / "bin" / "kelpie"
+ task = buildTask(engine.folder)
+ running = asyncio.create_task(task.run(lambda _: None, lambda: asyncio.sleep(0)))
+ try:
+ async with asyncio.timeout(10):
+ while ed2kSession.progressOf(task) is None:
+ await asyncio.sleep(0.05)
+ assert isEngineAlive(executable)
+ finally:
+ await engine.pack.deactivate()
+
+ with pytest.raises(asyncio.CancelledError):
+ await running
+ assert not isEngineAlive(executable)
+ assert ed2kSession.network is None
+
+
+async def test_stop_leaves_no_engine_process_and_the_next_run_starts_one(engine):
+ executable = engine.folder / "bin" / "kelpie"
+ await runUntilProgress(buildTask(engine.folder))
+ assert isEngineAlive(executable)
+
+ await ed2kSession.stop()
+
+ assert not isEngineAlive(executable)
+ assert ed2kSession.network is None
+ await runUntilProgress(buildTask(engine.folder))
+ assert isEngineAlive(executable)
+
+
+async def test_stop_with_an_open_run_leaves_the_engine_running(engine):
+ executable = engine.folder / "bin" / "kelpie"
+ task = buildTask(engine.folder)
+ running = asyncio.create_task(task.run(lambda _: None, lambda: asyncio.sleep(0)))
+ try:
+ async with asyncio.timeout(10):
+ while ed2kSession.progressOf(task) is None:
+ await asyncio.sleep(0.05)
+
+ await ed2kSession.stop()
+
+ assert isEngineAlive(executable)
+ assert not running.done()
+ finally:
+ running.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await running
+
+
+async def startRun(task: ED2kTask) -> asyncio.Task:
+ running = asyncio.create_task(task.run(lambda _: None, lambda: asyncio.sleep(0)))
+ async with asyncio.timeout(10):
+ while ed2kSession.progressOf(task) is None:
+ await asyncio.sleep(0.05)
+ return running
+
+
+async def test_session_lifecycle_round_trip_leaves_no_engine_process(engine):
+ executable = engine.folder / "bin" / "kelpie"
+ running = await startRun(buildTask(engine.folder))
+
+ await ed2kSession.stop()
+ assert isEngineAlive(executable)
+ running.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await running
+ await ed2kSession.stop()
+ assert not isEngineAlive(executable)
+
+ running = await startRun(buildTask(engine.folder))
+ assert isEngineAlive(executable)
+ await engine.pack.deactivate()
+ with pytest.raises(asyncio.CancelledError):
+ await running
+ assert not isEngineAlive(executable)
+
+ await engine.pack.activate()
+ running = await startRun(buildTask(engine.folder))
+ assert isEngineAlive(executable)
+ await engine.pack.deactivate()
+ with pytest.raises(asyncio.CancelledError):
+ await running
+
+ assert not isEngineAlive(executable)
+ assert len(engine.kelpies) == 2
diff --git a/tests/test_ed2k_task.py b/tests/test_ed2k_task.py
index b6590d40..c8b94874 100644
--- a/tests/test_ed2k_task.py
+++ b/tests/test_ed2k_task.py
@@ -1,88 +1,156 @@
import asyncio
-from dataclasses import replace
+import gc
+import weakref
+from contextlib import asynccontextmanager
+from dataclasses import dataclass
from pathlib import Path
+from types import SimpleNamespace
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 import android
+from ed2k_pack import config as configModule
+from ed2k_pack import pack as packModule
+from ed2k_pack.cards import toHeldText, toShortHeldText
+from ed2k_pack.config import ed2kConfig, kelpieRuntime
+from ed2k_pack.detail_cards import (
+ toAichHash,
+ toChannelText,
+ toPartCount,
+ toSourceStatusText,
+)
+from ed2k_pack.kelpie import Error, ErrorCode, Progress, Source
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
-from ed2k_pack.session import buildEd2kLink, parseEd2kLink, toTransferKey
+from ed2k_pack.pack import ED2kPack, ED2kParser
+from ed2k_pack.session import buildSettings, ed2kSession
from ed2k_pack.task import ED2kTask, ED2kTaskStep
+from app.config.cfg import cfg
+from app.models.task import TaskError, TaskOptions, TaskStatus
FILE_HASH = "D6E4FE0BA5FD8A2F22FC9C0326481791"
LINK = f"ed2k://|file|payload.bin|1234|{FILE_HASH}|h=TESTAICH|/"
-class FakeClient:
- isRunning = True
+def buildProgress(received: int = 0, uploaded: int = 0, heldSources: int = 0, heldUntil: int = 0) -> Progress:
+ return Progress(
+ hash=FILE_HASH, size=1234, received=received, downloadRate=256,
+ uploadRate=512, uploaded=uploaded, peers=5, activePeers=2, heldSources=heldSources, heldUntil=heldUntil,
+ sources=(),
+ )
+
- def __init__(self):
- self.added: list[tuple[str, Path]] = []
- self.paused: list[str] = []
+class FakeRun:
+ def __init__(self, *progresses: Progress, error: Error | None = None, isEndless: bool = False,
+ isCancelled: bool = False):
+ self.progresses = progresses
+ self.error = error
+ self.isEndless = isEndless
+ self.isCancelled = isCancelled
+ self.started = asyncio.Event()
+
+ async def __aiter__(self):
+ for progress in self.progresses:
+ yield progress
+ self.started.set()
+ if self.error is not None:
+ raise self.error
+ if self.isCancelled:
+ raise asyncio.CancelledError()
+ if self.isEndless:
+ await asyncio.Event().wait()
+
+
+class FakeKelpie:
+ def __init__(self, *runs: FakeRun):
+ self.runs = list(runs)
+ self.opened: list[tuple[str, str, Path]] = []
+ self.active: set[str] = set()
+ self.stopped: list[str] = []
self.removed: list[str] = []
- self.resumed: list[str] = []
- self.snapshotStarted = asyncio.Event()
- self.transfer: Transfer | None = None
-
- async def addLink(self, link: str, outputDir: Path) -> Transfer:
- self.added.append((link, outputDir))
- name, size, fileHash = parseEd2kLink(link)
- self.transfer = Transfer(
- hash=fileHash,
- name=name,
- path=outputDir / name,
- size=size,
- state=TransferState.DOWNLOADING,
- done=0,
- received=0,
- downloadRate=0,
- uploadRate=0,
- upload=0,
- activePeers=0,
- peers=0,
- )
- return self.transfer
-
- async def resume(self, fileHash: str) -> Transfer:
- self.resumed.append(fileHash)
- return self.transfer
-
- async def snapshots(self):
- self.snapshotStarted.set()
- yield Snapshot(transfers=(self.transfer,), serverConnected=True, kadNodes=0)
- await asyncio.Event().wait()
-
- async def pause(self, fileHash: str) -> None:
- self.paused.append(fileHash)
-
- async def remove(self, fileHash: str, deleteFile: bool = False) -> None:
- self.removed.append(fileHash)
-
-
-class DuplicateClient(FakeClient):
- async def addLink(self, link: str, outputDir: Path) -> Transfer:
- name, size, fileHash = parseEd2kLink(link)
- self.transfer = Transfer(
- hash=fileHash,
- name="payload.bin",
- path=outputDir / "payload.bin",
- size=size,
- state=TransferState.PAUSED,
- done=0,
- received=0,
- downloadRate=0,
- uploadRate=0,
- upload=0,
- activePeers=0,
- peers=0,
- )
- raise Error(ErrorCode.TRANSFER_EXISTS, "transfer already exists")
+ self.updateCount = 0
+ self.closeCount = 0
+ self.onNetwork = lambda _: None
+ self.startGate: asyncio.Event | None = None
+ self.exitGate: asyncio.Event | None = None
+ self.removeGate: asyncio.Event | None = None
+
+ def runDownload(self, link, file):
+ return self.run("download", link, file)
+
+ def runSeed(self, link, file):
+ return self.run("seed", link, file)
+
+ @asynccontextmanager
+ async def run(self, mode, link, file):
+ if link.hash in self.active:
+ raise Error(ErrorCode.TRANSFER_BUSY, "busy")
+ self.active.add(link.hash)
+ self.opened.append((mode, link.hash, file))
+ try:
+ if self.startGate is not None:
+ await self.startGate.wait()
+ yield self.runs.pop(0)
+ finally:
+ self.active.discard(link.hash)
+ self.stopped.append(link.hash)
+
+ def isActive(self, hash: str) -> bool:
+ return hash in self.active
+
+ async def remove(self, hash: str) -> None:
+ if self.removeGate is not None:
+ await self.removeGate.wait()
+ self.removed.append(hash)
+
+ def update(self) -> None:
+ self.updateCount += 1
+
+ async def close(self) -> None:
+ self.closeCount += 1
+ if self.exitGate is not None:
+ await self.exitGate.wait()
+ self.onNetwork(None)
+
+
+class FakeRunner:
+ def __init__(self):
+ self.works: list[asyncio.Task] = []
+
+ def submit(self, work, done=None, failed=None, *args, owner=None, **kwargs) -> str:
+ self.works.append(asyncio.ensure_future(work))
+ return ""
+
+ def post(self, callback, *args) -> None:
+ callback(*args)
+
+
+def runner() -> FakeRunner:
+ return FakeRunner()
+
+
+async def usePack(monkeypatch, runner):
+ monkeypatch.setattr(kelpieRuntime, "path", lambda: "/bin/kelpie")
+ monkeypatch.setattr(ed2kConfig.shouldRefreshLists, "value", False)
+
+ def use(*runs: FakeRun) -> tuple[ED2kPack, FakeKelpie]:
+ kelpie = FakeKelpie(*runs)
+
+ def createKelpie(onNetwork):
+ kelpie.onNetwork = onNetwork
+ return kelpie
+
+ monkeypatch.setattr(packModule, "createKelpie", createKelpie)
+ return ED2kPack(SimpleNamespace(coroutineRunner=runner)), kelpie
+
+ yield use
+ await ed2kSession.close()
+
+
+def useKelpie(usePack):
+ return lambda *runs: usePack(*runs)[1]
async def noLimit():
@@ -90,201 +158,284 @@ async def noLimit():
def makeTask(tmp_path: Path, name: str = "payload(1).bin") -> ED2kTask:
- task = ED2kTask(
- name=name,
- url=LINK,
- fileSize=1234,
- outputFolder=tmp_path,
- )
+ task = ED2kTask(name=name, url=LINK, fileSize=1234, outputFolder=tmp_path)
task.addStep(ED2kTaskStep(stepIndex=1))
task.setStatus(TaskStatus.RUNNING)
return task
-def test_build_ed2k_link_preserves_content_identity():
- renamed = buildEd2kLink(LINK, "payload(1).bin")
+async def completeDownload(useKelpie, tmp_path, *runs: FakeRun) -> tuple[ED2kTask, FakeKelpie]:
+ kelpie = useKelpie(FakeRun(buildProgress(received=1234)), *runs)
+ task = makeTask(tmp_path)
+ await task.run(lambda _: None, noLimit)
+ kelpie.opened.clear()
+ kelpie.stopped.clear()
+ return task, kelpie
+
+
+async def test_speed_meter_gets_the_bytes_received_since_the_last_progress(useKelpie, tmp_path):
+ useKelpie(FakeRun(
+ buildProgress(received=100),
+ buildProgress(received=300),
+ buildProgress(received=250),
+ buildProgress(received=1234),
+ ))
+ reported = []
- assert parseEd2kLink(renamed) == ("payload(1).bin", 1234, FILE_HASH)
- assert renamed.endswith("|h=TESTAICH|/")
+ await makeTask(tmp_path).run(reported.append, noLimit)
+ assert reported == [100, 200, 0, 984]
-async def test_step_submits_deduplicated_task_filename(monkeypatch, tmp_path):
- fakeClient = FakeClient()
- session = session_module.ED2kSession()
- session._client = fakeClient
- monkeypatch.setattr(session_module, "ed2kSession", session)
+async def test_download_runs_to_completion_at_the_task_name(useKelpie, tmp_path):
+ kelpie = useKelpie(FakeRun(
+ buildProgress(received=600, uploaded=10),
+ buildProgress(received=1234, uploaded=40),
+ ))
task = makeTask(tmp_path)
- running = asyncio.create_task(task.steps[0].run(lambda _: None, None))
- await fakeClient.snapshotStarted.wait()
- running.cancel()
- with pytest.raises(asyncio.CancelledError):
- await running
+ await task.run(lambda _: None, noLimit)
- submittedLink, submittedFolder = fakeClient.added[0]
- assert parseEd2kLink(submittedLink)[0] == "payload(1).bin"
- assert submittedFolder == tmp_path
- assert task.fileHash == FILE_HASH
- assert fakeClient.paused == [FILE_HASH]
- assert not session._activeTransfers
+ assert task.status == TaskStatus.COMPLETED
+ assert kelpie.opened == [("download", FILE_HASH, tmp_path / "payload(1).bin")]
+ assert task.steps[0].receivedBytes == 1234
+ assert task.uploadedBytes == 40
+ assert kelpie.stopped == [FILE_HASH]
+ assert ed2kSession.progressOf(task) is None
-async def test_resume_uses_saved_hash(monkeypatch, tmp_path):
- fakeClient = FakeClient()
- session = session_module.ED2kSession()
- session._client = fakeClient
- monkeypatch.setattr(session_module, "ed2kSession", session)
+async def test_progress_is_shown_only_while_the_run_is_open(useKelpie, tmp_path):
+ run = FakeRun(buildProgress(received=100), isEndless=True)
+ useKelpie(run)
task = makeTask(tmp_path)
+ assert ed2kSession.progressOf(task) is None
- running = asyncio.create_task(task.steps[0].run(lambda _: None, None))
- await fakeClient.snapshotStarted.wait()
+ running = asyncio.create_task(task.run(lambda _: None, noLimit))
+ await run.started.wait()
+ progress = ed2kSession.progressOf(task)
running.cancel()
with pytest.raises(asyncio.CancelledError):
await running
- fakeClient.snapshotStarted.clear()
- running = asyncio.create_task(task.steps[0].run(lambda _: None, None))
- await fakeClient.snapshotStarted.wait()
+ assert (progress.uploadRate, progress.activePeers, progress.peers) == (512, 2, 5)
+ assert ed2kSession.progressOf(task) is None
+
+
+HELD_UNTIL = 1_000_000_000
+
+
+async def readWhileHeld(useKelpie, tmp_path, heldSources: int, read):
+ run = FakeRun(buildProgress(received=100, heldSources=heldSources, heldUntil=HELD_UNTIL), isEndless=True)
+ useKelpie(run)
+ task = makeTask(tmp_path)
+ running = asyncio.create_task(task.run(lambda _: None, noLimit))
+ await run.started.wait()
+ result = read(task)
running.cancel()
with pytest.raises(asyncio.CancelledError):
await running
+ return result
- assert len(fakeClient.added) == 1
- assert fakeClient.resumed == [FILE_HASH]
+def heldTextsAt(*nows: int):
+ return lambda task: [toHeldText(ed2kSession.progressOf(task), now) for now in nows]
-async def test_cancel_during_addlink_preserves_identity(monkeypatch, tmp_path):
- class SlowAddClient(FakeClient):
- def __init__(self):
- super().__init__()
- self.addStarted = asyncio.Event()
- self.addReady = asyncio.Event()
- async def addLink(self, link: str, outputDir: Path) -> Transfer:
- self.addStarted.set()
- await self.addReady.wait()
- return await super().addLink(link, outputDir)
+async def test_held_sources_show_minutes_left_rounded_up(useKelpie, tmp_path):
+ texts = await readWhileHeld(useKelpie, tmp_path, 3, heldTextsAt(
+ HELD_UNTIL - 10 * 60_000, HELD_UNTIL - 2 * 60_000 - 1, HELD_UNTIL - 60_000, HELD_UNTIL - 59_999, HELD_UNTIL - 1,
+ ))
- fakeClient = SlowAddClient()
- session = session_module.ED2kSession()
- session._client = fakeClient
- monkeypatch.setattr(session_module, "ed2kSession", session)
- task = makeTask(tmp_path)
+ assert texts == [
+ "为免被对方判为请求过频而封禁,3 个来源约 10 分钟后再请求",
+ "为免被对方判为请求过频而封禁,3 个来源约 3 分钟后再请求",
+ "为免被对方判为请求过频而封禁,3 个来源约 1 分钟后再请求",
+ "为免被对方判为请求过频而封禁,3 个来源不到 1 分钟后再请求",
+ "为免被对方判为请求过频而封禁,3 个来源不到 1 分钟后再请求",
+ ]
- running = asyncio.create_task(task.steps[0].run(lambda _: None, None))
- await fakeClient.addStarted.wait()
- running.cancel()
- await asyncio.sleep(0)
- assert not running.done()
+async def test_held_sources_hint_disappears_when_due(useKelpie, tmp_path):
+ assert await readWhileHeld(useKelpie, tmp_path, 3, heldTextsAt(HELD_UNTIL, HELD_UNTIL + 1)) == [None, None]
- fakeClient.addReady.set()
- with pytest.raises(asyncio.CancelledError):
- await running
- assert task.fileHash == FILE_HASH
- assert fakeClient.paused == [FILE_HASH]
+async def test_no_held_sources_no_hint(useKelpie, tmp_path):
+ assert await readWhileHeld(useKelpie, tmp_path, 0, heldTextsAt(HELD_UNTIL - 60_000)) == [None]
+
+
+def test_task_card_shows_the_short_held_hint():
+ progress = buildProgress(received=100, heldSources=3, heldUntil=HELD_UNTIL)
+
+ assert toShortHeldText(progress, HELD_UNTIL - 10 * 60_000) == "3 个来源约 10 分钟后恢复"
+ assert toShortHeldText(progress, HELD_UNTIL - 1) == "3 个来源不到 1 分钟后恢复"
+ assert toShortHeldText(progress, HELD_UNTIL) is None
+
+
+def test_no_hint_without_a_run():
+ assert toHeldText(None, 0) is None
+ assert toShortHeldText(None, 0) is None
+
+def buildSource(status: str, rank: int = 0) -> Source:
+ return Source(address="1.2.3.4:4662", software="eMule 0.70b", status=status, rank=rank, downloadRate=0,
+ channel="server")
-async def test_transfer_exists_resumes_existing(monkeypatch, tmp_path):
- fakeClient = DuplicateClient()
- session = session_module.ED2kSession()
- session._client = fakeClient
- monkeypatch.setattr(session_module, "ed2kSession", session)
- task = makeTask(tmp_path, name="payload.bin")
- running = asyncio.create_task(task.steps[0].run(lambda _: None, None))
- await fakeClient.snapshotStarted.wait()
[email protected](("status", "rank", "text"), [
+ ("transferring", 0, "传输中"),
+ ("queued", 12, "排队 #12"),
+ ("queued", 0, "排队"),
+ ("connecting", 0, "连接中"),
+ ("held", 0, "暂缓"),
+ ("asking", 0, "asking"),
+])
+def test_source_status_text(status, rank, text):
+ assert toSourceStatusText(buildSource(status, rank)) == text
+
+
[email protected](("channel", "text"), [
+ ("link", "链接"),
+ ("server", "服务器"),
+ ("kad", "KAD"),
+ ("exchange", "来源交换"),
+ ("incoming", "对方连入"),
+ ("dht", "dht"),
+])
+def test_source_channel_text(channel, text):
+ assert toChannelText(channel) == text
+
+
[email protected](("size", "count"), [(1, 1), (9728000, 1), (9728001, 2), (3 * 9728000, 3)])
+def test_part_count(size, count):
+ assert toPartCount(size) == count
+
+
+def test_aich_hash_comes_from_the_link():
+ assert toAichHash(LINK) == "TESTAICH"
+ assert toAichHash(f"ed2k://|file|payload.bin|1234|{FILE_HASH}|/") == ""
+
+
+async def test_android_projects_held_sources_with_minutes_left(useKelpie, tmp_path, monkeypatch):
+ monkeypatch.setattr("time.time", lambda: (HELD_UNTIL - 90_000) / 1000)
+
+ held = await readWhileHeld(useKelpie, tmp_path, 3, lambda task: android.taskFields(task)["packFields"]["held"])
+
+ assert held == {"sources": 3, "minutes": 2}
+
+
+async def test_cancel_stops_the_download_run(useKelpie, tmp_path):
+ run = FakeRun(buildProgress(received=100), isEndless=True)
+ kelpie = useKelpie(run)
+ task = makeTask(tmp_path)
+
+ running = asyncio.create_task(task.run(lambda _: None, noLimit))
+ await run.started.wait()
running.cancel()
with pytest.raises(asyncio.CancelledError):
await running
- assert task.fileHash == FILE_HASH
- assert fakeClient.resumed == [FILE_HASH]
- assert fakeClient.removed == []
-
-
-class FinishedClient(FakeClient):
- async def addLink(self, link: str, outputDir: Path) -> Transfer:
- transfer = await super().addLink(link, outputDir)
- self.transfer = replace(
- transfer,
- state=TransferState.FINISHED,
- done=transfer.size,
- received=transfer.size,
- uploadRate=512,
- )
- return self.transfer
-
-
-async def test_download_completes_when_finished(monkeypatch, tmp_path):
- fakeClient = FinishedClient()
- session = session_module.ED2kSession()
- session._client = fakeClient
- monkeypatch.setattr(session_module, "ed2kSession", session)
+ assert kelpie.stopped == [FILE_HASH]
+ assert not kelpie.isActive(FILE_HASH)
+ assert task.steps[0].status != TaskStatus.COMPLETED
+
+
+async def test_download_closed_before_completion_is_not_completed(useKelpie, tmp_path):
+ useKelpie(FakeRun(buildProgress(received=100), isCancelled=True))
task = makeTask(tmp_path)
- await task.run(lambda _: None, noLimit)
+ with pytest.raises(asyncio.CancelledError):
+ await task.run(lambda _: None, noLimit)
+
+ assert task.steps[0].status != TaskStatus.COMPLETED
- assert task.status == TaskStatus.COMPLETED
- assert task.steps[0].receivedBytes == 1234
- assert fakeClient.paused == [FILE_HASH]
- assert not session._activeTransfers
[email protected]("code, message", [
+ (ErrorCode.INVALID_LINK, "不是有效的 eD2k 链接"),
+ (ErrorCode.OUTPUT_EXISTS, "目标文件已被占用"),
+ (ErrorCode.TRANSFER_BUSY, "该 eD2k 链接已在下载中"),
+ (ErrorCode.DISK_FULL, "磁盘空间不足"),
+ (ErrorCode.FILE_ERROR, "无法读写文件:{detail}"),
+ (ErrorCode.OUTDATED, "{name} 版本过旧,请在设置中更新"),
+ (ErrorCode.START_FAILED, "{name} 启动失败:{detail}"),
+ (ErrorCode.ENGINE_EXITED, "{name} 意外退出:{detail}"),
+ (ErrorCode.INTERNAL, "ED2k 错误:{detail}"),
+])
+async def test_run_error_becomes_a_task_error(useKelpie, tmp_path, code, message):
+ useKelpie(FakeRun(error=Error(code, "boom")))
+ task = makeTask(tmp_path)
+
+ with pytest.raises(TaskError) as raised:
+ await task.run(lambda _: None, noLimit)
-async def completeDownload(monkeypatch, tmp_path) -> tuple[ED2kTask, FakeClient]:
- fakeClient = FinishedClient()
- session = session_module.ED2kSession()
- session._client = fakeClient
- monkeypatch.setattr(session_module, "ed2kSession", session)
+ assert raised.value.message == message
+ assert task.steps[0].error.message == message
+ assert ed2kSession.progressOf(task) is None
+
+
+async def test_missing_runtime_never_opens_a_run(useKelpie, monkeypatch, tmp_path):
+ kelpie = useKelpie()
+ monkeypatch.setattr(kelpieRuntime, "path", lambda: "")
task = makeTask(tmp_path)
- await task.run(lambda _: None, noLimit)
- fakeClient.paused.clear()
- fakeClient.snapshotStarted.clear()
- return task, fakeClient
+
+ with pytest.raises(TaskError, match="未安装"):
+ await task.run(lambda _: None, noLimit)
+
+ assert kelpie.opened == []
-async def test_seeding_resumes_transfer_until_stopped(monkeypatch, tmp_path):
- task, fakeClient = await completeDownload(monkeypatch, tmp_path)
+async def test_seeding_runs_until_cancelled(useKelpie, tmp_path):
+ run = FakeRun(buildProgress(received=1234, uploaded=50), isEndless=True)
+ task, kelpie = await completeDownload(useKelpie, tmp_path, run)
seeding = asyncio.create_task(task.runSeeding(isManual=False))
- await fakeClient.snapshotStarted.wait()
- await asyncio.sleep(0)
+ await run.started.wait()
- assert fakeClient.resumed == [FILE_HASH]
- assert task.uploadRate == 512
+ assert kelpie.opened == [("seed", FILE_HASH, tmp_path / "payload(1).bin")]
+ assert ed2kSession.progressOf(task).uploadRate == 512
seeding.cancel()
with pytest.raises(asyncio.CancelledError):
await seeding
- assert fakeClient.paused == [FILE_HASH]
- assert task.uploadRate == 0
- assert not session_module.ed2kSession._activeTransfers
+ assert kelpie.stopped == [FILE_HASH]
+ assert ed2kSession.progressOf(task) is None
-async def test_seeding_ends_at_limit(monkeypatch, tmp_path):
- from ed2k_pack.config import ed2kConfig
+async def test_seeding_ends_at_time_limit(useKelpie, monkeypatch, tmp_path):
monkeypatch.setattr(ed2kConfig.seedingTimeLimit, "value", 1)
- task, fakeClient = await completeDownload(monkeypatch, tmp_path)
+ task, kelpie = await completeDownload(useKelpie, tmp_path, FakeRun(buildProgress(received=1234), isEndless=True))
task.seedingTimeSeconds = 120
await task.runSeeding(isManual=False)
- assert fakeClient.paused == [FILE_HASH]
+ assert kelpie.stopped == [FILE_HASH]
assert task.seedingTimeSeconds >= 120
+ assert ed2kSession.progressOf(task) is None
+
+
+async def test_seeding_ends_at_share_ratio_limit(useKelpie, monkeypatch, tmp_path):
+ monkeypatch.setattr(ed2kConfig.seedingRatioLimit, "value", 100)
+ task, kelpie = await completeDownload(useKelpie, tmp_path, FakeRun(
+ buildProgress(received=1234, uploaded=1200),
+ buildProgress(received=1234, uploaded=1240),
+ isEndless=True,
+ ))
+
+ await task.runSeeding(isManual=False)
+ assert task.uploadedBytes == 1240
+ assert task.shareRatioPercent >= 100
+ assert kelpie.stopped == [FILE_HASH]
-async def test_manual_seeding_ignores_limit(monkeypatch, tmp_path):
- from ed2k_pack.config import ed2kConfig
+
+async def test_manual_seeding_ignores_limit(useKelpie, monkeypatch, tmp_path):
monkeypatch.setattr(ed2kConfig.seedingTimeLimit, "value", 1)
- task, fakeClient = await completeDownload(monkeypatch, tmp_path)
+ run = FakeRun(buildProgress(received=1234), isEndless=True)
+ task, _ = await completeDownload(useKelpie, tmp_path, run)
task.seedingTimeSeconds = 120
seeding = asyncio.create_task(task.runSeeding(isManual=True))
- await fakeClient.snapshotStarted.wait()
- await asyncio.sleep(0)
+ await run.started.wait()
assert not seeding.done()
seeding.cancel()
@@ -292,113 +443,488 @@ async def test_manual_seeding_ignores_limit(monkeypatch, tmp_path):
await seeding
-class UploadingClient(FakeClient):
- def __init__(self, states: list[tuple[TransferState, int]]):
- super().__init__()
- self.states = states
+async def test_seeding_closed_by_kelpie_is_not_a_finished_seeding(useKelpie, tmp_path):
+ task, _ = await completeDownload(useKelpie, tmp_path, FakeRun(buildProgress(received=1234), isCancelled=True))
- async def snapshots(self):
- self.snapshotStarted.set()
- for state, upload in self.states:
- self.transfer = replace(self.transfer, state=state, upload=upload)
- yield Snapshot(transfers=(self.transfer,), serverConnected=True, kadNodes=0)
- await asyncio.Event().wait()
+ with pytest.raises(asyncio.CancelledError):
+ await task.runSeeding(isManual=False)
-async def test_download_adds_its_upload_to_the_task_total(monkeypatch, tmp_path):
- fakeClient = UploadingClient([
- (TransferState.DOWNLOADING, 10),
- (TransferState.FINISHED, 50),
- ])
- session = session_module.ED2kSession()
- session._client = fakeClient
- monkeypatch.setattr(session_module, "ed2kSession", session)
- task = makeTask(tmp_path)
- task.uploadedBytes = 100
+async def test_seeding_failure_is_a_task_error(useKelpie, tmp_path):
+ task, _ = await completeDownload(useKelpie, tmp_path, FakeRun(error=Error(ErrorCode.FILE_ERROR, "changed")))
- await task.run(lambda _: None, noLimit)
+ with pytest.raises(TaskError, match="无法读写文件"):
+ await task.runSeeding(isManual=False)
- assert task.uploadedBytes == 140
+ assert ed2kSession.progressOf(task) is None
-async def test_seeding_ends_at_share_ratio_limit(monkeypatch, tmp_path):
- from ed2k_pack.config import ed2kConfig
- monkeypatch.setattr(ed2kConfig.seedingRatioLimit, "value", 100)
- task, _ = await completeDownload(monkeypatch, tmp_path)
- fakeClient = UploadingClient([
- (TransferState.FINISHED, 0),
- (TransferState.FINISHED, 40),
- ])
- fakeClient.transfer = session_module.ed2kSession._client.transfer
- session_module.ed2kSession._client = fakeClient
- task.uploadedBytes = 1200
+def buildParser(pack: ED2kPack) -> ED2kParser:
+ parser = ED2kParser()
+ parser.pack = pack
+ return parser
- await task.runSeeding(isManual=False)
- assert task.uploadedBytes == 1240
- assert task.shareRatioPercent >= 100
- assert fakeClient.paused == [FILE_HASH]
+async def test_parser_rejects_an_active_link(usePack, tmp_path):
+ pack, kelpie = usePack()
+ kelpie.active.add(FILE_HASH)
+
+ with pytest.raises(TaskError, match="该 eD2k 链接已在下载中"):
+ await buildParser(pack).parse(TaskOptions(url=LINK, outputFolder=tmp_path))
-async def test_parser_rejects_active_duplicate_on_add_task_page(monkeypatch, tmp_path):
- session = session_module.ED2kSession()
- identity = toTransferKey(FILE_HASH, 1234)
- session._activeTransfers.add(identity)
- monkeypatch.setattr(session_module, "ed2kSession", session)
+async def test_parser_names_the_task_after_the_link(usePack, tmp_path):
+ pack, _ = usePack()
+
+ task = await buildParser(pack).parse(TaskOptions(url=f" {LINK} ", outputFolder=tmp_path))
+
+ assert task.name == "payload.bin"
+ assert task.fileSize == 1234
+ assert task.url == LINK
+
+
+async def test_parser_rejects_an_invalid_link(usePack, tmp_path):
+ pack, _ = usePack()
+
+ with pytest.raises(TaskError, match="不是有效的 eD2k 链接"):
+ await buildParser(pack).parse(TaskOptions(url="ed2k://|server|1.2.3.4|4661|/", outputFolder=tmp_path))
+
+
[email protected]("delete", [ED2kTask.reset, ED2kTask.deletePlaceholders])
+async def test_delete_and_redownload_remove_the_transfer(useKelpie, runner, tmp_path, delete):
+ task, kelpie = await completeDownload(useKelpie, tmp_path)
+
+ delete(task)
+ await asyncio.gather(*runner.works)
+
+ assert kelpie.removed == [FILE_HASH]
+
+
+async def test_deleting_task_and_files_removes_the_transfer_once(useKelpie, runner, tmp_path):
+ task, kelpie = await completeDownload(useKelpie, tmp_path)
+
+ task.deleteFiles()
+ task.deletePlaceholders()
+ await asyncio.gather(*runner.works)
+
+ assert kelpie.removed == [FILE_HASH]
+
+
+async def test_delete_before_any_progress_removes_the_transfer(useKelpie, runner, tmp_path):
+ kelpie = useKelpie()
+
+ makeTask(tmp_path).deletePlaceholders()
+ await asyncio.gather(*runner.works)
+
+ assert kelpie.removed == [FILE_HASH]
+
+
+def test_delete_without_runtime_leaves_kelpie_alone(useKelpie, runner, monkeypatch, tmp_path):
+ useKelpie()
+ monkeypatch.setattr(kelpieRuntime, "path", lambda: "")
+
+ makeTask(tmp_path).deletePlaceholders()
+
+ assert runner.works == []
+
+
+async def test_close_waits_for_a_delete_in_progress(usePack, runner, tmp_path):
+ pack, kelpie = usePack()
+ kelpie.removeGate = asyncio.Event()
+ makeTask(tmp_path).deletePlaceholders()
+ await asyncio.sleep(0)
+
+ closing = asyncio.create_task(pack.deactivate())
+ for _ in range(10):
+ await asyncio.sleep(0)
+ closedDuringDelete = kelpie.closeCount
+ kelpie.removeGate.set()
+ await closing
+
+ assert closedDuringDelete == 0
+ assert kelpie.removed == [FILE_HASH]
+ assert kelpie.closeCount == 1
- with pytest.raises(TaskError, match="该 eD2k 链接已在下载中"):
- await ED2kParser().parse(TaskOptions(url=LINK, outputFolder=tmp_path))
- session._activeTransfers.discard(identity)
+async def test_close_is_idempotent(usePack):
+ pack, kelpie = usePack()
+ await pack.deactivate()
+ await pack.deactivate()
+
+ assert kelpie.closeCount == 1
+
+
+async def test_run_before_open_never_starts_a_process(monkeypatch, tmp_path):
+ monkeypatch.setattr(kelpieRuntime, "path", lambda: "/bin/kelpie")
+
+ with pytest.raises(asyncio.CancelledError):
+ await makeTask(tmp_path).run(lambda _: None, noLimit)
+
+
+def test_no_task_is_active_before_open(tmp_path):
+ assert not ed2kSession.isActive(makeTask(tmp_path))
+
+
+async def test_run_after_deactivate_never_starts_the_engine(usePack, tmp_path):
+ pack, kelpie = usePack(FakeRun(buildProgress(received=1234)))
+ await pack.deactivate()
+
+ with pytest.raises(asyncio.CancelledError):
+ await makeTask(tmp_path).run(lambda _: None, noLimit)
+
+ assert kelpie.opened == []
+
+
+async def test_session_reopened_after_deactivate_runs_again(usePack, tmp_path):
+ pack, _ = usePack()
+ await pack.deactivate()
+ _, kelpie = usePack(FakeRun(buildProgress(received=1234)))
-async def test_active_duplicate_never_reaches_daemon(monkeypatch, tmp_path):
- fakeClient = FakeClient()
- session = session_module.ED2kSession()
- session._client = fakeClient
- identity = toTransferKey(FILE_HASH, 1234)
- session._activeTransfers.add(identity)
- monkeypatch.setattr(session_module, "ed2kSession", session)
task = makeTask(tmp_path)
+ await task.run(lambda _: None, noLimit)
+
+ assert task.status == TaskStatus.COMPLETED
+ assert [hash for _, hash, _ in kelpie.opened] == [FILE_HASH]
+
+
+async def test_session_lifecycle_from_open_to_reopen(monkeypatch, runner, tmp_path):
+ monkeypatch.setattr(kelpieRuntime, "path", lambda: "/bin/kelpie")
+ monkeypatch.setattr(ed2kConfig.shouldRefreshLists, "value", False)
+ held = FakeRun(buildProgress(received=100), isEndless=True)
+ first = FakeKelpie(held, FakeRun(buildProgress(received=1234)))
+ second = FakeKelpie(FakeRun(buildProgress(received=1234)))
+ kelpies = [first, second]
+
+ def createKelpie(onNetwork):
+ kelpie = kelpies.pop(0)
+ kelpie.onNetwork = onNetwork
+ return kelpie
+
+ monkeypatch.setattr(packModule, "createKelpie", createKelpie)
+ pack = ED2kPack(SimpleNamespace(coroutineRunner=runner))
+ await pack.activate()
+
+ running = asyncio.create_task(makeTask(tmp_path).run(lambda _: None, noLimit))
+ await held.started.wait()
+ await ed2kSession.stop()
+ assert first.closeCount == 0
+ running.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await running
+ assert ed2kSession.isIdle
+
+ await ed2kSession.stop()
+ assert first.closeCount == 1
+
+ reconnected = makeTask(tmp_path)
+ await reconnected.run(lambda _: None, noLimit)
+ assert reconnected.status == TaskStatus.COMPLETED
+ assert len(first.opened) == 2
+
+ await pack.deactivate()
+ assert first.closeCount == 2
+
+ pack = ED2kPack(SimpleNamespace(coroutineRunner=runner))
+ reactivated = makeTask(tmp_path)
+ await reactivated.run(lambda _: None, noLimit)
+ await pack.deactivate()
+
+ assert reactivated.status == TaskStatus.COMPLETED
+ assert [hash for _, hash, _ in second.opened] == [FILE_HASH]
+ assert second.closeCount == 1
+
+
+async def test_live_settings_reach_kelpie_once_after_reopening(usePack, watch):
+ for _ in range(3):
+ pack, _ = usePack()
+ await pack.deactivate()
+ pack, kelpie = usePack()
+ changes = watch(ed2kSession.networkChanged, lambda: ed2kSession.network)
+
+ ed2kConfig.enableKad.valueChanged.emit(ed2kConfig.enableKad.value)
+ await asyncio.sleep(0)
+
+ assert kelpie.updateCount == 1
+ assert changes == [None]
- with pytest.raises(TaskError, match="该 eD2k 链接已在下载中"):
- await task.run(lambda _: None, noLimit)
- assert fakeClient.added == []
- session._activeTransfers.discard(identity)
+async def test_closed_session_releases_kelpie(monkeypatch, runner):
+ created: list[weakref.ref] = []
+ def createKelpie(onNetwork):
+ kelpie = FakeKelpie()
+ created.append(weakref.ref(kelpie))
+ return kelpie
-class StartedClient:
- isRunning = True
+ monkeypatch.setattr(packModule, "createKelpie", createKelpie)
+ pack = ED2kPack(SimpleNamespace(coroutineRunner=runner))
+ await pack.deactivate()
+ gc.collect()
- def __init__(self, executable, dataDir):
- pass
+ assert created[0]() is None
- async def start(self, settings):
- return Snapshot(transfers=(), serverConnected=False, kadNodes=0)
[email protected]("version, isAccepted", [
- ("v0.2.3", False),
- ("v0.2.4", True),
- ("dev", True),
+
+def useInstallFolder(monkeypatch, folder: Path, payload: bytes | Exception):
+ async def fetchReleaseAsset(repo, tag, asset, outputPath, onProgress):
+ assert asset == configModule.buildAssetName()
+ if isinstance(payload, Exception):
+ outputPath.write_bytes(b"partial")
+ raise payload
+ outputPath.write_bytes(payload)
+ onProgress(100.0)
+
+ monkeypatch.setattr(ed2kConfig.installFolder, "value", str(folder))
+ monkeypatch.setattr(configModule, "fetchReleaseAsset", fetchReleaseAsset)
+ return configModule.kelpieRuntime
+
+
+async def test_install_replaces_a_running_binary_with_a_new_file(monkeypatch, tmp_path):
+ runtime = useInstallFolder(monkeypatch, tmp_path, b"new")
+ binary = runtime.installedPaths()[0]
+ binary.write_bytes(b"old")
+ (tmp_path / "notes.txt").write_bytes(b"user")
+ runningInode = binary.stat().st_ino
+ progresses = []
+
+ with binary.open("rb") as running:
+ await runtime.install("v0.1.0", progresses.append)
+ assert running.read() == b"old"
+
+ assert binary.read_bytes() == b"new"
+ assert binary.stat().st_ino != runningInode
+ assert runtime.path() == str(binary)
+ assert runtime.isAppManaged()
+ assert progresses == [100.0]
+ assert sorted(p.name for p in tmp_path.iterdir()) == sorted([binary.name, "notes.txt"])
+
+
+async def test_failed_install_keeps_the_old_binary(monkeypatch, tmp_path):
+ runtime = useInstallFolder(monkeypatch, tmp_path, ConnectionError("reset"))
+ binary = runtime.installedPaths()[0]
+ binary.write_bytes(b"old")
+
+ with pytest.raises(ConnectionError):
+ await runtime.install("v0.1.0", lambda _: None)
+
+ assert binary.read_bytes() == b"old"
+ assert [p.name for p in tmp_path.iterdir()] == [binary.name]
+
+
+def test_uninstall_deletes_only_the_binary(monkeypatch, tmp_path):
+ runtime = useInstallFolder(monkeypatch, tmp_path, b"")
+ runtime.installedPaths()[0].write_bytes(b"bin")
+ (tmp_path / "goed2kd").write_bytes(b"old engine")
+
+ runtime.delete()
+
+ assert runtime.path() == ""
+ assert [p.name for p in tmp_path.iterdir()] == ["goed2kd"]
+
+
+async def test_install_clears_binaries_left_by_earlier_installs(monkeypatch, tmp_path):
+ runtime = useInstallFolder(monkeypatch, tmp_path, b"new")
+ binary = runtime.installedPaths()[0]
+ binary.with_name(f"{binary.name}.1234abcd.old").write_bytes(b"older")
+
+ await runtime.install("v0.1.0", lambda _: None)
+
+ assert [p.name for p in tmp_path.iterdir()] == [binary.name]
+
+
+async def test_activate_refreshes_only_stale_lists(runner, monkeypatch):
+ class FakeList:
+ def __init__(self, isStale: bool):
+ self.isStale = lambda: isStale
+ self.refreshCount = 0
+
+ async def refresh(self):
+ self.refreshCount += 1
+
+ serverList, nodeList = FakeList(True), FakeList(False)
+ monkeypatch.setattr(packModule, "serverList", serverList)
+ monkeypatch.setattr(packModule, "nodeList", nodeList)
+ monkeypatch.setattr(ed2kConfig.shouldRefreshLists, "value", True)
+ monkeypatch.setattr(packModule, "createKelpie", lambda onNetwork: FakeKelpie())
+ pack = ED2kPack(SimpleNamespace(coroutineRunner=runner))
+
+ await pack.activate()
+ await asyncio.sleep(0)
+ await pack.deactivate()
+
+ assert (serverList.refreshCount, nodeList.refreshCount) == (1, 0)
+
+
[email protected](("isEnabled", "expected"), [(True, 2048), (False, 0)])
+def test_settings_follow_the_global_speed_limit(monkeypatch, isEnabled, expected):
+ monkeypatch.setattr(cfg.isSpeedLimitEnabled, "value", isEnabled)
+ monkeypatch.setattr(cfg.speedLimitation, "value", 2048)
+ monkeypatch.setattr(ed2kConfig.uploadRateLimit, "value", 1024)
+
+ settings = buildSettings()
+
+ assert (settings.downloadRateLimit, settings.uploadRateLimit) == (expected, 1024)
+
+
+ cfg.isSpeedLimitEnabled, cfg.speedLimitation,
+ ed2kConfig.uploadRateLimit, ed2kConfig.enableKad, ed2kConfig.enableUpnp,
])
-async def test_open_rejects_an_outdated_goed2kd(monkeypatch, version, isAccepted):
- async def probeVersion():
- return VersionInfo(version)
+async def test_live_setting_change_updates_kelpie(useKelpie, item):
+ kelpie = useKelpie()
+
+ item.valueChanged.emit(item.value)
+ await asyncio.sleep(0)
+
+ assert kelpie.updateCount == 1
+
+
[email protected]("item", [ed2kConfig.listenPort, ed2kConfig.serverListSources, ed2kConfig.nodeListSources])
+async def test_restart_setting_change_leaves_kelpie_alone(useKelpie, item):
+ kelpie = useKelpie()
+
+ item.valueChanged.emit(item.value)
+ await asyncio.sleep(0)
+
+ assert kelpie.updateCount == 0
+
+
+async def test_deactivated_pack_stops_updating_kelpie(usePack):
+ pack, kelpie = usePack()
+ await pack.deactivate()
+
+ ed2kConfig.enableKad.valueChanged.emit(ed2kConfig.enableKad.value)
+ await asyncio.sleep(0)
+
+ assert kelpie.closeCount == 1
+ assert kelpie.updateCount == 0
+
+
+def watch():
+ connections = []
+
+ def connect(signal, read) -> list:
+ changes = []
+ connections.append((signal, lambda: changes.append(read())))
+ signal.connect(connections[-1][1])
+ return changes
+
+ yield connect
+ for signal, slot in connections:
+ signal.disconnect(slot)
+
+
+async def test_network_pushed_by_kelpie_is_announced_without_a_run(usePack, watch):
+ network = FakeNetwork(isHighId=True)
+ pack, kelpie = usePack()
+ changes = watch(ed2kSession.networkChanged, lambda: ed2kSession.network)
+
+ kelpie.onNetwork(network)
+ kelpie.onNetwork(None)
+
+ assert changes == [network, None]
+
+
[email protected]("item", [ed2kConfig.enableKad, ed2kConfig.enableUpnp])
+async def test_live_setting_change_announces_the_network(usePack, watch, item):
+ pack, _ = usePack()
+ changes = watch(ed2kSession.networkChanged, lambda: ed2kSession.network)
+
+ item.valueChanged.emit(item.value)
+
+ assert changes == [None]
+
+
+async def test_open_and_ended_runs_are_announced(usePack, watch, tmp_path):
+ pack, _ = usePack(FakeRun(buildProgress(received=1234)))
+ changes = watch(ed2kSession.runsChanged, lambda: ed2kSession.isIdle)
+
+ await makeTask(tmp_path).run(lambda _: None, noLimit)
+
+ assert changes == [False, True]
+
+
+async def test_stop_closes_an_idle_engine_and_the_next_run_still_opens(usePack, tmp_path):
+ pack, kelpie = usePack(FakeRun(buildProgress(received=1234)))
+ kelpie.onNetwork(FakeNetwork())
+
+ await ed2kSession.stop()
+ task = makeTask(tmp_path)
+ await task.run(lambda _: None, noLimit)
+
+ assert kelpie.closeCount == 1
+ assert task.status == TaskStatus.COMPLETED
+
+
+async def test_stop_leaves_an_open_run_alone(usePack, tmp_path):
+ run = FakeRun(buildProgress(received=100), isEndless=True)
+ pack, kelpie = usePack(run)
+ running = asyncio.create_task(makeTask(tmp_path).run(lambda _: None, noLimit))
+ await run.started.wait()
+
+ await ed2kSession.stop()
+
+ assert kelpie.closeCount == 0
+ assert not running.done()
+ running.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await running
+
+
+async def test_stop_leaves_a_run_that_is_still_starting_alone(usePack, tmp_path):
+ pack, kelpie = usePack(FakeRun(buildProgress(received=1234)))
+ kelpie.startGate = asyncio.Event()
+ task = makeTask(tmp_path)
+ running = asyncio.create_task(task.run(lambda _: None, noLimit))
+ while not kelpie.opened:
+ await asyncio.sleep(0)
+
+ await ed2kSession.stop()
+ kelpie.startGate.set()
+ await running
+
+ assert kelpie.closeCount == 0
+ assert task.status == TaskStatus.COMPLETED
+
+
+async def test_run_during_stop_waits_for_the_old_engine_to_exit(usePack, tmp_path):
+ pack, kelpie = usePack(FakeRun(buildProgress(received=1234)))
+ kelpie.exitGate = asyncio.Event()
+ stopping = asyncio.create_task(ed2kSession.stop())
+ while kelpie.closeCount == 0:
+ await asyncio.sleep(0)
+ task = makeTask(tmp_path)
+ running = asyncio.create_task(task.run(lambda _: None, noLimit))
+ for _ in range(10):
+ await asyncio.sleep(0)
+ openedDuringStop = list(kelpie.opened)
+ kelpie.exitGate.set()
+ await stopping
+ await running
+
+ assert openedDuringStop == []
+ assert task.status == TaskStatus.COMPLETED
+
- monkeypatch.setattr(session_module.ed2kRuntime, "path", lambda: "/bin/goed2kd")
- monkeypatch.setattr(session_module.ed2kRuntime, "probeVersion", probeVersion)
- monkeypatch.setattr(session_module, "Client", StartedClient)
- session = session_module.ED2kSession()
+async def test_delete_during_stop_waits_for_the_old_engine_to_exit(usePack, runner, tmp_path):
+ pack, kelpie = usePack()
+ kelpie.exitGate = asyncio.Event()
+ stopping = asyncio.create_task(ed2kSession.stop())
+ while kelpie.closeCount == 0:
+ await asyncio.sleep(0)
+ makeTask(tmp_path).deletePlaceholders()
+ for _ in range(10):
+ await asyncio.sleep(0)
+ removedDuringStop = list(kelpie.removed)
+ kelpie.exitGate.set()
+ await stopping
+ await asyncio.gather(*runner.works)
- if isAccepted:
- await session._open()
- assert session._client is not None
- else:
- with pytest.raises(TaskError):
- await session._open()
- assert session._client is None
+ assert removedDuringStop == []
+ assert kelpie.removed == [FILE_HASH]
def u32(value: int) -> bytes:
@@ -457,3 +983,38 @@ def test_parse_server_list_reads_every_endpoint_past_the_tags():
def test_parse_server_list_rejects_broken_files(data):
with pytest.raises(ValueError):
parseServerList(data)
+
+
+@dataclass(frozen=True)
+class FakeNetwork:
+ isServerConnected: bool = True
+ isHighId: bool = False
+ isKadFirewalled: bool = False
+ kadNodes: int = 0
+ isBehindCarrierNat: bool = False
+
+
[email protected]("network, text", [
+ (FakeNetwork(isHighId=True), "已连接服务器(HighID)"),
+ (FakeNetwork(), "已连接服务器(LowID,开启 UPnP 或在路由器转发监听端口可获得 HighID)"),
+ (FakeNetwork(isBehindCarrierNat=True), "已连接服务器(LowID,运营商 NAT,无法获得 HighID)"),
+ (None, "未运行"),
+])
+async def test_server_text_explains_how_to_get_a_high_id(useKelpie, network, text):
+ useKelpie().onNetwork(network)
+
+ assert await ed2kConfig._probeServerText() == text
+
+
[email protected]("isKadEnabled, network, text", [
+ (False, FakeNetwork(kadNodes=0), "KAD 已关闭"),
+ (False, None, "KAD 已关闭"),
+ (True, FakeNetwork(kadNodes=12), "KAD 节点 12"),
+ (True, FakeNetwork(kadNodes=12, isKadFirewalled=True), "KAD 节点 12(处于防火墙后)"),
+ (True, None, "未运行"),
+])
+async def test_kad_text_says_when_kad_is_off(useKelpie, monkeypatch, isKadEnabled, network, text):
+ monkeypatch.setattr(ed2kConfig.enableKad, "value", isKadEnabled)
+ useKelpie().onNetwork(network)
+
+ assert await ed2kConfig._probeKadText() == text