# SPEC — `scorpiox-scorpioplayer-plus-web-api-client` (`spplus_`, v1.1.0)

## 1. Purpose

Pure-C99 client library for the SCORPIO+ web front (`https://plus.scorpiox.net` and self-hosted `scorpiox-plus-web` / `scorpiox-plus-api`) and legacy Movie/TV Detail Page resolution (`gcp.scorpioplayer.com`, `mfunc.scorpioplayer.com`, `spimdb.scorpioplayer.com`). Every native shell — Apple SwiftUI (iOS / macOS / tvOS), Windows WinUI3, Xbox UWP AppContainer, Android Kotlin Compose, and Linux GTK4 — calls the exact same 51 `spplus_*` exports instead of reimplementing URL construction, auth headers, image resizing, instant-start home caching, `GetFiles` + per-user fallback, `RuntimeConfig` transforms, OneDrive B `GetLink` resolution, external subtitles, or trailer lookup.
## 2. Dependencies & Transport Architecture

- **Zero external runtime dependencies** beyond:
  - Vendored `yyjson` (`vendor/yyjson/`)
  - Vendored fleet HTTP transport (`vendor/scorpiox-http-transport/`, `scorpiox-http.h` ABI v1)
- **Pluggable `scorpiox_http` vtable (`spplus_set_http_backend`)**:
  - `linux-x86_64`: defaults to `scorpiox_http_curl()` (libcurl)
  - `windows-x64`: defaults to `scorpiox_http_winhttp()` (WinHTTP, `winhttp.dll` only)
  - `windows-x64-uwp`: compiled with `-DSPPLUS_UWP -DSPPLUS_NO_CURL -DSCORPIOX_HTTP_NO_CURL -DSCORPIOX_HTTP_NO_WINHTTP`; imports `KERNEL32` + CRT ONLY (zero WinHTTP / Winsock / banned Win32 APIs); Xbox UWP shell installs an `HttpClient`-backed `scorpiox_http` vtable
  - `apple-xcframework` (iOS, iOS Simulator, macOS, tvOS, tvOS Simulator): compiled with `NO_CURL`; Swift shell installs a `URLSession`-backed `scorpiox_http` vtable
  - `android-arm64-v8a` / `android-x86_64` (16 KB ELF LOAD alignment): compiled with `NO_CURL`; Kotlin/JNI shell installs an `OkHttp` / `HttpURLConnection`-backed `scorpiox_http` vtable
  - Offline testing: built-in per-handle fake backend (`spplus_use_fake_http`, `spplus_fake_add_route`, `spplus_fake_reset`, `spplus_fake_request_count`, `spplus_fake_last_request_json`) exercising the exact same `scorpiox_http` vtable path.

## 3. Auth Modes & Security Invariants

| Mode | Constant | Wire Header | Notes |
|---|---|---|---|
| Cloud JWT (default) | `SPPLUS_AUTH_JWT` (0) | `Cookie: sx_token=<jwt>` | Token validated (3 base64url segments, no CR/LF). Obtained via `spplus_login()` (`POST <auth_url>/api/login`) or `spplus_set_token()`. |
| Self-host Password | `SPPLUS_AUTH_PASSWORD` (1) | `X-Plus-Password: <pw>` | For self-hosted `scorpiox-plus -P <pw>` (`PLUS_AUTH=password`). |
| Anonymous / Test | `SPPLUS_AUTH_NONE` (2) | (none) | Catalogue/offline test mode. |

- Passwords are **never** logged, written to disk, or echoed in `spplus_result_json()`. Login request buffers are wiped via volatile zeroing (`spplus_secure_zero`) immediately after `http->request()` returns.
- `spplus_logout()` and `spplus_destroy()` always wipe stored tokens/passwords and disarm writes.

## 4. Write-Arming Safety Guard

All mutating endpoints (`spplus_save_progress`, `spplus_watchlist_set`) are **REFUSED BY DEFAULT** with `SPPLUS_ERR_NOT_ARMED` (10) and emit **0 HTTP requests** until the caller explicitly invokes `spplus_arm_writes(h, 1)`. Automated test suites and `.console --test` only ever arm writes against the offline fake backend.

