diff --git a/AGENTS.md b/AGENTS.md
index 0fa0dd351..fdf91506f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1362,6 +1362,20 @@ 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, 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,
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..dbc359e94 100644
--- a/docs/torrent.md
+++ b/docs/torrent.md
@@ -536,6 +536,17 @@ 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, 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(...))`.
+
### How download settings apply to torrents
Torrent tasks follow the same download settings as HTTP and FTP tasks, with these differences:
@@ -775,7 +786,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..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
@@ -157,6 +157,21 @@ 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 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(
+ 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..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
@@ -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,64 @@ 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