# Torrent streaming (TorrServer)

Animetail streams magnet and `.torrent` videos through an embedded TorrServer
(a Go BitTorrent engine with an HTTP API). Yokan talks to the same
[TorrServer API](https://github.com/YouROK/TorrServer) from shared code. On
desktop it can run TorrServer itself; on every platform it can use a TorrServer
the user runs. Settings live in `DbSettings.features.torrent` and the page is
Settings → Player → Torrent streaming. The feature is off by default.

## What is wired

- **Playback.** `ProfileReaderContent.videos()` is the single source of player,
  quality-switch, failover, cast and external-player URLs.
  - A torrent library entry (Library → Torrent stream) is source-less and its
    chapter URL is a magnet link or a `.torrent` path/URL. It now resolves to
    TorrServer stream URLs. Local `.torrent` files are uploaded
    (`/torrent/upload`, 16 MiB cap) because a remote server cannot read them.
  - Extension video lists can contain magnet links or `.torrent` URLs, as in
    Animetail. These are expanded in place. Subtitle and audio tracks are kept,
    and the quality label becomes `<quality> · <file name>`.
- **File selection.** Yokan polls `get` until the torrent's metadata arrives
  (90 s limit). Each video file of a multi-file torrent becomes a separate
  stream, chosen in the player's quality list. Non-video files are listed only
  when the torrent has no video files. Animetail's `index=N` link parameter
  selects one file (TorrServer file ids start at 1).
- **Downloads.** The anime download resolver passes the chosen source video
  through the same expansion and downloads TorrServer's
  `/stream/<name>?link=<hash>&index=<id>&play` URL with the normal HTTP
  downloader. This is Animetail's `torrentDownload` path. Torrent library
  entries are not downloadable: they are local-archive titles, whose download
  deletion would remove the user's `.torrent` file.
- **Engine off.** Torrent entries are removed from mixed source lists.
  Torrent-only results and torrent library entries fail with a message that
  points to the setting.

## Server lifecycle

| Mode | Platforms | Behavior |
|---|---|---|
| Run TorrServer on this device | Desktop (macOS, Linux, Windows) | Supervised subprocess. Details below. |
| Remote TorrServer | All | Uses the configured URL and optional HTTP Basic credentials, which are sent only on API calls. `play` stream URLs need no credentials. |

Details of the desktop subprocess:

- **Binary.** On opt-in, Yokan downloads the official `MatriX.147` release
  binary. The SHA-256 digests are pinned in code. The binary is written to a
  `.part` file, verified, marked executable and moved atomically into
  `~/.local/share/yokan/torrserver-bin/`. A user-provided binary path can be
  used instead.
- **Launch.** `--port <port> --path <profile dir>/torrserver`, plus
  `--proxyurl/--proxymode` when a proxy is set. Output goes to
  `torrserver.log`.
- **Health.** Startup waits for `GET /echo`. It fails with a clear message if
  the process exits (including the log tail), if it does not answer within 20 s,
  or if another server already answers on the port.
- **Crash recovery.** An unexpected exit restarts the server with backoff (1,
  2, 4 s), up to 3 times in a row. After that, the next use restarts it.
  Stream URLs survive a restart because TorrServer re-adds a torrent from the
  `link` hash.
- **Yokan crash.** A pid file holding the pid and the process start time lets
  the next start kill a server left running by a crashed Yokan. The start time
  guards against pid reuse. A JVM shutdown hook stops the server on normal
  exit.
- **Option changes.** A new port, binary or proxy restarts the server on next
  use. Switching to remote mode stops the managed server.
- **Profiles.** Each profile has its own TorrServer state (`config.db`, cache)
  under its owned root, so profile deletion removes it. Session retirement
  (`YokanServices.closeAndJoin`) stops the server.

## Trackers and proxy

- The tracker list defaults to Animetail's anime list. It can be edited, and
  "Reset tracker list" restores the default.
- The list is pushed to the server's `/settings` API in `DefaultTrackers`,
  with `RetrackersMode = 1` (add to every torrent). Because `set` replaces all
  settings, Yokan reads the full `BTSets` and changes only these two fields.
- The list is pushed once per server per session, and again on
  "Check server and apply trackers" or a reset.
- Servers without `DefaultTrackers` are reported as too old. Older TorrServer
  builds only read a `trackers.txt` file.
- The proxy modes are None, Trackers, Peers+DHT and Full, as in Animetail.
  TorrServer accepts a proxy only as launch flags (`--proxyurl`,
  `--proxymode`), not through its settings API (checked in
  `server/settings/args.go` and `server/torr/btserver.go` at `a86d8fa`).
  - The desktop managed server receives the flags.
  - A remote server must be started with them where it runs; the settings page
    says so.
- Backups and sync exports clear the binary path, password and proxy URL
  (`DbTorrentPreferences.forExport`).

## Platform support and blockers

- **Desktop:** managed or remote. Casting a managed stream is refused because
  `127.0.0.1` is not reachable by a TV. A remote server configured with a LAN
  address can be cast.
- **Android:** remote only. The TorrServer app on the same phone counts
  (`http://127.0.0.1:8090`). Cleartext HTTP is already allowed. Yokan does not
  bundle or exec TorrServer:
  - `TorrServer-android-arm64` is 64,445,000 bytes, and each ABI adds about
    62–64 MB. That would roughly double the APK, and APK size is tracked for
    this project.
  - Android 10+ (W^X) refuses to exec files in app-writable storage, so a
    downloaded or user-provided binary cannot run. Only `nativeLibraryDir`
    (bundled) can.
  - Animetail instead links a JNI build (`libtorrserver.so`) into its APK.
- **iOS:** remote only. iOS forbids spawning processes. The official
  `TorrServerKit.xcframework` is 75 MB and GPL-3.0; GPL-3.0 terms conflict
  with App Store distribution terms. `NSAllowsLocalNetworking` is set so LAN
  servers work over HTTP. Public servers need HTTPS.
- **Web:** remote only. Browsers cannot spawn processes or accept BitTorrent
  peer connections.
  - TorrServer sends CORS headers for all origins: `AllowAllOrigins`,
    `AllowPrivateNetwork`, and an `Authorization` header allow-list
    (`server/web/server.go`, checked at `a86d8fa`). API calls and `<video>`
    playback therefore work cross-origin.
  - An HTTPS-hosted Yokan can reach only an HTTPS TorrServer or `localhost`,
    because of mixed-content blocking.

## License

TorrServer is GPL-3.0. The Yokan repository has no license file, so
compatibility with distributing TorrServer inside Yokan cannot be established.
Yokan therefore never ships TorrServer in its artifacts:

- Desktop downloads the unmodified official binary only on explicit user
  opt-in and runs it as a separate process over HTTP.
- Other platforms use a server the user installs.

## Verification

- `TorrentStreamsTest` (common, run on desktop and Kotlin/Wasm) uses MockEngine
  fixtures of the TorrServer API. It covers:
  - remote/hostless selection and Basic auth
  - metadata polling and the timeout
  - multi-file listing, `index=` selection and `.torrent` upload
  - the tracker push preserving `BTSets`, done once per session
  - old-server detection, error bodies and URL validation
  - managed-host launch options, including the proxy, and stopping the host
    in remote mode
  - disabled-engine filtering
- `DesktopTorrServerHostTest` runs real subprocesses of a fake TorrServer (a
  Java program behind a shell script). It covers:
  - start/health, proxy flags, crash restart and stop with pid-file cleanup
  - restart on option change
  - orphan kill after an app crash
  - a foreign server on the port, a startup crash with the log tail, and a
    missing binary
  - SHA-256-verified install, including a rejected mismatch that leaves no
    file behind
- No real TorrServer, swarm or device playback was exercised.
