From 239e581ce152910e7f599b6428e8aaeead1189fc Mon Sep 17 00:00:00 2001 From: Lin Zhang Date: Sat, 14 Nov 2026 18:29:34 +0900 Subject: [PATCH 1/2] feat(torrent): add and remove a torrent's trackers --- AGENTS.md | 13 ++ .../values-de/strings_inspector.xml | 5 + .../values-es/strings_inspector.xml | 5 + .../values-fr/strings_inspector.xml | 5 + .../values-ja/strings_inspector.xml | 5 + .../values-ko/strings_inspector.xml | 5 + .../values-pt/strings_inspector.xml | 5 + .../values-ru/strings_inspector.xml | 5 + .../values-zh-rTW/strings_inspector.xml | 5 + .../values-zh/strings_inspector.xml | 5 + .../values/strings_inspector.xml | 5 + .../app/ui/inspector/tabs/TrackersTab.kt | 145 ++++++++++++++++-- .../app/ui/inspector/tabs/TrackersTabTest.kt | 9 ++ .../app/snapshot/InspectorTabsSnapshots.kt | 47 ++++-- docs/developers.md | 1 + docs/torrent.md | 13 +- .../ketch/endpoints/torrent/Torrents.kt | 6 +- .../ketch/remote/RemoteTorrentController.kt | 14 ++ .../linroid/ketch/server/api/TorrentRoutes.kt | 13 ++ .../ketch/torrent/api/TorrentCapabilities.kt | 1 + .../ketch/torrent/api/TorrentController.kt | 14 ++ .../ketch/torrent/api/TorrentTrackers.kt | 14 ++ .../ketch/torrent/TorrentDownloadSource.kt | 111 ++++++++++++-- .../ketch/torrent/TorrentSourceMetainfo.kt | 4 + .../ketch/torrent/TorrentSourceState.kt | 5 + .../torrent/control/KetchTorrentController.kt | 47 ++++++ .../torrent/control/TorrentControlSource.kt | 19 +++ .../torrent/control/TorrentTrackerViews.kt | 58 +++++-- .../torrent/TorrentDownloadSourceTest.kt | 2 +- .../torrent/TorrentSeedingControlTest.kt | 57 +++++++ .../control/KetchTorrentControllerTest.kt | 63 ++++++++ .../control/TorrentTrackerViewsTest.kt | 42 +++++ 32 files changed, 700 insertions(+), 48 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0fa0dd351..717349a03 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1362,6 +1362,19 @@ docker/ # Docker image of `ketch server` (Dockerfile, entrypoint, compose metainfo's usable trackers, else a magnet's. Trackers Ketch adds to public torrents are never listed. The inspector's Trackers tab (`TrackersTab`, `trackerView`), offered for torrents on devices with the capability, asks again every 3 s while it shows +- Editing trackers: `TorrentController.editTrackers(taskId, TorrentTrackerEdit(add, remove))` + (REST `PUT /api/torrents/{id}/trackers`, answering the list; capability `tracker-edit`) removes + the trackers at the endpoints `remove` names and appends each announce URL of `add` as a tier + of its own (`editedTrackerTiers`, checked by `TrackerConfiguration.prepare`, at most + `MAX_TRACKERS`; a refusal is `INVALID_INPUT` and never repeats a URL). The result is the + task's `TorrentSourceState.trackerTiers`, which replaces the torrent's own trackers whenever a + session of it opens (v1 through `TorrentMetadata.announcingTo`, v2 and hybrid as the spec's + `trackerTiers`), written into the saved state (`SourceHost.changeSourceState`, + `withTrackers`) and into the states a run or a seeder saves from (`changeHeldState`). A + session announces to what it opened with, so a downloading task is paused and resumed and a + seeding one stopped and seeded again. A task that never ran keeps the edit for the process + only. Exports still describe the torrent as it was added. The Trackers tab shows a remove + button per tracker and an Add trackers field (`TrackerEditing`, `trackerUrls`) - Export: `TorrentController.export(taskId, metainfo)` (REST `GET /api/torrents/{id}/export`, `?metainfo=true`; capability `export`) answers a `TorrentExport`: the v1 and v2 info hashes, the name, the magnet link and, when asked for, the `.torrent` file as Base64 diff --git a/app/shared/src/commonMain/composeResources/values-de/strings_inspector.xml b/app/shared/src/commonMain/composeResources/values-de/strings_inspector.xml index c62704fe9..b687601f2 100644 --- a/app/shared/src/commonMain/composeResources/values-de/strings_inspector.xml +++ b/app/shared/src/commonMain/composeResources/values-de/strings_inspector.xml @@ -14,6 +14,11 @@ Seeder: %1$d Lädt herunter: %1$d Dieser Torrent nennt keine eigenen Tracker. + Tracker hinzufügen + udp://tracker.example:6969/announce + Announce-URLs, durch Leerzeichen oder Zeilenumbrüche getrennt. Ein laufender Torrent startet neu, um sie zu verwenden. + Gib Announce-URLs mit http, https oder udp ein. + Die Tracker konnten nicht geändert werden. Stockt seit %1$d s Stockt seit %1$d min diff --git a/app/shared/src/commonMain/composeResources/values-es/strings_inspector.xml b/app/shared/src/commonMain/composeResources/values-es/strings_inspector.xml index c0f1a9923..1c9e41de6 100644 --- a/app/shared/src/commonMain/composeResources/values-es/strings_inspector.xml +++ b/app/shared/src/commonMain/composeResources/values-es/strings_inspector.xml @@ -14,6 +14,11 @@ Compartiendo: %1$d Descargando: %1$d Este torrent no indica ningún tracker propio. + Añadir trackers + udp://tracker.example:6969/announce + URL de anuncio, separadas por espacios o saltos de línea. Un torrent en curso se reinicia para usarlas. + Introduce URL de anuncio http, https o udp. + No se pudieron cambiar los trackers. Atascada %1$d s Atascada %1$d min diff --git a/app/shared/src/commonMain/composeResources/values-fr/strings_inspector.xml b/app/shared/src/commonMain/composeResources/values-fr/strings_inspector.xml index 8d8c27a9c..cfcccf342 100644 --- a/app/shared/src/commonMain/composeResources/values-fr/strings_inspector.xml +++ b/app/shared/src/commonMain/composeResources/values-fr/strings_inspector.xml @@ -14,6 +14,11 @@ En partage : %1$d En téléchargement : %1$d Ce torrent ne nomme aucun tracker. + Ajouter des trackers + udp://tracker.example:6969/announce + URL d'annonce, séparées par des espaces ou des retours à la ligne. Un torrent en cours redémarre pour les utiliser. + Saisissez des URL d'annonce http, https ou udp. + Impossible de modifier les trackers. Bloquée depuis %1$d s Bloquée depuis %1$d min diff --git a/app/shared/src/commonMain/composeResources/values-ja/strings_inspector.xml b/app/shared/src/commonMain/composeResources/values-ja/strings_inspector.xml index fca484b0d..b2fa2a905 100644 --- a/app/shared/src/commonMain/composeResources/values-ja/strings_inspector.xml +++ b/app/shared/src/commonMain/composeResources/values-ja/strings_inspector.xml @@ -14,6 +14,11 @@ シード中:%1$d ダウンロード中:%1$d このトレントには独自のトラッカーがありません。 + トラッカーを追加 + udp://tracker.example:6969/announce + アナウンス URL をスペースまたは改行で区切って入力します。実行中のトレントは再開してそれらを使用します。 + http、https または udp のアナウンス URL を入力してください。 + トラッカーを変更できませんでした。 停滞%1$d秒 停滞%1$d分 diff --git a/app/shared/src/commonMain/composeResources/values-ko/strings_inspector.xml b/app/shared/src/commonMain/composeResources/values-ko/strings_inspector.xml index f5c1c84f2..0c2de1f03 100644 --- a/app/shared/src/commonMain/composeResources/values-ko/strings_inspector.xml +++ b/app/shared/src/commonMain/composeResources/values-ko/strings_inspector.xml @@ -14,6 +14,11 @@ 시딩: %1$d 다운로드 중: %1$d 이 토렌트에는 자체 트래커가 없습니다. + 트래커 추가 + udp://tracker.example:6969/announce + 공백이나 줄바꿈으로 구분한 어나운스 URL입니다. 실행 중인 토렌트는 다시 시작해 이를 사용합니다. + http, https 또는 udp 어나운스 URL을 입력하세요. + 트래커를 변경할 수 없습니다. %1$d초째 멈춤 %1$d분째 멈춤 diff --git a/app/shared/src/commonMain/composeResources/values-pt/strings_inspector.xml b/app/shared/src/commonMain/composeResources/values-pt/strings_inspector.xml index 03a5a66bf..7f86ee870 100644 --- a/app/shared/src/commonMain/composeResources/values-pt/strings_inspector.xml +++ b/app/shared/src/commonMain/composeResources/values-pt/strings_inspector.xml @@ -14,6 +14,11 @@ Semeando: %1$d Baixando: %1$d Este torrent não indica nenhum tracker próprio. + Adicionar trackers + udp://tracker.example:6969/announce + URLs de anúncio, separados por espaços ou quebras de linha. Um torrent em andamento reinicia para usá-los. + Digite URLs de anúncio http, https ou udp. + Não foi possível alterar os trackers. Parada há %1$d s Parada há %1$d min diff --git a/app/shared/src/commonMain/composeResources/values-ru/strings_inspector.xml b/app/shared/src/commonMain/composeResources/values-ru/strings_inspector.xml index 8bb9299c9..82a550d82 100644 --- a/app/shared/src/commonMain/composeResources/values-ru/strings_inspector.xml +++ b/app/shared/src/commonMain/composeResources/values-ru/strings_inspector.xml @@ -14,6 +14,11 @@ Раздают: %1$d Скачивают: %1$d У этого торрента нет своих трекеров. + Добавить трекеры + udp://tracker.example:6969/announce + Адреса анонса через пробел или с новой строки. Работающий торрент перезапустится, чтобы использовать их. + Введите адреса анонса http, https или udp. + Не удалось изменить трекеры. Простой %1$d с Простой %1$d мин diff --git a/app/shared/src/commonMain/composeResources/values-zh-rTW/strings_inspector.xml b/app/shared/src/commonMain/composeResources/values-zh-rTW/strings_inspector.xml index 0111aebfd..b0049337c 100644 --- a/app/shared/src/commonMain/composeResources/values-zh-rTW/strings_inspector.xml +++ b/app/shared/src/commonMain/composeResources/values-zh-rTW/strings_inspector.xml @@ -14,6 +14,11 @@ 做種:%1$d 下載中:%1$d 此種子沒有自帶的 Tracker。 + 新增 Tracker + udp://tracker.example:6969/announce + Announce 網址,以空格或換行分隔。執行中的種子會重新啟動以使用它們。 + 請輸入 http、https 或 udp 的 Announce 網址。 + 無法變更 Tracker。 已停滯 %1$d 秒 已停滯 %1$d 分鐘 diff --git a/app/shared/src/commonMain/composeResources/values-zh/strings_inspector.xml b/app/shared/src/commonMain/composeResources/values-zh/strings_inspector.xml index 19759f2d6..cd1af013f 100644 --- a/app/shared/src/commonMain/composeResources/values-zh/strings_inspector.xml +++ b/app/shared/src/commonMain/composeResources/values-zh/strings_inspector.xml @@ -14,6 +14,11 @@ 做种:%1$d 下载中:%1$d 此种子没有自带的 Tracker。 + 添加 Tracker + udp://tracker.example:6969/announce + Announce 地址,用空格或换行分隔。正在运行的种子会重新启动以使用它们。 + 请输入 http、https 或 udp 的 Announce 地址。 + 无法更改 Tracker。 停滞%1$d秒 停滞%1$d分钟 diff --git a/app/shared/src/commonMain/composeResources/values/strings_inspector.xml b/app/shared/src/commonMain/composeResources/values/strings_inspector.xml index 8fe7f12eb..eb324c4f8 100644 --- a/app/shared/src/commonMain/composeResources/values/strings_inspector.xml +++ b/app/shared/src/commonMain/composeResources/values/strings_inspector.xml @@ -20,6 +20,11 @@ Seeding: %1$d Downloading: %1$d This torrent names no trackers of its own. + Add trackers + udp://tracker.example:6969/announce + Announce URLs, separated by spaces or new lines. A running torrent starts again to use them. + Enter http, https or udp announce URLs. + Couldn't change the trackers. Stalled %1$d s diff --git a/app/shared/src/commonMain/kotlin/com/linroid/ketch/app/ui/inspector/tabs/TrackersTab.kt b/app/shared/src/commonMain/kotlin/com/linroid/ketch/app/ui/inspector/tabs/TrackersTab.kt index f74fde387..8cf4df66b 100644 --- a/app/shared/src/commonMain/kotlin/com/linroid/ketch/app/ui/inspector/tabs/TrackersTab.kt +++ b/app/shared/src/commonMain/kotlin/com/linroid/ketch/app/ui/inspector/tabs/TrackersTab.kt @@ -2,28 +2,43 @@ package com.linroid.ketch.app.ui.inspector.tabs import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import com.linroid.ketch.api.log.KetchLogger import com.linroid.ketch.api.log.describeCauses +import com.linroid.ketch.app.components.KetchButton +import com.linroid.ketch.app.components.KetchButtonSize +import com.linroid.ketch.app.components.KetchButtonVariant +import com.linroid.ketch.app.components.KetchIconButton +import com.linroid.ketch.app.components.KetchTextField import com.linroid.ketch.app.i18n.UiText import com.linroid.ketch.app.i18n.resolve import com.linroid.ketch.app.i18n.text +import com.linroid.ketch.app.icons.KetchIcon import com.linroid.ketch.app.state.AppState import com.linroid.ketch.app.state.TaskRow import com.linroid.ketch.app.state.catchingUnlessCancelled import com.linroid.ketch.app.theme.KetchTheme +import com.linroid.ketch.torrent.api.TorrentCapability +import com.linroid.ketch.torrent.api.TorrentCommandError +import com.linroid.ketch.torrent.api.TorrentCommandException import com.linroid.ketch.torrent.api.TorrentTracker +import com.linroid.ketch.torrent.api.TorrentTrackerEdit import com.linroid.ketch.torrent.api.TorrentTrackerState import ketch.app.shared.generated.resources.Res +import ketch.app.shared.generated.resources.action_add import ketch.app.shared.generated.resources.inspector_tracker_announcing import ketch.app.shared.generated.resources.inspector_tracker_failed import ketch.app.shared.generated.resources.inspector_tracker_idle @@ -32,9 +47,17 @@ import ketch.app.shared.generated.resources.inspector_tracker_peers import ketch.app.shared.generated.resources.inspector_tracker_seeders import ketch.app.shared.generated.resources.inspector_tracker_timed_out import ketch.app.shared.generated.resources.inspector_tracker_working +import ketch.app.shared.generated.resources.inspector_trackers_add +import ketch.app.shared.generated.resources.inspector_trackers_add_hint +import ketch.app.shared.generated.resources.inspector_trackers_add_placeholder import ketch.app.shared.generated.resources.inspector_trackers_empty +import ketch.app.shared.generated.resources.inspector_trackers_failed +import ketch.app.shared.generated.resources.inspector_trackers_invalid +import ketch.app.shared.generated.resources.settings_torrent_remove import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import org.jetbrains.compose.resources.StringResource import org.jetbrains.compose.resources.stringResource private val log = KetchLogger("Inspector") @@ -52,6 +75,33 @@ fun TrackersTab(state: AppState, row: TaskRow, modifier: Modifier = Modifier) { val features = rememberFeatures(state, row) val controller = remember(features, row.key) { state.torrentControllerOf(row.key.deviceId) } var trackers by remember(row.key, controller) { mutableStateOf?>(null) } + val editable by produceState(false, controller) { + value = controller != null && catchingUnlessCancelled { + controller.capabilities().supports(TorrentCapability.TRACKER_EDIT) + }.getOrDefault(false) + } + var draft by remember(row.key) { mutableStateOf("") } + var problem by remember(row.key) { mutableStateOf(null) } + val scope = rememberCoroutineScope() + val edit: (TorrentTrackerEdit, Boolean) -> Unit = { change, fromDraft -> + scope.launch { + catchingUnlessCancelled { controller?.editTrackers(row.key.taskId, change) } + .onSuccess { + if (it != null) trackers = it + if (fromDraft) draft = "" + problem = null + } + .onFailure { e -> + log.w { "Trackers of taskId=${row.key.taskId} not changed: ${e.describeCauses()}" } + val invalid = (e as? TorrentCommandException)?.error == TorrentCommandError.INVALID_INPUT + problem = if (invalid) { + Res.string.inspector_trackers_invalid + } else { + Res.string.inspector_trackers_failed + } + } + } + } LaunchedEffect(row.key, controller) { if (controller == null) return@LaunchedEffect while (true) { @@ -63,12 +113,47 @@ fun TrackersTab(state: AppState, row: TaskRow, modifier: Modifier = Modifier) { delay(REFRESH) } } - TrackersTabContent(trackers, modifier) + val editing = if (!editable) null else TrackerEditing( + draft = draft, + problem = problem, + onDraftChange = { + draft = it + problem = null + }, + onAdd = { edit(TorrentTrackerEdit(add = trackerUrls(draft)), true) }, + onRemove = { edit(TorrentTrackerEdit(remove = listOf(it.endpoint)), false) }, + ) + TrackersTabContent(trackers, modifier, editing) } -/** [TrackersTab] for [trackers], `null` until the device answered. */ +/** The announce URLs typed into the tab's field: separated by spaces, commas or new lines. */ +internal fun trackerUrls(text: String): List = + text.split(' ', ',', '\n', '\r', '\t').filter { it.isNotEmpty() }.distinct() + +/** + * What lets the tab change a torrent's trackers, on devices that can. + * + * @property draft the announce URLs typed so far + * @property problem why the last change did not happen, until the draft changes + */ +internal class TrackerEditing( + val draft: String, + val problem: StringResource?, + val onDraftChange: (String) -> Unit, + val onAdd: () -> Unit, + val onRemove: (TorrentTracker) -> Unit, +) + +/** + * [TrackersTab] for [trackers], `null` until the device answered; with [editing], each tracker + * can be removed and new ones added below them. + */ @Composable -internal fun TrackersTabContent(trackers: List?, modifier: Modifier = Modifier) { +internal fun TrackersTabContent( + trackers: List?, + modifier: Modifier = Modifier, + editing: TrackerEditing? = null, +) { val colors = KetchTheme.colors val spacing = KetchTheme.spacing val type = KetchTheme.typography @@ -87,13 +172,25 @@ internal fun TrackersTabContent(trackers: List?, modifier: Modif for (tracker in trackers) { val view = trackerView(tracker) Column(verticalArrangement = Arrangement.spacedBy(spacing.s0_5)) { - Text( - text = tracker.endpoint, - style = type.monoS, - color = colors.textPrimary, - maxLines = 1, - overflow = TextOverflow.MiddleEllipsis, - ) + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = tracker.endpoint, + modifier = Modifier.weight(1f), + style = type.monoS, + color = colors.textPrimary, + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis, + ) + if (editing != null) { + KetchIconButton( + icon = KetchIcon.Close, + onClick = { editing.onRemove(tracker) }, + size = KetchButtonSize.Small, + contentDescription = + stringResource(Res.string.settings_torrent_remove, tracker.endpoint), + ) + } + } Text( text = view.summary.map { it.resolve() }.joinToString(" · "), style = type.caption, @@ -108,6 +205,34 @@ internal fun TrackersTabContent(trackers: List?, modifier: Modif } } } + if (editing != null) { + Row( + verticalAlignment = Alignment.Bottom, + horizontalArrangement = Arrangement.spacedBy(spacing.s2), + ) { + KetchTextField( + value = editing.draft, + onValueChange = editing.onDraftChange, + modifier = Modifier.weight(1f), + placeholder = stringResource(Res.string.inspector_trackers_add_placeholder), + mono = true, + label = stringResource(Res.string.inspector_trackers_add), + error = editing.problem?.let { stringResource(it) }, + maxLines = 4, + ) + KetchButton( + text = stringResource(Res.string.action_add), + onClick = editing.onAdd, + variant = KetchButtonVariant.Secondary, + enabled = editing.draft.isNotBlank(), + ) + } + Text( + text = stringResource(Res.string.inspector_trackers_add_hint), + style = type.caption, + color = colors.textTertiary, + ) + } } } diff --git a/app/shared/src/commonTest/kotlin/com/linroid/ketch/app/ui/inspector/tabs/TrackersTabTest.kt b/app/shared/src/commonTest/kotlin/com/linroid/ketch/app/ui/inspector/tabs/TrackersTabTest.kt index fe4d66ed6..a6bd9452f 100644 --- a/app/shared/src/commonTest/kotlin/com/linroid/ketch/app/ui/inspector/tabs/TrackersTabTest.kt +++ b/app/shared/src/commonTest/kotlin/com/linroid/ketch/app/ui/inspector/tabs/TrackersTabTest.kt @@ -43,4 +43,13 @@ class TrackersTabTest { assertEquals(TrackerTone.Neutral, view.tone) assertNull(view.message) } + + @Test + fun `typed trackers are split on spaces commas and new lines and listed once`() { + assertEquals( + listOf("udp://a.example:6969", "https://b.example/announce"), + trackerUrls(" udp://a.example:6969\nhttps://b.example/announce, udp://a.example:6969\r\n"), + ) + assertEquals(emptyList(), trackerUrls(" \n ")) + } } diff --git a/app/shared/src/jvmTest/kotlin/com/linroid/ketch/app/snapshot/InspectorTabsSnapshots.kt b/app/shared/src/jvmTest/kotlin/com/linroid/ketch/app/snapshot/InspectorTabsSnapshots.kt index 803607324..2b148f140 100644 --- a/app/shared/src/jvmTest/kotlin/com/linroid/ketch/app/snapshot/InspectorTabsSnapshots.kt +++ b/app/shared/src/jvmTest/kotlin/com/linroid/ketch/app/snapshot/InspectorTabsSnapshots.kt @@ -29,11 +29,16 @@ import com.linroid.ketch.api.SourceFile import com.linroid.ketch.api.SpeedLimit import com.linroid.ketch.app.components.KetchEyebrow import com.linroid.ketch.app.i18n.verbatim +import com.linroid.ketch.app.state.FileOrder +import com.linroid.ketch.app.state.FileSelectionModel +import com.linroid.ketch.app.state.FileSort +import com.linroid.ketch.app.state.FileSortSurface import com.linroid.ketch.app.state.ListFixtures import com.linroid.ketch.app.state.SpeedHistory import com.linroid.ketch.app.state.TaskRow import com.linroid.ketch.app.state.TimelineEntry import com.linroid.ketch.app.state.TimelineKind +import com.linroid.ketch.app.state.appliedSelection import com.linroid.ketch.app.theme.KetchDensity import com.linroid.ketch.app.theme.KetchElevationLevel import com.linroid.ketch.app.theme.KetchTheme @@ -43,18 +48,14 @@ import com.linroid.ketch.app.ui.inspector.tabs.ActivityTabContent import com.linroid.ketch.app.ui.inspector.tabs.ConnectionsTab import com.linroid.ketch.app.ui.inspector.tabs.ConnectionsTabContent import com.linroid.ketch.app.ui.inspector.tabs.FilesTabContent -import com.linroid.ketch.app.ui.settings.BlockedAddressesGroup +import com.linroid.ketch.app.ui.inspector.tabs.TrackerEditing import com.linroid.ketch.app.ui.inspector.tabs.TrackersTabContent +import com.linroid.ketch.app.ui.settings.BlockedAddressesGroup +import com.linroid.ketch.app.util.SegmentRate import com.linroid.ketch.torrent.api.TorrentTracker import com.linroid.ketch.torrent.api.TorrentTrackerState -import com.linroid.ketch.app.state.FileOrder -import com.linroid.ketch.app.state.FileSort -import com.linroid.ketch.app.state.FileSortSurface -import com.linroid.ketch.app.state.FileSelectionModel -import com.linroid.ketch.app.state.appliedSelection -import kotlinx.coroutines.Job -import com.linroid.ketch.app.util.SegmentRate -import kotlinx.datetime.TimeZone +import ketch.app.shared.generated.resources.Res +import ketch.app.shared.generated.resources.inspector_trackers_invalid import kotlin.math.PI import kotlin.math.roundToLong import kotlin.math.sin @@ -62,6 +63,8 @@ import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.Job +import kotlinx.datetime.TimeZone /** * The inspector's Connections, Files and Activity tabs in the docked width, its widest and on a @@ -139,6 +142,32 @@ class InspectorTabsSnapshots { } } + @Test + fun trackers_editable_offersRemovingAndAdding() { + val size = SnapshotSize(360.dp, 420.dp, KetchDensity.Compact) + val trackers = listOf( + TorrentTracker("udp://tracker.opentrackr.org:1337", 0, TorrentTrackerState.WORKING, + peers = 48, seeders = 1204, leechers = 87), + TorrentTracker("udp://open.stealth.si:80", 1, TorrentTrackerState.TIMED_OUT, failures = 1), + ) + val drafts = mapOf( + "inspector-trackers-edit" to TrackerEditing("", null, {}, {}, {}), + "inspector-trackers-edit-invalid" to TrackerEditing("wss://web.example/announce", + Res.string.inspector_trackers_invalid, {}, {}, {}), + ) + for ((name, editing) in drafts) { + for (theme in SnapshotTheme.entries) { + snapshot(name, size, theme) { + Column(Modifier.padding(KetchTheme.spacing.s4)) { + TabCard("Trackers", DockedWidth) { + TrackersTabContent(trackers, editing = editing) + } + } + } + } + } + } + @Test fun connections_hoverAndKeyboard_highlightTheLaneAndFocus() { val size = SnapshotSize(360.dp, 420.dp, KetchDensity.Compact) diff --git a/docs/developers.md b/docs/developers.md index 4f58ea93d..cef4ecd50 100644 --- a/docs/developers.md +++ b/docs/developers.md @@ -181,6 +181,7 @@ These exist on servers listing `torrent.control`: | `GET /api/torrents/{id}/priority`, `PUT` | The files it downloads before its others, as `{"fileIds": [...]}`; `PUT` sets them, an empty list for the usual order (`file-priority` capability) | | `POST /api/torrents/{id}/recheck` | Check its files against the torrent's hashes again and download what is missing; answers its snapshot (`recheck` capability) | | `GET /api/torrents/{id}/trackers` | Its own trackers in tier order: endpoint (never the path), state (`idle`, `announcing`, `working`, `failed`, `timed-out`), peers named, seeders, leechers and what the tracker said (`trackers` capability) | +| `PUT /api/torrents/{id}/trackers` | Adds and removes its own trackers: `{"add": [announce URLs], "remove": [endpoints]}`, answering the new list; `invalid_input` for a URL that is not `http`, `https` or `udp` (`tracker-edit` capability) | | `GET /api/torrents/{id}/export?metainfo=true` | Its info hashes and magnet link (none for a private torrent), with its `.torrent` file as Base64 when `metainfo` is true (`export` capability) | | `GET /api/torrents/{id}/events` | Deprecated: SSE `snapshot` events of it; the event stream carries them | diff --git a/docs/torrent.md b/docs/torrent.md index eef0dcfea..37a0ffb98 100644 --- a/docs/torrent.md +++ b/docs/torrent.md @@ -536,6 +536,16 @@ of its swarms and lists each once, with the answer that says most. The trackers the settings above are not listed. REST: `GET /api/torrents/{id}/trackers`, on devices listing the `trackers` capability. +On devices listing the `tracker-edit` capability the tab also changes them: the × beside a +tracker removes it, and **Add trackers** takes `http`, `https` or `udp` announce URLs, separated +by spaces or new lines, each added after the torrent's own as a tier of its own, so it is asked +when those before it fail. A torrent that is downloading or seeding starts again to use the new +list; the change stays with the task, also after a restart, while a `.torrent` file or magnet +link exported from it still names the trackers it was added with. A torrent may have at most 128 +trackers. REST: `PUT /api/torrents/{id}/trackers` with +`{"add": ["udp://tracker.example:6969/announce"], "remove": ["udp://old.example:1337"]}`, which +answers the new list; SDK: `TorrentController.editTrackers(taskId, TorrentTrackerEdit(...))`. + ### How download settings apply to torrents Torrent tasks follow the same download settings as HTTP and FTP tasks, with these differences: @@ -775,7 +785,8 @@ which describe the backend, not its current settings, and `seeding` while the co `SEED_AFTER_COMPLETION`, also while uploads are paused), `snapshot(taskId)`, sorted file pages (`files`), `select` and `setSeeding` commands guarded by a revision and an idempotency key, `trackers(taskId)` (`TorrentTracker`: each own tracker's endpoint, tier, state, peers, -swarm counts and message; the `trackers` capability), `export(taskId, metainfo)` (`TorrentExport`: the info hashes, the magnet link and, when +swarm counts and message; the `trackers` capability), `editTrackers(taskId, edit)` (adds and +removes a task's own trackers; the `tracker-edit` capability), `export(taskId, metainfo)` (`TorrentExport`: the info hashes, the magnet link and, when asked for, the `.torrent` file; the `export` capability), and `settings()` and `updateSettings(change)` (`TorrentEngineSettings`, `TorrentSettingsChange`; the `settings` capability). In process, `updateSettings` runs diff --git a/library/endpoints/src/commonMain/kotlin/com/linroid/ketch/endpoints/torrent/Torrents.kt b/library/endpoints/src/commonMain/kotlin/com/linroid/ketch/endpoints/torrent/Torrents.kt index e427fb0f7..04b20b128 100644 --- a/library/endpoints/src/commonMain/kotlin/com/linroid/ketch/endpoints/torrent/Torrents.kt +++ b/library/endpoints/src/commonMain/kotlin/com/linroid/ketch/endpoints/torrent/Torrents.kt @@ -22,6 +22,7 @@ import kotlinx.serialization.Serializable * - `GET /api/torrents/{id}/priority`, `PUT` — the files it downloads before its others * - `POST /api/torrents/{id}/recheck` — check its files again and download what is missing * - `GET /api/torrents/{id}/trackers` — its own trackers and how each answers + * - `PUT /api/torrents/{id}/trackers` — adds and removes trackers (`TorrentTrackerEdit`) * - `GET /api/torrents/{id}/events` — SSE stream of its snapshots */ @Serializable @@ -95,7 +96,10 @@ data class Torrents(val parent: Api = Api()) { @Resource("recheck") data class Recheck(val parent: ById) - /** The task's own trackers in tier order, a list of `TorrentTracker`. */ + /** + * The task's own trackers in tier order, a list of `TorrentTracker`; `PUT` with a + * `TorrentTrackerEdit` changes them and answers the list. + */ @Serializable @Resource("trackers") data class Trackers(val parent: ById) diff --git a/library/remote/src/commonMain/kotlin/com/linroid/ketch/remote/RemoteTorrentController.kt b/library/remote/src/commonMain/kotlin/com/linroid/ketch/remote/RemoteTorrentController.kt index 942551a63..3010de474 100644 --- a/library/remote/src/commonMain/kotlin/com/linroid/ketch/remote/RemoteTorrentController.kt +++ b/library/remote/src/commonMain/kotlin/com/linroid/ketch/remote/RemoteTorrentController.kt @@ -27,6 +27,7 @@ import com.linroid.ketch.torrent.api.TorrentRevisionDecision import com.linroid.ketch.torrent.api.TorrentSettingsChange import com.linroid.ketch.torrent.api.TorrentSnapshot import com.linroid.ketch.torrent.api.TorrentTracker +import com.linroid.ketch.torrent.api.TorrentTrackerEdit import com.linroid.ketch.torrent.api.compareIncoming import io.ktor.client.HttpClient import io.ktor.client.call.body @@ -377,6 +378,19 @@ internal class RemoteTorrentController( } } + override suspend fun editTrackers( + taskId: String, + edit: TorrentTrackerEdit, + ): List { + requireCapability(TorrentCapability.TRACKER_EDIT) + return call>(notFoundIsNull = false) { + httpClient.put(Torrents.ById.Trackers(parent = Torrents.ById(id = taskId))) { + contentType(ContentType.Application.Json) + setBody(edit) + } + } ?: throw IllegalStateException("Empty response") + } + /** Fails with [TorrentCommandError.UNSUPPORTED], sending nothing, unless the server has it. */ private suspend fun requireCapability(capability: TorrentCapability) { if (!capabilities().supports(capability)) { diff --git a/library/server/src/main/kotlin/com/linroid/ketch/server/api/TorrentRoutes.kt b/library/server/src/main/kotlin/com/linroid/ketch/server/api/TorrentRoutes.kt index 91585f4e8..b4157415b 100644 --- a/library/server/src/main/kotlin/com/linroid/ketch/server/api/TorrentRoutes.kt +++ b/library/server/src/main/kotlin/com/linroid/ketch/server/api/TorrentRoutes.kt @@ -15,6 +15,7 @@ import com.linroid.ketch.torrent.api.TorrentFileOrder import com.linroid.ketch.torrent.api.TorrentInterest import com.linroid.ketch.torrent.api.TorrentPageRequest import com.linroid.ketch.torrent.api.TorrentSettingsChange +import com.linroid.ketch.torrent.api.TorrentTrackerEdit import io.ktor.http.HttpStatusCode import io.ktor.server.resources.get import io.ktor.server.resources.post @@ -157,6 +158,18 @@ internal fun Route.torrentRoutes(ketch: KetchApi, controller: TorrentController) call.respond(controller.trackers(taskId) ?: throw notFound(taskId)) } + put { resource -> + val taskId = resource.parent.id + // Never echoed or logged: announce URLs may carry passkeys. + val body = try { + call.receiveJson() + } catch (_: IllegalArgumentException) { + throw invalidInput("Invalid tracker edit") + } + log.d { "PUT /api/torrents/$taskId/trackers add=${body.add.size} remove=${body.remove.size}" } + call.respond(controller.editTrackers(taskId, body)) + } + sse("/api/torrents/{id}/events") { val taskId = call.parameters["id"]!! log.d { "SSE client connected to /api/torrents/$taskId/events" } diff --git a/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentCapabilities.kt b/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentCapabilities.kt index 6fbe0e800..d035341bd 100644 --- a/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentCapabilities.kt +++ b/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentCapabilities.kt @@ -30,6 +30,7 @@ enum class TorrentCapability(val wireName: String) { SEQUENTIAL("sequential"), FILE_PRIORITY("file-priority"), IP_FILTER("ip-filter"), + TRACKER_EDIT("tracker-edit"), } /** diff --git a/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentController.kt b/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentController.kt index 2b3ef45a0..8240e193c 100644 --- a/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentController.kt +++ b/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentController.kt @@ -157,6 +157,20 @@ interface TorrentController { message = "Tracker status is unavailable", ) + /** + * Changes the task's own trackers as [edit] says and answers them as [trackers] does. The + * change stays with the task, and a torrent that downloads or seeds starts again to announce + * to them. Fails with [TorrentCommandError.NOT_FOUND] for unknown and non-torrent tasks, with + * [TorrentCommandError.INVALID_INPUT] for a URL the backend cannot announce to or more + * trackers than a torrent may have, and with [TorrentCommandError.METADATA_UNAVAILABLE] while + * the torrent's trackers are not known yet. Advertised as [TorrentCapability.TRACKER_EDIT]. + */ + suspend fun editTrackers(taskId: String, edit: TorrentTrackerEdit): List = + throw TorrentCommandException( + error = TorrentCommandError.UNSUPPORTED, + message = "Editing trackers is unavailable", + ) + /** * Whether peers can connect to the backend's torrent engine, through how many NAT layers its * port is forwarded, and whether it punches through NATs; advertised as diff --git a/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentTrackers.kt b/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentTrackers.kt index bbb7467a2..988ca4c4d 100644 --- a/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentTrackers.kt +++ b/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentTrackers.kt @@ -57,6 +57,20 @@ data class TorrentTracker( val message: String? = null, ) +/** + * A change to a torrent's own trackers; see [TorrentController.editTrackers]. + * + * @property add announce URLs (`http`, `https` or `udp`) to announce to as well, each a tier of + * its own after the torrent's; one the torrent already has is left where it is + * @property remove the [TorrentTracker.endpoint]s of the trackers to stop announcing to: every + * tracker at that scheme, host and port, whatever its path + */ +@Serializable +data class TorrentTrackerEdit( + val add: List = emptyList(), + val remove: List = emptyList(), +) + internal object TorrentTrackerStateSerializer : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("TorrentTrackerState", PrimitiveKind.STRING) diff --git a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentDownloadSource.kt b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentDownloadSource.kt index 505a3880d..de3115bdb 100644 --- a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentDownloadSource.kt +++ b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentDownloadSource.kt @@ -37,7 +37,9 @@ import com.linroid.ketch.torrent.control.SeedingTask import com.linroid.ketch.torrent.control.TorrentControlSource import com.linroid.ketch.torrent.control.TorrentControls import com.linroid.ketch.torrent.control.exportOf +import com.linroid.ketch.torrent.control.editedTrackerTiers import com.linroid.ketch.torrent.control.idleTrackers +import com.linroid.ketch.torrent.control.torrentTrackerTiers import com.linroid.ketch.torrent.control.trackerViews import com.linroid.ketch.torrent.crypto.sha256Digest import com.linroid.ketch.torrent.engine.IncompleteSeedException @@ -287,6 +289,18 @@ class TorrentDownloadSource( override fun withSequential(state: SourceState, sequential: Boolean) = source.withSequential(state, sequential) + + override suspend fun editTrackers( + taskId: String, + url: String, + sourceState: SourceState?, + resolved: ResolvedSource?, + add: List, + remove: List, + ) = source.editTrackers(taskId, url, sourceState, resolved, add, remove) + + override fun withTrackers(state: SourceState, tiers: List>) = + source.withTrackers(state, tiers) override val restoresSeeding: Boolean get() = source.restoresSeeding override val sharingResumes: StateFlow get() = source.sharingResumes @@ -365,6 +379,7 @@ class TorrentDownloadSource( add(TorrentCapability.IMPORT.wireName) add(TorrentCapability.FILE_PRIORITY.wireName) add(TorrentCapability.IP_FILTER.wireName) + add(TorrentCapability.TRACKER_EDIT.wireName) if (lsdSupported) add(TorrentCapability.LOCAL_DISCOVERY.wireName) // Sharing follows the live upload setting, paused or not. if (uploadPolicy.load() == TorrentUploadPolicy.SEED_AFTER_COMPLETION) { @@ -408,12 +423,22 @@ class TorrentDownloadSource( */ internal suspend fun setPriorityFiles(taskId: String, fileIds: Set) { priorityChoices.update { it + (taskId to fileIds) } - stateMutex.withLock { - states[taskId]?.let { states[taskId] = it.copy(priorityFileIds = fileIds) } - } + changeHeldState(taskId) { it.copy(priorityFileIds = fileIds) } tasks.session(taskId)?.setPriorityFiles(fileIds) } + /** + * Applies [change] to the state a run of [taskId] saves from, and to the one its seeding + * session saves from, so neither saves over a setting changed meanwhile. + */ + private suspend fun changeHeldState( + taskId: String, + change: (TorrentSourceState) -> TorrentSourceState, + ) { + stateMutex.withLock { states[taskId]?.let { states[taskId] = change(it) } } + seedStates.update { seeds -> seeds[taskId]?.let { seeds + (taskId to change(it)) } ?: seeds } + } + /** The saved [state] as [change] makes it, or as it is when it cannot be read. */ private fun changed( state: SourceState, @@ -428,6 +453,59 @@ class TorrentDownloadSource( internal fun withSequential(state: SourceState, sequential: Boolean): SourceState = changed(state) { it.copy(sequential = sequential) } + /** What [TorrentControlSource.withTrackers] answers. */ + internal fun withTrackers(state: SourceState, tiers: List>): SourceState = + changed(state) { it.copy(trackerTiers = tiers) } + + /** The trackers tasks were last given by [editTrackers], in this process. */ + private val trackerChoices = MutableStateFlow>>>(emptyMap()) + + /** + * The trackers [taskId] announces to in place of its torrent's: what it was last given, else + * what its run or its saved [state] says; `null` for the torrent's own. + */ + private suspend fun editedTrackers( + taskId: String, + state: TorrentSourceState?, + ): List>? = trackerChoices.value[taskId] + ?: stateMutex.withLock { states[taskId]?.trackerTiers } ?: state?.trackerTiers + + /** What [taskId] announces to: its [editedTrackers], else the torrent's; `null` if unknown. */ + private suspend fun trackerTiers( + taskId: String, + url: String, + state: TorrentSourceState?, + resolved: ResolvedSource?, + ): List>? = editedTrackers(taskId, state) + ?: withContext(TorrentDispatchers.engine) { + torrentTrackerTiers(url, metainfoBytes(state, resolved), config.maxMetadataBytes) + } + + /** + * What [TorrentControlSource.editTrackers] does: the sessions of [taskId] that open from now + * on announce to the edited trackers, which its run saves with its state. + */ + internal suspend fun editTrackers( + taskId: String, + url: String, + sourceState: SourceState?, + resolved: ResolvedSource?, + add: List, + remove: List, + ): List>? = trackerEdits.withLock { + val state = sourceState?.let { runCatching { decodeState(it) }.getOrNull() } + val current = trackerTiers(taskId, url, state, resolved) ?: return@withLock null + val edited = editedTrackerTiers(current, add, remove) + trackerChoices.update { it + (taskId to edited) } + changeHeldState(taskId) { it.copy(trackerTiers = edited) } + val count = edited.sumOf { it.size } + log.i { "Trackers of taskId=$taskId edited: $count in ${edited.size} tiers" } + edited + } + + /** One [editTrackers] at a time, so none builds on trackers another is replacing. */ + private val trackerEdits = Mutex() + /** What tasks were last told by [setSequential], in this process. */ private val sequentialChoices = MutableStateFlow>(emptyMap()) @@ -443,9 +521,7 @@ class TorrentDownloadSource( /** Downloads [taskId]'s pieces in order or not, at once if it runs and whenever it next does. */ internal suspend fun setSequential(taskId: String, sequential: Boolean) { sequentialChoices.update { it + (taskId to sequential) } - stateMutex.withLock { - states[taskId]?.let { states[taskId] = it.copy(sequential = sequential) } - } + changeHeldState(taskId) { it.copy(sequential = sequential) } tasks.session(taskId)?.setSequential(sequential) } @@ -1089,10 +1165,8 @@ class TorrentDownloadSource( ): List? { val live = tasks.session(taskId)?.trackers().orEmpty() if (live.isNotEmpty()) return trackerViews(live) - val bytes = metainfoBytes(sourceState?.let { decodeState(it) }, resolved) - return withContext(TorrentDispatchers.engine) { - idleTrackers(url, bytes, config.maxMetadataBytes) - } + val state = sourceState?.let { decodeState(it) } + return trackerTiers(taskId, url, state, resolved)?.let(::idleTrackers) } /** @@ -1384,6 +1458,7 @@ class TorrentDownloadSource( } val selected = selectionOf(table, selection, state) val magnet = task.url.takeIf { it.startsWith("magnet:", true) } + val trackers = editedTrackers(task.taskId, state) val resumeData = state.resumeData.takeIf { it.isNotEmpty() } if (table.v2) { require(state.version == 3) { "Invalid v2 resume state" } @@ -1394,7 +1469,7 @@ class TorrentDownloadSource( return SeedPlan(hash, state) { (getEngine() as KotlinTorrentEngine).addV2Task(TorrentV2TaskSpec(task.taskId, document, output, selected, checkpointEncoded = resumeData, - trackerTiers = sourceTrackerTiers(bytes, config.maxMetadataBytes), + trackerTiers = trackers ?: sourceTrackerTiers(bytes, config.maxMetadataBytes), magnetUri = magnet, privacy = privacy, recoverCreations = true, legacySelections = listOfNotNull(state.selectedFileIds.takeIf { it.isNotEmpty() }), seedOnly = true, connections = task.connections)) @@ -1402,6 +1477,7 @@ class TorrentDownloadSource( } require(state.version != 3) { "Cannot downgrade a v2 task" } val metadata = TorrentMetadata.fromBencode(bytes, config.maxMetadataBytes) + .announcingTo(trackers) val hash = metadata.infoHash.hex require(hash == state.infoHash) { "Saved torrent changed" } return SeedPlan(hash, state) { @@ -1724,18 +1800,19 @@ class TorrentDownloadSource( require(!output.contains("://")) { "Torrent output requires a filesystem path" } val total = table.totalOf(selected) val privacy = previous?.privacy ?: resolvedPrivacy(resolved) + val trackers = editedTrackers(context.taskId, previous) // The metainfo is Ketch's to keep; only states older builds saved carry it. val state = TorrentSourceState(hash, total, previous?.resumeData ?: "", selected, output, previous?.metainfo.orEmpty(), version = 2, privacy = privacy, sequential = previous?.sequential == true, - priorityFileIds = previous?.priorityFileIds.orEmpty()) + priorityFileIds = previous?.priorityFileIds.orEmpty(), trackerTiers = trackers) log.i { "Starting torrent taskId=${context.taskId} (${logHash(hash)}): " + "files=${selected.size}/${table.files.size}, totalBytes=$total, output=$output, " + "resume=${previous != null}" } runSession(context, hash, table, state, initial.revision) { - getEngine().addTask(TorrentTaskSpec(context.taskId, metadata, output, + getEngine().addTask(TorrentTaskSpec(context.taskId, metadata.announcingTo(trackers), output, selected.mapTo(LinkedHashSet()) { it.toInt() }, context.url.takeIf { it.startsWith("magnet:", true) }, previous?.resumeData?.takeIf { it.isNotEmpty() }?.let(::decodeBase64), context.throttle, @@ -1760,12 +1837,13 @@ class TorrentDownloadSource( ?: error("Torrent output path has not been resolved") require("://" !in output) { "Torrent output requires a filesystem path" } val privacy = previous?.privacy ?: resolvedPrivacy(resolved) + val trackers = editedTrackers(context.taskId, previous) val hash = document.info.hash.hex val total = table.totalOf(selected) val state = TorrentSourceState(hash, total, previous?.resumeData.orEmpty(), selected, output, previous?.metainfo.orEmpty(), version = 3, privacy = privacy, sequential = previous?.sequential == true, - priorityFileIds = previous?.priorityFileIds.orEmpty()) + priorityFileIds = previous?.priorityFileIds.orEmpty(), trackerTiers = trackers) log.i { "Starting v2 torrent taskId=${context.taskId} (${logHash(hash)}): " + "files=${selected.size}/${table.files.size}, totalBytes=$total, output=$output, " + @@ -1775,7 +1853,7 @@ class TorrentDownloadSource( (getEngine() as KotlinTorrentEngine).addV2Task(TorrentV2TaskSpec(context.taskId, document, output, selected, checkpointEncoded = previous?.resumeData?.takeIf { it.isNotEmpty() }, - trackerTiers = sourceTrackerTiers(bytes, config.maxMetadataBytes), + trackerTiers = trackers ?: sourceTrackerTiers(bytes, config.maxMetadataBytes), magnetUri = context.url.takeIf { it.startsWith("magnet:", true) }, privacy = privacy, throttle = context.throttle, recoverCreations = true, // The creation log may still be bound to the selection the task last ran with. @@ -1845,7 +1923,8 @@ class TorrentDownloadSource( try { val sequential = sequentialChoices.value[taskId] ?: state.sequential val first = priorityChoices.value[taskId] ?: state.priorityFileIds - rememberState(taskId, state.copy(sequential = sequential, priorityFileIds = first)) + rememberState(taskId, state.copy(sequential = sequential, priorityFileIds = first, + trackerTiers = trackerChoices.value[taskId] ?: state.trackerTiers)) val running = adopted ?: open().also { created -> session = created tasks.attach(taskId, created) diff --git a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentSourceMetainfo.kt b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentSourceMetainfo.kt index a002f2e2d..423d1849a 100644 --- a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentSourceMetainfo.kt +++ b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentSourceMetainfo.kt @@ -73,6 +73,10 @@ internal fun sourceTrackerTiers(bytes: ByteArray, maxBytes: Int): List>?): TorrentMetadata = + if (tiers == null) this else copy(trackers = tiers.flatten(), trackerTiers = tiers) + /** * Refuses a torrent that could never find a peer: one that finds peers only through its * trackers, as a private torrent or one resolved [TorrentDiscoveryPrivacy.TRACKER_ONLY] does, diff --git a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentSourceState.kt b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentSourceState.kt index 778b98e8d..2ff8fe095 100644 --- a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentSourceState.kt +++ b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentSourceState.kt @@ -33,6 +33,11 @@ data class TorrentSourceState internal constructor( internal val sequential: Boolean = false, /** The files to download first; see [TorrentDownloadSource.setPriorityFiles]. */ internal val priorityFileIds: Set = emptySet(), + /** + * The trackers the task announces to in place of the torrent's own, once they were edited; + * see [TorrentDownloadSource.editTrackers]. `null` for the torrent's. + */ + internal val trackerTiers: List>? = null, ) { init { require(version in 1..3) { "Unsupported torrent resume version" } diff --git a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/KetchTorrentController.kt b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/KetchTorrentController.kt index 98bc9d9ec..707406564 100644 --- a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/KetchTorrentController.kt +++ b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/KetchTorrentController.kt @@ -39,6 +39,7 @@ import com.linroid.ketch.torrent.api.TorrentSettingsChange import com.linroid.ketch.torrent.api.TorrentSnapshot import com.linroid.ketch.torrent.api.TorrentStall import com.linroid.ketch.torrent.api.TorrentTracker +import com.linroid.ketch.torrent.api.TorrentTrackerEdit import com.linroid.ketch.torrent.engine.TorrentPayloadCounters import com.linroid.ketch.torrent.net.TorrentIpFilter import kotlin.time.Duration.Companion.seconds @@ -277,6 +278,52 @@ internal class KetchTorrentController( ) } + override suspend fun editTrackers( + taskId: String, + edit: TorrentTrackerEdit, + ): List { + val task = torrentTask(taskId) ?: throw notFound() + requireCapability(TorrentCapability.TRACKER_EDIT, TorrentCommandError.UNSUPPORTED) + if (edit.add.size > MAX_TRACKERS || edit.remove.size > MAX_TRACKERS) { + throw TorrentCommandException(TorrentCommandError.INVALID_INPUT, "Too many trackers") + } + val record = recordOf(task) + val tiers = try { + source.editTrackers( + taskId = taskId, + url = record.request.url, + sourceState = record.sourceState, + resolved = record.resolvedSource ?: record.request.resolvedSource, + add = edit.add, + remove = edit.remove, + ) + } catch (_: IllegalArgumentException) { + // Never the URL itself, which may hold a passkey. + throw TorrentCommandException( + TorrentCommandError.INVALID_INPUT, + "Trackers must be http, https or udp announce URLs, and no more than a torrent may have", + ) + } ?: throw TorrentCommandException( + TorrentCommandError.METADATA_UNAVAILABLE, + "The torrent is not known yet", + ) + // A task that is not running saves no state of its own until it next runs. + host.changeSourceState(task) { source.withTrackers(it, tiers) } + // A session announces to the trackers it opened with: one that runs opens again. + val state = task.state.value + if (state is DownloadState.Downloading && source.liveTorrent(taskId) != null) { + mapErrors { + task.pause() + task.resume() + } + } else if (state is DownloadState.Completed && taskId in source.seedingTaskIds.value) { + source.stopSeeding(taskId) + seed(task) + } + controlChanged() + return trackers(taskId) ?: throw notFound() + } + /** * Tells [observe] that a task's saved control changed, such as its intent to seed, which may * change nothing else it follows: a task that waits for uploads to resume neither starts nor diff --git a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/TorrentControlSource.kt b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/TorrentControlSource.kt index 079e1b2ac..8da0cc27a 100644 --- a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/TorrentControlSource.kt +++ b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/TorrentControlSource.kt @@ -74,6 +74,25 @@ internal interface TorrentControlSource { /** [state], as a task saved it, with [fileIds] as the files to download first. */ fun withPriorityFiles(state: SourceState, fileIds: Set): SourceState = state + /** + * Changes the own trackers of the task [taskId], which downloads [url], without those at the + * endpoints [remove] names and with the announce URLs [add]: what its next session announces + * to. Returns the trackers it then has, or `null` when the torrent's are not known. + * + * @throws IllegalArgumentException for a URL the engine cannot announce to, or too many + */ + suspend fun editTrackers( + taskId: String, + url: String, + sourceState: SourceState?, + resolved: ResolvedSource?, + add: List, + remove: List, + ): List>? = null + + /** [state], as a task saved it, announcing to [tiers] in place of the torrent's trackers. */ + fun withTrackers(state: SourceState, tiers: List>): SourceState = state + /** [state], as a task saved it, downloading its pieces in order or not. */ fun withSequential(state: SourceState, sequential: Boolean): SourceState = state diff --git a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/TorrentTrackerViews.kt b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/TorrentTrackerViews.kt index f4831807b..ab278d69b 100644 --- a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/TorrentTrackerViews.kt +++ b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/TorrentTrackerViews.kt @@ -3,6 +3,7 @@ package com.linroid.ketch.torrent.control import com.linroid.ketch.torrent.api.TorrentTracker import com.linroid.ketch.torrent.api.TorrentTrackerState import com.linroid.ketch.torrent.magnet.MagnetUri +import com.linroid.ketch.torrent.metainfo.MAX_TRACKERS import com.linroid.ketch.torrent.sourceTrackerTiers import com.linroid.ketch.torrent.tracker.TrackerConfiguration import com.linroid.ketch.torrent.tracker.TrackerStatus @@ -35,17 +36,32 @@ internal fun trackerViews(statuses: List): List = * [metainfo] that Ketch can announce to, else those a magnet [url] names; `null` when neither * is known. */ -internal fun idleTrackers(url: String, metainfo: ByteArray?, maxBytes: Int): List? { - val tiers = if (metainfo != null) { - sourceTrackerTiers(metainfo, maxBytes) - } else { - val magnet = try { - MagnetUri.parse(url) - } catch (_: IllegalArgumentException) { - return null - } - TrackerConfiguration.usable(magnet.trackers.map { listOf(it) }).tiers +internal fun idleTrackers( + url: String, + metainfo: ByteArray?, + maxBytes: Int, +): List? = torrentTrackerTiers(url, metainfo, maxBytes)?.let(::idleTrackers) + +/** + * The tiers of the trackers a torrent names that Ketch can announce to: those of its + * [metainfo], else those a magnet [url] names; `null` when neither is known. + */ +internal fun torrentTrackerTiers( + url: String, + metainfo: ByteArray?, + maxBytes: Int, +): List>? { + if (metainfo != null) return sourceTrackerTiers(metainfo, maxBytes) + val magnet = try { + MagnetUri.parse(url) + } catch (_: IllegalArgumentException) { + return null } + return TrackerConfiguration.usable(magnet.trackers.map { listOf(it) }).tiers +} + +/** The trackers of [tiers], all idle. */ +internal fun idleTrackers(tiers: List>): List { val seen = HashSet() // A tracker listed again in a later tier counts once, and a tier of repeats is none. return tiers.map { tier -> tier.filter(seen::add) }.filter { it.isNotEmpty() } @@ -53,3 +69,25 @@ internal fun idleTrackers(url: String, metainfo: ByteArray?, maxBytes: Int): Lis tier.map { TorrentTracker(endpoint = trackerLabel(it), tier = index) } } } + +/** + * [tiers] without the trackers at the endpoints [remove] names and with the announce URLs + * [add] after them, each a tier of its own unless [tiers] has it already. + * + * @throws IllegalArgumentException for a URL Ketch cannot announce to, or more than + * [MAX_TRACKERS] trackers + */ +internal fun editedTrackerTiers( + tiers: List>, + add: List, + remove: List, +): List> { + val gone = remove.toSet() + val kept = tiers.map { tier -> tier.filter { trackerLabel(it) !in gone } } + .filter { it.isNotEmpty() } + val known = kept.flatten().toHashSet() + val added = add.map { it.trim() }.filter { it.isNotEmpty() && known.add(it) } + val edited = TrackerConfiguration.prepare(kept + added.map { listOf(it) }).tiers + require(edited.sumOf { it.size } <= MAX_TRACKERS) { "Too many trackers" } + return edited +} diff --git a/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/TorrentDownloadSourceTest.kt b/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/TorrentDownloadSourceTest.kt index 95272705a..e3c97cbf7 100644 --- a/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/TorrentDownloadSourceTest.kt +++ b/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/TorrentDownloadSourceTest.kt @@ -240,7 +240,7 @@ class TorrentDownloadSourceTest { val engine = setOf("file-selection", "v1", "v2", "hybrid", "utp", "mse-pe", "reachability", "settings", "seed-goals", "sequential", "export", "trackers", "recheck", "import", "file-priority", - "ip-filter") + "ip-filter", "tracker-edit") // Local discovery only where the platform can join the LAN group. assertEquals(if (lsdSupported) engine + "local-discovery" else engine, source.torrentCapabilities) diff --git a/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/TorrentSeedingControlTest.kt b/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/TorrentSeedingControlTest.kt index ad6429d56..9989a7491 100644 --- a/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/TorrentSeedingControlTest.kt +++ b/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/TorrentSeedingControlTest.kt @@ -6,6 +6,7 @@ import com.linroid.ketch.api.DownloadState import com.linroid.ketch.api.DownloadTask import com.linroid.ketch.core.Ketch import com.linroid.ketch.core.engine.HttpEngine +import com.linroid.ketch.core.engine.decodeState import com.linroid.ketch.core.engine.SourceState import com.linroid.ketch.core.task.TaskControl import com.linroid.ketch.core.task.TaskRecord @@ -17,6 +18,7 @@ import com.linroid.ketch.torrent.api.TorrentCommandContext import com.linroid.ketch.torrent.api.TorrentCommandError import com.linroid.ketch.torrent.api.TorrentCommandException import com.linroid.ketch.torrent.api.TorrentController +import com.linroid.ketch.torrent.api.TorrentTrackerEdit import com.linroid.ketch.torrent.control.SeedingOutcome import com.linroid.ketch.torrent.control.SeedingTask import com.linroid.ketch.torrent.crypto.torrentRandomBytes @@ -67,6 +69,9 @@ class TorrentSeedingControlTest { /** Tracker announces sent through [http]. */ val announces = AtomicInt(0) + /** Announces sent to [EXTRA_TRACKER], a tracker no torrent of the tests names. */ + val extraAnnounces = AtomicInt(0) + /** The seeder's engine, counting announces. */ val http: HttpEngine = object : HttpEngine by seeder.http { override suspend fun download( @@ -76,6 +81,7 @@ class TorrentSeedingControlTest { onData: suspend (ByteArray) -> Unit, ) { if (url.startsWith(GatedSeeder.ANNOUNCE)) announces.incrementAndFetch() + if (url.startsWith(EXTRA_TRACKER)) extraAnnounces.incrementAndFetch() seeder.http.download(url, range, headers, onData) } } @@ -595,6 +601,52 @@ class TorrentSeedingControlTest { source.assertNoLeaks() } + @Test + fun editTrackers_seedingTask_announcesToTheNewTrackers_andSavesThem() = harness { + val store = MemoryTaskStore() + val source = source() + val ketch = ketch(source, store) + ketch.start() + val task = ketch.download(request(0)) + task.awaitCompleted() + task.awaitSeeding(true) + val controller = assertNotNull(ketch.controller(TorrentController)) + assertEquals(0, extraAnnounces.load()) + + // The seeder opens again and announces to the tracker it was given in place of its own. + val swapped = controller.editTrackers(task.taskId, + TorrentTrackerEdit(add = listOf(EXTRA_TRACKER), remove = listOf("http://fixture:80"))) + assertEquals(listOf("http://extra.example:80"), swapped.map { it.endpoint }) + awaitStage("an announce to the added tracker", task) { + while (extraAnnounces.load() == 0) delay(20) + } + task.awaitSeeding(true) + + // A tracker added later is a tier after it, and one it has already is not added again. + val before = extraAnnounces.load() + val left = controller.editTrackers(task.taskId, + TorrentTrackerEdit(add = listOf(GatedSeeder.ANNOUNCE, EXTRA_TRACKER))) + assertEquals(listOf("http://extra.example:80", "http://fixture:80"), left.map { it.endpoint }) + assertEquals(listOf(0, 1), left.map { it.tier }) + awaitStage("the seeder to announce again", task) { + while (extraAnnounces.load() == before) delay(20) + } + task.awaitSeeding(true) + val saved = source.decodeState(assertNotNull(store.load(task.taskId)?.sourceState)) + assertEquals(listOf(listOf(EXTRA_TRACKER), listOf(GatedSeeder.ANNOUNCE)), saved.trackerTiers) + + // A URL Ketch cannot announce to changes nothing. + val refused = assertFailsWith { + controller.editTrackers(task.taskId, TorrentTrackerEdit(add = listOf("wss://w.example/a"))) + } + assertEquals(TorrentCommandError.INVALID_INPUT, refused.error) + assertEquals(left.map { it.endpoint }, + controller.trackers(task.taskId)?.map { it.endpoint }) + + source.stopSeeding(task.taskId) + source.assertNoLeaks() + } + @Test fun restore_disabled_neverStartsSessions() = harness { val store = MemoryTaskStore() @@ -892,4 +944,9 @@ class TorrentSeedingControlTest { assertNull(store.intent(task.taskId)) source.assertNoLeaks() } + + private companion object { + /** A tracker no torrent of these tests names. */ + const val EXTRA_TRACKER = "http://extra.example/announce" + } } diff --git a/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/control/KetchTorrentControllerTest.kt b/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/control/KetchTorrentControllerTest.kt index ca94ae4cf..24600e08b 100644 --- a/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/control/KetchTorrentControllerTest.kt +++ b/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/control/KetchTorrentControllerTest.kt @@ -26,6 +26,7 @@ import com.linroid.ketch.torrent.api.TorrentCommandException import com.linroid.ketch.torrent.api.TorrentController import com.linroid.ketch.torrent.api.TorrentExport import com.linroid.ketch.torrent.api.TorrentTracker +import com.linroid.ketch.torrent.api.TorrentTrackerEdit import com.linroid.ketch.torrent.api.TorrentTrackerState import com.linroid.ketch.torrent.api.TorrentFileOrder import com.linroid.ketch.torrent.api.TorrentInterest @@ -106,6 +107,24 @@ class KetchTorrentControllerTest { override fun withPriorityFiles(state: SourceState, fileIds: Set) = state.copy(data = state.data.substringBefore(" first=") + " first=" + fileIds.sorted()) + /** The tiers [editTrackers] answers, or `null` for a torrent that is not known. */ + var tiers: List>? = null + + override suspend fun editTrackers( + taskId: String, + url: String, + sourceState: SourceState?, + resolved: ResolvedSource?, + add: List, + remove: List, + ): List>? { + require(add.none { it.startsWith("wss:") }) + return tiers?.let { it + add.map(::listOf) }.also { tiers = it } + } + + override fun withTrackers(state: SourceState, tiers: List>) = + state.copy(data = state.data.substringBefore(" tiers=") + " tiers=" + tiers.size) + override fun withSequential(state: SourceState, sequential: Boolean) = state.copy(data = state.data.substringBefore(" ordered=") + " ordered=" + sequential) @@ -1246,6 +1265,50 @@ class KetchTorrentControllerTest { } } + @Test + fun `editing trackers is saved with the task and refused when it cannot be done`() = runTest { + val source = ControlledSource() + val ketch = ketch(source) + try { + val task = completedTask(ketch, source) + assertNotNull(source.saveState)(task.taskId, SourceState(source.type, "seeded")) + val edit = TorrentTrackerEdit(add = listOf("udp://t.example:6969")) + + val unsupported = assertFailsWith { + ketch.torrents.editTrackers(task.taskId, edit) + } + assertEquals(TorrentCommandError.UNSUPPORTED, unsupported.error) + source.capabilities += TorrentCapability.TRACKER_EDIT.wireName + source.capabilities += TorrentCapability.TRACKERS.wireName + + // A torrent whose trackers are not known has none to edit. + val unknown = assertFailsWith { + ketch.torrents.editTrackers(task.taskId, edit) + } + assertEquals(TorrentCommandError.METADATA_UNAVAILABLE, unknown.error) + + source.tiers = emptyList() + source.trackers = listOf(TorrentTracker("udp://t.example:6969")) + assertEquals(source.trackers, ketch.torrents.editTrackers(task.taskId, edit)) + assertEquals("seeded tiers=1", task.saved.sourceState?.data) + + // The refusal never repeats the URL, which may hold a passkey. + val refused = assertFailsWith { + ketch.torrents.editTrackers(task.taskId, + TorrentTrackerEdit(add = listOf("wss://t.example/announce?passkey=secret"))) + } + assertEquals(TorrentCommandError.INVALID_INPUT, refused.error) + assertFalse("secret" in refused.message.orEmpty()) + assertEquals("seeded tiers=1", task.saved.sourceState?.data) + val missing = assertFailsWith { + ketch.torrents.editTrackers("missing", edit) + } + assertEquals(TorrentCommandError.NOT_FOUND, missing.error) + } finally { + ketch.close() + } + } + @Test fun `export is unsupported for a source without the capability`() = runTest { val source = ControlledSource() diff --git a/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/control/TorrentTrackerViewsTest.kt b/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/control/TorrentTrackerViewsTest.kt index 05505f1f0..1cf84bcf6 100644 --- a/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/control/TorrentTrackerViewsTest.kt +++ b/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/control/TorrentTrackerViewsTest.kt @@ -4,10 +4,12 @@ import com.linroid.ketch.torrent.MultiFileTorrent import com.linroid.ketch.torrent.api.TorrentTracker import com.linroid.ketch.torrent.api.TorrentTrackerState import com.linroid.ketch.torrent.metainfo.Bencode +import com.linroid.ketch.torrent.metainfo.MAX_TRACKERS import com.linroid.ketch.torrent.tracker.TrackerScrape import com.linroid.ketch.torrent.tracker.TrackerStatus import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertNull /** What a torrent's trackers list as, live and while it is not running. */ @@ -77,4 +79,44 @@ class TorrentTrackerViewsTest { assertEquals(emptyList(), idleTrackers("magnet:?xt=urn:btih:" + "a".repeat(40), null, maxBytes)) assertNull(idleTrackers("https://example.com/pack.torrent", null, maxBytes)) } + + @Test + fun `an edit removes trackers by endpoint and adds new ones as tiers of their own`() { + val tiers = listOf( + listOf("http://a.example/announce?passkey=secret", "udp://b.example:1337"), + listOf("https://c.example/announce"), + ) + + val edited = editedTrackerTiers(tiers, + add = listOf(" udp://d.example:6969 ", "https://c.example/announce", "", + "udp://d.example:6969"), + remove = listOf("http://a.example:80", "udp://missing.example:1")) + + assertEquals( + listOf( + listOf("udp://b.example:1337"), + listOf("https://c.example/announce"), + listOf("udp://d.example:6969"), + ), + edited, + ) + // Removing a whole tier removes the tier. + assertEquals(listOf(listOf("udp://b.example:1337")), + editedTrackerTiers(edited, emptyList(), + listOf("https://c.example:443", "udp://d.example:6969"))) + assertEquals(emptyList(), editedTrackerTiers(emptyList(), emptyList(), emptyList())) + } + + @Test + fun `an edit refuses trackers Ketch cannot announce to and more than a torrent may have`() { + assertFailsWith { + editedTrackerTiers(emptyList(), listOf("wss://web.example/announce"), emptyList()) + } + assertFailsWith { + editedTrackerTiers(emptyList(), listOf("not a url"), emptyList()) + } + val many = (1..MAX_TRACKERS + 1).map { "udp://t$it.example:6969" } + assertFailsWith { editedTrackerTiers(emptyList(), many, emptyList()) } + assertEquals(MAX_TRACKERS, editedTrackerTiers(emptyList(), many.dropLast(1), emptyList()).size) + } } From 57031ed17da93f1f7124c2d96ba51fa99eb09c24 Mon Sep 17 00:00:00 2001 From: Lin Zhang Date: Sat, 14 Nov 2026 22:50:07 +0900 Subject: [PATCH 2/2] fix(torrent): restart a checking seeder for a tracker edit and refuse edits before metadata --- AGENTS.md | 5 +++-- docs/torrent.md | 3 ++- .../linroid/ketch/torrent/api/TorrentController.kt | 3 ++- .../linroid/ketch/torrent/TorrentDownloadSource.kt | 13 ++++++++++++- .../ketch/torrent/control/KetchTorrentController.kt | 3 ++- .../ketch/torrent/TorrentDownloadSourceTest.kt | 10 ++++++++++ 6 files changed, 31 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 717349a03..fdf91506f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1372,8 +1372,9 @@ docker/ # Docker image of `ketch server` (Dockerfile, entrypoint, compose `trackerTiers`), written into the saved state (`SourceHost.changeSourceState`, `withTrackers`) and into the states a run or a seeder saves from (`changeHeldState`). A session announces to what it opened with, so a downloading task is paused and resumed and a - seeding one stopped and seeded again. A task that never ran keeps the edit for the process - only. Exports still describe the torrent as it was added. The Trackers tab shows a remove + seeding one, also one still checking its files, stopped and seeded again. A magnet without + metadata yet refuses the edit (`METADATA_UNAVAILABLE`), as its lookup announces to what its + link names. A task that never ran keeps the edit for the process only. Exports still describe the torrent as it was added. The Trackers tab shows a remove button per tracker and an Add trackers field (`TrackerEditing`, `trackerUrls`) - Export: `TorrentController.export(taskId, metainfo)` (REST `GET /api/torrents/{id}/export`, `?metainfo=true`; capability `export`) answers a `TorrentExport`: the v1 and v2 info hashes, diff --git a/docs/torrent.md b/docs/torrent.md index 37a0ffb98..dbc359e94 100644 --- a/docs/torrent.md +++ b/docs/torrent.md @@ -542,7 +542,8 @@ by spaces or new lines, each added after the torrent's own as a tier of its own, when those before it fail. A torrent that is downloading or seeding starts again to use the new list; the change stays with the task, also after a restart, while a `.torrent` file or magnet link exported from it still names the trackers it was added with. A torrent may have at most 128 -trackers. REST: `PUT /api/torrents/{id}/trackers` with +trackers, and a magnet link's trackers can be edited only once its metadata is found. REST: +`PUT /api/torrents/{id}/trackers` with `{"add": ["udp://tracker.example:6969/announce"], "remove": ["udp://old.example:1337"]}`, which answers the new list; SDK: `TorrentController.editTrackers(taskId, TorrentTrackerEdit(...))`. diff --git a/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentController.kt b/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentController.kt index 8240e193c..75ebde2b9 100644 --- a/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentController.kt +++ b/library/torrent-api/src/commonMain/kotlin/com/linroid/ketch/torrent/api/TorrentController.kt @@ -163,7 +163,8 @@ interface TorrentController { * to them. Fails with [TorrentCommandError.NOT_FOUND] for unknown and non-torrent tasks, with * [TorrentCommandError.INVALID_INPUT] for a URL the backend cannot announce to or more * trackers than a torrent may have, and with [TorrentCommandError.METADATA_UNAVAILABLE] while - * the torrent's trackers are not known yet. Advertised as [TorrentCapability.TRACKER_EDIT]. + * the torrent is not known yet, as for a magnet link still looking for its metadata, which + * announces to the trackers its link names. Advertised as [TorrentCapability.TRACKER_EDIT]. */ suspend fun editTrackers(taskId: String, edit: TorrentTrackerEdit): List = throw TorrentCommandException( diff --git a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentDownloadSource.kt b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentDownloadSource.kt index de3115bdb..85b0382fe 100644 --- a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentDownloadSource.kt +++ b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/TorrentDownloadSource.kt @@ -494,6 +494,11 @@ class TorrentDownloadSource( remove: List, ): List>? = trackerEdits.withLock { val state = sourceState?.let { runCatching { decodeState(it) }.getOrNull() } + // A magnet still looking for its metadata announces to what its link names: an edit would + // change nothing there, so there is none until the torrent is known. + if (editedTrackers(taskId, state) == null && metainfoBytes(state, resolved) == null) { + return@withLock null + } val current = trackerTiers(taskId, url, state, resolved) ?: return@withLock null val edited = editedTrackerTiers(current, add, remove) trackerChoices.update { it + (taskId to edited) } @@ -1351,7 +1356,13 @@ class TorrentDownloadSource( val state = if (seeded == task.selectedFileIds) plan.state else { plan.state.copy(selectedFileIds = seeded, totalBytes = session.totalBytes) } - seedStates.update { it + (taskId to state) } + // With what the task was told while it checked, which found no state here to change. + val held = state.copy( + sequential = sequentialChoices.value[taskId] ?: state.sequential, + priorityFileIds = priorityChoices.value[taskId] ?: state.priorityFileIds, + trackerTiers = trackerChoices.value[taskId] ?: state.trackerTiers, + ) + seedStates.update { it + (taskId to held) } markSeeding(taskId) checkingSeeders.update { it - taskId } watchSeeder(taskId, session) diff --git a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/KetchTorrentController.kt b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/KetchTorrentController.kt index 707406564..0fe1e299e 100644 --- a/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/KetchTorrentController.kt +++ b/library/torrent/src/commonMain/kotlin/com/linroid/ketch/torrent/control/KetchTorrentController.kt @@ -316,7 +316,8 @@ internal class KetchTorrentController( task.pause() task.resume() } - } else if (state is DownloadState.Completed && taskId in source.seedingTaskIds.value) { + } else if (state is DownloadState.Completed && source.liveTorrent(taskId) != null) { + // Seeding, or still checking its files before it seeds. source.stopSeeding(taskId) seed(task) } diff --git a/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/TorrentDownloadSourceTest.kt b/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/TorrentDownloadSourceTest.kt index e3c97cbf7..062d09889 100644 --- a/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/TorrentDownloadSourceTest.kt +++ b/library/torrent/src/commonTest/kotlin/com/linroid/ketch/torrent/TorrentDownloadSourceTest.kt @@ -232,6 +232,16 @@ class TorrentDownloadSourceTest { assertEquals(other, source.withSequential(other, true)) } + @Test + fun editTrackers_magnetWithoutMetadata_hasNoneToEdit() = runTest { + // Its lookup announces to what the link names, which an edit would not change. + val magnet = "magnet:?xt=urn:btih:" + "a".repeat(40) + "&tr=http%3A%2F%2Fa.example%2Fannounce" + assertNull(source.editTrackers("waiting", magnet, null, null, + add = listOf("udp://b.example:1337"), remove = emptyList())) + assertEquals(listOf("http://a.example:80"), + source.torrentTrackers("waiting", magnet, null, null)?.map { it.endpoint }) + } + @Test fun features_listSelectionFeatures() { assertEquals(setOf(KetchFeatures.FILE_SELECTION,