Skip to content

A full-featured download manager.

17.1 KB
Raw Blame
import type { EngineConnectionSnapshot } from '@shared/schemas/engine-connection'
import type { DownloadCookie } from '../engine-adapter'
import type { Aria2LegacyCheckpointImport } from './aria2-legacy-checkpoint'
import { Aria2PauseState } from './aria2-pause-state'
import type { JsonRpcProtocol } from './json-rpc-protocol'
import type {
  Aria2CheckpointStatus,
  Aria2HistoryCount,
  Aria2HistoryFilter,
  Aria2MethodCall,
  Aria2RawFile,
  Aria2RawGlobalStat,
  Aria2RawPeer,
  Aria2RawStatus,
  Aria2RawUri,
  Aria2RequeueResult,
  Aria2SearchQuery,
  Aria2Version,
} from './types'
import type { WebSocketTransport } from './web-socket-transport'

interface Aria2Event {
  gid: string
}

type EventHandler = (event: Aria2Event) => void
type Unsubscribe = () => void

// Methods that do NOT require secret injection
const SECRET_EXEMPT_METHODS = new Set([
  'system.listMethods',
  'system.listNotifications',
])

export class Aria2RpcClient {
  private notificationHandlers = new Map<string, Set<EventHandler>>()
  private pauseState = new Aria2PauseState()
  private requestSequence = 0
  private metadataListeners = new Set<(gid?: string) => void>()

  onTaskMetadataChanged(handler: (gid?: string) => void): Unsubscribe {
    this.metadataListeners.add(handler)
    return () => this.metadataListeners.delete(handler)
  }

  private invalidateTaskMetadata(gid?: string): void {
    for (const listener of this.metadataListeners) listener(gid)
  }

  constructor(
    private transport: WebSocketTransport,
    private protocol: JsonRpcProtocol,
    private secret: string
  ) {
    this.protocol.onNotification((method, params) => {
      this.handleNotification(method, params as unknown[])
    })
  }

  // ─── Connection ──────────────────────────────────────────────

  async connect(port: number, retries = 10, delayMs = 500): Promise<void> {
    this.pauseState.clear()
    this.invalidateTaskMetadata()
    const url = `ws://127.0.0.1:${port}/jsonrpc`
    for (let attempt = 0; attempt < retries; attempt++) {
      try {
        await this.transport.connect(url)
        return
      } catch (err) {
        if (attempt === retries - 1) throw err
        await new Promise((r) => setTimeout(r, delayMs))
      }
    }
  }

  disconnect(): void {
    this.pauseState.clear()
    this.invalidateTaskMetadata()
    this.transport.disconnect()
  }

  isConnected(): boolean {
    return this.transport.isConnected()
  }

  getConnectionStatus(): EngineConnectionSnapshot {
    return { transport: 'websocket', connected: this.transport.isConnected() }
  }

  // ─── Secret injection ────────────────────────────────────────

  /** Synchronize the credential used for all subsequent RPC calls. */
  setSecret(secret: string): void {
    this.secret = secret
  }

  private withSecret(params: unknown[]): unknown[] {
    return this.secret === '' ? params : [`token:${this.secret}`, ...params]
  }

  private async call<T>(method: string, params: unknown[]): Promise<T> {
    const sequence = ++this.requestSequence
    const finalParams = SECRET_EXEMPT_METHODS.has(method)
      ? params
      : this.withSecret(params)
    // Large file maps can take longer to initialize even when the request is
    // within the wire budget. Keep ordinary status/control deadlines short.
    const result = await this.protocol.call<T>(
      method,
      finalParams,
      method === 'aria2.addTorrent' ? { timeoutMs: 60_000 } : undefined
    )
    return this.reconcileResult(method, params, result, sequence) as T
  }

  private reconcileResult(
    method: string,
    params: unknown[],
    result: unknown,
    sequence: number
  ): unknown {
    if (
      method === 'aria2.changeOption' &&
      result === 'OK' &&
      typeof params[0] === 'string'
    ) {
      // Includes selection, output paths and URI-affecting task options.
      this.invalidateTaskMetadata(params[0])
    }
    return this.pauseState.reconcile(method, params, result, sequence)
  }

  // ─── Download management ─────────────────────────────────────

  addUri(
    uris: string[],
    options?: Record<string, string | string[]>,
    position?: number
  ): Promise<string> {
    const params: unknown[] = [uris]
    if (options !== undefined) params.push(options)
    if (position !== undefined) params.push(position)
    return this.call<string>('aria2.addUri', params)
  }

