Skip to content

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

feat(task): 做种不再占着活动列表和任务槽

XiaoYouChR612103bc1d5d
diff --git a/CONTEXT.md b/CONTEXT.md
index ce3c5d85..c4529fb3 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -58,6 +58,11 @@ _Avoid_: 与泛义"资源"混淆
Task 在下载循环中的当前执行。一个 Task 同时只有零或一个活跃的 Task Run。
_Avoid_: execution、session
+**Seeding**:
+已完成的 Task 继续向他人提供其成品。不是 Task Run,不占任务槽,Task 保持 COMPLETED。
+用户可随时开关;到达上限或用户关掉后不再自动恢复,否则随应用启动恢复。
+_Avoid_: 与 Seed(Pack 同步)混淆;sharing;第六个 Task 状态
+
**Task Step**:
Task 内的一个可执行步骤。一个 Task 可能有一个或多个 Step。
_Avoid_: stage、phase、action
diff --git a/app/assets/i18n/gd3.en_US.ts b/app/assets/i18n/gd3.en_US.ts
index b1397b14..470e6ea2 100644
--- a/app/assets/i18n/gd3.en_US.ts
+++ b/app/assets/i18n/gd3.en_US.ts
@@ -311,9 +311,8 @@
<translation>Queued for Checks</translation>
</message>
<message>
- <location filename="../../../features/bittorrent_pack/cards.py" line="62" />
<source>已暂停做种</source>
- <translation>Seeding Paused</translation>
+ <translation type="vanished">Seeding Paused</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/cards.py" line="63" />
@@ -710,22 +709,22 @@ http://example.com/{mp4,mkv}/video</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="75" />
- <source>自动暂停做种分享率</source>
+ <source>自动停止做种分享率</source>
<translation>Auto Seeding Ratio Limit</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="76" />
- <source>0 表示不按分享率自动暂停,100% 表示分享率 1.0</source>
+ <source>0 表示不按分享率自动停止,100% 表示分享率 1.0</source>
<translation>0 means no seed ratio limit, 100% means a seed ratio of 1.0</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="78" />
- <source>自动暂停做种时长</source>
+ <source>自动停止做种时长</source>
<translation>Auto Seeding Time Limit</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="79" />
- <source>0 表示不按做种时长自动暂停</source>
+ <source>0 表示不按做种时长自动停止</source>
<translation>0 means no seeding time limit</translation>
</message>
<message>
@@ -1568,12 +1567,12 @@ You can adjust options in Settings at any time.</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="76" />
- <source>自动暂停共享时长</source>
+ <source>自动停止共享时长</source>
<translation>Auto Sharing Time Limit</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="77" />
- <source>0 表示不按共享时长自动暂停</source>
+ <source>0 表示不按共享时长自动停止</source>
<translation>0 means no sharing time limit</translation>
</message>
</context>
diff --git a/app/assets/i18n/gd3.es_ES.ts b/app/assets/i18n/gd3.es_ES.ts
index a0455e95..22318900 100644
--- a/app/assets/i18n/gd3.es_ES.ts
+++ b/app/assets/i18n/gd3.es_ES.ts
@@ -167,9 +167,8 @@
<translation>Esperando verificación</translation>
</message>
<message>
- <location filename="../../../features/bittorrent_pack/cards.py" line="62" />
<source>已暂停做种</source>
- <translation>Compartición pausada</translation>
+ <translation type="vanished">Compartición pausada</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/cards.py" line="63" />
@@ -518,22 +517,22 @@ http://example.com/{mp4,mkv}/video</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="75" />
- <source>自动暂停做种分享率</source>
+ <source>自动停止做种分享率</source>
<translation>Automático Seeding Ratio Límite</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="76" />
- <source>0 表示不按分享率自动暂停,100% 表示分享率 1.0</source>
+ <source>0 表示不按分享率自动停止,100% 表示分享率 1.0</source>
<translation>0 = sin límite de ratio; 100% = ratio de 1.0</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="78" />
- <source>自动暂停做种时长</source>
+ <source>自动停止做种时长</source>
<translation>Automático Seeding Time Límite</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="79" />
- <source>0 表示不按做种时长自动暂停</source>
+ <source>0 表示不按做种时长自动停止</source>
<translation>0 = sin límite de tiempo de compartición</translation>
</message>
<message>
@@ -1102,12 +1101,12 @@ You can adjust all options in Ajustes at any time.</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="76" />
- <source>自动暂停共享时长</source>
+ <source>自动停止共享时长</source>
<translation>Tiempo límite de compartición automática</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="77" />
- <source>0 表示不按共享时长自动暂停</source>
+ <source>0 表示不按共享时长自动停止</source>
<translation>0 = sin límite por tiempo de compartición</translation>
</message>
</context>
diff --git a/app/assets/i18n/gd3.ja_JP.ts b/app/assets/i18n/gd3.ja_JP.ts
index 0164fd70..2d2ee647 100644
--- a/app/assets/i18n/gd3.ja_JP.ts
+++ b/app/assets/i18n/gd3.ja_JP.ts
@@ -323,9 +323,8 @@
<translation>検証待ち</translation>
</message>
<message>
- <location filename="../../../features/bittorrent_pack/cards.py" line="62" />
<source>已暂停做种</source>
- <translation>シード一時停止中</translation>
+ <translation type="vanished">シード一時停止中</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/cards.py" line="63" />
@@ -726,23 +725,23 @@ http://example.com/{mp4,mkv}/video</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="75" />
- <source>自动暂停做种分享率</source>
- <translation>自動一時停止シード共有率</translation>
+ <source>自动停止做种分享率</source>
+ <translation>自動停止シード共有率</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="76" />
- <source>0 表示不按分享率自动暂停,100% 表示分享率 1.0</source>
- <translation>0 は共有率による自動一時停止無効、100% は共有率 1.0</translation>
+ <source>0 表示不按分享率自动停止,100% 表示分享率 1.0</source>
+ <translation>0 は共有率による自動停止無効、100% は共有率 1.0</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="78" />
- <source>自动暂停做种时长</source>
- <translation>自動一時停止シード時間</translation>
+ <source>自动停止做种时长</source>
+ <translation>自動停止シード時間</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="79" />
- <source>0 表示不按做种时长自动暂停</source>
- <translation>0 はシード時間による自動一時停止無効</translation>
+ <source>0 表示不按做种时长自动停止</source>
+ <translation>0 はシード時間による自動停止無効</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="81" />
@@ -1587,13 +1586,13 @@ http://example.com/{mp4,mkv}/video</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="76" />
- <source>自动暂停共享时长</source>
- <translation>共有時間の自動一時停止</translation>
+ <source>自动停止共享时长</source>
+ <translation>共有時間の自動停止</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="77" />
- <source>0 表示不按共享时长自动暂停</source>
- <translation>0 は共有時間による自動一時停止無効</translation>
+ <source>0 表示不按共享时长自动停止</source>
+ <translation>0 は共有時間による自動停止無効</translation>
</message>
</context>
<context>
diff --git a/app/assets/i18n/gd3.pt_BR.ts b/app/assets/i18n/gd3.pt_BR.ts
index a6e14505..f7008e5f 100644
--- a/app/assets/i18n/gd3.pt_BR.ts
+++ b/app/assets/i18n/gd3.pt_BR.ts
@@ -267,9 +267,8 @@
<translation>Aguardando verificação</translation>
</message>
<message>
- <location filename="../../../features/bittorrent_pack/cards.py" line="62" />
<source>已暂停做种</source>
- <translation>Seeding pausado</translation>
+ <translation type="vanished">Seeding pausado</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/cards.py" line="63" />
@@ -622,23 +621,23 @@ http://example.com/{mp4,mkv}/video</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="75" />
- <source>自动暂停做种分享率</source>
- <translation>Taxa de compartilhamento para pausa automática de seeding</translation>
+ <source>自动停止做种分享率</source>
+ <translation>Taxa de compartilhamento para parada automática de seeding</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="76" />
- <source>0 表示不按分享率自动暂停,100% 表示分享率 1.0</source>
- <translation>0 desativa a pausa automática por taxa de compartilhamento; 100% significa taxa 1,0</translation>
+ <source>0 表示不按分享率自动停止,100% 表示分享率 1.0</source>
+ <translation>0 desativa a parada automática por taxa de compartilhamento; 100% significa taxa 1,0</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="78" />
- <source>自动暂停做种时长</source>
- <translation>Duração de seeding para pausa automática</translation>
+ <source>自动停止做种时长</source>
+ <translation>Duração de seeding para parada automática</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="79" />
- <source>0 表示不按做种时长自动暂停</source>
- <translation>0 desativa a pausa automática por duração de seeding</translation>
+ <source>0 表示不按做种时长自动停止</source>
+ <translation>0 desativa a parada automática por duração de seeding</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="81" />
@@ -1240,13 +1239,13 @@ Você pode ajustar todas as opções nas configurações a qualquer momento.</tr
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="76" />
- <source>自动暂停共享时长</source>
- <translation>Duração de compartilhamento para pausa automática</translation>
+ <source>自动停止共享时长</source>
+ <translation>Duração de compartilhamento para parada automática</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="77" />
- <source>0 表示不按共享时长自动暂停</source>
- <translation>0 desativa a pausa automática por duração de compartilhamento</translation>
+ <source>0 表示不按共享时长自动停止</source>
+ <translation>0 desativa a parada automática por duração de compartilhamento</translation>
</message>
</context>
<context>
diff --git a/app/assets/i18n/gd3.ru_RU.ts b/app/assets/i18n/gd3.ru_RU.ts
index 18a03c2d..805fedde 100644
--- a/app/assets/i18n/gd3.ru_RU.ts
+++ b/app/assets/i18n/gd3.ru_RU.ts
@@ -323,9 +323,8 @@
<translation>Ожидание проверки</translation>
</message>
<message>
- <location filename="../../../features/bittorrent_pack/cards.py" line="62" />
<source>已暂停做种</source>
- <translation>Приостановлена раздача</translation>
+ <translation type="vanished">Приостановлена раздача</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/cards.py" line="63" />
@@ -726,22 +725,22 @@ http://example.com/{mp4,mkv}/video</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="75" />
- <source>自动暂停做种分享率</source>
- <translation>Автопауза по ratio</translation>
+ <source>自动停止做种分享率</source>
+ <translation>Автоостановка по ratio</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="76" />
- <source>0 表示不按分享率自动暂停,100% 表示分享率 1.0</source>
+ <source>0 表示不按分享率自动停止,100% 表示分享率 1.0</source>
<translation>0 — не останавливать по коэффициенту, 100% — коэффициент 1.0</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="78" />
- <source>自动暂停做种时长</source>
- <translation>Автопауза по времени</translation>
+ <source>自动停止做种时长</source>
+ <translation>Автоостановка по времени</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="79" />
- <source>0 表示不按做种时长自动暂停</source>
+ <source>0 表示不按做种时长自动停止</source>
<translation>0 — не останавливать по времени сидирования</translation>
</message>
<message>
@@ -1587,12 +1586,12 @@ http://example.com/{mp4,mkv}/video</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="76" />
- <source>自动暂停共享时长</source>
- <translation>Автопауза по времени раздачи</translation>
+ <source>自动停止共享时长</source>
+ <translation>Автоостановка по времени раздачи</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="77" />
- <source>0 表示不按共享时长自动暂停</source>
+ <source>0 表示不按共享时长自动停止</source>
<translation>0 — не останавливать по времени раздачи</translation>
</message>
</context>
diff --git a/app/assets/i18n/gd3.zh_CN.ts b/app/assets/i18n/gd3.zh_CN.ts
index 88b17bfa..459c29b4 100644
--- a/app/assets/i18n/gd3.zh_CN.ts
+++ b/app/assets/i18n/gd3.zh_CN.ts
@@ -162,11 +162,6 @@
<source>等待校验</source>
<translation type="unfinished"></translation>
</message>
- <message>
- <location filename="../../../features/bittorrent_pack/cards.py" line="62"/>
- <source>已暂停做种</source>
- <translation type="unfinished"></translation>
- </message>
<message>
<location filename="../../../features/bittorrent_pack/cards.py" line="63"/>
<source>已暂停下载</source>
@@ -509,22 +504,22 @@ http://example.com/{mp4,mkv}/video</source>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="75"/>
- <source>自动暂停做种分享率</source>
+ <source>自动停止做种分享率</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="76"/>
- <source>0 表示不按分享率自动暂停,100% 表示分享率 1.0</source>
+ <source>0 表示不按分享率自动停止,100% 表示分享率 1.0</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="78"/>
- <source>自动暂停做种时长</source>
+ <source>自动停止做种时长</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="79"/>
- <source>0 表示不按做种时长自动暂停</source>
+ <source>0 表示不按做种时长自动停止</source>
<translation type="unfinished"></translation>
</message>
<message>
@@ -1087,12 +1082,12 @@ http://example.com/{mp4,mkv}/video</source>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="76"/>
- <source>自动暂停共享时长</source>
+ <source>自动停止共享时长</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="77"/>
- <source>0 表示不按共享时长自动暂停</source>
+ <source>0 表示不按共享时长自动停止</source>
<translation type="unfinished"></translation>
</message>
</context>
diff --git a/app/assets/i18n/gd3.zh_HK.ts b/app/assets/i18n/gd3.zh_HK.ts
index 3b950f10..2c8adfee 100644
--- a/app/assets/i18n/gd3.zh_HK.ts
+++ b/app/assets/i18n/gd3.zh_HK.ts
@@ -323,9 +323,8 @@
<translation>等候校驗</translation>
</message>
<message>
- <location filename="../../../features/bittorrent_pack/cards.py" line="62" />
<source>已暂停做种</source>
- <translation>已暫停做種</translation>
+ <translation type="vanished">已暫停做種</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/cards.py" line="63" />
@@ -726,23 +725,23 @@ http://example.com/{mp4,mkv}/video</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="75" />
- <source>自动暂停做种分享率</source>
- <translation>自動暫停做種分享率</translation>
+ <source>自动停止做种分享率</source>
+ <translation>自動停止做種分享率</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="76" />
- <source>0 表示不按分享率自动暂停,100% 表示分享率 1.0</source>
- <translation>0 表示唔按分享率自動暫停,100% 表示分享率 1.0</translation>
+ <source>0 表示不按分享率自动停止,100% 表示分享率 1.0</source>
+ <translation>0 表示唔按分享率自動停止,100% 表示分享率 1.0</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="78" />
- <source>自动暂停做种时长</source>
- <translation>自動暫停做種時長</translation>
+ <source>自动停止做种时长</source>
+ <translation>自動停止做種時長</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="79" />
- <source>0 表示不按做种时长自动暂停</source>
- <translation>0 表示唔按做種時長自動暫停</translation>
+ <source>0 表示不按做种时长自动停止</source>
+ <translation>0 表示唔按做種時長自動停止</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="81" />
@@ -1587,13 +1586,13 @@ http://example.com/{mp4,mkv}/video</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="76" />
- <source>自动暂停共享时长</source>
- <translation>自動暫停共享時長</translation>
+ <source>自动停止共享时长</source>
+ <translation>自動停止共享時長</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="77" />
- <source>0 表示不按共享时长自动暂停</source>
- <translation>0 表示不按共享時長自動暫停</translation>
+ <source>0 表示不按共享时长自动停止</source>
+ <translation>0 表示不按共享時長自動停止</translation>
</message>
</context>
<context>
diff --git a/app/assets/i18n/gd3.zh_TW.ts b/app/assets/i18n/gd3.zh_TW.ts
index b4cb2199..76256801 100644
--- a/app/assets/i18n/gd3.zh_TW.ts
+++ b/app/assets/i18n/gd3.zh_TW.ts
@@ -323,9 +323,8 @@
<translation>等待校驗</translation>
</message>
<message>
- <location filename="../../../features/bittorrent_pack/cards.py" line="62" />
<source>已暂停做种</source>
- <translation>已暫停做種</translation>
+ <translation type="vanished">已暫停做種</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/cards.py" line="63" />
@@ -726,23 +725,23 @@ http://example.com/{mp4,mkv}/video</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="75" />
- <source>自动暂停做种分享率</source>
- <translation>自動暫停做種分享率</translation>
+ <source>自动停止做种分享率</source>
+ <translation>自動停止做種分享率</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="76" />
- <source>0 表示不按分享率自动暂停,100% 表示分享率 1.0</source>
- <translation>0 表示不按分享率自動暫停,100% 表示分享率 1.0</translation>
+ <source>0 表示不按分享率自动停止,100% 表示分享率 1.0</source>
+ <translation>0 表示不按分享率自動停止,100% 表示分享率 1.0</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="78" />
- <source>自动暂停做种时长</source>
- <translation>自動暫停做種時長</translation>
+ <source>自动停止做种时长</source>
+ <translation>自動停止做種時長</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="79" />
- <source>0 表示不按做种时长自动暂停</source>
- <translation>0 表示不按做種時長自動暫停</translation>
+ <source>0 表示不按做种时长自动停止</source>
+ <translation>0 表示不按做種時長自動停止</translation>
</message>
<message>
<location filename="../../../features/bittorrent_pack/config.py" line="81" />
@@ -1587,13 +1586,13 @@ http://example.com/{mp4,mkv}/video</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="76" />
- <source>自动暂停共享时长</source>
- <translation>自動暫停共享時長</translation>
+ <source>自动停止共享时长</source>
+ <translation>自動停止共享時長</translation>
</message>
<message>
<location filename="../../../features/ed2k_pack/config.py" line="77" />
- <source>0 表示不按共享时长自动暂停</source>
- <translation>0 表示不按共享時長自動暫停</translation>
+ <source>0 表示不按共享时长自动停止</source>
+ <translation>0 表示不按共享時長自動停止</translation>
</message>
</context>
<context>
diff --git a/app/models/task.py b/app/models/task.py
index a4fee88d..a1d0608f 100644
--- a/app/models/task.py
+++ b/app/models/task.py
@@ -201,6 +201,7 @@ class Task:
canEdit: ClassVar[bool] = False
fileType: ClassVar[type] = TaskFile
hasOutputFile: ClassVar[bool] = True
+ canSeed: ClassVar[bool] = False
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
@@ -218,6 +219,8 @@ class Task:
fileSize: int = 0
files: list[TaskFile] | None = None
category: str | None = None
+ shouldSeed: bool = False
+ isSeeding: bool = field(default=False, init=False, repr=False)
@property
def outputPath(self) -> str:
@@ -360,6 +363,7 @@ class Task:
def reset(self) -> TaskStatus:
self.completedAt = 0
+ self.shouldSeed = True
if not self.steps:
self.status = TaskStatus.WAITING
return self.status
@@ -441,6 +445,9 @@ class Task:
logger.opt(exception=e).error("{} failed", self.name)
raise
+ async def runSeeding(self, isManual: bool) -> None:
+ raise NotImplementedError
+
def toDict(self) -> dict:
from app.models.serialization import toDict
return toDict(self)
diff --git a/app/services/task_service.py b/app/services/task_service.py
index ada9dfbb..932a9a7b 100644
--- a/app/services/task_service.py
+++ b/app/services/task_service.py
@@ -141,6 +141,8 @@ class TaskService:
taskCompleted = Signal(object)
taskFailed = Signal(object)
tasksAllCompleted = Signal()
+ seedingStarted = Signal(object)
+ seedingStopped = Signal(object)
queueChanged = Signal()
fileDisappeared = Signal(object)
fileDeleteDenied = Signal()
@@ -152,6 +154,7 @@ class TaskService:
self._speedMeter = speedMeter
self._store = TaskStore()
self._queue = TaskQueue()
+ self._seeding: dict[str, str] = {}
self._fileWatcher = fileWatcher
self._watchedPaths: dict[str, str] = {}
self._fileWatcher.fileChanged.connect(self._onWatchedFileChanged)
@@ -189,6 +192,7 @@ class TaskService:
if task.taskId in self._store.tasks:
return
task.category, task.outputFolder = self._categoryService.outputFolderOf(task)
+ task.shouldSeed = True
self._deduplicateOutput(task)
self._store.add(task)
self._flushSoon()
@@ -228,9 +232,19 @@ class TaskService:
return
self._schedule(task)
+ def startSeeding(self, task: Task) -> None:
+ task.shouldSeed = True
+ self._flushSoon()
+ self._seed(task, isManual=True)
+
+ def stopSeeding(self, task: Task) -> None:
+ task.shouldSeed = False
+ self._flushSoon()
+ self._cancelWork(task)
+
def pause(self, task: Task) -> None:
from app.models.task import TaskStatus
- self._cancelRun(task)
+ self._cancelWork(task)
task.setStatus(TaskStatus.PAUSED)
self._flushSoon()
self.taskPaused.emit(task)
@@ -242,7 +256,7 @@ class TaskService:
if shouldDeleteFiles and not canDelete and not self._hasNotifiedDeleteDenied:
self._hasNotifiedDeleteDenied = True
self.fileDeleteDenied.emit()
- self._cancelRun(task, finished=task.deleteFiles if canDelete else None)
+ self._cancelWork(task, finished=task.deleteFiles if canDelete else None)
self._store.remove(task.taskId)
self._flushSoon()
self.taskRemoved.emit(task.taskId)
@@ -255,7 +269,7 @@ class TaskService:
task.reset()
self._flushSoon()
self._schedule(task)
- self._cancelRun(task, finished=onStopped)
+ self._cancelWork(task, finished=onStopped)
def edit(self, task: Task, options: dict, newTask: Task | None = None) -> None:
needsDelete = newTask is not None and not task.canReuseProgress(newTask)
@@ -267,7 +281,7 @@ class TaskService:
task.setOptions(options)
self._flushSoon()
self._schedule(task)
- self._cancelRun(task, finished=onStopped)
+ self._cancelWork(task, finished=onStopped)
def setCategory(self, task: Task, categoryId: str) -> None:
task.category = categoryId
@@ -284,7 +298,7 @@ class TaskService:
if wasCompleted and task.files and any(f.selected and not f.completed for f in task.files):
task.completedAt = 0
self._unwatchFile(task)
- self._schedule(task)
+ self._cancelWork(task, finished=lambda: self._schedule(task))
self._flushSoon()
isRunningDeselected = False
@@ -299,7 +313,7 @@ class TaskService:
def onStopped():
apply()
self._schedule(task)
- self._cancelRun(task, finished=onStopped)
+ self._cancelWork(task, finished=onStopped)
return
apply()
@@ -320,6 +334,8 @@ class TaskService:
self.taskAdded.emit(task)
if task.status == TaskStatus.COMPLETED and task.hasOutputFile and isExisting(task.outputPath):
self._watchFile(task)
+ if task.canSeed and task.shouldSeed:
+ self._seed(task)
elif task.status in {TaskStatus.WAITING, TaskStatus.RUNNING}:
task.setStatus(TaskStatus.WAITING)
self._schedule(task)
@@ -373,6 +389,25 @@ class TaskService:
self._queue.run(task.taskId, workId)
self.taskStarted.emit(task)
+ def _seed(self, task: Task, isManual: bool = False) -> None:
+ task.isSeeding = True
+ self._seeding[task.taskId] = self._coroutineRunner.submit(
+ task.runSeeding(isManual),
+ done=lambda _: self._onSeedingDone(task),
+ failed=lambda _: self._onSeedingEnded(task),
+ )
+ self.seedingStarted.emit(task)
+
+ def _onSeedingDone(self, task: Task) -> None:
+ task.shouldSeed = False
+ self._onSeedingEnded(task)
+
+ def _onSeedingEnded(self, task: Task) -> None:
+ self._seeding.pop(task.taskId, None)
+ task.isSeeding = False
+ self._flushSoon()
+ self.seedingStopped.emit(task)
+
def _canDeleteIn(self, folder: Path) -> bool:
if sys.platform != "darwin":
return True
@@ -384,9 +419,12 @@ class TaskService:
except OSError:
return True
- def _cancelRun(self, task: Task, finished: Callable = None) -> None:
- workId = self._queue.workIdOf(task.taskId)
+ def _cancelWork(self, task: Task, finished: Callable = None) -> None:
+ workId = self._queue.workIdOf(task.taskId) or self._seeding.pop(task.taskId, None)
self._queue.cancel(task.taskId)
+ if task.isSeeding:
+ task.isSeeding = False
+ self.seedingStopped.emit(task)
if workId is not None:
self._coroutineRunner.cancel(workId, finished=finished)
elif finished is not None:
@@ -397,7 +435,7 @@ class TaskService:
for taskId in self._queue.runningIds()[cfg.maxTaskNum.value:]:
task = self._store.taskById(taskId)
if task is not None and task.canPause:
- self._cancelRun(task)
+ self._cancelWork(task)
task.setStatus(TaskStatus.WAITING)
self._queue.wait(taskId)
self._pump()
@@ -412,11 +450,14 @@ class TaskService:
self._dispatch(task)
def _onRunDone(self, task: Task) -> None:
+ from app.models.task import TaskStatus
self._queue.done(task.taskId)
self._flushSoon()
self.taskCompleted.emit(task)
if task.hasOutputFile:
self._watchFile(task)
+ if task.status == TaskStatus.COMPLETED and task.canSeed and task.shouldSeed:
+ self._seed(task)
self._pump()
if self._queue.runningCount() == 0:
self.tasksAllCompleted.emit()
@@ -447,4 +488,5 @@ class TaskService:
return
task = self._store.taskById(taskId)
if task is not None:
+ self._cancelWork(task)
self.fileDisappeared.emit(task)
diff --git a/app/view/cards/task_cards.py b/app/view/cards/task_cards.py
index 519812e4..7801bc8d 100644
--- a/app/view/cards/task_cards.py
+++ b/app/view/cards/task_cards.py
@@ -80,7 +80,9 @@ SIZE_FIELD = FieldSpec("size", FluentIcon.LIBRARY, {None: toSizeText})
TOGGLE_BUTTON = ButtonSpec("toggle", FluentIcon.PLAY, N("TaskCard", "暂停/继续"), PrimaryToolButton, states={
TaskStatus.RUNNING: lambda t: ButtonState(icon=FluentIcon.PAUSE, enabled=t.canPause),
- TaskStatus.COMPLETED: lambda t: ButtonState(enabled=False),
+ TaskStatus.COMPLETED: lambda t: ButtonState(
+ icon=FluentIcon.PAUSE if t.isSeeding else None,
+ enabled=t.canSeed and (not t.hasOutputFile or isExisting(t.outputPath))),
})
SELECT_FILES_BUTTON = ButtonSpec("selectFiles", FluentIcon.LIBRARY, N("TaskCard", "选择文件"),
@@ -214,7 +216,8 @@ class TaskCard(CardWidget):
self._categoryService.categoriesChanged.connect(self._refreshCategoryIcon)
def refresh(self, force: bool = False) -> None:
- if not force and self._lastStatus == self._task.status and self._task.status != TaskStatus.RUNNING:
+ if (not force and self._lastStatus == self._task.status
+ and self._task.status != TaskStatus.RUNNING and not self._task.isSeeding):
return
task = self._task
@@ -316,7 +319,11 @@ class TaskCard(CardWidget):
button.setEnabled(state.enabled)
def _onToggleClicked(self) -> None:
- if self._task.status == TaskStatus.RUNNING:
+ if self._task.isSeeding:
+ self._taskService.stopSeeding(self._task)
+ elif self._task.status == TaskStatus.COMPLETED:
+ self._taskService.startSeeding(self._task)
+ elif self._task.status == TaskStatus.RUNNING:
self._taskService.pause(self._task)
else:
self._taskService.start(self._task)
diff --git a/app/view/pages/task_page.py b/app/view/pages/task_page.py
index c50dfdf6..ef494bbe 100644
--- a/app/view/pages/task_page.py
+++ b/app/view/pages/task_page.py
@@ -150,7 +150,7 @@ class TaskPage(QWidget):
self._selectedIds: set[str] = set()
self._bandSnapshot: set[str] = set()
self._bandMerge = set.__or__
- self._runningIds: set[str] = set()
+ self._tickingIds: set[str] = set()
self._refreshListTimer = QTimer(self, singleShot=True)
self._refreshListTimer.setInterval(0)
@@ -158,7 +158,7 @@ class TaskPage(QWidget):
self._cardRefreshTimer = QTimer(self)
self._cardRefreshTimer.setInterval(1000)
- self._cardRefreshTimer.timeout.connect(self._refreshRunningCards)
+ self._cardRefreshTimer.timeout.connect(self._refreshTickingCards)
self.scrollArea = ScrollArea(self)
self.scrollWidget = QWidget(self)
@@ -284,7 +284,8 @@ class TaskPage(QWidget):
self._taskService.taskPaused.connect(self._onTaskStopped)
self._taskService.taskCompleted.connect(self._onTaskStopped)
self._taskService.taskFailed.connect(self._onTaskStopped)
- self._taskService.tasksAllCompleted.connect(self._onAllCompleted)
+ self._taskService.seedingStarted.connect(self._onSeedingStarted)
+ self._taskService.seedingStopped.connect(self._onSeedingStopped)
self._taskService.queueChanged.connect(self._onQueueChanged)
self._taskService.fileDisappeared.connect(self._onFileDisappeared)
self._taskService.fileDeleteDenied.connect(self._onFileDeleteDenied)
@@ -633,10 +634,11 @@ class TaskPage(QWidget):
tasks.sort(key=lambda t: t.createdAt, reverse=not self._sortAscending)
self._displayOrder = [t.taskId for t in tasks]
- self._runningIds = {t.taskId for t in self._taskService.tasks if t.status == TaskStatus.RUNNING}
- if self._runningIds and not self._cardRefreshTimer.isActive():
+ self._tickingIds = {t.taskId for t in self._taskService.tasks
+ if t.status == TaskStatus.RUNNING or t.isSeeding}
+ if self._tickingIds and not self._cardRefreshTimer.isActive():
self._cardRefreshTimer.start()
- elif not self._runningIds and self._cardRefreshTimer.isActive():
+ elif not self._tickingIds and self._cardRefreshTimer.isActive():
self._cardRefreshTimer.stop()
stride = TaskCard.ROW_HEIGHT + self.ROW_SPACING
count = len(self._displayOrder)
@@ -720,14 +722,14 @@ class TaskPage(QWidget):
card.setGeometry(self.SIDE_PADDING, idx * stride, max(0, width - 2 * self.SIDE_PADDING), TaskCard.ROW_HEIGHT)
card.show()
- def _refreshRunningCards(self) -> None:
- for taskId in self._runningIds:
+ def _refreshTickingCards(self) -> None:
+ for taskId in self._tickingIds:
card = self._liveCards.get(taskId)
if card is not None:
card.refresh()
def _onTaskStarted(self, task: Task) -> None:
- self._runningIds.add(task.taskId)
+ self._tickingIds.add(task.taskId)
card = self._liveCards.get(task.taskId)
if card is not None:
card.refresh()
@@ -736,17 +738,29 @@ class TaskPage(QWidget):
self._onQueueChanged()
def _onTaskStopped(self, task: Task) -> None:
- self._runningIds.discard(task.taskId)
+ self._tickingIds.discard(task.taskId)
card = self._liveCards.get(task.taskId)
if card is not None:
card.refresh()
- if not self._runningIds:
+ if not self._tickingIds:
self._cardRefreshTimer.stop()
self._onQueueChanged()
- def _onAllCompleted(self) -> None:
- self._runningIds.clear()
- self._cardRefreshTimer.stop()
+ def _onSeedingStarted(self, task: Task) -> None:
+ self._tickingIds.add(task.taskId)
+ card = self._liveCards.get(task.taskId)
+ if card is not None:
+ card.refresh()
+ if not self._cardRefreshTimer.isActive():
+ self._cardRefreshTimer.start()
+
+ def _onSeedingStopped(self, task: Task) -> None:
+ self._tickingIds.discard(task.taskId)
+ card = self._liveCards.get(task.taskId)
+ if card is not None:
+ card.refresh(force=True)
+ if not self._tickingIds:
+ self._cardRefreshTimer.stop()
# ── band selection ──
@@ -824,10 +838,10 @@ class TaskPage(QWidget):
if card is not None:
self._unmountCard(card)
self._selectedIds.discard(taskId)
- self._runningIds.discard(taskId)
+ self._tickingIds.discard(taskId)
if self._selectionAnchor == taskId:
self._selectionAnchor = None
- if not self._runningIds:
+ if not self._tickingIds:
self._cardRefreshTimer.stop()
self._refreshListTimer.start()
diff --git a/docs/adr/0011-seeding-is-not-a-task-run.md b/docs/adr/0011-seeding-is-not-a-task-run.md
new file mode 100644
index 00000000..d422a487
--- /dev/null
+++ b/docs/adr/0011-seeding-is-not-a-task-run.md
@@ -0,0 +1,20 @@
+# 做种不是 Task Run
+
+BT 与 eD2k 下载完成即结束 Task Run,Task 进入 COMPLETED;随后的 Seeding 是 App 管理生命周期的独立工作,
+不占任务槽,不阻塞 Plan、完成通知与睡眠抑制。一个 Task 同时最多一份活跃工作:Task Run 或 Seeding。
+App 只知道「已完成的 Task 可以继续服务他人、用户可开关」;分享率、时间上限、peers、上传速率等协议知识留在 pack,
+通过 `Task.runSeeding(isManual)` 这一 seam 接入——正常返回表示自行结束,取消表示被停止。
+
+## Considered Options
+
+- **做种期间保持 RUNNING,用 `usesSlot` 豁免槽位**(`d65b373e` 前的做法):Step RUNNING 而 Task 该算完成,
+ 状态派生、任务列表、Plan、完成通知都要为此开例外,且违反「零或一个 Task Run」。
+- **做种完全留在 pack 内,App 暴露生命周期钩子**:pack 看不到启动、删除、Revive、退出、文件消失这些时刻,
+ 需要一组 `onCompleted`/`onRemoved`/… 钩子,每个 pack 各自重搭同一台状态机——浅模块,两份实现。
+
+## Consequences
+
+- 正常退出不改 `shouldSeed`,下次启动自动恢复做种;到达上限或用户停止才置 False。
+- 用户手动开始做种(`isManual=True`)时 pack 忽略上限。
+- `shouldSeed` 默认 False,由 `TaskService.add` 置 True:升级前的 Task Record 没有这个字段,不会在升级后集体开始做种。
+- 桌面上做种不阻止睡眠;Android 上做种计入前台保活——前者是「防睡眠」,后者是「防杀进程」。
diff --git a/features/bittorrent_pack/android.py b/features/bittorrent_pack/android.py
index e46a1fcc..964c6e79 100644
--- a/features/bittorrent_pack/android.py
+++ b/features/bittorrent_pack/android.py
@@ -1,5 +1,6 @@
"""Android View adapter for BittorrentPack."""
from app.i18n import N
+from app.models.task import TaskStatus
UI_CLASS = "com.xychr.ghostdownloader.features.bittorrent_pack.BitTorrentUi"
@@ -9,15 +10,21 @@ STATE_TEXT = {
"downloading_metadata": N("TaskState", "获取元数据"),
"allocating": N("TaskState", "分配文件中"),
"queued_for_checking": N("TaskState", "等待校验"),
- "seeding": N("TaskState", "做种中"),
- "paused_seeding": N("TaskState", "暂停做种"),
}
+def toStatusText(task) -> str:
+ if task.isSeeding:
+ return N("TaskState", "做种中")
+ if task.status == TaskStatus.COMPLETED:
+ return ""
+ return STATE_TEXT.get(task.stateText, "")
+
+
def taskFields(task) -> dict:
return {
"progressMode": "hidden" if task.isSeeding else "determinate",
- "statusText": STATE_TEXT.get(task.stateText, ""),
+ "statusText": toStatusText(task),
"secondarySpeed": task.uploadRate,
"packFields": {
"peers": {"active": task.peerCount, "total": task.totalPeerCount},
diff --git a/features/bittorrent_pack/cards.py b/features/bittorrent_pack/cards.py
index fd1fdd09..04c79511 100644
--- a/features/bittorrent_pack/cards.py
+++ b/features/bittorrent_pack/cards.py
@@ -5,7 +5,7 @@ from qfluentwidgets import FluentIcon
from app.format import toReadableSize, toReadableTime
from app.models.task import TaskStatus
from app.view.cards.draft_cards import MultiFileDraftCard
-from app.view.cards.task_cards import MultiFileTaskCard, FieldSpec, toSizeText
+from app.view.cards.task_cards import ETA_FIELD, SIZE_FIELD, FieldSpec, MultiFileTaskCard
from app.view.components.labels import IconBodyLabel
from app.view.dialogs.file_select import FileSelectDialog
from .task import BTTask
@@ -16,28 +16,17 @@ class TorrentFileSelectDialog(FileSelectDialog):
return self._task.toRelativePath(file)
-def toBtEtaText(task: BTTask, speed: int, received: int) -> str | None:
- if task.isSeeding:
- return None
- if task.fileSize > 0 and speed > 0:
- return toReadableTime(int((task.fileSize - received) / speed))
- return "--"
-
-
-def toBtSizeText(task: BTTask, speed: int, received: int) -> str | None:
- if task.status == TaskStatus.RUNNING and task.isSeeding:
- return None
- return toSizeText(task, speed, received)
+def toUploadText(task: BTTask, _speed: int, _received: int) -> str:
+ return f"{toReadableSize(task.uploadRate)}/s"
BT_SPEED_FIELD = FieldSpec("speed", FluentIcon.DOWNLOAD, {
- TaskStatus.RUNNING: lambda t, s, r: None if t.isSeeding else f"{toReadableSize(s)}/s",
+ TaskStatus.RUNNING: lambda t, s, r: f"{toReadableSize(s)}/s",
})
BT_UPLOAD_FIELD = FieldSpec("upload", FluentIcon.SHARE, {
- TaskStatus.RUNNING: lambda t, s, r: f"{toReadableSize(t.uploadRate)}/s",
+ TaskStatus.RUNNING: toUploadText,
+ TaskStatus.COMPLETED: lambda t, s, r: toUploadText(t, s, r) if t.isSeeding else None,
})
-BT_ETA_FIELD = FieldSpec("eta", FluentIcon.STOP_WATCH, {TaskStatus.RUNNING: toBtEtaText})
-BT_SIZE_FIELD = FieldSpec("size", FluentIcon.LIBRARY, {None: toBtSizeText})
def toPeerText(task: BTTask, _speed: int, _received: int) -> str:
@@ -46,9 +35,10 @@ def toPeerText(task: BTTask, _speed: int, _received: int) -> str:
)
-BT_PEERS_FIELD = FieldSpec(
- "peers", FluentIcon.INFO, {TaskStatus.RUNNING: toPeerText}
-)
+BT_PEERS_FIELD = FieldSpec("peers", FluentIcon.INFO, {
+ TaskStatus.RUNNING: toPeerText,
+ TaskStatus.COMPLETED: lambda t, s, r: toPeerText(t, s, r) if t.isSeeding else None,
+})
BT_STATE_LABELS = {
"checking_files": N("BTTaskCard", "校验已有文件"),
@@ -59,7 +49,6 @@ BT_STATE_LABELS = {
"seeding": N("BTTaskCard", "做种中"),
"allocating": N("BTTaskCard", "分配文件中"),
"queued_for_checking": N("BTTaskCard", "等待校验"),
- "paused_seeding": N("BTTaskCard", "已暂停做种"),
"paused_downloading": N("BTTaskCard", "已暂停下载"),
}
@@ -87,14 +76,13 @@ class BTTaskCard(MultiFileTaskCard):
uploadLabel: IconBodyLabel
fileSelectDialog = TorrentFileSelectDialog
infoFields = [
- BT_SPEED_FIELD, BT_UPLOAD_FIELD, BT_ETA_FIELD, BT_SIZE_FIELD,
+ BT_SPEED_FIELD, BT_UPLOAD_FIELD, ETA_FIELD, SIZE_FIELD,
BT_PEERS_FIELD,
]
def _refreshForStatus(self, task):
super()._refreshForStatus(task)
- if task.status == TaskStatus.RUNNING and task.isSeeding:
- self.progressBar.hide()
+ if task.isSeeding and not self._isFileMissing:
parts = []
if task.shareRatioPercent > 0:
parts.append(self.tr("分享率 {0}").format(f"{task.shareRatioPercent:.1f}%"))
diff --git a/features/bittorrent_pack/config.py b/features/bittorrent_pack/config.py
index 5c2197a0..4808ccdd 100644
--- a/features/bittorrent_pack/config.py
+++ b/features/bittorrent_pack/config.py
@@ -72,11 +72,11 @@ class BitTorrentConfig(PackConfig):
SpinBoxSettingCard(FluentIcon.SHARE, self.tr("上传限速"),
self.tr("0 表示不限速,单位为 session 级别的 KB/s"), " KB/s",
self.maxUploadSpeed, btGroup, 64, 1 / 1024),
- SpinBoxSettingCard(FluentIcon.SHARE, self.tr("自动暂停做种分享率"),
- self.tr("0 表示不按分享率自动暂停,100% 表示分享率 1.0"), " %",
+ SpinBoxSettingCard(FluentIcon.SHARE, self.tr("自动停止做种分享率"),
+ self.tr("0 表示不按分享率自动停止,100% 表示分享率 1.0"), " %",
self.seedingRatioLimit, btGroup, 50),
- SpinBoxSettingCard(FluentIcon.STOP_WATCH, self.tr("自动暂停做种时长"),
- self.tr("0 表示不按做种时长自动暂停"), " min",
+ SpinBoxSettingCard(FluentIcon.STOP_WATCH, self.tr("自动停止做种时长"),
+ self.tr("0 表示不按做种时长自动停止"), " min",
self.seedingTimeLimit, btGroup, 10),
ComboBoxSettingCard(self.storageMode, FluentIcon.SAVE, self.tr("文件分配模式"),
self.tr("稀疏分配更省磁盘写入,预分配更容易提前暴露空间不足"),
diff --git a/features/bittorrent_pack/session.py b/features/bittorrent_pack/session.py
index a38986fb..cc34d535 100644
--- a/features/bittorrent_pack/session.py
+++ b/features/bittorrent_pack/session.py
@@ -80,6 +80,7 @@ class TorrentProgress:
totalPeerCount: int
seedCount: int
isSeeding: bool
+ isFinished: bool
downloadRate: int
uploadRate: int
shareRatioPercent: float
@@ -95,6 +96,7 @@ class ActiveTorrent:
handle: lt.torrent_handle
done: asyncio.Future
onProgress: Callable[[TorrentProgress], None] | None
+ isDone: Callable[[TorrentProgress], bool]
seedBase: int
seedStart: int | None = None
pollCount: int = 0
@@ -136,6 +138,18 @@ class BTSession:
async def run(self, taskId: str, params: TorrentParams,
onProgress: Callable[[TorrentProgress], None] | None = None) -> bytes:
+ return await self._run(taskId, params, onProgress, isDone=lambda p: p.isFinished)
+
+ async def runSeeding(self, taskId: str, params: TorrentParams, isManual: bool,
+ onProgress: Callable[[TorrentProgress], None] | None = None) -> bytes:
+ def isDone(p: TorrentProgress) -> bool:
+ return not isManual and p.isSeeding and self._isSeedingLimitReached(
+ p.shareRatioPercent, p.seedingTimeSeconds)
+ return await self._run(taskId, params, onProgress, isDone)
+
+ async def _run(self, taskId: str, params: TorrentParams,
+ onProgress: Callable[[TorrentProgress], None] | None,
+ isDone: Callable[[TorrentProgress], bool]) -> bytes:
self._ensureSession()
handle = self._addTorrent(params)
@@ -146,7 +160,7 @@ class BTSession:
done = asyncio.get_running_loop().create_future()
entry = ActiveTorrent(
- handle=handle, done=done, onProgress=onProgress,
+ handle=handle, done=done, onProgress=onProgress, isDone=isDone,
seedBase=params.seedingTimeSeconds,
)
self._active[taskId] = entry
@@ -474,32 +488,31 @@ class BTSession:
totalWanted = status.total_wanted
progress = (receivedBytes / totalWanted * 100) if totalWanted > 0 else 0
+ torrentProgress = TorrentProgress(
+ stateText=stateText,
+ peerCount=status.num_peers,
+ totalPeerCount=max(status.num_peers, status.list_peers),
+ seedCount=status.num_seeds,
+ isSeeding=isSeeding,
+ isFinished=status.is_finished,
+ downloadRate=downloadRate,
+ uploadRate=uploadRate,
+ shareRatioPercent=shareRatioPercent,
+ seedingTimeSeconds=seedingTimeSeconds,
+ progress=progress,
+ receivedBytes=receivedBytes,
+ totalWanted=totalWanted,
+ fileProgress=list(entry.handle.file_progress()),
+ )
if entry.onProgress is not None:
- entry.onProgress(TorrentProgress(
- stateText=stateText,
- peerCount=status.num_peers,
- totalPeerCount=max(status.num_peers, status.list_peers),
- seedCount=status.num_seeds,
- isSeeding=isSeeding,
- downloadRate=downloadRate,
- uploadRate=uploadRate,
- shareRatioPercent=shareRatioPercent,
- seedingTimeSeconds=seedingTimeSeconds,
- progress=progress,
- receivedBytes=receivedBytes,
- totalWanted=totalWanted,
- fileProgress=list(entry.handle.file_progress()),
- ))
+ entry.onProgress(torrentProgress)
if entry.pendingPriorities is not None:
entry.handle.prioritize_files(entry.pendingPriorities)
entry.pendingPriorities = None
- if isSeeding and not entry.done.done():
- if self._isSeedingLimitReached(shareRatioPercent, seedingTimeSeconds):
- logger.info("自动暂停做种: 分享率 {:.2f}%, 做种时间 {}s",
- shareRatioPercent, seedingTimeSeconds)
- entry.done.set_result(None)
+ if not entry.done.done() and entry.isDone(torrentProgress):
+ entry.done.set_result(None)
entry.pollCount += 1
if entry.pollCount % _RESUME_SAVE_INTERVAL == 0:
diff --git a/features/bittorrent_pack/task.py b/features/bittorrent_pack/task.py
index 83f28352..7b359ffe 100644
--- a/features/bittorrent_pack/task.py
+++ b/features/bittorrent_pack/task.py
@@ -4,11 +4,15 @@ import asyncio
from base64 import b64decode, b64encode
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
+from typing import TYPE_CHECKING
from app.models.task import Task, TaskError, TaskStep, TaskFile, TaskStatus
from app.platform.filesystem import deletePath, toPosixPath
from .config import bittorrentConfig
+if TYPE_CHECKING:
+ from .session import TorrentParams, TorrentProgress
+
@dataclass(kw_only=True)
class BTFile(TaskFile):
@@ -22,6 +26,7 @@ class BTFile(TaskFile):
class BTTask(Task):
packId: str = "bt"
canEdit = True
+ canSeed = True
fileType = BTFile
sourceType: str = "torrent"
torrentData: str = ""
@@ -29,7 +34,6 @@ class BTTask(Task):
trackers: list[str] = field(default_factory=list)
shareRatioPercent: float = 0
seedingTimeSeconds: int = 0
- isSeeding: bool = False
stateText: str = ""
peerCount: int = 0
totalPeerCount: int = 0
@@ -43,7 +47,7 @@ class BTTask(Task):
item if isinstance(item, BTFile) else BTFile(**item)
for item in self.files
]
- self._fileSelectionVersion = 0
+ self.selectionVersion = 0
super().__post_init__()
self.fileSize = sum(f.size for f in self.files if f.selected)
@@ -89,7 +93,7 @@ class BTTask(Task):
f.completed = False
if not changed:
return
- self._fileSelectionVersion += 1
+ self.selectionVersion += 1
self.fileSize = sum(f.size for f in self.files if f.selected)
from .session import btSession
@@ -119,7 +123,6 @@ class BTTask(Task):
self.resumeData = ""
self.shareRatioPercent = 0
self.seedingTimeSeconds = 0
- self.isSeeding = False
self.stateText = ""
self.peerCount = 0
self.totalPeerCount = 0
@@ -131,6 +134,48 @@ class BTTask(Task):
f.completed = False
return result
+ def buildParams(self) -> TorrentParams:
+ from .session import TorrentParams
+ fileRenames = {}
+ for f in self.files:
+ mapped = self.toRelativePath(f)
+ if mapped != f.relativePath:
+ fileRenames[f.index] = mapped
+ return TorrentParams(
+ torrentData=b64decode(self.torrentData),
+ savePath=str(self.outputFolder),
+ resumeData=b64decode(self.resumeData) if self.resumeData else b"",
+ trackers=self.trackers.copy(),
+ filePriorities=self.priorities(),
+ fileRenames=fileRenames,
+ seedingTimeSeconds=self.seedingTimeSeconds,
+ )
+
+ def updateStats(self, p: TorrentProgress) -> None:
+ self.stateText = p.stateText
+ self.peerCount = p.peerCount
+ self.totalPeerCount = p.totalPeerCount
+ self.seedCount = p.seedCount
+ self.downloadRate = p.downloadRate
+ self.uploadRate = p.uploadRate
+ self.shareRatioPercent = p.shareRatioPercent
+ self.seedingTimeSeconds = p.seedingTimeSeconds
+
+ async def runSeeding(self, isManual: bool) -> None:
+ from loguru import logger
+ from .session import btSession
+ try:
+ resumeData = await btSession.runSeeding(
+ self.taskId, self.buildParams(), isManual, onProgress=self.updateStats)
+ self.resumeData = b64encode(resumeData).decode()
+ logger.info("{} 做种达到上限: 分享率 {:.2f}%, 做种时间 {}s",
+ self.name, self.shareRatioPercent, self.seedingTimeSeconds)
+ finally:
+ cached = btSession.lastResumeData(self.taskId)
+ if cached:
+ self.resumeData = b64encode(cached).decode()
+ self.uploadRate = 0
+
@dataclass(kw_only=True)
class BTTaskStep(TaskStep):
@property
@@ -138,7 +183,7 @@ class BTTaskStep(TaskStep):
return self.task.outputPath
async def run(self, reportSpeed, waitForSpeedLimit) -> None:
- from .session import btSession, TorrentParams, TorrentProgress
+ from .session import btSession, TorrentProgress
task: BTTask = self.task
@@ -157,32 +202,8 @@ class BTTaskStep(TaskStep):
from loguru import logger
logger.opt(exception=e).warning("保存 magnet 种子文件失败 {}", task.name)
- fileRenames = {}
- for f in task.files:
- mapped = task.toRelativePath(f)
- if mapped != f.relativePath:
- fileRenames[f.index] = mapped
-
- params = TorrentParams(
- torrentData=b64decode(task.torrentData),
- savePath=str(task.outputFolder),
- resumeData=b64decode(task.resumeData) if task.resumeData else b"",
- trackers=task.trackers.copy(),
- filePriorities=task.priorities(),
- fileRenames=fileRenames,
- seedingTimeSeconds=task.seedingTimeSeconds,
- )
-
def onProgress(p: TorrentProgress):
- task.stateText = p.stateText
- task.peerCount = p.peerCount
- task.totalPeerCount = p.totalPeerCount
- task.seedCount = p.seedCount
- task.isSeeding = p.isSeeding
- task.downloadRate = p.downloadRate
- task.uploadRate = p.uploadRate
- task.shareRatioPercent = p.shareRatioPercent
- task.seedingTimeSeconds = p.seedingTimeSeconds
+ task.updateStats(p)
if p.totalWanted > 0:
task.fileSize = p.totalWanted
@@ -201,20 +222,22 @@ class BTTaskStep(TaskStep):
f.downloadedBytes = dl
f.completed = f.size > 0 and dl >= f.size
- try:
- resumeData = await btSession.run(task.taskId, params, onProgress=onProgress)
- task.resumeData = b64encode(resumeData).decode()
- except asyncio.CancelledError:
- cached = btSession.lastResumeData(task.taskId)
- if cached:
- task.resumeData = b64encode(cached).decode()
- task.stateText = "paused_seeding" if task.isSeeding else "paused_downloading"
- task.isSeeding = False
- raise
- except Exception:
- cached = btSession.lastResumeData(task.taskId)
- if cached:
- task.resumeData = b64encode(cached).decode()
- raise
+ selectionVersion = None
+ while selectionVersion != task.selectionVersion:
+ selectionVersion = task.selectionVersion
+ try:
+ resumeData = await btSession.run(task.taskId, task.buildParams(), onProgress=onProgress)
+ task.resumeData = b64encode(resumeData).decode()
+ except asyncio.CancelledError:
+ cached = btSession.lastResumeData(task.taskId)
+ if cached:
+ task.resumeData = b64encode(cached).decode()
+ task.stateText = "paused_downloading"
+ raise
+ except Exception:
+ cached = btSession.lastResumeData(task.taskId)
+ if cached:
+ task.resumeData = b64encode(cached).decode()
+ raise
self.setStatus(TaskStatus.COMPLETED)
diff --git a/features/ed2k_pack/android.py b/features/ed2k_pack/android.py
index d500e83c..a3cded29 100644
--- a/features/ed2k_pack/android.py
+++ b/features/ed2k_pack/android.py
@@ -7,14 +7,14 @@ UI_CLASS = "com.xychr.ghostdownloader.features.ed2k_pack.Ed2kUi"
def taskFields(task) -> dict:
active = task.activePeerCount
return {
- "progressMode": "hidden" if task.isSharing else "determinate",
- "statusText": N("TaskState", "共享中") if task.isSharing else "",
+ "progressMode": "hidden" if task.isSeeding else "determinate",
+ "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),
},
- "seedingSeconds": task.sharingTimeSeconds,
+ "seedingSeconds": task.seedingTimeSeconds,
"uploadSpeed": task.uploadRate,
},
}
diff --git a/features/ed2k_pack/cards.py b/features/ed2k_pack/cards.py
index 32213a5f..b9bfb146 100644
--- a/features/ed2k_pack/cards.py
+++ b/features/ed2k_pack/cards.py
@@ -3,7 +3,7 @@ from qfluentwidgets import FluentIcon
from app.format import toReadableSize, toReadableTime
from app.models.task import TaskStatus
-from app.view.cards.task_cards import FieldSpec, TaskCard, toSizeText
+from app.view.cards.task_cards import ETA_FIELD, SIZE_FIELD, SPEED_FIELD, FieldSpec, TaskCard
from .task import ED2kTask
@@ -16,42 +16,36 @@ def toPeerText(task: ED2kTask, _speed: int, _received: int) -> str | None:
)
-ED2K_SPEED_FIELD = FieldSpec("speed", FluentIcon.SPEED_HIGH, {
- TaskStatus.RUNNING: lambda t, s, r: None if t.isSharing else f"{toReadableSize(s)}/s",
-})
+def toUploadText(task: ED2kTask, _speed: int, _received: int) -> str:
+ return f"{toReadableSize(task.uploadRate)}/s"
+
+
ED2K_UPLOAD_FIELD = FieldSpec("upload", FluentIcon.SHARE, {
- TaskStatus.RUNNING: lambda t, s, r: f"{toReadableSize(t.uploadRate)}/s",
-})
-ED2K_ETA_FIELD = FieldSpec("eta", FluentIcon.STOP_WATCH, {
- TaskStatus.RUNNING: lambda t, s, r: None if t.isSharing else (
- toReadableTime(int((t.fileSize - r) / s)) if t.fileSize > 0 and s > 0 else "--"
- ),
+ TaskStatus.RUNNING: toUploadText,
+ TaskStatus.COMPLETED: lambda t, s, r: toUploadText(t, s, r) if t.isSeeding else None,
})
-ED2K_SIZE_FIELD = FieldSpec("size", FluentIcon.LIBRARY, {
- None: lambda t, s, r: None if t.status == TaskStatus.RUNNING and t.isSharing else toSizeText(t, s, r),
+ED2K_PEERS_FIELD = FieldSpec("peers", FluentIcon.INFO, {
+ TaskStatus.RUNNING: toPeerText,
+ TaskStatus.COMPLETED: lambda t, s, r: toPeerText(t, s, r) if t.isSeeding else None,
})
-ED2K_PEERS_FIELD = FieldSpec(
- "peers", FluentIcon.INFO, {TaskStatus.RUNNING: toPeerText}
-)
class ED2kTaskCard(TaskCard):
infoFields = [
- ED2K_SPEED_FIELD, ED2K_UPLOAD_FIELD, ED2K_ETA_FIELD, ED2K_SIZE_FIELD,
+ SPEED_FIELD, ED2K_UPLOAD_FIELD, ETA_FIELD, SIZE_FIELD,
ED2K_PEERS_FIELD,
]
def _refreshForStatus(self, task: ED2kTask):
super()._refreshForStatus(task)
- if task.status == TaskStatus.RUNNING and task.isSharing:
- self.progressBar.hide()
+ if task.isSeeding and not self._isFileMissing:
parts = []
- if task.sharingTimeSeconds > 0:
+ if task.seedingTimeSeconds > 0:
parts.append(self.tr("已共享 {0}").format(
- toReadableTime(task.sharingTimeSeconds)))
+ toReadableTime(task.seedingTimeSeconds)))
self._setStatus(self.tr("共享中") + (" " + " · ".join(parts) if parts else ""))
- elif task.status != TaskStatus.RUNNING and task.sharingTimeSeconds > 0:
+ elif task.status != TaskStatus.RUNNING and task.seedingTimeSeconds > 0:
self.statusLabel.setText(
self.statusLabel.text() + " · " + self.tr("已共享 {0}").format(
- toReadableTime(task.sharingTimeSeconds))
+ toReadableTime(task.seedingTimeSeconds))
)
diff --git a/features/ed2k_pack/config.py b/features/ed2k_pack/config.py
index aff0c3b3..bf667ed5 100644
--- a/features/ed2k_pack/config.py
+++ b/features/ed2k_pack/config.py
@@ -26,7 +26,7 @@ class ED2kConfig(PackConfig):
listenPort = RangeConfigItem("ED2k", "ListenPort", 0, RangeValidator(0, 65535))
serverMetSource = ConfigItem("ED2k", "ServerMetSource", "http://upd.emule-security.org/server.met")
nodesDatSource = ConfigItem("ED2k", "NodesDatSource", "http://upd.emule-security.org/nodes.dat")
- sharingTimeLimit = RangeConfigItem("ED2k", "SharingTimeLimitMinutes", 0, RangeValidator(0, 43200))
+ seedingTimeLimit = RangeConfigItem("ED2k", "SharingTimeLimitMinutes", 0, RangeValidator(0, 43200))
def settingGroups(self, parent: QWidget) -> list[CollapsibleSettingCardGroup]:
from qfluentwidgets import FluentIcon, SwitchSettingCard
@@ -73,9 +73,9 @@ class ED2kConfig(PackConfig):
self.listenPort, group, 1,
),
SpinBoxSettingCard(
- FluentIcon.STOP_WATCH, self.tr("自动暂停共享时长"),
- self.tr("0 表示不按共享时长自动暂停"), " min",
- self.sharingTimeLimit, group, 10,
+ FluentIcon.STOP_WATCH, self.tr("自动停止共享时长"),
+ self.tr("0 表示不按共享时长自动停止"), " min",
+ self.seedingTimeLimit, group, 10,
),
])
runtimeCard.refreshStatus()
diff --git a/features/ed2k_pack/session.py b/features/ed2k_pack/session.py
index 4c46f1c4..58e36cb5 100644
--- a/features/ed2k_pack/session.py
+++ b/features/ed2k_pack/session.py
@@ -40,8 +40,7 @@ class ED2kSession:
name: str,
outputFolder: Path,
onStarted: Callable[[RunResult], None] | None = None,
- onProgress: Callable[[Transfer, int], None] | None = None,
- sharingTimeSeconds: int = 0,
+ onProgress: Callable[[Transfer], None] | None = None,
) -> None:
_, linkSize, linkHash = parseEd2kLink(link)
identity = toTransferKey(linkHash, linkSize)
@@ -84,18 +83,13 @@ class ED2kSession:
if wasCancelled:
raise asyncio.CancelledError()
- sharingStart = 0.0
- loop = asyncio.get_running_loop()
async for snapshot in client.snapshots():
for t in snapshot.transfers:
if t.hash != fileHash:
continue
- if not sharingStart and t.state == TransferState.FINISHED:
- sharingStart = loop.time() - sharingTimeSeconds
- elapsed = int(loop.time() - sharingStart) if sharingStart else 0
if onProgress:
- onProgress(t, elapsed)
- if sharingStart and isSharingLimitReached(elapsed):
+ onProgress(t)
+ if t.state == TransferState.FINISHED:
await client.pause(fileHash)
return
break
@@ -110,6 +104,47 @@ class ED2kSession:
finally:
self._activeTransfers.discard(identity)
+ async def runSeeding(
+ self,
+ link: str,
+ fileHash: str,
+ seedingTimeSeconds: int,
+ isManual: bool,
+ onProgress: Callable[[Transfer, int], None],
+ ) -> None:
+ _, linkSize, linkHash = parseEd2kLink(link)
+ identity = toTransferKey(linkHash, linkSize)
+ if identity in self._activeTransfers:
+ raise TaskError("该 eD2k 链接已在下载中")
+ self._activeTransfers.add(identity)
+
+ try:
+ await self._open()
+ client = self._client
+ await client.resume(fileHash)
+ loop = asyncio.get_running_loop()
+ seedingStart = loop.time() - seedingTimeSeconds
+ async for snapshot in client.snapshots():
+ for t in snapshot.transfers:
+ if t.hash != fileHash:
+ continue
+ elapsed = int(loop.time() - seedingStart)
+ onProgress(t, elapsed)
+ if not isManual and isSeedingLimitReached(elapsed):
+ await client.pause(fileHash)
+ return
+ break
+ 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
+ finally:
+ self._activeTransfers.discard(identity)
+
def remove(self, fileHash: str) -> None:
if self.submit is None:
return
@@ -157,8 +192,8 @@ class ED2kSession:
ed2kSession = ED2kSession()
-def isSharingLimitReached(elapsed: int) -> bool:
- limit = ed2kConfig.sharingTimeLimit.value
+def isSeedingLimitReached(elapsed: int) -> bool:
+ limit = ed2kConfig.seedingTimeLimit.value
return limit > 0 and elapsed >= limit * 60
diff --git a/features/ed2k_pack/task.py b/features/ed2k_pack/task.py
index a8d8f99a..d0ab7181 100644
--- a/features/ed2k_pack/task.py
+++ b/features/ed2k_pack/task.py
@@ -1,33 +1,46 @@
from __future__ import annotations
-import asyncio
import sys
from dataclasses import dataclass
from pathlib import Path
from app.models.task import Task, TaskError, TaskStep, TaskStatus
-from .python_ed2k import Transfer, TransferState
+from .python_ed2k import Transfer
@dataclass(kw_only=True, eq=False)
class ED2kTask(Task):
packId: str = "ed2k"
+ canSeed = True
fileHash: str = ""
activePeerCount: int | None = None
totalPeerCount: int = 0
- isSharing: bool = False
uploadRate: int = 0
- sharingTimeSeconds: int = 0
+ seedingTimeSeconds: int = 0
def reset(self) -> TaskStatus:
self.fileHash = ""
self.activePeerCount = None
self.totalPeerCount = 0
- self.isSharing = False
self.uploadRate = 0
- self.sharingTimeSeconds = 0
+ self.seedingTimeSeconds = 0
return super().reset()
+ async def runSeeding(self, isManual: bool) -> None:
+ from .session import ed2kSession
+
+ def onProgress(t: Transfer, elapsed: int):
+ self.uploadRate = t.uploadRate
+ self.activePeerCount = t.activePeers
+ self.totalPeerCount = t.peers
+ self.seedingTimeSeconds = elapsed
+
+ try:
+ await ed2kSession.runSeeding(
+ self.url, self.fileHash, self.seedingTimeSeconds, isManual, onProgress)
+ finally:
+ self.uploadRate = 0
+
def deleteFiles(self):
if self.fileHash:
from .session import ed2kSession
@@ -48,37 +61,23 @@ class ED2kTaskStep(TaskStep):
if result.fileSize:
task.fileSize = result.fileSize
- def onProgress(t: Transfer, sharingElapsed: int):
- task.isSharing = t.state == TransferState.FINISHED
+ def onProgress(t: Transfer):
task.uploadRate = t.uploadRate
task.activePeerCount = t.activePeers
task.totalPeerCount = t.peers
self.receivedBytes = t.received
- if task.isSharing:
- task.sharingTimeSeconds = sharingElapsed
- self.speed = 0
- reportSpeed(0)
- else:
- 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)
+ 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)
- try:
- await ed2kSession.run(
- task.url, task.fileHash, task.name, task.outputFolder,
- onStarted=onStarted,
- onProgress=onProgress,
- sharingTimeSeconds=task.sharingTimeSeconds,
- )
- self.setStatus(TaskStatus.COMPLETED)
- except asyncio.CancelledError:
- task.isSharing = False
- raise
- except Exception:
- task.isSharing = False
- raise
+ await ed2kSession.run(
+ task.url, task.fileHash, task.name, task.outputFolder,
+ onStarted=onStarted,
+ onProgress=onProgress,
+ )
+ self.setStatus(TaskStatus.COMPLETED)
@dataclass(kw_only=True)
diff --git a/tests/test_android_speed_meter.py b/tests/test_android_speed_meter.py
new file mode 100644
index 00000000..016be7d8
--- /dev/null
+++ b/tests/test_android_speed_meter.py
@@ -0,0 +1,65 @@
+"""engine.py 何时让 SpeedMeter 走表:它驱动 taskProgress 推送,做种时也要走。"""
+from tests.test_task_service import finishRun, makeSeedTask, makeTask, service # noqa: F401
+
+
+class SpyMeter:
+ def __init__(self):
+ self.isRunning = False
+
+ def start(self):
+ self.isRunning = True
+
+ def stop(self):
+ self.isRunning = False
+
+
+def bindEngine(bridge, taskService) -> SpyMeter:
+ engine = bridge.Engine.__new__(bridge.Engine)
+ engine._taskService = taskService
+ engine._speedMeter = SpyMeter()
+ engine._bindSpeedMeter()
+ return engine._speedMeter
+
+
+def test_meter_keeps_running_while_seeding(bridge, service, tmp_path):
+ svc, runner = service
+ meter = bindEngine(bridge, svc)
+ task = makeSeedTask("sm1", tmp_path)
+ svc.add(task)
+ finishRun(runner, task)
+ assert task.isSeeding
+ assert meter.isRunning
+
+
+def test_meter_stops_when_seeding_stops_and_nothing_runs(bridge, service, tmp_path):
+ svc, runner = service
+ meter = bindEngine(bridge, svc)
+ task = makeSeedTask("sm2", tmp_path)
+ svc.add(task)
+ finishRun(runner, task)
+ svc.stopSeeding(task)
+ assert not meter.isRunning
+
+
+def test_meter_keeps_running_when_seeding_stops_but_a_download_runs(bridge, service, tmp_path):
+ svc, runner = service
+ meter = bindEngine(bridge, svc)
+ seed = makeSeedTask("sm3", tmp_path)
+ svc.add(seed)
+ finishRun(runner, seed)
+ svc.add(makeTask("sm3-other"))
+ svc.stopSeeding(seed)
+ assert meter.isRunning
+
+
+def test_meter_starts_for_seeding_restored_at_launch(bridge, service, tmp_path):
+ from app.models.task import TaskStatus
+ svc, runner = service
+ meter = bindEngine(bridge, svc)
+ task = makeSeedTask("sm4", tmp_path)
+ task.shouldSeed = True
+ task.setStatus(TaskStatus.COMPLETED)
+ (tmp_path / task.name).touch()
+ svc._store.loadSaved = lambda: [task]
+ svc.resumeSaved()
+ assert meter.isRunning
diff --git a/tests/test_bt_task.py b/tests/test_bt_task.py
new file mode 100644
index 00000000..237bf108
--- /dev/null
+++ b/tests/test_bt_task.py
@@ -0,0 +1,57 @@
+import asyncio
+from base64 import b64encode
+from pathlib import Path
+
+from app.models.task import TaskStatus
+from bittorrent_pack import session as session_module
+from bittorrent_pack import android
+from bittorrent_pack.task import BTFile, BTTask, BTTaskStep
+
+
+class FakeSession:
+ def __init__(self, onRun=None):
+ self.runPriorities: list[list[int]] = []
+ self.onRun = onRun
+
+ async def run(self, taskId, params, onProgress=None) -> bytes:
+ self.runPriorities.append(list(params.filePriorities))
+ if self.onRun is not None:
+ onRun, self.onRun = self.onRun, None
+ onRun()
+ return b"resume"
+
+ def updatePriorities(self, taskId, priorities):
+ pass
+
+ def lastResumeData(self, taskId):
+ return None
+
+
+def makeTask(tmp_path: Path) -> BTTask:
+ task = BTTask(
+ name="pack", url="x.torrent", outputFolder=tmp_path,
+ steps=[BTTaskStep(stepIndex=1)], torrentData=b64encode(b"x").decode(),
+ files=[BTFile(index=0, relativePath="pack/a", size=1),
+ BTFile(index=1, relativePath="pack/b", size=1, selected=False, priority=0)],
+ )
+ task.setStatus(TaskStatus.RUNNING)
+ return task
+
+
+def test_file_added_while_download_finishes_is_downloaded(monkeypatch, tmp_path):
+ task = makeTask(tmp_path)
+ fake = FakeSession(onRun=lambda: task.setSelection({0, 1}))
+ monkeypatch.setattr(session_module, "btSession", fake)
+
+ asyncio.run(task.steps[0].run(lambda _: None, None))
+
+ assert fake.runPriorities == [[4, 0], [4, 4]]
+ assert task.status == TaskStatus.COMPLETED
+
+
+def test_completed_task_that_is_not_seeding_has_no_state_text(tmp_path):
+ task = makeTask(tmp_path)
+ task.setStatus(TaskStatus.COMPLETED)
+ task.stateText = "checking_resume_data"
+
+ assert android.taskFields(task)["statusText"] == ""
diff --git a/tests/test_ed2k_task.py b/tests/test_ed2k_task.py
index 014052b6..fab17910 100644
--- a/tests/test_ed2k_task.py
+++ b/tests/test_ed2k_task.py
@@ -197,34 +197,91 @@ async def test_transfer_exists_resumes_existing(monkeypatch, tmp_path):
assert fakeClient.removed == []
-async def test_finished_enters_sharing_immediately(monkeypatch, tmp_path):
- 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,
- )
- return self.transfer
+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)
task = makeTask(tmp_path)
- running = asyncio.create_task(task.steps[0].run(lambda _: None, None))
- await fakeClient.snapshotStarted.wait()
+ await task.steps[0].run(lambda _: None, None)
- assert task.isSharing
- assert task.sharingTimeSeconds == 0
+ assert task.status == TaskStatus.COMPLETED
assert task.steps[0].receivedBytes == 1234
+ assert fakeClient.paused == [FILE_HASH]
+ assert not session._activeTransfers
- running.cancel()
+
+async def completeDownload(monkeypatch, tmp_path) -> tuple[ED2kTask, FakeClient]:
+ fakeClient = FinishedClient()
+ session = session_module.ED2kSession()
+ session._client = fakeClient
+ monkeypatch.setattr(session_module, "ed2kSession", session)
+ task = makeTask(tmp_path)
+ await task.steps[0].run(lambda _: None, None)
+ fakeClient.paused.clear()
+ fakeClient.snapshotStarted.clear()
+ return task, fakeClient
+
+
+async def test_seeding_resumes_transfer_until_stopped(monkeypatch, tmp_path):
+ task, fakeClient = await completeDownload(monkeypatch, tmp_path)
+
+ seeding = asyncio.create_task(task.runSeeding(isManual=False))
+ await fakeClient.snapshotStarted.wait()
+ await asyncio.sleep(0)
+
+ assert fakeClient.resumed == [FILE_HASH]
+ assert task.uploadRate == 512
+
+ seeding.cancel()
with pytest.raises(asyncio.CancelledError):
- await running
+ await seeding
+
+ assert fakeClient.paused == [FILE_HASH]
+ assert task.uploadRate == 0
+ assert not session_module.ed2kSession._activeTransfers
+
+
+async def test_seeding_ends_at_limit(monkeypatch, tmp_path):
+ from ed2k_pack.config import ed2kConfig
+ monkeypatch.setattr(ed2kConfig.seedingTimeLimit, "value", 1)
+ task, fakeClient = await completeDownload(monkeypatch, tmp_path)
+ task.seedingTimeSeconds = 120
+
+ await task.runSeeding(isManual=False)
+
+ assert fakeClient.paused == [FILE_HASH]
+ assert task.seedingTimeSeconds >= 120
+
+
+async def test_manual_seeding_ignores_limit(monkeypatch, tmp_path):
+ from ed2k_pack.config import ed2kConfig
+ monkeypatch.setattr(ed2kConfig.seedingTimeLimit, "value", 1)
+ task, fakeClient = await completeDownload(monkeypatch, tmp_path)
+ task.seedingTimeSeconds = 120
+
+ seeding = asyncio.create_task(task.runSeeding(isManual=True))
+ await fakeClient.snapshotStarted.wait()
+ await asyncio.sleep(0)
+
+ assert not seeding.done()
+ seeding.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await seeding
async def test_parser_rejects_active_duplicate_on_add_task_page(monkeypatch, tmp_path):
diff --git a/tests/test_task_service.py b/tests/test_task_service.py
index cd084723..e48cea45 100644
--- a/tests/test_task_service.py
+++ b/tests/test_task_service.py
@@ -524,3 +524,236 @@ class TestEdit:
initial_count = len(runner.submitted)
svc.edit(task, {})
assert len(runner.submitted) > initial_count
+
+
+@dataclass(kw_only=True, eq=False)
+class SeedTask(Task):
+ canSeed = True
+
+ def __post_init__(self):
+ super().__post_init__()
+ self.seedingCalls: list[bool] = []
+
+ def runSeeding(self, isManual):
+ self.seedingCalls.append(isManual)
+ return StubStep(stepIndex=0).run(None, None)
+
+
+def makeSeedTask(taskId: str, tmp_path: Path) -> SeedTask:
+ task = SeedTask(name=f"{taskId}.bin", url="magnet:?xt=urn:btih:x", packId="bt",
+ taskId=taskId, steps=[StubStep(stepIndex=0)], outputFolder=tmp_path)
+ return task
+
+
+def finishRun(runner, task):
+ workId, done, _ = runner.dispatched[-1]
+ task.setStatus(TaskStatus.COMPLETED)
+ done(None)
+ return workId
+
+
+class TestSeeding:
+
+ def test_completed_run_frees_slot_and_starts_seeding(self, service, tmp_path, qtbot):
+ svc, runner = service
+ task = makeSeedTask("sd1", tmp_path)
+ svc.add(task)
+ with qtbot.waitSignal(svc.seedingStarted, timeout=1000), \
+ qtbot.waitSignal(svc.tasksAllCompleted, timeout=1000):
+ finishRun(runner, task)
+ assert task.status == TaskStatus.COMPLETED
+ assert task.isSeeding
+ assert task.seedingCalls == [False]
+ assert svc.runningCount() == 0
+
+ def test_seeding_does_not_block_queue(self, service, tmp_path, monkeypatch):
+ from app.config.cfg import cfg
+ svc, runner = service
+ monkeypatch.setattr(cfg.maxTaskNum, "value", 1)
+ seed = makeSeedTask("sd2", tmp_path)
+ other = makeTask("sd2-other")
+ svc.add(seed)
+ svc.add(other)
+ finishRun(runner, seed)
+ assert other.status == TaskStatus.RUNNING
+
+ def test_task_that_cannot_seed_does_not_seed(self, service):
+ svc, runner = service
+ task = makeTask("sd3")
+ svc.add(task)
+ count = len(runner.dispatched)
+ finishRun(runner, task)
+ assert not task.isSeeding
+ assert len(runner.dispatched) == count
+
+ def test_should_not_seed_skips_seeding(self, service, tmp_path):
+ svc, runner = service
+ task = makeSeedTask("sd4", tmp_path)
+ svc.add(task)
+ task.shouldSeed = False
+ finishRun(runner, task)
+ assert not task.isSeeding
+ assert task.seedingCalls == []
+
+ def test_stop_seeding_cancels_and_remembers(self, service, tmp_path, qtbot):
+ svc, runner = service
+ task = makeSeedTask("sd5", tmp_path)
+ svc.add(task)
+ finishRun(runner, task)
+ seedingWorkId = runner.submitted[-1][0]
+ with qtbot.waitSignal(svc.seedingStopped, timeout=1000):
+ svc.stopSeeding(task)
+ assert seedingWorkId in runner.cancelled
+ assert not task.isSeeding
+ assert not task.shouldSeed
+ assert task.status == TaskStatus.COMPLETED
+
+ def test_start_seeding_is_manual(self, service, tmp_path):
+ svc, runner = service
+ task = makeSeedTask("sd6", tmp_path)
+ svc.add(task)
+ task.shouldSeed = False
+ finishRun(runner, task)
+ svc.startSeeding(task)
+ assert task.isSeeding
+ assert task.shouldSeed
+ assert task.seedingCalls == [True]
+ assert svc.runningCount() == 0
+
+ def test_seeding_ending_by_itself_is_remembered(self, service, tmp_path, qtbot):
+ svc, runner = service
+ task = makeSeedTask("sd7", tmp_path)
+ svc.add(task)
+ finishRun(runner, task)
+ _, done, _ = runner.submitted[-1]
+ with qtbot.waitSignal(svc.seedingStopped, timeout=1000):
+ done(None)
+ assert not task.isSeeding
+ assert not task.shouldSeed
+
+ def test_seeding_failure_keeps_wish(self, service, tmp_path):
+ svc, runner = service
+ task = makeSeedTask("sd8", tmp_path)
+ svc.add(task)
+ finishRun(runner, task)
+ _, _, failed = runner.submitted[-1]
+ failed(RuntimeError("tracker"))
+ assert not task.isSeeding
+ assert task.shouldSeed
+ assert task.status == TaskStatus.COMPLETED
+
+ def test_delete_stops_seeding(self, service, tmp_path):
+ svc, runner = service
+ task = makeSeedTask("sd9", tmp_path)
+ svc.add(task)
+ finishRun(runner, task)
+ seedingWorkId = runner.submitted[-1][0]
+ svc.delete(task, shouldDeleteFiles=False)
+ assert seedingWorkId in runner.cancelled
+
+ def test_redownload_stops_seeding_and_restores_wish(self, service, tmp_path):
+ svc, runner = service
+ task = makeSeedTask("sd10", tmp_path)
+ svc.add(task)
+ finishRun(runner, task)
+ svc.stopSeeding(task)
+ svc.startSeeding(task)
+ seedingWorkId = runner.submitted[-1][0]
+ task.shouldSeed = False
+ svc.redownload(task)
+ assert seedingWorkId in runner.cancelled
+ assert task.shouldSeed
+ assert task.status == TaskStatus.RUNNING
+
+ def test_revive_stops_seeding_before_run(self, service, tmp_path):
+ from app.models.task import TaskFile
+ svc, runner = service
+ task = makeSeedTask("sd11", tmp_path)
+ task.files = [TaskFile(index=0, relativePath="a", completed=True),
+ TaskFile(index=1, relativePath="b", selected=False)]
+ svc.add(task)
+ finishRun(runner, task)
+ seedingWorkId = runner.submitted[-1][0]
+ task.setSelection = lambda indexes: setattr(task.files[1], "selected", True)
+ svc.updateSelection(task, {0, 1})
+ assert seedingWorkId in runner.cancelled
+ assert not task.isSeeding
+ assert runner.submitted[-1][0] != seedingWorkId
+
+ def test_saved_seeding_task_resumes_seeding(self, service, tmp_path):
+ svc, runner = service
+ task = makeSeedTask("sd12", tmp_path)
+ task.shouldSeed = True
+ task.setStatus(TaskStatus.COMPLETED)
+ (tmp_path / task.name).touch()
+ svc._store.loadSaved = lambda: [task]
+ svc.resumeSaved()
+ assert task.isSeeding
+ assert task.seedingCalls == [False]
+
+ def test_saved_task_with_missing_file_does_not_seed(self, service, tmp_path):
+ svc, runner = service
+ task = makeSeedTask("sd13", tmp_path)
+ task.setStatus(TaskStatus.COMPLETED)
+ svc._store.loadSaved = lambda: [task]
+ svc.resumeSaved()
+ assert not task.isSeeding
+
+ def test_file_disappearing_stops_seeding(self, service, tmp_path):
+ svc, runner = service
+ task = makeSeedTask("sd14", tmp_path)
+ svc.add(task)
+ finishRun(runner, task)
+ seedingWorkId = runner.submitted[-1][0]
+ svc._onWatchedFileChanged(task.outputPath)
+ assert seedingWorkId in runner.cancelled
+ assert not task.isSeeding
+ assert task.shouldSeed
+
+ def test_seeding_state_is_not_persisted(self, tmp_path):
+ task = makeSeedTask("sd15", tmp_path)
+ task.shouldSeed = True
+ task.isSeeding = True
+ data = task.toDict()
+ assert "isSeeding" not in data
+ assert data["shouldSeed"] is True
+
+ def test_new_task_wants_seeding(self, service, tmp_path):
+ svc, runner = service
+ task = makeSeedTask("sd16", tmp_path)
+ svc.add(task)
+ assert task.shouldSeed
+
+ def test_record_from_before_seeding_existed_does_not_seed(self, service, tmp_path):
+ svc, runner = service
+ old = makeSeedTask("sd17", tmp_path)
+ old.setStatus(TaskStatus.COMPLETED)
+ record = old.toDict()
+ record.pop("shouldSeed")
+ restored = SeedTask.fromDict(record)
+ (tmp_path / restored.name).touch()
+ svc._store.loadSaved = lambda: [restored]
+ svc.resumeSaved()
+ assert not restored.shouldSeed
+ assert not restored.isSeeding
+
+ def test_stale_run_done_after_revive_does_not_seed(self, service, tmp_path):
+ from app.models.task import TaskFile
+ svc, runner = service
+ task = makeSeedTask("sd18", tmp_path)
+ task.files = [TaskFile(index=0, relativePath="a", completed=True),
+ TaskFile(index=1, relativePath="b", selected=False)]
+ svc.add(task)
+ _, staleDone, _ = runner.dispatched[-1]
+ task.setStatus(TaskStatus.COMPLETED)
+
+ def select(indexes):
+ task.files[1].selected = True
+ task.steps[0].status = TaskStatus.WAITING
+ task.updateStatus()
+ task.setSelection = select
+ svc.updateSelection(task, {0, 1})
+ assert task.status == TaskStatus.RUNNING
+
+ staleDone(None)
+ assert not task.isSeeding