Speed up downloads by combining multiple network connections in parallel
TypeScript bandwidth-aggregationcross-platformdesktop-appdownloaderdownloadmanagerlinuxmacosmulticonnectionparallel-downloadswindows
feat(torrent): allow viewing and manually adding trackers to torrents… (#224)
Dhruvil Patelffabdd154794
diff --git a/e2e/downloadActions.spec.ts b/e2e/downloadActions.spec.tsindex 3679cf5..3aaf5e5 100644--- a/e2e/downloadActions.spec.ts+++ b/e2e/downloadActions.spec.ts@@ -103,7 +103,7 @@ test.describe('what each state offers', () => {test('a torrent from a .torrent file has no link to copy', () => {const torrent = download({ status: 'paused', kind: 'torrent', url: '/tmp/a.torrent' })- expect(ids([torrent])).toEqual(['resume', 'reveal', 'cancel'])+ expect(ids([torrent])).toEqual(['resume', 'reveal', 'trackers', 'cancel'])})})diff --git a/e2e/torrent.spec.ts b/e2e/torrent.spec.tsindex 9da468d..dc738af 100644--- a/e2e/torrent.spec.ts+++ b/e2e/torrent.spec.ts@@ -257,3 +257,73 @@ test.describe('uploading', () => {expect(done.uploadSpeedBytesPerSec ?? 0).toBe(0)})})++test.describe('managing trackers', () => {+ test('a torrent with an unreachable tracker finds the seeder after addTorrentTrackers', async ({+ plexo+ }) => {+ const data = seededBytes(1 * MB, 61)+ const torrent = await swarm.seed([named(data, 'isolated.bin')], { pieceLength: PIECE })+ const { default: parseTorrent, toTorrentFile } = await import('parse-torrent' as string)+ const parsed = await parseTorrent(torrent.torrentFile)+ const realAnnounce = [...(parsed.announce as string[])]+ parsed.announce = ['http://127.0.0.1:9/announce']+ const rewritten = toTorrentFile(parsed)+ const torrentPath = await torrentFileOnDisk({ ...torrent, torrentFile: rewritten })++ const id = await plexo.start(torrentPath, sha256(data))+ await new Promise((resolve) => setTimeout(resolve, 500))+ const initial = await plexo.current()+ expect(initial?.bytesDownloaded ?? 0).toBe(0)++ await plexo.api.addTorrentTrackers(id, realAnnounce)+ const done = await plexo.waitForTorrentStatus('completed', 30_000)+ expect(done.bytesDownloaded).toBe(1 * MB)+ })++ test('trackers added while paused survive relaunch', async ({ plexo }) => {+ const data = seededBytes(1 * MB, 62)+ const torrent = await swarm.seed([named(data, 'paused-trackers.bin')], { pieceLength: PIECE })+ const { default: parseTorrent, toTorrentFile } = await import('parse-torrent' as string)+ const parsed = await parseTorrent(torrent.torrentFile)+ const realAnnounce = [...(parsed.announce as string[])]+ parsed.announce = ['http://127.0.0.1:9/announce']+ const rewritten = toTorrentFile(parsed)+ const torrentPath = await torrentFileOnDisk({ ...torrent, torrentFile: rewritten })++ const id = await plexo.start(torrentPath, sha256(data))+ await plexo.api.pauseDownload(id)+ await plexo.waitForTorrentStatus('paused')++ await plexo.api.addTorrentTrackers(id, realAnnounce)+ const beforeRelaunch = await plexo.api.torrentTrackers(id)+ expect(beforeRelaunch.customTrackers).toEqual(realAnnounce)++ await plexo.relaunch()+ const afterRelaunch = await plexo.api.torrentTrackers(id)+ expect(afterRelaunch.customTrackers).toEqual(realAnnounce)++ await plexo.api.resumeDownload(id)+ const done = await plexo.waitForTorrentStatus('completed', 30_000)+ expect(done.bytesDownloaded).toBe(1 * MB)+ })++ test('a private torrent refuses added trackers', async ({ plexo }) => {+ const data = seededBytes(1 * MB, 63)+ const torrent = await swarm.seed([named(data, 'private.bin')], { pieceLength: PIECE })+ const { default: parseTorrent, toTorrentFile } = await import('parse-torrent' as string)+ const parsed = await parseTorrent(torrent.torrentFile)+ parsed.info = { ...parsed.info, private: 1 }+ ;(parsed as { private?: number | boolean }).private = 1+ const rewritten = toTorrentFile(parsed)+ const torrentPath = await torrentFileOnDisk({ ...torrent, torrentFile: rewritten })++ const id = await plexo.start(torrentPath, sha256(data))+ const trackers = await plexo.api.torrentTrackers(id)+ expect(trackers.isPrivate).toBe(true)++ await expect(+ plexo.api.addTorrentTrackers(id, ['http://127.0.0.1:1234/announce'])+ ).rejects.toThrow(/private/i)+ })+})diff --git a/e2e/torrentTrackers.spec.ts b/e2e/torrentTrackers.spec.tsnew file mode 100644index 0000000..d173449--- /dev/null+++ b/e2e/torrentTrackers.spec.ts@@ -0,0 +1,102 @@+import { expect, test } from '@playwright/test'+import { mergeTrackers, normalizeTrackerUrl, parseTrackerList } from '../src/shared/torrentTrackers'++test.describe('torrent tracker helpers', () => {+ test('normalizeTrackerUrl accepts valid tracker URLs and cleans them', () => {+ expect(normalizeTrackerUrl('udp://tracker.opentrackr.org:1337/announce')).toBe(+ 'udp://tracker.opentrackr.org:1337/announce'+ )+ expect(normalizeTrackerUrl(' http://tracker.example.com/announce/ ')).toBe(+ 'http://tracker.example.com/announce'+ )+ expect(normalizeTrackerUrl('https://tracker.tamersunion.org:443/announce/')).toBe(+ 'https://tracker.tamersunion.org/announce'+ )+ expect(normalizeTrackerUrl('http://tracker.example.com:8080/announce/')).toBe(+ 'http://tracker.example.com:8080/announce'+ )+ })++ test('normalizeTrackerUrl rejects invalid schemes and malformed URLs', () => {+ expect(normalizeTrackerUrl('')).toBeNull()+ expect(normalizeTrackerUrl(' ')).toBeNull()+ expect(normalizeTrackerUrl('ftp://tracker.example.com/announce')).toBeNull()+ expect(normalizeTrackerUrl('file:///path/to/file')).toBeNull()+ expect(normalizeTrackerUrl('wss://tracker.btorrent.xyz')).toBeNull()+ expect(normalizeTrackerUrl('ws://tracker.openwebtorrent.com/')).toBeNull()+ expect(normalizeTrackerUrl('not-a-url')).toBeNull()+ expect(normalizeTrackerUrl('udp://')).toBeNull()+ expect(normalizeTrackerUrl('javascript:alert(1)')).toBeNull()+ expect(normalizeTrackerUrl(null)).toBeNull()+ expect(normalizeTrackerUrl(42)).toBeNull()+ expect(normalizeTrackerUrl('http://tracker.example.com/' + 'a'.repeat(2050))).toBeNull()+ })++ test('parseTrackerList parses multi-line or comma-separated trackers, counts invalid lines, and deduplicates', () => {+ const input = `+ udp://tracker.opentrackr.org:1337/announce+ http://tracker.example.com/announce/++ invalid-url+ udp://tracker.opentrackr.org:1337/announce+ https://tracker.tamersunion.org/announce, ws://tracker.openwebtorrent.com/+ `+ const { valid, invalidCount } = parseTrackerList(input)+ expect(valid).toEqual([+ 'udp://tracker.opentrackr.org:1337/announce',+ 'http://tracker.example.com/announce',+ 'https://tracker.tamersunion.org/announce'+ ])+ // invalid-url and ws://tracker.openwebtorrent.com/ are invalid+ expect(invalidCount).toBe(2)+ })++ test('parseTrackerList supports Windows (CRLF), Linux (LF), and macOS (CR) line breaks', () => {+ const windowsCrlf =+ 'udp://tracker.opentrackr.org:1337/announce\r\n\r\nhttp://tracker.example.com/announce\r\n'+ const linuxLf =+ 'udp://tracker.opentrackr.org:1337/announce\n\nhttp://tracker.example.com/announce\n'+ const macCr =+ 'udp://tracker.opentrackr.org:1337/announce\r\rhttp://tracker.example.com/announce\r'++ const expected = [+ 'udp://tracker.opentrackr.org:1337/announce',+ 'http://tracker.example.com/announce'+ ]+ expect(parseTrackerList(windowsCrlf)).toEqual({ valid: expected, invalidCount: 0 })+ expect(parseTrackerList(linuxLf)).toEqual({ valid: expected, invalidCount: 0 })+ expect(parseTrackerList(macCr)).toEqual({ valid: expected, invalidCount: 0 })+ })++ test('mergeTrackers appends only unique new trackers', () => {+ const existing = [+ 'udp://tracker.opentrackr.org:1337/announce',+ 'http://tracker.example.com/announce'+ ]+ const additional = [+ 'http://tracker.example.com/announce/',+ 'https://tracker.tamersunion.org/announce',+ 'udp://newtracker.org:6969/announce'+ ]+ const merged = mergeTrackers(existing, additional)+ expect(merged).toEqual([+ 'udp://tracker.opentrackr.org:1337/announce',+ 'http://tracker.example.com/announce',+ 'https://tracker.tamersunion.org/announce',+ 'udp://newtracker.org:6969/announce'+ ])+ })++ test('mergeTrackers handles case-insensitive duplicates and empty inputs', () => {+ expect(mergeTrackers([], [])).toEqual([])+ expect(mergeTrackers(['http://tracker.com/announce'], [])).toEqual([+ 'http://tracker.com/announce'+ ])+ expect(+ mergeTrackers(+ ['udp://tracker.org:1337/announce'],+ ['UDP://TRACKER.ORG:1337/ANNOUNCE', 'udp://tracker2.org:1337/announce']+ )+ ).toEqual(['udp://tracker.org:1337/announce', 'udp://tracker2.org:1337/announce'])+ })+})diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.tsindex 0f4eebd..d5ffbec 100644--- a/src/main/download/downloadManager.ts+++ b/src/main/download/downloadManager.ts@@ -40,8 +40,10 @@ import {type TorrentDownloadState,type TorrentFileEntry,type TorrentInfo,- type TorrentPieceState+ type TorrentPieceState,+ type TorrentTrackersResult} from '../../shared/types'+import { mergeTrackers, normalizeTrackerUrl } from '../../shared/torrentTrackers'import { Limits } from '../network/limits'import { loadSettings } from '../settings'import type { TelegramServiceApi } from '../telegram/service'@@ -165,6 +167,7 @@ interface PersistedDownloadBase {requestPayload: StartDownloadRequest/** Kept apart from requestPayload, sealed (see sealBrowser). */browser?: string+ customTrackers?: string[]}type PersistedState =@@ -700,7 +703,8 @@ export class DownloadManager {requestPayload: StartTorrentDownloadRequest,file: TorrentDestination,pieces: TorrentDownloadState['pieces'],- torrentFile: Uint8Array+ torrentFile: Uint8Array,+ customTrackers: string[] = []): TorrentDownloadRuntime {const target: TorrentTransferTarget = {state,@@ -709,7 +713,8 @@ export class DownloadManager {file,pieces,meters: new Meters(),- uploadMeters: new Meters()+ uploadMeters: new Meters(),+ customTrackers}const host: TransferHost = {networks: this.networks,@@ -978,7 +983,8 @@ export class DownloadManager {torrent.files.map((file) => file.path)),pieces,- torrentFile+ torrentFile,+ persisted.customTrackers)} else if (persisted.state.kind === 'nzb' && requestPayload.kind === 'nzb') {const nzbFile = await readFile(this.nzbFilePath(id)).catch((error: unknown) => {@@ -1155,6 +1161,7 @@ export class DownloadManager {const id = randomUUID()let runtime: DownloadRuntimeif (requestPayload.kind === 'torrent') {+ delete (requestPayload as { trackers?: unknown }).trackersconst torrentFile = probedTorrentFile(requestPayload.infoHash)if (!torrentFile) throw new Error('Add the torrent again to start downloading.')const torrentProbe = await describeTorrent(torrentFile, requestPayload.url)@@ -1833,6 +1840,74 @@ export class DownloadManager {this.pushUpdate(runtime)}+ /** A torrent download's trackers: default trackers from the .torrent, and any custom trackers added. */+ async torrentTrackers(id: string): Promise<TorrentTrackersResult> {+ const runtime = this.runtimes.get(id)+ if (runtime?.kind !== 'torrent') throw new Error('Not a torrent download')+ const torrent = await this.torrentInfo(id)+ if (!torrent) throw new Error('Not a torrent download')+ const defaultTrackers = torrent.trackers ?? []+ const customTrackers = runtime.customTrackers ?? []+ return {+ defaultTrackers,+ customTrackers,+ isPrivate: Boolean(torrent.isPrivate)+ }+ }++ /** Adds custom trackers to a torrent download. */+ async addTorrentTrackers(id: string, rawTrackers: unknown): Promise<TorrentTrackersResult> {+ if (!Array.isArray(rawTrackers) || rawTrackers.some((t) => typeof t !== 'string')) {+ throw new Error("That doesn't look like a tracker link")+ }+ if (rawTrackers.length === 0) {+ throw new Error("That doesn't look like a tracker link")+ }+ if (rawTrackers.length > 100) {+ throw new Error('Too many trackers (maximum 100)')+ }+ for (const tracker of rawTrackers) {+ if (tracker.length > 2048) {+ throw new Error("That doesn't look like a tracker link")+ }+ }++ const runtime = this.runtimes.get(id)+ if (runtime?.kind !== 'torrent') throw new Error('Not a torrent download')+ const torrent = await this.torrentInfo(id)+ if (!torrent) throw new Error('Not a torrent download')+ if (torrent.isPrivate) throw new Error('Cannot add trackers to a private torrent')++ const settled =+ runtime.publishing ||+ runtime.state.status === 'completed' ||+ runtime.state.status === 'cancelled' ||+ this.runtimes.get(id) !== runtime+ if (settled) throw new Error('This download’s trackers can’t change now')++ const defaultTrackers = torrent.trackers ?? []+ const existingCustom = runtime.customTrackers ?? []+ const merged = mergeTrackers([...defaultTrackers, ...existingCustom], rawTrackers)+ const newCustom = merged.filter((url) => !defaultTrackers.includes(url))+ if (newCustom.length > 100) {+ throw new Error('Too many trackers (maximum 100)')+ }++ const validTrackers = rawTrackers.map(normalizeTrackerUrl).filter(Boolean)+ if (validTrackers.length === 0) {+ throw new Error("That doesn't look like a tracker link")+ }++ runtime.customTrackers = newCustom+ runtime.transfer.trackersChanged()+ await this.persistNow(runtime)+ return {+ defaultTrackers,+ customTrackers: newCustom,+ isPrivate: false+ }+ }+async cancel(id: string): Promise<void> {const runtime = this.runtimes.get(id)if (runtime?.cancelPromise) return runtime.cancelPromise@@ -2433,7 +2508,8 @@ export class DownloadManager {partialPath: runtime.file.path,publicationPath: runtime.publicationPath,publicationIdentity: runtime.publicationIdentity,- ...savedRequest(runtime)+ ...savedRequest(runtime),+ customTrackers: runtime.kind === 'torrent' ? runtime.customTrackers : undefined}if (['downloading', 'paused', 'queued'].includes(runtime.state.status)) {await runtime.file.sync()diff --git a/src/main/download/torrent/engine.ts b/src/main/download/torrent/engine.tsindex 9c174c5..2900f7c 100644--- a/src/main/download/torrent/engine.ts+++ b/src/main/download/torrent/engine.ts@@ -27,6 +27,24 @@ export function loadClientNamer(): Promise<(peerId: string) => string | null> {return peerIdParser}+let bencodeDecoder: Promise<(data: Uint8Array) => unknown> | null = null++/** Checks whether a .torrent file is marked private (BEP 27). */+export async function isTorrentPrivate(torrentFile: Uint8Array): Promise<boolean> {+ bencodeDecoder ??= import('bencode').then(+ ({ default: bencode }) =>+ (data) =>+ bencode.decode(data)+ )+ const decode = await bencodeDecoder+ try {+ const decoded = decode(torrentFile) as { info?: { private?: number | Uint8Array } }+ return Number(decoded?.info?.private) === 1+ } catch {+ return false+ }+}+/*** webtorrent's own file store, writing the torrent's top entry (its folder, or its one file) under* `name` rather than the torrent's: a download claims a free name, "Name (1)" when the torrent'sdiff --git a/src/main/download/torrent/metadata.ts b/src/main/download/torrent/metadata.tsindex fdf7f4d..48d56b2 100644--- a/src/main/download/torrent/metadata.ts+++ b/src/main/download/torrent/metadata.ts@@ -51,7 +51,13 @@ export async function describeTorrent(torrentFile: Uint8Array, link: string): PrcontentType: 'application/x-bittorrent',etag: null,lastModified: null,- torrent: { infoHash: parsed.infoHash, pieceLength: parsed.pieceLength ?? 0, files }+ torrent: {+ infoHash: parsed.infoHash,+ pieceLength: parsed.pieceLength ?? 0,+ files,+ trackers: Array.isArray(parsed.announce) ? parsed.announce : [],+ isPrivate: Boolean(parsed.private)+ }}}diff --git a/src/main/download/torrent/modules.d.ts b/src/main/download/torrent/modules.d.tsindex 9a7c789..a6746b7 100644--- a/src/main/download/torrent/modules.d.ts+++ b/src/main/download/torrent/modules.d.ts@@ -131,6 +131,9 @@ declare module 'parse-torrent' {announce?: string[]peerAddresses?: string[]xs?: string | string[]+ private?: boolean+ info?: { [key: string]: unknown; private?: number | boolean }}+ export function toTorrentFile(parsed: ParsedTorrent | object): Bufferexport default function parseTorrent(torrentId: string | Uint8Array): Promise<ParsedTorrent>}diff --git a/src/main/download/torrent/torrentTransfer.ts b/src/main/download/torrent/torrentTransfer.tsindex 7de22d4..5da802e 100644--- a/src/main/download/torrent/torrentTransfer.ts+++ b/src/main/download/torrent/torrentTransfer.ts@@ -2,6 +2,7 @@ import { isIP, Socket } from 'node:net'import { basename, dirname } from 'node:path'import type WebTorrent from 'webtorrent'import type { Store, Torrent, Wire } from 'webtorrent'+import { normalizeTrackerUrl } from '../../../shared/torrentTrackers'import type { TorrentDownloadNetwork, TorrentPeerState } from '../../../shared/types'import { connectRoute } from '../../network/deviceBinding'import { routesFor, type NetworkRoute } from '../../network/routes'@@ -11,7 +12,7 @@ import {type TransferHost,type TorrentTransferTarget} from '../transfer'-import { createClient, loadClientNamer, storeNamed } from './engine'+import { createClient, isTorrentPrivate, loadClientNamer, storeNamed } from './engine'import { bitfieldOf, creditPiece, pickNetwork } from './peers'/** Peers each network in use may have at once (webtorrent's maxConns is this times the networks). */@@ -83,6 +84,7 @@ export class TorrentTransfer implements Transfer {private twinIds = new Map<string, string>()/** By twin key: when it may be dialled again. */private twinRetryAt = new Map<string, number>()+ private isPrivate: boolean | null = nullconstructor(private readonly runtime: TorrentTransferTarget,@@ -166,6 +168,7 @@ export class TorrentTransfer implements Transfer {const stop = this.runtime.stop.signaltry {this.nameClient ??= await loadClientNamer()+ this.isPrivate ??= await isTorrentPrivate(this.torrentFile)this.store ??= await storeNamed(basename(this.destination), (path) =>this.runtime.file.written.add(path))@@ -212,6 +215,22 @@ export class TorrentTransfer implements Transfer {if (this.torrent) this.selectFiles(this.torrent)}+ /** The trackers changed (runtime.customTrackers). If running, the client is restarted+ * so WebTorrent announces to the new trackers. */+ trackersChanged(): void {+ if (this.client) {+ const restart = async (): Promise<void> => {+ this.closeClient?.()+ await this.ended+ this.reset()+ if (!this.runtime.stop.signal.aborted) {+ this.reconcile()+ }+ }+ void restart()+ }+ }+/** Asks the engine for the chosen files' pieces only, all of them with no choice made. What it* fetched before stays: a deselected piece just isn't asked for. */private selectFiles(torrent: Torrent): void {@@ -234,13 +253,21 @@ export class TorrentTransfer implements Transfer {}private add(client: WebTorrent): void {+ const custom =+ this.isPrivate === false && this.runtime.customTrackers+ ? this.runtime.customTrackers+ .map((url) => normalizeTrackerUrl(url))+ .filter((url): url is string => Boolean(url))+ : undefined+const torrent = client.add(this.torrentFile, {path: dirname(this.destination),store: this.store!,// Trusted as done, bar a hash check of a piece or two per file (more if one fails).bitfield: bitfieldOf(this.runtime.pieces.map((block) => block.status === 'completed')),// Nothing until webtorrent is ready to be told which files (below), as on a change.- deselect: true+ deselect: true,+ announce: custom && custom.length > 0 ? custom : undefined})this.engineTorrent = torrenttorrent.on('wire', (wire: Wire, address: string, key?: string) =>diff --git a/src/main/download/transfer.ts b/src/main/download/transfer.tsindex ff1c988..e99a70a 100644--- a/src/main/download/transfer.ts+++ b/src/main/download/transfer.ts@@ -71,6 +71,8 @@ export interface TorrentTransferTarget extends TransferTargetBase {meters: Meters/** What each peer, and each network, has sent. */uploadMeters: Meters+ /** Custom tracker announce URLs added to the torrent. */+ customTrackers?: string[]}export interface TelegramTransferTarget extends TransferTargetBase {diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.tsindex cd1d4ce..d07c714 100644--- a/src/main/ipc/handlers.ts+++ b/src/main/ipc/handlers.ts@@ -255,6 +255,13 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Downhandle('chooseTorrentFiles', async (_event, id, selected) =>manager.chooseTorrentFiles(id, selected))+ handle('torrentTrackers', async (_event, id) => manager.torrentTrackers(id))+ handle('addTorrentTrackers', async (_event, id, trackers) => {+ if (!Array.isArray(trackers) || trackers.some((t) => typeof t !== 'string')) {+ throw new Error("That doesn't look like a tracker link")+ }+ return manager.addTorrentTrackers(id, trackers)+ })handle('pauseDownload', async (_event, id) => {await manager.pause(id)diff --git a/src/preload/index.ts b/src/preload/index.tsindex 137773c..5ad367b 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -51,6 +51,9 @@ const plexoApi = {torrentFiles: (downloadId: string) => invoke('torrentFiles', downloadId),chooseTorrentFiles: (downloadId: string, selected: number[]) =>invoke('chooseTorrentFiles', downloadId, selected),+ torrentTrackers: (downloadId: string) => invoke('torrentTrackers', downloadId),+ addTorrentTrackers: (downloadId: string, trackers: string[]) =>+ invoke('addTorrentTrackers', downloadId, trackers),pauseDownload: (downloadId: string) => invoke('pauseDownload', downloadId),resumeDownload: (downloadId: string) => invoke('resumeDownload', downloadId),relinkDownload: (downloadId: string, url: string) => invoke('relinkDownload', downloadId, url),diff --git a/src/renderer/src/components/DownloadActionsProvider.tsx b/src/renderer/src/components/DownloadActionsProvider.tsxindex 1ceae0c..3cd3c45 100644--- a/src/renderer/src/components/DownloadActionsProvider.tsx+++ b/src/renderer/src/components/DownloadActionsProvider.tsx@@ -8,6 +8,7 @@ import { ACTION_META } from './downloadActionMeta'import { ActionsContext, StateContext } from './downloadActionsContext'import { FixLinkDialog } from './FixLinkDialog'import { RemoveDialog, type RemoveMode } from './RemoveDialog'+import { TrackersDialog } from './TrackersDialog'/** What can be done to a download, done: from its row, its menu, the selection toolbar and its* own screen alike. It owns the two questions an action can lead to (fix the link, confirm a@@ -25,6 +26,7 @@ export function DownloadActionsProvider({clearAll: boolean} | null>(null)const [fixing, setFixing] = useState<DownloadState | null>(null)+ const [managingTrackers, setManagingTrackers] = useState<DownloadState | null>(null)const [busy, setBusy] = useState(false)const [failure, setFailure] = useState<{ title: string; message: string } | null>(null)const [dialogError, setDialogError] = useState<string | null>(null)@@ -53,6 +55,9 @@ export function DownloadActionsProvider({case 'fix':setFixing(targets[0] as DownloadState)return true+ case 'trackers':+ setManagingTrackers(targets[0] as DownloadState)+ return truecase 'again': {// Nothing of it can be kept: it goes, and its link waits in New download to start over.// Only once it's really gone, so the new one can't collide with what's left of it.@@ -163,6 +168,7 @@ export function DownloadActionsProvider({onConfirm={() => void confirmRemoval()}/><FixLinkDialog download={fixing} onClose={() => setFixing(null)} />+ <TrackersDialog download={managingTrackers} onClose={() => setManagingTrackers(null)} /><ActionErrorDialog failure={failure} onClose={() => setFailure(null)} /></StateContext.Provider></ActionsContext.Provider>diff --git a/src/renderer/src/components/TrackersDialog.tsx b/src/renderer/src/components/TrackersDialog.tsxnew file mode 100644index 0000000..39115cc--- /dev/null+++ b/src/renderer/src/components/TrackersDialog.tsx@@ -0,0 +1,210 @@+import type { DownloadState, TorrentTrackersResult } from '@shared/types'+import { parseTrackerList } from '@shared/torrentTrackers'+import { useEffect, useState } from 'react'+import { describeError } from '../utils/format'+import { Button } from './ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle+} from './ui/dialog'+import { Textarea } from './ui/textarea'++const SHORTCUT = window.plexo.platform === 'darwin' ? 'Cmd+Enter' : 'Ctrl+Enter'++/**+ * Manages trackers for an active or paused torrent download.+ * Lists the torrent's default trackers and allows adding custom announce URLs.+ */+export function TrackersDialog({+ download,+ onClose+}: {+ download: DownloadState | null+ onClose: () => void+}): React.JSX.Element {+ const [data, setData] = useState<TorrentTrackersResult | null>(null)+ const [input, setInput] = useState('')+ const [submitting, setSubmitting] = useState(false)+ const [error, setError] = useState<string | null>(null)+ const [warning, setWarning] = useState<string | null>(null)++ const isOpen = download !== null && download.kind === 'torrent'+ const downloadId = isOpen ? download.id : null+ const loading = data === null && error === null++ const close = (): void => {+ setData(null)+ setInput('')+ setError(null)+ setWarning(null)+ onClose()+ }++ useEffect(() => {+ if (!downloadId) return++ let active = true+ window.plexo+ .torrentTrackers(downloadId)+ .then((result) => {+ if (active) setData(result)+ })+ .catch((failure) => {+ if (active) setError(describeError(failure))+ })++ return () => {+ active = false+ }+ }, [downloadId])++ const handleAdd = async (): Promise<void> => {+ if (!download || !input.trim()) return+ const { valid, invalidCount } = parseTrackerList(input)+ if (valid.length === 0) {+ setError(+ invalidCount > 0+ ? `${invalidCount} ${invalidCount === 1 ? "line wasn't a tracker link" : "lines weren't tracker links"}`+ : 'Please enter at least one valid tracker URL (e.g. udp://... or http://...)'+ )+ setWarning(null)+ return+ }++ setSubmitting(true)+ setError(null)+ setWarning(null)+ try {+ const updated = await window.plexo.addTorrentTrackers(download.id, valid)+ setData(updated)+ setInput('')+ if (invalidCount > 0) {+ setWarning(+ `${invalidCount} ${invalidCount === 1 ? "line wasn't a tracker link" : "lines weren't tracker links"} and was ignored`+ )+ }+ } catch (failure) {+ setError(describeError(failure))+ } finally {+ setSubmitting(false)+ }+ }++ const allTrackers = [+ ...(data?.defaultTrackers ?? []).map((url) => ({ url, custom: false })),+ ...(data?.customTrackers ?? []).map((url) => ({ url, custom: true }))+ ]++ return (+ <Dialog open={isOpen} onOpenChange={(open) => !open && close()} disablePointerDismissal>+ <DialogContent showCloseButton={false} className="sm:max-w-[480px]">+ <DialogHeader>+ <DialogTitle>Trackers</DialogTitle>+ <DialogDescription>+ {download?.fileName+ ? `Trackers for ${download.fileName}.`+ : 'Manage torrent announce URLs.'}{' '}+ Trackers help discover peers sharing this torrent.+ </DialogDescription>+ </DialogHeader>++ <div className="flex flex-col gap-3 py-1">+ {data?.isPrivate && (+ <div className="rounded-[7px] border border-amber-500/30 bg-amber-500/10 p-2.5 text-[12px] text-amber-600 dark:text-amber-400">+ This is a private torrent. External trackers cannot be added to private swarms.+ </div>+ )}++ <div className="flex flex-col gap-1.5">+ <span className="text-[12px] font-medium text-foreground">+ Active trackers ({loading ? '…' : allTrackers.length})+ </span>+ <div+ tabIndex={0}+ aria-label="Active trackers"+ className="max-h-40 overflow-y-auto rounded-[8px] border border-border bg-card/60 p-2 font-mono text-[11px] select-text"+ >+ {loading ? (+ <div className="text-muted-foreground">Loading trackers…</div>+ ) : allTrackers.length === 0 ? (+ <div className="text-muted-foreground">No announce trackers configured.</div>+ ) : (+ allTrackers.map(({ url, custom }, index) => (+ <div+ key={`${url}-${index}`}+ className="flex items-center justify-between gap-2 py-0.5 border-b border-border/40 last:border-0"+ >+ <span className="min-w-0 truncate text-foreground" title={url}>+ {url}+ </span>+ {custom && (+ <span className="shrink-0 rounded bg-secondary px-1 py-0.5 text-[9.5px] font-sans font-medium text-muted-foreground">+ Custom+ </span>+ )}+ </div>+ ))+ )}+ </div>+ </div>++ {!data?.isPrivate && (+ <form+ className="flex flex-col gap-2"+ onSubmit={(event) => {+ event.preventDefault()+ void handleAdd()+ }}+ >+ <label className="flex flex-col gap-1.5 text-[12px] font-medium text-foreground">+ <span>Add trackers</span>+ <Textarea+ autoFocus={!data?.isPrivate}+ aria-label="New trackers"+ placeholder={`udp://tracker.opentrackr.org:1337/announce\nhttp://tracker.example.com/announce`}+ value={input}+ onChange={(event) => setInput(event.target.value)}+ onKeyDown={(event) => {+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {+ event.preventDefault()+ void handleAdd()+ }+ }}+ className="min-h-20 font-mono text-[11.5px]"+ disabled={submitting || data?.isPrivate}+ />+ </label>+ <span className="text-[11px] text-muted-foreground">+ Paste one or more tracker URLs, separated by line breaks ({SHORTCUT} to add).+ </span>+ </form>+ )}++ {warning && (+ <div className="text-[12px] text-amber-600 dark:text-amber-400">{warning}</div>+ )}+ {error && <div className="text-[12px] text-[var(--color-danger)]">{error}</div>}+ </div>++ <DialogFooter>+ <Button type="button" variant="secondary" onClick={close}>+ Close+ </Button>+ {!data?.isPrivate && (+ <Button+ type="button"+ disabled={submitting || !input.trim() || data?.isPrivate}+ onClick={() => void handleAdd()}+ >+ {submitting ? 'Adding…' : 'Add trackers'}+ </Button>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/src/renderer/src/components/downloadActionMeta.ts b/src/renderer/src/components/downloadActionMeta.tsindex 2ab8a6f..0da5522 100644--- a/src/renderer/src/components/downloadActionMeta.ts+++ b/src/renderer/src/components/downloadActionMeta.ts@@ -6,6 +6,7 @@ import {ListX,Pause,Play,+ Radio,RotateCw,Trash2,Wrench,@@ -118,6 +119,13 @@ export const ACTION_META: Record<ActionId, ActionMeta> = {failure: SOMETHING_WRONG,icon: Trash2,destructive: true+ },+ trackers: {+ label: 'Trackers',+ toolbar: 'Trackers',+ single: true,+ failure: SOMETHING_WRONG,+ icon: Radio}}diff --git a/src/renderer/src/screens/DownloadingScreen.tsx b/src/renderer/src/screens/DownloadingScreen.tsxindex f26f697..9e68428 100644--- a/src/renderer/src/screens/DownloadingScreen.tsx+++ b/src/renderer/src/screens/DownloadingScreen.tsx@@ -19,6 +19,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '../components/ui/tooltiimport { useNetworkVisuals } from '../hooks/useNetworkVisuals'import { useDownloadSchedule } from '../hooks/useDownloadSchedule'import { useAppStore } from '../store/useAppStore'+import { useDownloadActions } from '../components/downloadActionsContext'import { KIND_PALETTE, NETWORK_ROW_GRID_COLUMNS } from '../theme'import {describeError,@@ -122,6 +123,7 @@ export const DownloadingScreen = memo(function DownloadingScreen({const peakSpeedBytesPerSec = download.peakSpeedBytesPerSecconst networkVisual = useNetworkVisuals()const { window: scheduleWindow, message: scheduleMessage } = useDownloadSchedule()+ const { perform } = useDownloadActions()const isQueued = download.status === 'queued'// Waiting in the queue looks like a pause: nothing moves.const isPaused = download.status === 'paused' || isQueued@@ -408,6 +410,20 @@ export const DownloadingScreen = memo(function DownloadingScreen({</Button></>)}+ {download.kind === 'torrent' && (+ <>+ <Dot />+ <Button+ type="button"+ variant="outline"+ size="xs"+ onClick={() => void perform('trackers', [download])}+ className="h-auto cursor-default rounded-[4px] border-[0.5px] bg-card px-[7px] py-[3px] font-mono text-[10.5px] leading-none font-medium text-[var(--text-secondary)] hover:bg-secondary dark:bg-card"+ >+ Trackers+ </Button>+ </>+ )}{!isPaused && download.timeLeftSeconds !== undefined && (<><Dot />diff --git a/src/renderer/src/utils/downloadActions.ts b/src/renderer/src/utils/downloadActions.tsindex e82b273..505d597 100644--- a/src/renderer/src/utils/downloadActions.ts+++ b/src/renderer/src/utils/downloadActions.ts@@ -17,6 +17,7 @@ export type ActionId =| 'cancel'| 'remove'| 'trash'+ | 'trackers'export type DownloadItem = DownloadState | FinishedDownload@@ -58,16 +59,17 @@ const appliesTo: Record<ActionId, (item: DownloadItem) => boolean> = {copy: (item) => /^(https?:|magnet:)/i.test(item.url),cancel: isCancellable,remove: (item) => isDone(item) || isFailed(item),- trash: isTrashable+ trash: isTrashable,+ trackers: (item) => !isFinished(item) && item.kind === 'torrent'}/** These make sense for one download at a time: with several selected, they aren't offered. */-const SINGLE_ONLY: ReadonlySet<ActionId> = new Set(['fix', 'again', 'open', 'reveal'])+const SINGLE_ONLY: ReadonlySet<ActionId> = new Set(['fix', 'again', 'open', 'reveal', 'trackers'])/** The order they're shown in, in groups: what to do with it, its link, getting rid of it.* Menus put a separator between groups. */export const ACTION_GROUPS: readonly (readonly ActionId[])[] = [- ['pause', 'resume', 'retry', 'fix', 'again', 'open', 'reveal'],+ ['pause', 'resume', 'retry', 'fix', 'again', 'open', 'reveal', 'trackers'],['copy'],['cancel', 'remove', 'trash']]diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.tsindex b533b12..d347ed6 100644--- a/src/shared/ipc-channels.ts+++ b/src/shared/ipc-channels.ts@@ -20,6 +20,8 @@ export const IpcChannels = {historyChanged: 'history:changed',torrentFiles: 'download:torrent-files',chooseTorrentFiles: 'download:choose-torrent-files',+ torrentTrackers: 'download:torrent-trackers',+ addTorrentTrackers: 'download:add-torrent-trackers',pauseDownload: 'download:pause',resumeDownload: 'download:resume',relinkDownload: 'download:relink',diff --git a/src/shared/ipc-contract.ts b/src/shared/ipc-contract.tsindex 98c408b..c0fc997 100644--- a/src/shared/ipc-contract.ts+++ b/src/shared/ipc-contract.ts@@ -10,6 +10,7 @@ import type {TelegramCredentials,TelegramMediaPage,TorrentFileEntry,+ TorrentTrackersResult,UpdateState,UsenetServer,UsenetServerInput@@ -54,6 +55,10 @@ export interface IpcContract {/** Which of a torrent download's files to fetch, by index, as it runs or not. Refused for one* already downloaded, or with no room on disk for what's added. */chooseTorrentFiles: { args: [id: string, selected: number[]]; result: void }+ /** The trackers for a torrent download: default trackers from the metadata, and custom ones added. */+ torrentTrackers: { args: [id: string]; result: TorrentTrackersResult }+ /** Adds custom trackers to a torrent download. */+ addTorrentTrackers: { args: [id: string, trackers: string[]]; result: TorrentTrackersResult }pauseDownload: { args: [id: string]; result: void }resumeDownload: { args: [id: string]; result: void }/** A fresh link to the same file, for a download whose link stopped working; it resumes. */diff --git a/src/shared/torrentTrackers.ts b/src/shared/torrentTrackers.tsnew file mode 100644index 0000000..f65d170--- /dev/null+++ b/src/shared/torrentTrackers.ts@@ -0,0 +1,78 @@+const VALID_TRACKER_SCHEMES = new Set(['http:', 'https:', 'udp:'])+const MAX_TRACKER_URL_LENGTH = 2048++/**+ * Normalizes and validates a tracker announce URL.+ * Strips whitespace and trailing slashes, ensuring standard BitTorrent tracker schemes (udp, http, https).+ * Returns null if the URL is invalid, exceeds 2048 characters, or uses an unsupported scheme.+ */+export function normalizeTrackerUrl(rawUrl: unknown): string | null {+ if (typeof rawUrl !== 'string') return null+ const trimmed = rawUrl.trim()+ if (!trimmed || trimmed.length > MAX_TRACKER_URL_LENGTH) return null++ try {+ const parsed = new URL(trimmed)+ if (!VALID_TRACKER_SCHEMES.has(parsed.protocol)) return null+ if (!parsed.hostname) return null++ return parsed.href.replace(/\/+$/, '')+ } catch {+ return null+ }+}++export interface ParsedTrackers {+ valid: string[]+ invalidCount: number+}++/**+ * Parses a block of text containing tracker URLs separated by newlines or commas.+ * Drops invalid or duplicate URLs and reports the count of invalid lines.+ */+export function parseTrackerList(input: string): ParsedTrackers {+ const tokens = input.split(/[\r\n,]+/)+ const valid: string[] = []+ const seen = new Set<string>()+ let invalidCount = 0++ for (const token of tokens) {+ const trimmed = token.trim()+ if (!trimmed) continue+ const normalized = normalizeTrackerUrl(trimmed)+ if (!normalized) {+ invalidCount+++ continue+ }+ if (!seen.has(normalized.toLowerCase())) {+ seen.add(normalized.toLowerCase())+ valid.push(normalized)+ }+ }++ return { valid, invalidCount }+}++/**+ * Merges new tracker URLs into an existing tracker list without duplicates.+ */+export function mergeTrackers(+ existing: readonly string[],+ additional: readonly string[]+): string[] {+ const result = [...existing]+ const seen = new Set(+ existing.map((url) => normalizeTrackerUrl(url)?.toLowerCase() ?? url.toLowerCase())+ )++ for (const item of additional) {+ const normalized = normalizeTrackerUrl(item)+ if (normalized && !seen.has(normalized.toLowerCase())) {+ seen.add(normalized.toLowerCase())+ result.push(normalized)+ }+ }++ return result+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex dc15448..6327cb0 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -65,6 +65,16 @@ export interface TorrentInfo {/** Where each file will be written, relative to the destination folder, already checked to be* safe (see main/download/torrent/paths.ts). */files: { path: string; length: number }[]+ /** Trackers listed in the torrent's metadata. */+ trackers?: string[]+ /** Whether the torrent is marked private (BEP 27). */+ isPrivate?: boolean+}++export interface TorrentTrackersResult {+ defaultTrackers: string[]+ customTrackers: string[]+ isPrivate: boolean}/** What an NZB holds: Usenet articles, grouped into the files they make up once decoded. */