  addUriWithCookies(
    uris: string[],
    cookies: readonly DownloadCookie[],
    options?: Record<string, string | string[]>,
    position?: number
  ): Promise<string> {
    const params: unknown[] = [uris, cookies]
    if (options !== undefined || position !== undefined)
      params.push(options ?? {})
    if (position !== undefined) params.push(position)
    return this.call<string>('aria2.addUriWithCookies', params)
  }

  addTorrent(
    torrentBase64: string,
    uris?: string[],
    options?: Record<string, string | string[]>
  ): Promise<string> {
    const params: unknown[] = [torrentBase64]
    if (uris !== undefined) params.push(uris)
    if (options !== undefined) params.push(options)
    return this.call<string>('aria2.addTorrent', params)
  }

  addMetalink(
    metalinkBase64: string,
    options?: Record<string, string>
  ): Promise<string[]> {
    const params: unknown[] = [metalinkBase64]
    if (options !== undefined) params.push(options)
    return this.call<string[]>('aria2.addMetalink', params)
  }

  // ─── Task control ────────────────────────────────────────────

  remove(gid: string): Promise<string> {
    return this.call<string>('aria2.remove', [gid])
  }

  forceRemove(gid: string): Promise<string> {
    return this.call<string>('aria2.forceRemove', [gid])
  }

  pause(gid: string): Promise<string> {
    return this.call<string>('aria2.pause', [gid])
  }

  forcePause(gid: string): Promise<string> {
    return this.call<string>('aria2.forcePause', [gid])
  }

  async unpause(gid: string): Promise<string> {
    const pause = this.pauseState.getPendingPause(gid)
    const wasUnconfirmed = pause?.confirmedBy === undefined
    for (;;) {
      try {
        return await this.call<string>('aria2.unpause', [gid])
      } catch (error) {
        // A graceful BT pause is acknowledged before tracker requests drain.
        // Retry only that accepted pause, within its existing settle deadline.
        if (
          !pause ||
          !wasUnconfirmed ||
          pause !== this.pauseState.getPendingPause(gid) ||
          !(error instanceof Error) ||
          error.message !== `GID#${gid} cannot be unpaused now`
        ) {
          throw error
        }
        await new Promise((resolve) => setTimeout(resolve, 100))
        // Disconnect, expiry, or a newer pause invalidates this resume intent.
        if (pause !== this.pauseState.getPendingPause(gid)) throw error
      }
    }
  }

  pauseAll(): Promise<'OK'> {
    return this.call<'OK'>('aria2.pauseAll', [])
  }

  unpauseAll(): Promise<'OK'> {
    return this.call<'OK'>('aria2.unpauseAll', [])
  }

  removeDownloadResult(gid: string): Promise<'OK'> {
    return this.call<'OK'>('aria2.removeDownloadResult', [gid])
  }

  changePosition(
    gid: string,
    pos: number,
    how: 'POS_SET' | 'POS_CUR' | 'POS_END'
  ): Promise<number> {
    return this.call<number>('aria2.changePosition', [gid, pos, how])
  }

  // ─── Status queries ──────────────────────────────────────────

  tellStatus(gid: string, keys?: string[]): Promise<Aria2RawStatus> {
    const params: unknown[] = [gid]
    if (keys !== undefined) params.push(keys)
    return this.call<Aria2RawStatus>('aria2.tellStatus', params)
  }

  tellActive(keys?: string[]): Promise<Aria2RawStatus[]> {
    const params: unknown[] = []
    if (keys !== undefined) params.push(keys)
    return this.call<Aria2RawStatus[]>('aria2.tellActive', params)
  }

  tellWaiting(
    offset: number,
    num: number,
    keys?: string[]
  ): Promise<Aria2RawStatus[]> {
    const params: unknown[] = [offset, num]
    if (keys !== undefined) params.push(keys)
    return this.call<Aria2RawStatus[]>('aria2.tellWaiting', params)
  }

  tellStopped(
    offset: number,
    num: number,
    keys?: string[]
  ): Promise<Aria2RawStatus[]> {
    const params: unknown[] = [offset, num]
    if (keys !== undefined) params.push(keys)
    return this.call<Aria2RawStatus[]>('aria2.tellStopped', params)
  }