## 5. Endpoints & Wire Contract

| Export | HTTP Method & Path | Behaviour |
|---|---|---|
| `spplus_login` | `POST <auth_url>/api/login` | Sends `{"email","password"}`, extracts `token` (JSON or `Set-Cookie: sx_token=`), `userId` (`sub`), `email`; returns canonical session JSON. |
| `spplus_home` | `GET /?format=json&cap=<cap>&profile=<profile>` | Default `cap=15` (clamped `1..200`); rewrites `/t/p/original/` URLs; computes FNV-1a signature over `generated` + `continue[]`; sets `"changed": true\|false`; atomically caches to `cache_dir` if configured. |
| `spplus_home_cached` | (disk only, 0 HTTP) | Reads `<cache_dir>/spplus-home-p<profile>.json` for 0 ms cold launch; returns `SPPLUS_ERR_NOT_FOUND` on miss or when `cache_dir == NULL`. |
| `spplus_browse` | `GET /browse?[kind=][&list=][&page=]&format=json` | URL-encodes `kind` and `list_name`; rewrites card image URLs. |
| `spplus_title` | `GET /title?id=<tt...>&format=json` | Validates `tt[0-9]+`; rewrites detail poster (`detail_w`), backdrop (`backdrop_w`), and similar/cast cards (`card_w`). |
| `spplus_tv` | `GET /tv?id=<tt...>[&season=N]&format=json` | Validates `tt[0-9]+`; `season < 0` omits `season` param for lowest raw season. |
| `spplus_person` | `GET /person?id=<encoded>&format=json` | Accepts `nm...`, numeric TMDb ID, or plain UTF-8 name. |
| `spplus_search` | `GET /search?q=<encoded>&page=N&format=json` | `page <= 0` defaults to 1. |
| `spplus_account` | `GET /account?format=json` | Returns user, active memberships, enabled-first profiles, menu. |
| `spplus_continue` | `GET /continue?profile=N&format=json` | On HTTP 404 (older web front), automatically falls back to `GET /?format=json&cap=1&profile=N` and extracts `continue[]` into `{"ok":true,"profile":N,"fallback":true,"items":[...]}`. |
| `spplus_prewarm` | `GET /prewarm?id=<tt...>[&s=S&e=E]` | Warms GetFiles + GetLink + ffprobe caches without starting a transcode job. |
| `spplus_watch` | `GET /watch?id=<tt...>[&s=S&e=E][&native=1][&file_index=N]&format=json` | Supports native direct playback (`native_mode=1`, `file_index`) and normalizes `direct_url` / `stream_url` cleanly. |
| `spplus_watchlist_get` | `GET /watchlist?format=json` | Returns user's watchlist IDs. |
| `spplus_save_progress` | `POST /progress` (armed) | Body `{"id","s","e","position","duration","size"}`; accepts HTTP 204 or 200. |
| `spplus_watchlist_set` | `POST /watchlist` (armed) | Body `{"op":"add"\|"remove","id":"tt..."}`. |
| `spplus_set_gcp_url` / `spplus_set_mfunc_url` / `spplus_set_spimdb_url` | (config) | Override default upstream hosts (`https://gcp.scorpioplayer.com`, `https://mfunc.scorpioplayer.com`, `https://spimdb.scorpioplayer.com`); pass NULL/empty to restore defaults. |
| `spplus_detail_files` | `KeyValue/StartsWith` + `IsMovie` + `finder/getfiles` + `users/{uid}/api/finder/getfiles` | Full legacy Movie/TV Detail page file discovery: per-user progress (`last_season`, `movie_progress_pct`, `IsDuration` < 6h ms vs file-size match), Supreme global `GetFiles` with automatic per-user fallback, `IsActive` filtering, `FileName` dedup, `ResolutionStandard`, badges (`SCORPIO+`, `SKYDRIVE`, `Chromecast`), `entry_kind`, single-decoded `marker_path`, `runtime_group_id`/`runtime_path`, `gcp9`->`cdn` display host swap, and `episodes_map`. |
| `spplus_resolve_entry` | `cdn/Drive/GetLink` / `api/getgroup` / pure | Unified 4-way resolver: (1) CDN marker -> single-decoded path (no `%2520` double-encoding!) -> 600 s TTL cache -> `GetLink` (refuses empty/NXDOMAIN fallback with `SPPLUS_ERR_UPSTREAM`), (2) `runtimeconfig://{groupId}/path` -> local lookup or cached `/api/getgroup` fallback -> `SPFS`/`ASPNET`/`WebDAV`/`HTTP` direct URL + auth headers or structured `requires_handler` descriptor (`SMB2`, `SPMS`, `SFTP`, `NFS`, `EMBY`, `JELLYFIN`, `ONEDRIVE`, `ONEDRIVEB`, `DROPBOX`, `SYNOLOGY`, `EXTDOC`), (3) `Magnet`/`Torrent` -> Debrid `RuntimeConfig` matching (`ALLDEBRID`, `REALDEBRID`, `Premiumize`, `DEBRIDLINK`), (4) direct `http`/`https` passthrough. |
| `spplus_get_group` | `GET {mfunc}/api/getgroup?id=<group_id>` | Standalone 600 s cached `RuntimeConfig` group fetch with legacy `GetRuntimeConfigDisplayName` resolution. |
| `spplus_external_subtitles` | `GET {gcp}/api/KeyValue/StartsWith?k=SMF_ExternalSubtitle_<tt...>` | Filters to `S/E` (negative -> 0 for movies), computes C# `GetStableHashCode()` UTF-16 djb2 track IDs, detects child tracks (`---<parent.p5>`), infers format & language. |
| `spplus_resolve_trailer` | `GET {gcp}/cdn/Drive/tls%2F<tt...>.mp4?redirect=false&preferHighSpped=false` | Returns `{"ok":true,"imdb_id":"...","direct_url":"..."}` or `{"ok":false,"imdb_id":"...","direct_url":""}` cleanly on 404/empty. |
| `spplus_clear_link_cache` | (in-memory) | Clears `GetLink` and `getgroup` TTL caches (e.g. before retry after expired SharePoint `tempauth`). |

