docs/providers.md
361 lines · 15016 bytes
1# Curd streaming providers
2
3Curd separates **what you watch** (AniList / local history) from **where streams come from** (providers). Providers are compile-time modules that implement a small interface and register themselves at startup. The host application handles menus, tracking, mpv playback, and provider stack fallback — providers only answer search, episode list, and stream URL questions.
4
5This document explains the intent of the design, how to add a provider, how users enable or disable providers, and what to do when a new provider needs something the current contract does not cover.
6
7---
8
9## Design intent
10
11### Goals
12
131. **Adding a provider should be mechanical** — new package, implement three methods, register in `init()`, add one import line. No edits to central maps, name switches, or `curd.go` provider-specific branches.
142. **Disabling a broken provider should not require a release** — users can turn providers off in `curd.conf` without rebuilding.
153. **Keep one binary** — providers ship inside the curd repo (or as Go packages imported at build time). We are not using runtime plugin binaries or `.so` loading.
164. **Host owns orchestration** — ordered fallback, sub/dub prompts, AniList → provider matching, and mpv IPC stay in `internal/`. Providers return data; they do not drive the watch loop.
17
18### Non-goals (for now)
19
20- Installable third-party plugin binaries
21- Providers replacing AniList search or the TUI/Rofi selector
22- Providers running arbitrary host code or reading OAuth tokens
23
24### Architecture (high level)
25
26```
27┌─────────────────────────────────────────────────────────┐
28│ internal/ (host) │
29│ SetupCurd · provider stack · mpv · tracking · config │
30│ │ uses providers.New() + adapter │
31│ │ wires curdhost.* hooks for HTTP, log, storage │
32└───────┼─────────────────────────────────────────────────┘
33 │
34 ▼
35┌─────────────────────────────────────────────────────────┐
36│ internal/providers/ │
37│ registry · types · Provider interface │
38├─────────────────────────────────────────────────────────┤
39│ allanime/ animepahe/ yourprovider/ │
40│ search · episodes · streams · register.go │
41└─────────────────────────────────────────────────────────┘
42```
43
44Providers **must not** import `internal` (that would create an import cycle). They use `curdhost` for shared services and `providers` for types and registration.
45
46---
47
48## Provider contract
49
50### Required interface
51
52Defined in `internal/providers/types.go`:
53
54```go
55type Provider interface {
56 Name() string
57 SearchAnime(query, mode string) ([]SelectionOption, error)
58 EpisodesList(showID, mode string) ([]string, error)
59 GetEpisodeURL(config PlaybackConfig, id string, epNo int) ([]string, error)
60}
61```
62
63| Method | Purpose |
64|--------|---------|
65| `Name()` | Canonical provider id (e.g. `allanime`). Must match `Meta.Name` from registration. |
66| `SearchAnime` | Find shows on the streaming site. `mode` is `sub` or `dub` where relevant. |
67| `EpisodesList` | Return episode numbers as strings for a provider show id. |
68| `GetEpisodeURL` | Resolve playable URLs for episode `epNo` (1-based, aligned with AniList progress). |
69
70### Shared types
71
72```go
73type SelectionOption struct {
74 Key string // provider show id (stored in history / ProviderId)
75 Label string // menu line
76 Title string // plain title for matching
77 Thumbnail string // optional cover URL
78 ExtraData any // optional provider-specific payload (e.g. metadata for matching)
79}
80
81type PlaybackConfig struct {
82 SubOrDub string // "sub" or "dub"
83}
84```
85
86Use `providers.NormalizeTranslationType(mode)` and `providers.AlternateTranslationType(mode)` from `internal/providers/lang.go` for sub/dub handling.
87
88### Optional interfaces
89
90Implement only when the default behavior is not enough:
91
92| Interface | When to implement |
93|-----------|-------------------|
94| `ModeResolver` | Sub and dub use different APIs or URLs; host calls `GetEpisodeURLForMode` explicitly during fallback. |
95| `HintResolver` | Streams need per-URL mpv metadata (Referer header, external subtitle URL). Used by AllAnime. |
96| `IDResolver` | Stored show ids go stale and must be refreshed via search (Animepahe sessions). |
97
98The host discovers these via type assertion on the registered provider — no extra registration step.
99
100### Show IDs and the provider stack
101
102- Configured stack: `Provider = ["allanime", "animepahe"]` — tried left to right for search and playback.
103- Qualified ids in menus when multiple providers are active: `allanime::ShowIdHere`.
104- Host qualifies ids with `providername::id` when merging stacked search results.
105
106Your `Key` in `SearchAnime` should be the **raw** provider id. The host adds the `provider::` prefix when needed.
107
108---
109
110## Adding a new provider
111
112### 1. Create the package
113
114```
115internal/providers/yoursite/
116 register.go # providers.Register in init()
117 provider.go # Provider struct + interface methods
118 search.go # HTTP / API search (optional split)
119 episodes.go
120 streams.go
121 provider_test.go
122```
123
124Use `allanime` as a reference for a GraphQL/REST provider, `animepahe` for cookie/browser-heavy sites.
125
126### 2. Implement `Provider`
127
128```go
129package yoursite
130
131import "github.com/wraient/curd/internal/providers"
132
133type Provider struct{}
134
135func (p *Provider) Name() string { return "yoursite" }
136
137func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
138 // ...
139}
140
141func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
142 // ...
143}
144
145func (p *Provider) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
146 // ...
147}
148```
149
150### 3. Register in `init()`
151
152```go
153func init() {
154 providers.Register(providers.Meta{
155 Name: "yoursite",
156 Aliases: []string{"ys"}, // optional config/menu aliases
157 Referrer: "https://yoursite.example/", // mpv Referer for streams
158 }, func() providers.Provider {
159 return &Provider{}
160 })
161}
162```
163
164`Meta` fields:
165
166| Field | Meaning |
167|-------|---------|
168| `Name` | Canonical name (lowercase, no spaces; normalized to compact form e.g. `allanime`). |
169| `Aliases` | Alternate names accepted in config. |
170| `Referrer` | Default HTTP Referer for mpv when playing this provider's links. |
171| `DefaultDisabled` | If true, provider is off until user enables it (see Animepahe). |
172| `DisableReason` | Shown when a disabled provider is requested. |
173| `OptOutToken` | Config token to permanently skip fallback prompts (e.g. `no-animepahe`). |
174| `FallbackPrompt` | Reserved for host fallback UX (Animepahe chromium warning). |
175
176### 4. Wire the package into the binary
177
178Add a blank import in `internal/loadproviders/load.go`:
179
180```go
181import (
182 _ "github.com/wraient/curd/internal/providers/allanime"
183 _ "github.com/wraient/curd/internal/providers/animepahe"
184 _ "github.com/wraient/curd/internal/providers/yoursite"
185)
186```
187
188`internal` already imports `loadproviders` from `provider_bridge.go`, so registration runs on startup.
189
190### 5. Use `curdhost` for host services
191
192Providers must not call `internal` helpers directly. Use hooks in `internal/curdhost/host.go`:
193
194| Hook | Use |
195|------|-----|
196| `curdhost.HTTPClient()` | Shared cookie jar HTTP client |
197| `curdhost.Log(string)` | Debug log (`debug.log` in storage path) |
198| `curdhost.Out(string)` | User-visible terminal message |
199| `curdhost.StoragePath()` | `~/.local/share/curd` (or configured path) |
200| `curdhost.AnimeNameLanguage()` | `"english"` or `"romaji"` for search result labels |
201| `curdhost.HTTPStatusOK` / `HTTPStatusError` | Consistent HTTP error formatting |
202
203Example:
204
205```go
206resp, err := curdhost.HTTPClient().Do(req)
207if err != nil {
208 return nil, err
209}
210body, _ := io.ReadAll(resp.Body)
211resp.Body.Close()
212if !curdhost.HTTPStatusOK(resp.StatusCode) {
213 return nil, curdhost.HTTPStatusError("yoursite search", resp.StatusCode, body)
214}
215```
216
217### 6. Tests
218
219- Unit tests live in the provider package (`httptest` transport, no live site).
220- Use `curdhost` hooks in test setup (see `animepahe/provider_test.go`).
221- Host-level stack tests use `providers.SetFactoryForTest` via `withProviderFactories` in `provider_stack_test.go`.
222- Live tests: gate behind env vars (e.g. `CURD_LIVE_ALLANIME_TEST=1`).
223
224### 7. User configuration
225
226Users add the provider to their stack in `~/.config/curd/curd.conf`:
227
228```ini
229Provider=["yoursite"]
230# or fallback stack:
231Provider=["yoursite","allanime"]
232```
233
234---
235
236## Enabling and disabling providers
237
238Disable order (first match wins):
239
2401. **Test override** — `withAllProvidersEnabledForTest` in tests only.
2412. **`DisabledProviders` in config** — runtime kill switch, no rebuild:
242
243 ```ini
244 DisabledProviders=["animepahe","yoursite"]
245 ```
246
2473. **`DefaultDisabled` in `Meta`** — compile-time default (Animepahe ships disabled with a reason).
248
249To ship a provider that is **off by default** but opt-in capable, set `DefaultDisabled: true` and a clear `DisableReason`. Users remove it from `DisabledProviders` or we can add a menu entry later to toggle it.
250
251---
252
253## When a provider needs something new
254
255Follow this order — prefer extending the contract over special-casing in `curd.go`.
256
257### A. Needs fit an optional interface
258
259| Need | Action |
260|------|--------|
261| Explicit sub/dub resolution | Implement `ModeResolver` |
262| Per-stream Referer / subtitles | Implement `HintResolver` |
263| Stale show id refresh | Implement `IDResolver` |
264
265No registry or host changes required beyond what the interface already supports.
266
267### B. Needs a new `Meta` field
268
269Examples: capability flags (`RequiresBrowser: true`), max quality, consent text.
270
2711. Add the field to `providers.Meta`.
2722. Teach the host to read it via `providers.MetaFor(name)` (config UI, fallback prompts, doctor command).
2733. Do **not** hardcode the provider name in `curd.go`.
274
275### C. Needs a new host hook (in `curdhost`)
276
277Examples: headless browser factory, shared rate limiter, proxy setting.
278
2791. Add a function variable to `internal/curdhost/host.go`.
2802. Wire it in `internal/provider_bridge.go` `init()` from existing `internal` infrastructure.
2813. Document it in this file.
2824. Use it only from provider packages that need it.
283
284Avoid importing `internal` from providers.
285
286### D. Needs new `PlaybackConfig` fields
287
288If every provider needs a new playback preference (e.g. subtitle language on resolve):
289
2901. Add the field to `providers.PlaybackConfig`.
2912. Map it in `toPlaybackConfig()` in `provider_bridge.go`.
2923. Update existing providers if the field is required; otherwise ignore in providers that do not care.
293
294### E. Needs AniList matching behavior
295
296Prefer putting provider-specific match data in `SelectionOption.ExtraData` and scoring in the host (see `scoreProviderSearchOption` in `provider.go`).
297
298If matching is truly provider-specific and complex, implement `IDResolver` or export small helpers from your provider package (as `animepahe.ParseProviderID` does) and call them from the host through interfaces — **never** `if providerName == "yoursite"` in `curd.go`.
299
300### F. Needs runtime install without rebuild
301
302That is outside the current model. Options for a future iteration:
303
304- External JSON/script providers invoked via subprocess
305- Separate Go module imported at build time (`go install` with build tags)
306
307Document the decision in a short ADR before building. The compile-time registry is intentional for reliability and packaging.
308
309---
310
311## Checklist for a new provider PR
312
313- [ ] Package under `internal/providers/<name>/`
314- [ ] `register.go` with `providers.Register` and complete `Meta`
315- [ ] Blank import added in `internal/loadproviders/load.go`
316- [ ] Uses `curdhost` only (no `internal` import)
317- [ ] `provider_test.go` with HTTP mocks
318- [ ] Episode numbers compatible with AniList 1-based progress
319- [ ] Stream URLs return formats mpv can play (m3u8, mp4, etc.)
320- [ ] `Referrer` set correctly if the CDN checks Referer
321- [ ] No provider-specific branches added to `curd.go`
322- [ ] README or this doc updated if new config keys or hooks were added
323
324---
325
326## Reference implementations
327
328| Provider | Package | Notes |
329|----------|---------|-------|
330| Senshi | `internal/providers/senshi` | REST search/episodes, direct HLS from `/episode-embeds`, MAL id keys and `/posters/{mal_id}.webp` thumbnails |
331| AniPub | `internal/providers/anipub` | JSON search/info/details APIs, MegaPlay embed resolution via `/stream/getSources`, MAL id in `ExtraData` for tracker matching |
332| AniNeko | `internal/providers/anineko` | AJAX search, HTML scrape, bibiemb/vibeplayer embed resolution, `SubStyle` / `HintResolver` |
333| AllAnime | `internal/providers/allanime` | GraphQL search/episodes, parallel stream resolution, `HintResolver` |
334| Animepahe | `internal/providers/animepahe` | DDoS-Guard + rod browser, `IDResolver`, `DefaultDisabled`, `OptOutToken` |
335
336Key host files:
337
338| File | Role |
339|------|------|
340| `internal/providers/registry.go` | Registration and lookup |
341| `internal/providers/types.go` | Interfaces and DTOs |
342| `internal/loadproviders/load.go` | Built-in provider imports |
343| `internal/provider_bridge.go` | Host hooks + internal adapter |
344| `internal/provider.go` | Stack, search, resolve orchestration |
345| `internal/provider_disabled.go` | Enable/disable logic |
346
347---
348
349## FAQ
350
351**Why not dynamic plugins?**
352Curd is a single-session CLI binary. Compile-time modules give fast startup, simple packaging (AUR, nix, releases), and easy debugging. Config-based disable covers “site is broken right now” without a plugin marketplace.
353
354**Can providers live in another repo?**
355Yes, as a Go module that imports `github.com/wraient/curd/internal/providers` and `curdhost`, calls `Register` in `init()`, and is blank-imported from a fork or custom `loadproviders` package. Same binary model, different import path.
356
357**What if episode URL resolution is slow?**
358That is expected for some sites. Do heavy work inside the provider (parallel HTTP, caching cookies on disk under `curdhost.StoragePath()`). The host already prefetches the next episode in a goroutine during playback.
359
360**Who owns breaking site changes?**
361The provider package. Fix the provider, release curd. Users can disable a broken provider with `DisabledProviders` until a fix ships.