  getFiles(gid: string): Promise<Aria2RawFile[]> {
    return this.call<Aria2RawFile[]>('aria2.getFiles', [gid])
  }

  getUris(gid: string): Promise<Aria2RawUri[]> {
    return this.call<Aria2RawUri[]>('aria2.getUris', [gid])
  }

  getPeers(gid: string): Promise<Aria2RawPeer[]> {
    return this.call<Aria2RawPeer[]>('aria2.getPeers', [gid])
  }

  // ─── Global ──────────────────────────────────────────────────

  getGlobalStat(): Promise<Aria2RawGlobalStat> {
    return this.call<Aria2RawGlobalStat>('aria2.getGlobalStat', [])
  }

  getGlobalOption(): Promise<Record<string, string>> {
    return this.call<Record<string, string>>('aria2.getGlobalOption', [])
  }

  changeGlobalOption(options: Record<string, string>): Promise<'OK'> {
    return this.call<'OK'>('aria2.changeGlobalOption', [options])
  }

  getOption(gid: string): Promise<Record<string, string>> {
    return this.call<Record<string, string>>('aria2.getOption', [gid])
  }

  changeOption(gid: string, options: Record<string, string>): Promise<'OK'> {
    return this.call<'OK'>('aria2.changeOption', [gid, options])
  }

  // ─── System ──────────────────────────────────────────────────

  getVersion(): Promise<Aria2Version> {
    return this.call<Aria2Version>('aria2.getVersion', [])
  }

  getSessionInfo(): Promise<{ sessionId: string }> {
    return this.call<{ sessionId: string }>('aria2.getSessionInfo', [])
  }

  shutdown(): Promise<'OK'> {
    return this.call<'OK'>('aria2.shutdown', [])
  }

  forceShutdown(): Promise<'OK'> {
    return this.call<'OK'>('aria2.forceShutdown', [])
  }

  saveSession(): Promise<'OK'> {
    return this.call<'OK'>('aria2.saveSession', [])
  }

  listMethods(): Promise<string[]> {
    return this.call<string[]>('system.listMethods', [])
  }

  listNotifications(): Promise<string[]> {
    return this.call<string[]>('system.listNotifications', [])
  }

  // ─── Batch (performance) ─────────────────────────────────────

  async multicall(calls: Aria2MethodCall[]): Promise<unknown[]> {
    const sequence = ++this.requestSequence
    // Each sub-call needs the same secret-injection treatment as a
    // single `call()`. Without it aria2 returns `{faultCode:1,
    // faultString:"Unauthorized"}` for every entry; the protocol
    // layer's `r[0]` extraction then yields `undefined`, which
    // silently corrupts every downstream consumer (most visibly
    // PollingScheduler). See spec 2026-04-25-engine-config-design.
    const withSecret = calls.map((c) => ({
      method: c.method,
      params: SECRET_EXEMPT_METHODS.has(c.method)
        ? c.params
        : this.withSecret(c.params),
    }))
    const results = await this.protocol.multicall(withSecret)
    return results.map((result, index) =>
      this.reconcileResult(
        calls[index].method,
        calls[index].params,
        result,
        sequence
      )
    )
  }

  /**
   * Fault-aware batch: same per-entry secret injection as {@link multicall},
   * but per-entry outcomes survive (see JsonRpcProtocol.multicallSettled).
   * Required for any batch of MUTATING calls, where a swallowed fault would
   * silently corrupt caller bookkeeping.
   */
  async multicallSettled(
    calls: Aria2MethodCall[]
  ): Promise<PromiseSettledResult<unknown>[]> {
    const sequence = ++this.requestSequence
    const withSecret = calls.map((c) => ({
      method: c.method,
      params: SECRET_EXEMPT_METHODS.has(c.method)
        ? c.params
        : this.withSecret(c.params),
    }))
    const results = await this.protocol.multicallSettled(withSecret)
    return results.map((result, index) =>
      result.status === 'fulfilled'
        ? {
            status: 'fulfilled',
            value: this.reconcileResult(
              calls[index].method,
              calls[index].params,
              result.value,
              sequence
            ),
          }
        : result
    )
  }

  // ─── SQLite3-Persistence RPCs (aria2_motrix fork) ────────────
  //
  // Each call requires `--enable-sqlite3-persistence=true` on the engine.
  // When disabled, the fork raises "SQLite3 persistence is not enabled".
  // Adapters MUST gate UI on EngineFeatureReport.hasSqlitePersistence
  // before calling these.

