Skip to content

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

feat(ed2k): 做种和 BT 对齐,要求 goed2kd 0.2.4

XiaoYouChRee210fbd656e
diff --git a/features/bittorrent_pack/cards.py b/features/bittorrent_pack/cards.py
index 4b7adfbf..3e14f842 100644
--- a/features/bittorrent_pack/cards.py
+++ b/features/bittorrent_pack/cards.py
@@ -83,12 +83,7 @@ class BTTaskCard(MultiFileTaskCard):
def _refreshForStatus(self, task):
super()._refreshForStatus(task)
if task.isSeeding and not self._isFileMissing:
- parts = []
- if task.shareRatioPercent > 0:
- parts.append(self.tr("分享率 {0}").format(f"{task.shareRatioPercent:.1f}%"))
- if task.seedingTimeSeconds > 0:
- parts.append(self.tr("做种 {0}").format(toReadableTime(task.seedingTimeSeconds)))
- self._setStatus(self.tr("做种中") + " " + " · ".join(parts))
+ self._setStatus(self.tr(",").join([self.tr("做种中"), *self._toSeedingParts(task)]))
elif task.status == TaskStatus.RUNNING and task.stateText and task.stateText != "downloading":
self.progressBar.hide()
label = BT_STATE_LABELS.get(task.stateText)
@@ -100,10 +95,14 @@ class BTTaskCard(MultiFileTaskCard):
label = BT_STATE_LABELS.get(task.stateText)
if label:
parts.append(self.tr(label))
- if task.shareRatioPercent > 0:
- parts.append(self.tr("分享率 {0}").format(f"{task.shareRatioPercent:.1f}%"))
- if task.seedingTimeSeconds > 0:
- parts.append(self.tr("做种 {0}").format(toReadableTime(task.seedingTimeSeconds)))
- summary = " · ".join(parts)
- if summary and not self._isFileMissing:
- self.statusLabel.setText(summary)
+ parts += self._toSeedingParts(task)
+ if parts and not self._isFileMissing:
+ self.statusLabel.setText(self.tr(",").join(parts))
+
+ def _toSeedingParts(self, task: BTTask) -> list[str]:
+ parts = []
+ if task.shareRatioPercent > 0:
+ parts.append(self.tr("分享率 {0}").format(f"{task.shareRatioPercent:.1f}%"))
+ if task.seedingTimeSeconds > 0:
+ parts.append(self.tr("已做种 {0}").format(toReadableTime(task.seedingTimeSeconds)))
+ return parts
diff --git a/features/ed2k_pack/android.py b/features/ed2k_pack/android.py
index a3cded29..5f4c8423 100644
--- a/features/ed2k_pack/android.py
+++ b/features/ed2k_pack/android.py
@@ -8,12 +8,13 @@ def taskFields(task) -> dict:
active = task.activePeerCount
return {
"progressMode": "hidden" if task.isSeeding else "determinate",
- "statusText": N("TaskState", "共享中") if task.isSeeding else "",
+ "statusText": N("TaskState", "做种中") if task.isSeeding else "",
"secondarySpeed": task.uploadRate,
"packFields": {
"peers": None if active is None else {
"active": active, "total": max(active, task.totalPeerCount),
},
+ "shareRatio": task.shareRatioPercent,
"seedingSeconds": task.seedingTimeSeconds,
"uploadSpeed": task.uploadRate,
},
diff --git a/features/ed2k_pack/cards.py b/features/ed2k_pack/cards.py
index b9bfb146..cb1ab640 100644
--- a/features/ed2k_pack/cards.py
+++ b/features/ed2k_pack/cards.py
@@ -39,13 +39,16 @@ class ED2kTaskCard(TaskCard):
def _refreshForStatus(self, task: ED2kTask):
super()._refreshForStatus(task)
if task.isSeeding and not self._isFileMissing:
- parts = []
- if task.seedingTimeSeconds > 0:
- parts.append(self.tr("已共享 {0}").format(
- toReadableTime(task.seedingTimeSeconds)))
- self._setStatus(self.tr("共享中") + (" " + " · ".join(parts) if parts else ""))
- elif task.status != TaskStatus.RUNNING and task.seedingTimeSeconds > 0:
- self.statusLabel.setText(
- self.statusLabel.text() + " · " + self.tr("已共享 {0}").format(
- toReadableTime(task.seedingTimeSeconds))
- )
+ 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))
+
+ def _toSeedingParts(self, task: ED2kTask) -> list[str]:
+ parts = []
+ if task.shareRatioPercent > 0:
+ parts.append(self.tr("分享率 {0}").format(f"{task.shareRatioPercent:.1f}%"))
+ if task.seedingTimeSeconds > 0:
+ parts.append(self.tr("已做种 {0}").format(toReadableTime(task.seedingTimeSeconds)))
+ return parts
diff --git a/features/ed2k_pack/config.py b/features/ed2k_pack/config.py
index b8c5abe8..52fee0ff 100644
--- a/features/ed2k_pack/config.py
+++ b/features/ed2k_pack/config.py
@@ -19,11 +19,12 @@ ED2K_REPO = Repo("XiaoYouChR/Python-eD2k", mirrors={"gitcode": "XiaoYouChR/Pytho
class ED2kConfig(PackConfig):
associateUriSchemes = ConfigItem("ED2k", "AssociateUriSchemes", False, BoolValidator())
installFolder = ConfigItem("ED2k", "InstallFolder", f"{APP_DATA_DIR}/goed2kd")
- enableDht = ConfigItem("ED2k", "EnableDHT", True, BoolValidator())
- enableUpnp = ConfigItem("ED2k", "EnableUPnP", True, BoolValidator())
- listenPort = RangeConfigItem("ED2k", "ListenPort", 0, RangeValidator(0, 65535))
+ enableDht = ConfigItem("ED2k", "EnableDHT", True, BoolValidator(), restart=True)
+ enableUpnp = ConfigItem("ED2k", "EnableUPnP", True, BoolValidator(), restart=True)
+ listenPort = RangeConfigItem("ED2k", "ListenPort", 0, RangeValidator(0, 65535), restart=True)
serverMetSource = ConfigItem("ED2k", "ServerMetSource", "http://upd.emule-security.org/server.met")
nodesDatSource = ConfigItem("ED2k", "NodesDatSource", "http://upd.emule-security.org/nodes.dat")
+ seedingRatioLimit = RangeConfigItem("ED2k", "SeedRatioLimitPercent", 0, RangeValidator(0, 10000))
seedingTimeLimit = RangeConfigItem("ED2k", "SharingTimeLimitMinutes", 0, RangeValidator(0, 43200))
def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:
@@ -71,8 +72,13 @@ class ED2kConfig(PackConfig):
self.listenPort, group, 1,
),
SpinBoxSettingCard(
- FluentIcon.STOP_WATCH, self.tr("自动停止共享时长"),
- self.tr("0 表示不按共享时长自动停止"), " min",
+ FluentIcon.SHARE, self.tr("自动停止做种分享率"),
+ self.tr("0 表示不按分享率自动停止,100% 表示分享率 1.0"), " %",
+ self.seedingRatioLimit, group, 50,
+ ),
+ SpinBoxSettingCard(
+ FluentIcon.STOP_WATCH, self.tr("自动停止做种时长"),
+ self.tr("0 表示不按做种时长自动停止"), " min",
self.seedingTimeLimit, group, 10,
),
])
diff --git a/features/ed2k_pack/python_ed2k/client.py b/features/ed2k_pack/python_ed2k/client.py
index a9b6ec81..299f4075 100644
--- a/features/ed2k_pack/python_ed2k/client.py
+++ b/features/ed2k_pack/python_ed2k/client.py
@@ -281,7 +281,11 @@ class Client:
def _toSnapshot(value: Any) -> Snapshot:
try:
- return Snapshot(transfers=tuple(_toTransfer(transfer) for transfer in value["transfers"]))
+ 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
@@ -297,6 +301,7 @@ def _toSettings(settings: Settings) -> dict[str, Any]:
"enableDht": settings.enableDht,
"enableUpnp": settings.enableUpnp,
"reconnectToServer": settings.reconnectToServer,
+ "enableDebugLog": settings.enableDebugLog,
}
@@ -312,7 +317,8 @@ def _toTransfer(value: Any) -> Transfer:
received=value["received"],
downloadRate=value["downloadRate"],
uploadRate=value["uploadRate"],
- activePeers=value.get("activePeers"),
+ upload=value["upload"],
+ activePeers=value["activePeers"],
peers=value["peers"],
)
except (KeyError, TypeError, ValueError) as error:
diff --git a/features/ed2k_pack/python_ed2k/models.py b/features/ed2k_pack/python_ed2k/models.py
index f57b27ad..50c7b16a 100644
--- a/features/ed2k_pack/python_ed2k/models.py
+++ b/features/ed2k_pack/python_ed2k/models.py
@@ -22,6 +22,7 @@ class Settings:
enableDht: bool = True
enableUpnp: bool = True
reconnectToServer: bool = True
+ enableDebugLog: bool = False
@dataclass(frozen=True, slots=True)
@@ -35,10 +36,13 @@ class Transfer:
received: int
downloadRate: int
uploadRate: int
- activePeers: int | None
+ 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 86ad67cc..ba884cb3 100644
--- a/features/ed2k_pack/session.py
+++ b/features/ed2k_pack/session.py
@@ -10,11 +10,15 @@ from loguru import logger
from app.config.paths import APP_DATA_DIR
from app.models.task import TaskError
+from app.update import parseVersion
from .config import ed2kConfig, ed2kRuntime
from .python_ed2k import Client, Settings, Transfer, TransferState
from .python_ed2k.errors import ErrorCode, Error
+MIN_GOED2KD_VERSION = (0, 2, 4)
+
+
@dataclass(frozen=True)
class RunResult:
fileHash: str
@@ -39,8 +43,9 @@ class ED2kSession:
fileHash: str,
name: str,
outputFolder: Path,
- onStarted: Callable[[RunResult], None] | None = None,
- onProgress: Callable[[Transfer], None] | None = None,
+ uploadedBytes: int,
+ onStarted: Callable[[RunResult], None],
+ onProgress: Callable[[Transfer, int], None],
) -> None:
_, linkSize, linkHash = parseEd2kLink(link)
identity = toTransferKey(linkHash, linkSize)
@@ -76,21 +81,22 @@ class ED2kSession:
raise TaskError("ED2k 错误:{detail}", detail=str(e)) from e
fileHash = transfer.hash
- if onStarted:
- onStarted(RunResult(
+ onStarted(RunResult(
fileHash=fileHash,
- name=transfer.name or name,
- fileSize=transfer.size,
- ))
+ 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 onProgress:
- onProgress(t)
+ if firstUpload is None:
+ firstUpload = t.upload
+ onProgress(t, uploadedBytes + t.upload - firstUpload)
if t.state == TransferState.FINISHED:
await client.pause(fileHash)
return
@@ -111,8 +117,9 @@ class ED2kSession:
link: str,
fileHash: str,
seedingTimeSeconds: int,
+ uploadedBytes: int,
isManual: bool,
- onProgress: Callable[[Transfer, int], None],
+ onProgress: Callable[[Transfer, int, int], None],
) -> None:
_, linkSize, linkHash = parseEd2kLink(link)
identity = toTransferKey(linkHash, linkSize)
@@ -126,13 +133,17 @@ class ED2kSession:
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)
- onProgress(t, elapsed)
- if not isManual and isSeedingLimitReached(elapsed):
+ uploaded = uploadedBytes + t.upload - firstUpload
+ onProgress(t, elapsed, uploaded)
+ if not isManual and isSeedingLimitReached(elapsed, uploaded, t.size):
await client.pause(fileHash)
return
break
@@ -173,6 +184,11 @@ class ED2kSession:
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,
@@ -194,9 +210,12 @@ class ED2kSession:
ed2kSession = ED2kSession()
-def isSeedingLimitReached(elapsed: int) -> bool:
- limit = ed2kConfig.seedingTimeLimit.value
- return limit > 0 and elapsed >= limit * 60
+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]:
diff --git a/features/ed2k_pack/task.py b/features/ed2k_pack/task.py
index 520bf05c..b6d38482 100644
--- a/features/ed2k_pack/task.py
+++ b/features/ed2k_pack/task.py
@@ -14,28 +14,36 @@ class ED2kTask(Task):
activePeerCount: int | None = None
totalPeerCount: int = 0
uploadRate: int = 0
+ uploadedBytes: int = 0
seedingTimeSeconds: int = 0
+ @property
+ def shareRatioPercent(self) -> float:
+ 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
+ self.uploadedBytes = 0
self.seedingTimeSeconds = 0
return super().reset()
async def runSeeding(self, isManual: bool) -> None:
from .session import ed2kSession
- def onProgress(t: Transfer, elapsed: int):
+ 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, isManual, onProgress)
+ self.url, self.fileHash, self.seedingTimeSeconds, self.uploadedBytes,
+ isManual, onProgress)
finally:
self.uploadRate = 0
@@ -60,8 +68,9 @@ class ED2kTaskStep(TaskStep):
if result.fileSize:
task.fileSize = result.fileSize
- def onProgress(t: Transfer):
+ 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
@@ -72,7 +81,7 @@ class ED2kTaskStep(TaskStep):
self.progress = min(99.9, t.received / t.size * 100)
await ed2kSession.run(
- task.url, task.fileHash, task.name, task.outputFolder,
+ task.url, task.fileHash, task.name, task.outputFolder, task.uploadedBytes,
onStarted=onStarted,
onProgress=onProgress,
)
diff --git a/scripts/sync_python_ed2k.py b/scripts/sync_python_ed2k.py
new file mode 100644
index 00000000..fadbe9b3
--- /dev/null
+++ b/scripts/sync_python_ed2k.py
@@ -0,0 +1,23 @@
+#!/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_task.py b/tests/test_ed2k_task.py
index 16ce8661..1630aba8 100644
--- a/tests/test_ed2k_task.py
+++ b/tests/test_ed2k_task.py
@@ -4,6 +4,7 @@ from pathlib import Path
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.pack import ED2kParser
@@ -41,6 +42,7 @@ class FakeClient:
received=0,
downloadRate=0,
uploadRate=0,
+ upload=0,
activePeers=0,
peers=0,
)
@@ -52,7 +54,7 @@ class FakeClient:
async def snapshots(self):
self.snapshotStarted.set()
- yield Snapshot(transfers=(self.transfer,))
+ yield Snapshot(transfers=(self.transfer,), serverConnected=True, kadNodes=0)
await asyncio.Event().wait()
async def pause(self, fileHash: str) -> None:
@@ -75,6 +77,7 @@ class DuplicateClient(FakeClient):
received=0,
downloadRate=0,
uploadRate=0,
+ upload=0,
activePeers=0,
peers=0,
)
@@ -288,6 +291,54 @@ 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 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()
+
+
+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
+
+ await task.run(lambda _: None, noLimit)
+
+ assert task.uploadedBytes == 140
+
+
+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
+
+ await task.runSeeding(isManual=False)
+
+ assert task.uploadedBytes == 1240
+ assert task.shareRatioPercent >= 100
+ assert fakeClient.paused == [FILE_HASH]
+
+
async def test_parser_rejects_active_duplicate_on_add_task_page(monkeypatch, tmp_path):
session = session_module.ED2kSession()
identity = toTransferKey(FILE_HASH, 1234)
@@ -314,3 +365,36 @@ async def test_active_duplicate_never_reaches_daemon(monkeypatch, tmp_path):
assert fakeClient.added == []
session._activeTransfers.discard(identity)
+
+
+class StartedClient:
+ isRunning = True
+
+ def __init__(self, executable, dataDir):
+ pass
+
+ 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),
+])
+async def test_open_rejects_an_outdated_goed2kd(monkeypatch, version, isAccepted):
+ async def probeVersion():
+ return VersionInfo(version)
+
+ 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()
+
+ if isAccepted:
+ await session._open()
+ assert session._client is not None
+ else:
+ with pytest.raises(TaskError):
+ await session._open()
+ assert session._client is None