Defaults: `card_w = 342`, `detail_w = 500`, `backdrop_w = 780` (configurable via `spplus_set_image_widths(h, card_w, detail_w, backdrop_w)`; pass `0` to leave raw). Any `/t/p/original/` URL in poster/backdrop/still/gallery fields is rewritten to `/t/p/w<N>/`, saving ~90% bandwidth on mobile/TV while leaving non-TMDB paths (such as spotlight logos) untouched.

## 7. Error Taxonomy

| Code | Name | Meaning |
|---|---|---|
| 0 | `SPPLUS_OK` | Success |
| 1 | `SPPLUS_ERR_INVALID_ARG` | Invalid/NULL argument or malformed IMDb ID / URL / JWT |
| 2 | `SPPLUS_ERR_NO_IO` | No HTTP backend installed (UWP/Apple/Android before `spplus_set_http_backend`) |
| 3 | `SPPLUS_ERR_TRANSPORT` | Network/DNS/TLS/timeout failure |
| 4 | `SPPLUS_ERR_AUTH` | HTTP 401/403, 302 login redirect, or `unauthorized`/`no_user_id` |
| 5 | `SPPLUS_ERR_NOT_FOUND` | HTTP 404, `not_found`, or cache miss |
| 6 | `SPPLUS_ERR_UPSTREAM` | HTTP 5xx or `upstream`/`upstream_timeout` |
| 7 | `SPPLUS_ERR_HTTP` | Other non-2xx HTTP status |
| 8 | `SPPLUS_ERR_PARSE` | Malformed JSON response |
| 9 | `SPPLUS_ERR_OOM` | Out of memory |
| 10 | `SPPLUS_ERR_NOT_ARMED` | Write export refused (call `spplus_arm_writes(h, 1)`) |
| 11 | `SPPLUS_ERR_IO` | Cache disk I/O error |