  getDownloadResultCount(
    filter?: Aria2HistoryFilter
  ): Promise<Aria2HistoryCount> {
    const params: unknown[] = []
    if (filter !== undefined) params.push(filter)
    return this.call<Aria2HistoryCount>('aria2.getDownloadResultCount', params)
  }

  searchDownloadResult(
    query: Aria2SearchQuery,
    offset: number,
    num: number,
    keys?: string[]
  ): Promise<Aria2RawStatus[]> {
    const params: unknown[] = [query, offset, num]
    if (keys !== undefined) params.push(keys)
    return this.call<Aria2RawStatus[]>('aria2.searchDownloadResult', params)
  }

  getCheckpointStatus(outputPath: string): Promise<Aria2CheckpointStatus> {
    return this.call<Aria2CheckpointStatus>('aria2.getCheckpointStatus', [
      outputPath,
    ])
  }

  getHttpRetryStatusV1(gid: string, uri: string, outputPath: string) {
    return this.call<{ available: 'true' | 'false'; reason: string }>(
      'aria2.getHttpRetryStatusV1',
      [gid, uri, outputPath]
    )
  }

  retryHttpDownloadV1(gid: string, uri: string, outputPath: string) {
    return this.call<string>('aria2.retryHttpDownloadV1', [
      gid,
      uri,
      outputPath,
    ])
  }

  inspectLegacyCheckpointV1(input: { controlFile: string }): Promise<unknown> {
    return this.call('aria2.inspectLegacyCheckpointV1', [input])
  }

  addLegacyTorrentV1(input: {
    token: string
    targetPath: string
    metadataFile: string
    metadataDigest: string
    metadata: string
    options: Record<string, string | string[]>
  }): Promise<string> {
    return this.call<string>('aria2.addLegacyTorrentV1', [input])
  }

  importLegacyCheckpointV1(
    input: Aria2LegacyCheckpointImport
  ): Promise<unknown> {
    return this.call('aria2.importLegacyCheckpointV1', [input])
  }

  reconcileLegacyCheckpointV1(input: {
    token: string
    targetPath: string
  }): Promise<unknown> {
    return this.call('aria2.reconcileLegacyCheckpointV1', [input])
  }

  exportSession(filePath: string): Promise<'OK'> {
    return this.call<'OK'>('aria2.exportSession', [filePath])
  }

  requeueDownloadResult(
    gid: string,
    options?: Record<string, string>
  ): Promise<Aria2RequeueResult> {
    const params: unknown[] = [gid]
    if (options !== undefined) params.push(options)
    return this.call<Aria2RequeueResult>('aria2.requeueDownloadResult', params)
  }

  // ─── Event subscriptions (WebSocket push) ────────────────────

  onDownloadStart(handler: EventHandler): Unsubscribe {
    return this.addHandler('aria2.onDownloadStart', handler)
  }

  onDownloadPause(handler: EventHandler): Unsubscribe {
    return this.addHandler('aria2.onDownloadPause', handler)
  }

  onDownloadStop(handler: EventHandler): Unsubscribe {
    return this.addHandler('aria2.onDownloadStop', handler)
  }

  onDownloadComplete(handler: EventHandler): Unsubscribe {
    return this.addHandler('aria2.onDownloadComplete', handler)
  }

  onDownloadError(handler: EventHandler): Unsubscribe {
    return this.addHandler('aria2.onDownloadError', handler)
  }

  onBtDownloadComplete(handler: EventHandler): Unsubscribe {
    return this.addHandler('aria2.onBtDownloadComplete', handler)
  }

  // ─── Internal ────────────────────────────────────────────────

  private addHandler(method: string, handler: EventHandler): Unsubscribe {
    if (!this.notificationHandlers.has(method)) {
      this.notificationHandlers.set(method, new Set())
    }
    const handlers = this.notificationHandlers.get(method)
    handlers?.add(handler)
    let subscribed = true
    return () => {
      if (!subscribed) return
      subscribed = false
      handlers?.delete(handler)
      if (handlers?.size === 0) {
        this.notificationHandlers.delete(method)
      }
    }
  }

  private handleNotification(method: string, params: unknown[]): void {
    const handlers = this.notificationHandlers.get(method)
    if (handlers && params.length > 0) {
      const event = params[0] as Aria2Event
      for (const handler of [...handlers]) {
        handler(event)
      }
    }
  }
}