Commit 60789e58c4

60789e58c494c731d4c5720ef0567459d2770906

parent: d0c088ce23

Unsigned

Wraient <wraient.911@gmail.com> · 2026-06-22 13:55 UTC

feat: compile-time provider registry with allanime, animepahe, and anineko

Split monolithic provider code into internal/providers with a registry,
loadproviders bridge, and curdhost for embed resolution. Port AllAnime,
Animepahe, and AniNeko (bibiemb, vibeplayer, vibeproxy) as separate
providers with per-provider registration and default disable flags.

Layout: unified · split

docs/providers.md added +358
@@ -0,0 +1,358 @@
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| AllAnime | `internal/providers/allanime` | GraphQL search/episodes, parallel stream resolution, `HintResolver` |
331| Animepahe | `internal/providers/animepahe` | DDoS-Guard + rod browser, `IDResolver`, `DefaultDisabled`, `OptOutToken` |
332
333Key host files:
334
335| File | Role |
336|------|------|
337| `internal/providers/registry.go` | Registration and lookup |
338| `internal/providers/types.go` | Interfaces and DTOs |
339| `internal/loadproviders/load.go` | Built-in provider imports |
340| `internal/provider_bridge.go` | Host hooks + internal adapter |
341| `internal/provider.go` | Stack, search, resolve orchestration |
342| `internal/provider_disabled.go` | Enable/disable logic |
343
344---
345
346## FAQ
347
348**Why not dynamic plugins?**
349Curd 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.
350
351**Can providers live in another repo?**
352Yes, 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.
353
354**What if episode URL resolution is slow?**
355That 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.
356
357**Who owns breaking site changes?**
358The provider package. Fix the provider, release curd. Users can disable a broken provider with `DisabledProviders` until a fix ships.
internal/bench_test.go −17
@@ -69,23 +69,6 @@ func BenchmarkMergeAnimeLists(b *testing.B) {
6969 }
7070}
7171
72func BenchmarkSortAllanimeSourcesByPriority(b *testing.B) {
73 sources := make([]allanimeSource, 0, 1000)
74 for i := 0; i < 1000; i++ {
75 sources = append(sources, allanimeSource{
76 SourceUrl: fmt.Sprintf("https://example.com/%d.mp4", i),
77 SourceName: "Yt-mp4",
78 Priority: float64((i * 37) % 100),
79 })
80 }
81
82 b.ReportAllocs()
83 b.ResetTimer()
84 for i := 0; i < b.N; i++ {
85 _ = sortAllanimeSourcesByPriority(sources)
86 }
87}
88
8972func BenchmarkLevenshteinAnimeTitles(b *testing.B) {
9073 for i := 0; i < b.N; i++ {
9174 _ = levenshtein("Sousou no Frieren Beyond Journey's End", "Frieren Beyond Journey's End")
internal/curdhost/host.go added +42
@@ -0,0 +1,42 @@
1package curdhost
2
3import (
4 "fmt"
5 "net/http"
6 "net/url"
7 "strings"
8)
9
10// PromptOption is a minimal menu item for provider-driven prompts.
11type PromptOption struct {
12 Key string
13 Label string
14}
15
16// Host hooks are wired from the main application package during init.
17var (
18 HTTPClient func() *http.Client
19 Log func(string)
20 Out func(string)
21 PromptSelect func(options []PromptOption) (PromptOption, error)
22 CurrentSubStyle func() string
23 PersistSubStylePreference func(style string) error
24 StoragePath func() string
25 AnimeNameLanguage func() string
26 SetCookiesForAnimepahe func(u *url.URL, cookies []*http.Cookie)
27)
28
29func HTTPStatusOK(statusCode int) bool {
30 return statusCode >= http.StatusOK && statusCode < http.StatusMultipleChoices
31}
32
33func HTTPStatusError(context string, statusCode int, body []byte) error {
34 snippet := strings.TrimSpace(string(body))
35 if len(snippet) > 300 {
36 snippet = snippet[:300] + "..."
37 }
38 if snippet != "" {
39 return fmt.Errorf("%s failed with status %d: %s", context, statusCode, snippet)
40 }
41 return fmt.Errorf("%s failed with status %d", context, statusCode)
42}
internal/episode_url_live_test.go +20 −2
@@ -10,9 +10,18 @@ func TestAllanimeMarchLionDubEp1Live(t *testing.T) {
1010 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" {
1111 t.Skip("set CURD_LIVE_ALLANIME_TEST=1")
1212 }
13 withAllProvidersEnabledForTest(t)
1314
1415 showID := "NPpCgzb2MbnpiyxZ3"
15 links, err := getAllanimeEpisodeURLForMode(showID, "dub", 1)
16 provider, err := ProviderByName("allanime")
17 if err != nil {
18 t.Fatalf("allanime provider: %v", err)
19 }
20 resolver, ok := provider.(ProviderModeResolver)
21 if !ok {
22 t.Fatal("expected allanime provider to implement ProviderModeResolver")
23 }
24 links, err := resolver.GetEpisodeURLForMode(CurdConfig{SubOrDub: "dub"}, showID, 1, "dub")
1625 if err == nil {
1726 for _, link := range links {
1827 if strings.Contains(link, "fast4speed.rsvp") {
@@ -27,9 +36,18 @@ func TestAllanimeMarchLionSubEp1Live(t *testing.T) {
2736 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" {
2837 t.Skip("set CURD_LIVE_ALLANIME_TEST=1")
2938 }
39 withAllProvidersEnabledForTest(t)
3040
3141 showID := "NPpCgzb2MbnpiyxZ3"
32 links, err := getAllanimeEpisodeURLForMode(showID, "sub", 1)
42 provider, err := ProviderByName("allanime")
43 if err != nil {
44 t.Fatalf("allanime provider: %v", err)
45 }
46 resolver, ok := provider.(ProviderModeResolver)
47 if !ok {
48 t.Fatal("expected allanime provider to implement ProviderModeResolver")
49 }
50 links, err := resolver.GetEpisodeURLForMode(CurdConfig{SubOrDub: "sub"}, showID, 1, "sub")
3351 if err != nil {
3452 t.Fatalf("sub episode link lookup failed: %v", err)
3553 }
internal/links.go +20
@@ -42,3 +42,23 @@ func linkSelectionScore(link string) int {
4242 score += wixmpQualityScore(link)
4343 return score
4444}
45
46func wixmpQualityScore(link string) int {
47 for _, quality := range []string{"1080p", "720p", "480p", "360p", "240p"} {
48 if strings.Contains(link, quality) {
49 switch quality {
50 case "1080p":
51 return 1080
52 case "720p":
53 return 720
54 case "480p":
55 return 480
56 case "360p":
57 return 360
58 case "240p":
59 return 240
60 }
61 }
62 }
63 return 0
64}
internal/loadproviders/load.go added +8
@@ -0,0 +1,8 @@
1// Package loadproviders registers built-in streaming providers via init side effects.
2package loadproviders
3
4import (
5 _ "github.com/wraient/curd/internal/providers/allanime"
6 _ "github.com/wraient/curd/internal/providers/animepahe"
7 _ "github.com/wraient/curd/internal/providers/anineko"
8)
internal/logic_regression_test.go +4 −4
@@ -219,8 +219,8 @@ func TestGetProviderNormalizesConfiguredProviderName(t *testing.T) {
219219 CurrentProvider = nil
220220 SetGlobalConfig(&CurdConfig{Provider: " AllAnime "})
221221
222 if got := GetProvider().Name(); got != "allanime" {
223 t.Fatalf("expected allanime provider, got %q", got)
222 if got := GetProvider().Name(); got != "anineko" {
223 t.Fatalf("expected anineko provider when allanime is disabled, got %q", got)
224224 }
225225}
226226
@@ -235,8 +235,8 @@ func TestGetProviderFallsBackWhenConfiguredProviderDisabled(t *testing.T) {
235235 CurrentProvider = nil
236236 SetGlobalConfig(&CurdConfig{Provider: " AnimePahe "})
237237
238 if got := GetProvider().Name(); got != "allanime" {
239 t.Fatalf("expected allanime fallback for disabled provider, got %q", got)
238 if got := GetProvider().Name(); got != "anineko" {
239 t.Fatalf("expected anineko fallback for disabled provider, got %q", got)
240240 }
241241}
242242
internal/player.go +4 −2
@@ -12,6 +12,8 @@ import (
1212 "strings"
1313 "sync"
1414 "time"
15
16 "github.com/wraient/curd/internal/providers"
1517)
1618
1719var logFile = "debug.log"
@@ -23,8 +25,8 @@ func streamReferrerForLink(link, provider string) string {
2325 if strings.Contains(strings.ToLower(link), "tools.fast4speed.rsvp") {
2426 return "https://allanime.to"
2527 }
26 if provider == "animepahe" {
27 return "https://kwik.cx/"
28 if referrer := providers.Referrer(provider); referrer != "" {
29 return referrer
2830 }
2931 return defaultStreamReferrer
3032}
internal/provider.go +49 −30
@@ -4,6 +4,9 @@ import (
44 "fmt"
55 "strconv"
66 "strings"
7
8 "github.com/wraient/curd/internal/providers"
9 "github.com/wraient/curd/internal/providers/animepahe"
710)
811
912// Provider interface defines methods for an anime provider.
@@ -27,26 +30,12 @@ type ProviderEpisodeResult struct {
2730}
2831
2932const providerIDSeparator = "::"
30const animepaheOptOutProvider = "no-animepahe"
3133
3234// Global variable to keep the current provider
3335var CurrentProvider Provider
3436
35var providerFactories = map[string]func() Provider{
36 "allanime": func() Provider { return &AllanimeProvider{} },
37 "animepahe": func() Provider { return &AnimepaheProvider{} },
38}
39
4037func normalizeProviderName(providerName string) string {
41 providerName = strings.Trim(strings.TrimSpace(providerName), "\"'[]")
42 switch strings.ToLower(strings.TrimSpace(providerName)) {
43 case "allanime", "all-anime", "all anime":
44 return "allanime"
45 case "animepahe", "pahe":
46 return "animepahe"
47 default:
48 return ""
49 }
38 return providers.NormalizeName(providerName)
5039}
5140
5241func normalizeProviderConfigToken(token string) string {
@@ -69,7 +58,7 @@ func parseProviderConfigParts(rawProvider string) []string {
6958func parseProviderConfig(rawProvider string) ([]string, bool) {
7059 rawProvider = strings.TrimSpace(rawProvider)
7160 if rawProvider == "" {
72 rawProvider = "allanime"
61 rawProvider = firstEnabledProviderName()
7362 }
7463
7564 normalizedRaw := strings.ToLower(rawProvider)
@@ -83,7 +72,7 @@ func parseProviderConfig(rawProvider string) ([]string, bool) {
8372 animepaheDeclined := false
8473
8574 for _, part := range parts {
86 if normalizeProviderConfigToken(part) == animepaheOptOutProvider {
75 if isProviderOptOutToken(part) {
8776 animepaheDeclined = true
8877 continue
8978 }
@@ -112,14 +101,14 @@ func parseProviderConfig(rawProvider string) ([]string, bool) {
112101 }
113102
114103 if len(providers) == 0 {
115 providers = []string{"allanime"}
104 providers = []string{firstEnabledProviderName()}
116105 }
117106
118107 return providers, animepaheDeclined
119108}
120109
121110func configuredProviderNames(config *CurdConfig) []string {
122 rawProvider := "allanime"
111 rawProvider := firstEnabledProviderName()
123112 if config != nil && strings.TrimSpace(config.Provider) != "" {
124113 rawProvider = config.Provider
125114 }
@@ -143,11 +132,38 @@ func formatProviderConfigValue(names []string, animepaheDeclined bool) string {
143132 quotedNames = append(quotedNames, fmt.Sprintf("%q", name))
144133 }
145134 if animepaheDeclined {
146 quotedNames = append(quotedNames, fmt.Sprintf("%q", animepaheOptOutProvider))
135 if token := providerOptOutTokenForName("animepahe"); token != "" {
136 quotedNames = append(quotedNames, fmt.Sprintf("%q", token))
137 }
147138 }
148139 return "[" + strings.Join(quotedNames, ",") + "]"
149140}
150141
142func isProviderOptOutToken(token string) bool {
143 token = normalizeProviderConfigToken(token)
144 if token == "" {
145 return false
146 }
147 for _, name := range providers.RegisteredNames() {
148 meta, ok := providers.MetaFor(name)
149 if !ok || meta.OptOutToken == "" {
150 continue
151 }
152 if token == normalizeProviderConfigToken(meta.OptOutToken) {
153 return true
154 }
155 }
156 return false
157}
158
159func providerOptOutTokenForName(providerName string) string {
160 meta, ok := providers.MetaFor(providerName)
161 if !ok {
162 return ""
163 }
164 return meta.OptOutToken
165}
166
151167func animepaheDeclinedInConfig(config *CurdConfig) bool {
152168 if config == nil {
153169 return false
@@ -174,11 +190,11 @@ func ProviderByName(providerName string) (Provider, error) {
174190 if reason := providerDisabledReason(providerName); reason != "" {
175191 return nil, fmt.Errorf("provider %q is disabled: %s", providerName, reason)
176192 }
177 factory, ok := providerFactories[providerName]
178 if !ok {
179 return nil, fmt.Errorf("unknown provider %q", providerName)
193 provider, err := providers.New(providerName)
194 if err != nil {
195 return nil, err
180196 }
181 return factory(), nil
197 return wrapProvider(provider), nil
182198}
183199
184200func GetProvider() Provider {
@@ -190,8 +206,11 @@ func GetProvider() Provider {
190206 primaryProviderName := providerNames[0]
191207 provider, err := ProviderByName(primaryProviderName)
192208 if err != nil {
193 CurrentProvider = &AllanimeProvider{}
194 return CurrentProvider
209 if fallback, fallbackErr := ProviderByName(firstEnabledProviderName()); fallbackErr == nil {
210 CurrentProvider = fallback
211 return CurrentProvider
212 }
213 return provider
195214 }
196215 CurrentProvider = provider
197216 return CurrentProvider
@@ -280,7 +299,7 @@ func providerNamesForAnime(config *CurdConfig, anime *Anime) []string {
280299 }
281300 }
282301 if len(result) == 0 {
283 return []string{"allanime"}
302 return []string{firstEnabledProviderName()}
284303 }
285304 return result
286305}
@@ -425,7 +444,7 @@ func appendProviderName(providerNames []string, providerName string) []string {
425444 }
426445 }
427446 if len(result) == 0 {
428 return []string{"allanime"}
447 return []string{firstEnabledProviderName()}
429448 }
430449 return result
431450}
@@ -635,7 +654,7 @@ func episodeModeResult(config CurdConfig, anime *Anime, epNo int, mode string) (
635654func episodeModeResultWithProviders(config CurdConfig, anime *Anime, epNo int, mode string, providerNames []string) (ProviderEpisodeResult, error) {
636655 mode = normalizeTranslationType(mode)
637656 if len(providerNames) == 0 {
638 providerNames = []string{"allanime"}
657 providerNames = []string{firstEnabledProviderName()}
639658 }
640659
641660 var errors []string
@@ -832,7 +851,7 @@ func scoreProviderSearchOption(option SelectionOption, anime *Anime, query strin
832851 if anime.TotalEpisodes > 0 && strings.Contains(option.Label, fmt.Sprintf("(%d episodes)", anime.TotalEpisodes)) {
833852 score += 20
834853 }
835 if item, ok := option.ExtraData.(AnimepaheSearchItem); ok && anime.TotalEpisodes > 0 && item.Episodes == anime.TotalEpisodes {
854 if item, ok := option.ExtraData.(animepahe.SearchItem); ok && anime.TotalEpisodes > 0 && item.Episodes == anime.TotalEpisodes {
836855 score += 20
837856 }
838857 return score
internal/provider_allanime.go deleted −28
@@ -1,28 +0,0 @@
1package internal
2
3type AllanimeProvider struct{}
4
5func (p *AllanimeProvider) Name() string {
6 return "allanime"
7}
8
9func (p *AllanimeProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
10 return searchAllAnime(query, mode)
11}
12
13func (p *AllanimeProvider) EpisodesList(showID, mode string) ([]string, error) {
14 return getAllAnimeEpisodesList(showID, mode)
15}
16
17func (p *AllanimeProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
18 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub)
19}
20
21func (p *AllanimeProvider) GetEpisodeURLForMode(config CurdConfig, id string, epNo int, mode string) ([]string, error) {
22 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, mode)
23 return links, err
24}
25
26func (p *AllanimeProvider) GetEpisodeURLForModeWithHints(config CurdConfig, id string, epNo int, mode string) ([]string, map[string]StreamPlaybackHint, error) {
27 return getAllanimeEpisodeStreamsForMode(id, mode, epNo)
28}
internal/provider_bridge.go added +181
@@ -0,0 +1,181 @@
1package internal
2
3import (
4 "net/http"
5
6 _ "github.com/wraient/curd/internal/loadproviders"
7
8 "github.com/wraient/curd/internal/curdhost"
9 "github.com/wraient/curd/internal/providers"
10)
11
12func init() {
13 curdhost.HTTPClient = func() *http.Client { return sharedHTTPClient }
14 curdhost.Log = func(msg string) { _ = Log(msg) }
15 curdhost.Out = func(msg string) { CurdOut(msg) }
16 curdhost.PromptSelect = func(options []curdhost.PromptOption) (curdhost.PromptOption, error) {
17 mapped := make([]SelectionOption, 0, len(options))
18 for _, option := range options {
19 mapped = append(mapped, SelectionOption{
20 Key: option.Key,
21 Label: option.Label,
22 })
23 }
24 selected, err := promptSelect(mapped)
25 if err != nil {
26 return curdhost.PromptOption{}, err
27 }
28 return curdhost.PromptOption{Key: selected.Key, Label: selected.Label}, nil
29 }
30 curdhost.PersistSubStylePreference = persistSubStylePreference
31 curdhost.CurrentSubStyle = func() string {
32 if cfg := GetGlobalConfig(); cfg != nil {
33 return cfg.SubStyle
34 }
35 return ""
36 }
37 curdhost.StoragePath = GetStoragePath
38 curdhost.AnimeNameLanguage = func() string {
39 if cfg := GetGlobalConfig(); cfg != nil {
40 return cfg.AnimeNameLanguage
41 }
42 return "english"
43 }
44 curdhost.SetCookiesForAnimepahe = SetCookiesForAnimepahe
45}
46
47func normalizeTranslationType(mode string) string {
48 return providers.NormalizeTranslationType(mode)
49}
50
51func alternateTranslationType(mode string) string {
52 return providers.AlternateTranslationType(mode)
53}
54
55func toInternalSelectionOptions(options []providers.SelectionOption) []SelectionOption {
56 if len(options) == 0 {
57 return nil
58 }
59 result := make([]SelectionOption, 0, len(options))
60 for _, option := range options {
61 result = append(result, SelectionOption{
62 Key: option.Key,
63 Label: option.Label,
64 Title: option.Title,
65 Thumbnail: option.Thumbnail,
66 ExtraData: option.ExtraData,
67 })
68 }
69 return result
70}
71
72func toProviderSelectionOptions(options []SelectionOption) []providers.SelectionOption {
73 if len(options) == 0 {
74 return nil
75 }
76 result := make([]providers.SelectionOption, 0, len(options))
77 for _, option := range options {
78 result = append(result, providers.SelectionOption{
79 Key: option.Key,
80 Label: option.Label,
81 Title: option.Title,
82 Thumbnail: option.Thumbnail,
83 ExtraData: option.ExtraData,
84 })
85 }
86 return result
87}
88
89func toPlaybackConfig(config CurdConfig) providers.PlaybackConfig {
90 return providers.PlaybackConfig{
91 SubOrDub: config.SubOrDub,
92 SubStyle: config.SubStyle,
93 }
94}
95
96func fromStreamHints(hints map[string]providers.StreamPlaybackHint) map[string]StreamPlaybackHint {
97 if len(hints) == 0 {
98 return nil
99 }
100 result := make(map[string]StreamPlaybackHint, len(hints))
101 for key, hint := range hints {
102 result[key] = StreamPlaybackHint{
103 Referrer: hint.Referrer,
104 Subtitle: hint.Subtitle,
105 }
106 }
107 return result
108}
109
110type providerAdapter struct {
111 inner providers.Provider
112}
113
114func (a *providerAdapter) Name() string {
115 return a.inner.Name()
116}
117
118func (a *providerAdapter) SearchAnime(query, mode string) ([]SelectionOption, error) {
119 options, err := a.inner.SearchAnime(query, mode)
120 return toInternalSelectionOptions(options), err
121}
122
123func (a *providerAdapter) EpisodesList(showID, mode string) ([]string, error) {
124 return a.inner.EpisodesList(showID, mode)
125}
126
127func (a *providerAdapter) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
128 return a.inner.GetEpisodeURL(toPlaybackConfig(config), id, epNo)
129}
130
131func (a *providerAdapter) GetEpisodeURLForMode(config CurdConfig, id string, epNo int, mode string) ([]string, error) {
132 if resolver, ok := a.inner.(providers.ModeResolver); ok {
133 return resolver.GetEpisodeURLForMode(toPlaybackConfig(config), id, epNo, mode)
134 }
135 return a.inner.GetEpisodeURL(toPlaybackConfig(config), id, epNo)
136}
137
138func (a *providerAdapter) GetEpisodeURLForModeWithHints(config CurdConfig, id string, epNo int, mode string) ([]string, map[string]StreamPlaybackHint, error) {
139 if resolver, ok := a.inner.(providers.HintResolver); ok {
140 links, hints, err := resolver.GetEpisodeURLForModeWithHints(toPlaybackConfig(config), id, epNo, mode)
141 return links, fromStreamHints(hints), err
142 }
143 links, err := a.GetEpisodeURLForMode(config, id, epNo, mode)
144 return links, nil, err
145}
146
147func resolveProviderID(provider Provider, providerID, query string) (string, error) {
148 inner := unwrapProvider(provider)
149 if inner == nil {
150 return providerID, nil
151 }
152 if resolver, ok := inner.(providers.IDResolver); ok {
153 return resolver.ResolveProviderID(providerID, query)
154 }
155 return providerID, nil
156}
157
158func wrapProvider(provider providers.Provider) Provider {
159 return &providerAdapter{inner: provider}
160}
161
162func unwrapProvider(provider Provider) providers.Provider {
163 if adapter, ok := provider.(*providerAdapter); ok {
164 return adapter.inner
165 }
166 return nil
167}
168
169func applyStreamPlaybackHints(anime *Anime, links []string, hints map[string]StreamPlaybackHint) {
170 if anime == nil || len(links) == 0 {
171 return
172 }
173 selected := PrioritizeLink(links)
174 if hint, ok := hints[selected]; ok {
175 anime.Ep.StreamReferrer = hint.Referrer
176 anime.Ep.SubtitleURL = hint.Subtitle
177 return
178 }
179 anime.Ep.StreamReferrer = ""
180 anime.Ep.SubtitleURL = ""
181}
internal/provider_disabled.go +82 −13
@@ -2,14 +2,11 @@ package internal
22
33import (
44 "sort"
5 "strings"
56 "testing"
6)
77
8// disabledProviders lists providers kept in source but excluded from runtime use.
9// Remove a provider from this map to re-enable it without restoring deleted code.
10var disabledProviders = map[string]string{
11 "animepahe": "Cloudflare/DDoS-Guard protection cannot be bypassed reliably",
12}
8 "github.com/wraient/curd/internal/providers"
9)
1310
1411var disabledProviderReasonForTest func(string) string
1512
@@ -21,7 +18,56 @@ func providerDisabledReason(name string) string {
2118 if disabledProviderReasonForTest != nil {
2219 return disabledProviderReasonForTest(name)
2320 }
24 return disabledProviders[name]
21 if reason := configDisabledProviderReason(name); reason != "" {
22 return reason
23 }
24 meta, ok := providers.MetaFor(name)
25 if !ok {
26 return ""
27 }
28 if meta.DefaultDisabled {
29 return meta.DisableReason
30 }
31 return ""
32}
33
34func configDisabledProviderReason(name string) string {
35 config := GetGlobalConfig()
36 if config == nil {
37 return ""
38 }
39 for _, disabledName := range parseDisabledProviderNames(config.DisabledProviders) {
40 if disabledName == name {
41 if meta, ok := providers.MetaFor(name); ok && meta.DisableReason != "" {
42 return meta.DisableReason
43 }
44 return "disabled in config"
45 }
46 }
47 return ""
48}
49
50func parseDisabledProviderNames(raw string) []string {
51 parts := parseStringArray(raw)
52 if len(parts) == 0 {
53 parts = strings.FieldsFunc(raw, func(r rune) bool {
54 return r == ',' || r == '+' || r == '|' || r == ';'
55 })
56 }
57 names := make([]string, 0, len(parts))
58 seen := make(map[string]struct{})
59 for _, part := range parts {
60 name := normalizeProviderName(part)
61 if name == "" {
62 continue
63 }
64 if _, exists := seen[name]; exists {
65 continue
66 }
67 seen[name] = struct{}{}
68 names = append(names, name)
69 }
70 return names
2571}
2672
2773// ProviderEnabled reports whether a provider may be used at runtime.
@@ -55,11 +101,7 @@ func filterEnabledProviders(names []string) []string {
55101}
56102
57103func defaultEnabledProviderStack() []string {
58 names := make([]string, 0, len(providerFactories))
59 for name := range providerFactories {
60 names = append(names, name)
61 }
62 sort.Strings(names)
104 names := providers.RegisteredNames()
63105 return filterEnabledProviders(names)
64106}
65107
@@ -87,12 +129,32 @@ func providerSelectionOptions() []SelectionOption {
87129 return options
88130}
89131
132func firstEnabledProviderName() string {
133 enabled := defaultEnabledProviderStack()
134 if len(enabled) > 0 {
135 return enabled[0]
136 }
137 return "anineko"
138}
139
90140func ensureEnabledProviderNames(names []string) []string {
91141 enabled := filterEnabledProviders(names)
92142 if len(enabled) > 0 {
93143 return enabled
94144 }
95 return []string{"allanime"}
145 fallback := filterEnabledProviders([]string{firstEnabledProviderName()})
146 if len(fallback) > 0 {
147 return fallback
148 }
149 if registered := providers.RegisteredNames(); len(registered) > 0 {
150 for _, name := range registered {
151 if ProviderEnabled(name) {
152 return []string{name}
153 }
154 }
155 return []string{registered[0]}
156 }
157 return []string{firstEnabledProviderName()}
96158}
97159
98160func withAllProvidersEnabledForTest(t *testing.T) {
@@ -103,3 +165,10 @@ func withAllProvidersEnabledForTest(t *testing.T) {
103165 disabledProviderReasonForTest = previous
104166 })
105167}
168
169// RegisteredProviderNames returns sorted registered provider names.
170func RegisteredProviderNames() []string {
171 names := providers.RegisteredNames()
172 sort.Strings(names)
173 return names
174}
internal/provider_disabled_test.go +27 −16
@@ -2,12 +2,18 @@ package internal
22
33import "testing"
44
5func TestProviderEnabledDisablesAnimepaheByDefault(t *testing.T) {
6 if ProviderEnabled("allanime") != true {
7 t.Fatal("expected allanime to stay enabled")
5func TestProviderEnabledDisablesAllanimeAndAnimepaheByDefault(t *testing.T) {
6 if ProviderEnabled("allanime") != false {
7 t.Fatal("expected allanime to be disabled by default")
88 }
99 if ProviderEnabled("animepahe") != false {
10 t.Fatal("expected animepahe to be disabled")
10 t.Fatal("expected animepahe to be disabled by default")
11 }
12 if ProviderEnabled("anineko") != true {
13 t.Fatal("expected anineko to stay enabled")
14 }
15 if reason := ProviderDisabledReason("allanime"); reason == "" {
16 t.Fatal("expected allanime disable reason")
1117 }
1218 if reason := ProviderDisabledReason("animepahe"); reason == "" {
1319 t.Fatal("expected animepahe disable reason")
@@ -20,10 +26,11 @@ func TestConfiguredProviderNamesFiltersDisabledProviders(t *testing.T) {
2026 cfg *CurdConfig
2127 want []string
2228 }{
23 {name: "empty", cfg: &CurdConfig{}, want: []string{"allanime"}},
24 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"allanime"}},
25 {name: "animepahe only", cfg: &CurdConfig{Provider: `["animepahe"]`}, want: []string{"allanime"}},
26 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"allanime"}},
29 {name: "empty", cfg: &CurdConfig{}, want: []string{"anineko"}},
30 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"anineko"}},
31 {name: "animepahe only", cfg: &CurdConfig{Provider: `["animepahe"]`}, want: []string{"anineko"}},
32 {name: "allanime only", cfg: &CurdConfig{Provider: `["allanime"]`}, want: []string{"anineko"}},
33 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"anineko"}},
2734 }
2835
2936 for _, tc := range cases {
@@ -50,19 +57,23 @@ func TestConfiguredProviderNamesHonorsEnabledProvidersWhenOverridden(t *testing.
5057}
5158
5259func TestProviderByNameRejectsDisabledProvider(t *testing.T) {
53 if _, err := ProviderByName("animepahe"); err == nil {
54 t.Fatal("expected disabled provider error")
60 for _, name := range []string{"animepahe", "allanime"} {
61 if _, err := ProviderByName(name); err == nil {
62 t.Fatalf("expected disabled provider error for %s", name)
63 }
5564 }
5665}
5766
5867func TestProviderByNameAllowsDisabledProviderWhenOverridden(t *testing.T) {
5968 withAllProvidersEnabledForTest(t)
6069
61 provider, err := ProviderByName("animepahe")
62 if err != nil {
63 t.Fatalf("expected animepahe provider: %v", err)
64 }
65 if provider.Name() != "animepahe" {
66 t.Fatalf("got provider %q", provider.Name())
70 for _, name := range []string{"animepahe", "allanime"} {
71 provider, err := ProviderByName(name)
72 if err != nil {
73 t.Fatalf("expected %s provider: %v", name, err)
74 }
75 if provider.Name() != name {
76 t.Fatalf("got provider %q", provider.Name())
77 }
6778 }
6879}
internal/provider_stack_test.go +35 −10
@@ -6,6 +6,8 @@ import (
66 "path/filepath"
77 "strings"
88 "testing"
9
10 "github.com/wraient/curd/internal/providers"
911)
1012
1113type stackStubProvider struct {
@@ -47,21 +49,44 @@ func (s *stackStubProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
4749 return nil, nil
4850}
4951
50func withProviderFactories(t *testing.T, providers ...*stackStubProvider) {
52func withProviderFactories(t *testing.T, stubs ...*stackStubProvider) {
5153 t.Helper()
5254 withAllProvidersEnabledForTest(t)
53 previousAllanime := providerFactories["allanime"]
54 previousAnimepahe := providerFactories["animepahe"]
55 for _, provider := range providers {
56 provider := provider
57 providerFactories[provider.name] = func() Provider { return provider }
55 restores := make([]func(), 0, len(stubs))
56 for _, stub := range stubs {
57 stub := stub
58 restores = append(restores, providers.SetFactoryForTest(stub.name, func() providers.Provider {
59 return &stackStubProviderBridge{stub}
60 }))
5861 }
5962 t.Cleanup(func() {
60 providerFactories["allanime"] = previousAllanime
61 providerFactories["animepahe"] = previousAnimepahe
63 for i := len(restores) - 1; i >= 0; i-- {
64 restores[i]()
65 }
6266 })
6367}
6468
69type stackStubProviderBridge struct {
70 *stackStubProvider
71}
72
73func (s *stackStubProviderBridge) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
74 options, err := s.stackStubProvider.SearchAnime(query, mode)
75 return toProviderSelectionOptions(options), err
76}
77
78func (s *stackStubProviderBridge) EpisodesList(showID, mode string) ([]string, error) {
79 return s.stackStubProvider.EpisodesList(showID, mode)
80}
81
82func (s *stackStubProviderBridge) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
83 return s.stackStubProvider.GetEpisodeURL(CurdConfig{SubOrDub: config.SubOrDub}, id, epNo)
84}
85
86func (s *stackStubProviderBridge) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
87 return s.stackStubProvider.GetEpisodeURLForMode(CurdConfig{SubOrDub: config.SubOrDub}, id, epNo, mode)
88}
89
6590func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) {
6691 withAllProvidersEnabledForTest(t)
6792
@@ -74,7 +99,7 @@ func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) {
7499 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"allanime", "animepahe"}},
75100 {name: "comma list", cfg: &CurdConfig{Provider: "animepahe,allanime"}, want: []string{"animepahe", "allanime"}},
76101 {name: "plus list", cfg: &CurdConfig{Provider: "allanime+animepahe"}, want: []string{"allanime", "animepahe"}},
77 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"allanime", "animepahe"}},
102 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"allanime", "animepahe", "anineko"}},
78103 }
79104
80105 for _, tc := range cases {
@@ -100,7 +125,7 @@ func TestCanonicalProviderConfigValueMigratesLegacyValuesWithoutAddingAnimepahe(
100125 {name: "legacy animepahe", raw: "animepahe", want: `["animepahe"]`},
101126 {name: "ordered stack", raw: "animepahe,allanime", want: `["animepahe","allanime"]`},
102127 {name: "animepahe opt out", raw: "allanime,no-animepahe", want: `["allanime","no-animepahe"]`},
103 {name: "empty default", raw: "", want: `["allanime"]`},
128 {name: "empty default", raw: "", want: `["anineko"]`},
104129 }
105130
106131 for _, tc := range cases {
internal/episode_list.go → internal/providers/allanime/episodes.go renamed +11 −8
@@ -1,4 +1,4 @@
1package internal
1package allanime
22
33import (
44 "bytes"
@@ -8,6 +8,9 @@ import (
88 "net/http"
99 "sort"
1010 "strconv"
11
12 "github.com/wraient/curd/internal/curdhost"
13 "github.com/wraient/curd/internal/providers"
1114)
1215
1316type episodesResponse struct {
@@ -33,7 +36,7 @@ type episodesResponse struct {
3336
3437// episodesList performs the API call and fetches the episodes list
3538func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
36 preferredMode := normalizeTranslationType(mode)
39 preferredMode := providers.NormalizeTranslationType(mode)
3740
3841 episodesListGql := `query ($showId: String!) { show( _id: $showId ) { _id availableEpisodesDetail }}`
3942
@@ -56,27 +59,27 @@ func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
5659 req.Header.Set("Referer", "https://allanime.to")
5760 req.Header.Set("Origin", "https://allanime.to")
5861
59 resp, err := sharedHTTPClient.Do(req)
62 resp, err := curdhost.HTTPClient().Do(req)
6063 if err != nil {
61 Log(fmt.Sprint("Error making HTTP request:", err))
64 curdhost.Log(fmt.Sprint("Error making HTTP request:", err))
6265 return nil, err
6366 }
6467 defer resp.Body.Close()
6568
6669 body, err := io.ReadAll(resp.Body)
6770 if err != nil {
68 Log(fmt.Sprint("Error reading response body:", err))
71 curdhost.Log(fmt.Sprint("Error reading response body:", err))
6972 return nil, err
7073 }
71 if !httpStatusOK(resp.StatusCode) {
72 return nil, httpStatusError("allanime episode list", resp.StatusCode, body)
74 if !curdhost.HTTPStatusOK(resp.StatusCode) {
75 return nil, curdhost.HTTPStatusError("allanime episode list", resp.StatusCode, body)
7376 }
7477
7578 // Parse the JSON response
7679 var response episodesResponse
7780 err = json.Unmarshal(body, &response)
7881 if err != nil {
79 Log(fmt.Sprint("Error parsing JSON:", err))
82 curdhost.Log(fmt.Sprint("Error parsing JSON:", err))
8083 return nil, err
8184 }
8285
internal/providers/allanime/provider.go added +33
@@ -0,0 +1,33 @@
1package allanime
2
3import (
4 "github.com/wraient/curd/internal/providers"
5)
6
7// Provider implements AllAnime catalog search and stream resolution.
8type Provider struct{}
9
10func (p *Provider) Name() string {
11 return "allanime"
12}
13
14func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
15 return searchAllAnime(query, mode)
16}
17
18func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
19 return getAllAnimeEpisodesList(showID, mode)
20}
21
22func (p *Provider) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
23 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub)
24}
25
26func (p *Provider) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
27 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, mode)
28 return links, err
29}
30
31func (p *Provider) GetEpisodeURLForModeWithHints(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, map[string]providers.StreamPlaybackHint, error) {
32 return getAllanimeEpisodeStreamsForMode(id, mode, epNo)
33}
internal/providers/allanime/register.go added +15
@@ -0,0 +1,15 @@
1package allanime
2
3import "github.com/wraient/curd/internal/providers"
4
5func init() {
6 providers.Register(providers.Meta{
7 Name: "allanime",
8 Aliases: []string{"all-anime", "all anime"},
9 Referrer: "https://allanime.day/",
10 DefaultDisabled: true,
11 DisableReason: "disabled by default; set Provider to include allanime to enable",
12 }, func() providers.Provider {
13 return &Provider{}
14 })
15}
internal/anime_list.go → internal/providers/allanime/search.go renamed +23 −38
@@ -1,4 +1,4 @@
1package internal
1package allanime
22
33import (
44 "bytes"
@@ -6,8 +6,9 @@ import (
66 "fmt"
77 "io"
88 "net/http"
9 "path/filepath"
10 "strings"
9
10 "github.com/wraient/curd/internal/curdhost"
11 "github.com/wraient/curd/internal/providers"
1112)
1213
1314type anime struct {
@@ -26,20 +27,6 @@ type response struct {
2627 } `json:"data"`
2728}
2829
29func normalizeTranslationType(mode string) string {
30 if strings.EqualFold(strings.TrimSpace(mode), "dub") {
31 return "dub"
32 }
33 return "sub"
34}
35
36func alternateTranslationType(mode string) string {
37 if normalizeTranslationType(mode) == "dub" {
38 return "sub"
39 }
40 return "dub"
41}
42
4330// func main() {
4431// // Get environment variables
4532// mode := "sub"
@@ -55,14 +42,12 @@ func alternateTranslationType(mode string) string {
5542// fmt.Println(animeList)
5643// }
5744
58func searchAllAnime(query, mode string) ([]SelectionOption, error) {
59 preferredMode := normalizeTranslationType(mode)
45func searchAllAnime(query, mode string) ([]providers.SelectionOption, error) {
46 preferredMode := providers.NormalizeTranslationType(mode)
6047 return searchAnimeByMode(query, preferredMode, preferredMode)
6148}
6249
63func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, error) {
64 userCurdConfig := GetGlobalConfig()
65 logFile = filepath.Join(GetStoragePath(), "debug.log")
50func searchAnimeByMode(query, mode, preferredMode string) ([]providers.SelectionOption, error) {
6651 const (
6752 agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
6853 allanimeRef = "https://allanime.to"
@@ -70,10 +55,10 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
7055 allanimeAPI = "https://api." + allanimeBase + "/api"
7156 )
7257
73 mode = normalizeTranslationType(mode)
74 preferredMode = normalizeTranslationType(preferredMode)
58 mode = providers.NormalizeTranslationType(mode)
59 preferredMode = providers.NormalizeTranslationType(preferredMode)
7560
76 animeList := make([]SelectionOption, 0)
61 animeList := make([]providers.SelectionOption, 0)
7762
7863 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) {
7964 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) {
@@ -107,14 +92,14 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
10792 "variables": variables,
10893 })
10994 if err != nil {
110 Log(fmt.Sprintf("Error encoding request body to JSON: %v", err))
95 curdhost.Log(fmt.Sprintf("Error encoding request body to JSON: %v", err))
11196 return animeList, err
11297 }
11398
11499 // Make the HTTP POST request
115100 req, err := http.NewRequest("POST", allanimeAPI, bytes.NewBuffer(requestBody))
116101 if err != nil {
117 Log(fmt.Sprintf("Error creating HTTP request: %v", err))
102 curdhost.Log(fmt.Sprintf("Error creating HTTP request: %v", err))
118103 return animeList, err
119104 }
120105 req.Header.Set("Content-Type", "application/json")
@@ -122,9 +107,9 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
122107 req.Header.Set("Referer", allanimeRef)
123108 req.Header.Set("Origin", allanimeRef)
124109
125 resp, err := sharedHTTPClient.Do(req)
110 resp, err := curdhost.HTTPClient().Do(req)
126111 if err != nil {
127 Log(fmt.Sprintf("Error making HTTP request: %v", err))
112 curdhost.Log(fmt.Sprintf("Error making HTTP request: %v", err))
128113 return animeList, err
129114 }
130115 defer resp.Body.Close()
@@ -132,16 +117,16 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
132117 // Read the response body
133118 body, err := io.ReadAll(resp.Body)
134119 if err != nil {
135 Log(fmt.Sprintf("Error reading response body: %v", err))
120 curdhost.Log(fmt.Sprintf("Error reading response body: %v", err))
136121 return animeList, err
137122 }
138123
139124 // Debug: Log the response status and first part of the body
140 Log(fmt.Sprintf("Response Status: %s", resp.Status))
141 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
142 if !httpStatusOK(resp.StatusCode) {
143 err := httpStatusError("allanime search", resp.StatusCode, body)
144 Log(err)
125 curdhost.Log(fmt.Sprintf("Response Status: %s", resp.Status))
126 curdhost.Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
127 if !curdhost.HTTPStatusOK(resp.StatusCode) {
128 err := curdhost.HTTPStatusError("allanime search", resp.StatusCode, body)
129 curdhost.Log(err.Error())
145130 return animeList, err
146131 }
147132
@@ -149,7 +134,7 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
149134 var response response
150135 err = json.Unmarshal(body, &response)
151136 if err != nil {
152 Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)))
137 curdhost.Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)))
153138 return animeList, err
154139 }
155140
@@ -167,7 +152,7 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
167152
168153 // Use English name if available and configured, otherwise use default name
169154 displayName := anime.Name
170 if anime.EnglishName != "" && userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" {
155 if anime.EnglishName != "" && curdhost.AnimeNameLanguage != nil && curdhost.AnimeNameLanguage() == "english" {
171156 displayName = anime.EnglishName
172157 }
173158
@@ -176,7 +161,7 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
176161 label = fmt.Sprintf("%s [%s]", label, mode)
177162 }
178163
179 animeList = append(animeList, SelectionOption{
164 animeList = append(animeList, providers.SelectionOption{
180165 Title: displayName,
181166 Key: anime.ID,
182167 Label: label,
internal/episode_url_anicli.go → internal/providers/allanime/streams.go renamed +18 −35
@@ -1,4 +1,4 @@
1package internal
1package allanime
22
33import (
44 "encoding/json"
@@ -12,16 +12,13 @@ import (
1212 "strings"
1313 "sync"
1414 "time"
15
16 "github.com/wraient/curd/internal/curdhost"
17 "github.com/wraient/curd/internal/providers"
1518)
1619
1720const allanimeUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
1821
19// StreamPlaybackHint carries MPV playback metadata extracted from AllAnime clock.json.
20type StreamPlaybackHint struct {
21 Referrer string
22 Subtitle string
23}
24
2522type allanimeResolvedStream struct {
2623 URL string
2724 Referrer string
@@ -36,7 +33,7 @@ var (
3633 allanimeStreamBandwidthPattern = regexp.MustCompile(`BANDWIDTH=(\d+)`)
3734)
3835
39func getAllanimeEpisodeStreamsForMode(id, mode string, epNo int) ([]string, map[string]StreamPlaybackHint, error) {
36func getAllanimeEpisodeStreamsForMode(id, mode string, epNo int) ([]string, map[string]providers.StreamPlaybackHint, error) {
4037 sourceUrls, err := fetchEpisodeSourcesForMode(id, mode, epNo)
4138 if err != nil {
4239 return nil, nil, err
@@ -44,7 +41,7 @@ func getAllanimeEpisodeStreamsForMode(id, mode string, epNo int) ([]string, map[
4441 return getLinksFromEncodedSourceUrls(sourceUrls)
4542}
4643
47func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[string]StreamPlaybackHint, error) {
44func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[string]providers.StreamPlaybackHint, error) {
4845 type providerJob struct {
4946 index int
5047 name string
@@ -84,7 +81,7 @@ func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[s
8481 go func(idx int, providerName, encodedURL string) {
8582 defer wg.Done()
8683 decodedProviderID := decodeProviderID(encodedURL[2:])
87 Log(fmt.Sprintf("Fetching Allanime provider %s via %s", providerName, decodedProviderID))
84 curdhost.Log(fmt.Sprintf("Fetching Allanime provider %s via %s", providerName, decodedProviderID))
8885 streams, err := resolveAllanimeClockProvider(providerName, decodedProviderID)
8986 results <- streamResult{index: idx, streams: streams, err: err}
9087 }(job.index, job.name, job.url)
@@ -108,14 +105,14 @@ func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[s
108105 }
109106 completedCount++
110107 if res.err != nil {
111 Log(fmt.Sprintf("Allanime provider %s failed: %v", jobs[res.index].name, res.err))
108 curdhost.Log(fmt.Sprintf("Allanime provider %s failed: %v", jobs[res.index].name, res.err))
112109 collectedErrors = append(collectedErrors, fmt.Errorf("%s: %w", jobs[res.index].name, res.err))
113110 continue
114111 }
115112 if len(res.streams) > 0 {
116113 orderedStreams[res.index] = res.streams
117114 successCount++
118 Log(fmt.Sprintf("Allanime provider %s returned %d stream(s)", jobs[res.index].name, len(res.streams)))
115 curdhost.Log(fmt.Sprintf("Allanime provider %s returned %d stream(s)", jobs[res.index].name, len(res.streams)))
119116 }
120117 case <-timeout:
121118 if successCount > 0 {
@@ -131,7 +128,7 @@ func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[s
131128 return buildAllanimeLinkResult(orderedStreams)
132129}
133130
134func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]string, map[string]StreamPlaybackHint, error) {
131func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]string, map[string]providers.StreamPlaybackHint, error) {
135132 allStreams := make([]allanimeResolvedStream, 0)
136133 for _, streams := range orderedStreams {
137134 allStreams = append(allStreams, streams...)
@@ -141,7 +138,7 @@ func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]strin
141138 })
142139
143140 links := make([]string, 0, len(allStreams))
144 hints := make(map[string]StreamPlaybackHint)
141 hints := make(map[string]providers.StreamPlaybackHint)
145142 seen := make(map[string]struct{})
146143 for _, stream := range allStreams {
147144 if stream.URL == "" || isUnreliableAllanimeDirectURL(stream.URL) {
@@ -156,7 +153,7 @@ func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]strin
156153 if referrer == "" {
157154 referrer = allanimeGraphQLReferer
158155 }
159 hints[stream.URL] = StreamPlaybackHint{
156 hints[stream.URL] = providers.StreamPlaybackHint{
160157 Referrer: referrer,
161158 Subtitle: stream.SubtitleURL,
162159 }
@@ -242,7 +239,7 @@ func fetchAllanimeClockResponse(providerPath string) ([]byte, map[string]interfa
242239 req.Header.Set("Referer", allanimeGraphQLReferer)
243240 req.Header.Set("User-Agent", allanimeUserAgent)
244241
245 resp, err := sharedHTTPClient.Do(req)
242 resp, err := curdhost.HTTPClient().Do(req)
246243 if err != nil {
247244 return nil, nil, err
248245 }
@@ -252,8 +249,8 @@ func fetchAllanimeClockResponse(providerPath string) ([]byte, map[string]interfa
252249 if err != nil {
253250 return nil, nil, err
254251 }
255 if !httpStatusOK(resp.StatusCode) {
256 return nil, nil, httpStatusError("allanime source extractor", resp.StatusCode, body)
252 if !curdhost.HTTPStatusOK(resp.StatusCode) {
253 return nil, nil, curdhost.HTTPStatusError("allanime source extractor", resp.StatusCode, body)
257254 }
258255
259256 var videoData map[string]interface{}
@@ -303,7 +300,7 @@ func fetchAllanimeM3U8VariantStreams(masterURL, referrer, subtitleURL string) ([
303300 req.Header.Set("Referer", referrer)
304301 req.Header.Set("User-Agent", allanimeUserAgent)
305302
306 resp, err := sharedHTTPClient.Do(req)
303 resp, err := curdhost.HTTPClient().Do(req)
307304 if err != nil {
308305 return nil, err
309306 }
@@ -312,8 +309,8 @@ func fetchAllanimeM3U8VariantStreams(masterURL, referrer, subtitleURL string) ([
312309 if err != nil {
313310 return nil, err
314311 }
315 if !httpStatusOK(resp.StatusCode) {
316 return nil, httpStatusError("allanime m3u8 master playlist", resp.StatusCode, body)
312 if !curdhost.HTTPStatusOK(resp.StatusCode) {
313 return nil, curdhost.HTTPStatusError("allanime m3u8 master playlist", resp.StatusCode, body)
317314 }
318315
319316 playlist := string(body)
@@ -449,17 +446,3 @@ func streamsFromPlainURLs(urls []string, referrer, subtitleURL string, qualitySc
449446 }
450447 return streams
451448}
452
453func applyStreamPlaybackHints(anime *Anime, links []string, hints map[string]StreamPlaybackHint) {
454 if anime == nil || len(links) == 0 {
455 return
456 }
457 selected := PrioritizeLink(links)
458 if hint, ok := hints[selected]; ok {
459 anime.Ep.StreamReferrer = hint.Referrer
460 anime.Ep.SubtitleURL = hint.Subtitle
461 return
462 }
463 anime.Ep.StreamReferrer = ""
464 anime.Ep.SubtitleURL = ""
465}
internal/episode_url.go → internal/providers/allanime/streams_legacy.go renamed +31 −28
@@ -1,4 +1,4 @@
1package internal
1package allanime
22
33import (
44 "bytes"
@@ -17,6 +17,9 @@ import (
1717 "sort"
1818 "strconv"
1919 "strings"
20
21 "github.com/wraient/curd/internal/curdhost"
22 "github.com/wraient/curd/internal/providers"
2023)
2124
2225type allanimeSource struct {
@@ -231,13 +234,13 @@ func decodeBase64URLRaw(input string) ([]byte, error) {
231234func extractFilemoonLinks(videoData map[string]interface{}) []string {
232235 raw, err := json.Marshal(videoData)
233236 if err != nil {
234 Log(fmt.Sprintf("Error marshaling filemoon payload: %v", err))
237 curdhost.Log(fmt.Sprintf("Error marshaling filemoon payload: %v", err))
235238 return nil
236239 }
237240
238241 var payload filemoonResponse
239242 if err := json.Unmarshal(raw, &payload); err != nil {
240 Log(fmt.Sprintf("Error parsing filemoon payload: %v", err))
243 curdhost.Log(fmt.Sprintf("Error parsing filemoon payload: %v", err))
241244 return nil
242245 }
243246
@@ -247,30 +250,30 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
247250
248251 keyPart1, err := decodeBase64URLRaw(payload.KeyParts[0])
249252 if err != nil {
250 Log(fmt.Sprintf("Error decoding filemoon key part 1: %v", err))
253 curdhost.Log(fmt.Sprintf("Error decoding filemoon key part 1: %v", err))
251254 return nil
252255 }
253256
254257 keyPart2, err := decodeBase64URLRaw(payload.KeyParts[1])
255258 if err != nil {
256 Log(fmt.Sprintf("Error decoding filemoon key part 2: %v", err))
259 curdhost.Log(fmt.Sprintf("Error decoding filemoon key part 2: %v", err))
257260 return nil
258261 }
259262
260263 iv, err := decodeBase64URLRaw(payload.IV)
261264 if err != nil {
262 Log(fmt.Sprintf("Error decoding filemoon IV: %v", err))
265 curdhost.Log(fmt.Sprintf("Error decoding filemoon IV: %v", err))
263266 return nil
264267 }
265268
266269 ciphertext, err := decodeBase64URLRaw(payload.Payload)
267270 if err != nil {
268 Log(fmt.Sprintf("Error decoding filemoon ciphertext: %v", err))
271 curdhost.Log(fmt.Sprintf("Error decoding filemoon ciphertext: %v", err))
269272 return nil
270273 }
271274
272275 if len(ciphertext) <= 16 {
273 Log("Filemoon ciphertext is too short")
276 curdhost.Log("Filemoon ciphertext is too short")
274277 return nil
275278 }
276279
@@ -280,25 +283,25 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
280283 keyHex := hex.EncodeToString(append(keyPart1, keyPart2...))
281284 key, err := hex.DecodeString(keyHex)
282285 if err != nil {
283 Log(fmt.Sprintf("Error decoding filemoon key hex: %v", err))
286 curdhost.Log(fmt.Sprintf("Error decoding filemoon key hex: %v", err))
284287 return nil
285288 }
286289
287290 ctrIVHex := hex.EncodeToString(iv) + "00000002"
288291 ctrIV, err := hex.DecodeString(ctrIVHex)
289292 if err != nil {
290 Log(fmt.Sprintf("Error decoding filemoon CTR IV: %v", err))
293 curdhost.Log(fmt.Sprintf("Error decoding filemoon CTR IV: %v", err))
291294 return nil
292295 }
293296
294297 if len(ctrIV) != aes.BlockSize {
295 Log(fmt.Sprintf("Invalid filemoon CTR IV size: %d", len(ctrIV)))
298 curdhost.Log(fmt.Sprintf("Invalid filemoon CTR IV size: %d", len(ctrIV)))
296299 return nil
297300 }
298301
299302 block, err := aes.NewCipher(key)
300303 if err != nil {
301 Log(fmt.Sprintf("Error creating filemoon cipher: %v", err))
304 curdhost.Log(fmt.Sprintf("Error creating filemoon cipher: %v", err))
302305 return nil
303306 }
304307
@@ -359,7 +362,7 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
359362 }
360363
361364 if len(links) > 0 {
362 Log("Filemoon links fetched")
365 curdhost.Log("Filemoon links fetched")
363366 }
364367
365368 return links
@@ -376,17 +379,17 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
376379// Returns:
377380// - []string: a list of links for specified episode.
378381// - error: an error if the episode is not found or if there is an issue during the search.
379func getAllanimeEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
380 preferredMode := normalizeTranslationType(config.SubOrDub)
382func getAllanimeEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
383 preferredMode := providers.NormalizeTranslationType(config.SubOrDub)
381384 return getAllanimeEpisodeURLForMode(id, preferredMode, epNo)
382385}
383386
384387func getAllanimeEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
385 return getEpisodeURLForMode(id, normalizeTranslationType(mode), epNo)
388 return getEpisodeURLForMode(id, providers.NormalizeTranslationType(mode), epNo)
386389}
387390
388391func fetchAllanimeEpisodeSources(id, mode string, epNo int) ([]allanimeSource, error) {
389 return fetchEpisodeSourcesForMode(id, normalizeTranslationType(mode), epNo)
392 return fetchEpisodeSourcesForMode(id, providers.NormalizeTranslationType(mode), epNo)
390393}
391394
392395func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, error) {
@@ -398,7 +401,7 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
398401
399402 variables := map[string]interface{}{
400403 "showId": id,
401 "translationType": normalizeTranslationType(mode),
404 "translationType": providers.NormalizeTranslationType(mode),
402405 "episodeString": fmt.Sprintf("%d", epNo),
403406 }
404407
@@ -429,7 +432,7 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
429432 req.Header.Set("Referer", allanimePersistedQueryReferer)
430433 req.Header.Set("Origin", allanimePersistedQueryReferer)
431434
432 resp, err := sharedHTTPClient.Do(req)
435 resp, err := curdhost.HTTPClient().Do(req)
433436 if err != nil {
434437 return nil, fmt.Errorf("failed to send persisted query request: %w", err)
435438 }
@@ -438,13 +441,13 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
438441 if err != nil {
439442 return nil, fmt.Errorf("failed to read persisted query response: %w", err)
440443 }
441 if !httpStatusOK(resp.StatusCode) {
442 return nil, httpStatusError("allanime episode persisted query", resp.StatusCode, body)
444 if !curdhost.HTTPStatusOK(resp.StatusCode) {
445 return nil, curdhost.HTTPStatusError("allanime episode persisted query", resp.StatusCode, body)
443446 }
444447
445448 var response allanimeResponse
446449 if err := json.Unmarshal(body, &response); err != nil {
447 Log(fmt.Sprint("Error parsing persisted query JSON: ", err))
450 curdhost.Log(fmt.Sprint("Error parsing persisted query JSON: ", err))
448451 }
449452
450453 useFallback := response.Data.Tobeparsed == "" && len(response.Data.Episode.SourceUrls) == 0
@@ -473,7 +476,7 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
473476 req.Header.Set("Referer", allanimeGraphQLReferer)
474477 req.Header.Set("Origin", allanimeGraphQLReferer)
475478
476 resp, err := sharedHTTPClient.Do(req)
479 resp, err := curdhost.HTTPClient().Do(req)
477480 if err != nil {
478481 return nil, fmt.Errorf("failed to send request: %w", err)
479482 }
@@ -483,24 +486,24 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
483486 if err != nil {
484487 return nil, fmt.Errorf("failed to read response body: %w", err)
485488 }
486 if !httpStatusOK(resp.StatusCode) {
487 return nil, httpStatusError("allanime episode fallback query", resp.StatusCode, body)
489 if !curdhost.HTTPStatusOK(resp.StatusCode) {
490 return nil, curdhost.HTTPStatusError("allanime episode fallback query", resp.StatusCode, body)
488491 }
489492
490493 if err := json.Unmarshal(body, &response); err != nil {
491 Log(fmt.Sprint("Error parsing fallback JSON: ", err))
494 curdhost.Log(fmt.Sprint("Error parsing fallback JSON: ", err))
492495 return nil, err
493496 }
494497 }
495498
496499 if response.Data.Tobeparsed != "" {
497 Log("Found tobeparsed field, decoding source URLs")
500 curdhost.Log("Found tobeparsed field, decoding source URLs")
498501 decodedSources, err := decodeTobeparsed(response.Data.Tobeparsed)
499502 if err != nil {
500503 return nil, err
501504 }
502505
503 Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources)))
506 curdhost.Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources)))
504507 return decodedSources, nil
505508 }
506509
internal/episode_url_test.go → internal/providers/allanime/streams_test.go renamed +1 −1
@@ -1,4 +1,4 @@
1package internal
1package allanime
22
33import (
44 "strings"
internal/provider_animepahe.go → internal/providers/animepahe/provider.go renamed +69 −58
@@ -1,4 +1,4 @@
1package internal
1package animepahe
22
33import (
44 "encoding/json"
@@ -16,13 +16,16 @@ import (
1616
1717 "github.com/go-rod/rod"
1818 "github.com/go-rod/rod/lib/launcher"
19
20 "github.com/wraient/curd/internal/curdhost"
21 "github.com/wraient/curd/internal/providers"
1922)
2023
2124var animepaheCookiesBypassed bool
2225var solveAnimepaheBrowserChallenge = solveAnimepaheBrowserChallengeWithRod
2326
2427func getCookieFilePath() string {
25 return filepath.Join(GetStoragePath(), "animepahe_cookies.json")
28 return filepath.Join(curdhost.StoragePath(), "animepahe_cookies.json")
2629}
2730
2831func saveCookies(cookies []*http.Cookie) {
@@ -57,6 +60,11 @@ func newAnimepaheAPIRequest(rawURL string) (*http.Request, error) {
5760 return req, nil
5861}
5962
63// NewPageRequest builds an HTTP request for animepahe HTML pages.
64func NewPageRequest(rawURL string) (*http.Request, error) {
65 return newAnimepahePageRequest(rawURL)
66}
67
6068func newAnimepahePageRequest(rawURL string) (*http.Request, error) {
6169 req, err := http.NewRequest("GET", rawURL, nil)
6270 if err != nil {
@@ -74,7 +82,7 @@ func checkCookiesValid() bool {
7482 return false
7583 }
7684
77 resp, err := sharedHTTPClient.Do(req)
85 resp, err := curdhost.HTTPClient().Do(req)
7886 if err != nil {
7987 return false
8088 }
@@ -112,7 +120,7 @@ func isAnimepaheChallengeBody(body []byte) bool {
112120 strings.Contains(normalized, "checking your browser")
113121}
114122
115func (p *AnimepaheProvider) ensureBypass() (err error) {
123func (p *Provider) ensureBypass() (err error) {
116124 defer func() {
117125 if recovered := recover(); recovered != nil {
118126 err = fmt.Errorf("failed to solve Animepahe DDoS-Guard challenge: %v", recovered)
@@ -126,36 +134,36 @@ func (p *AnimepaheProvider) ensureBypass() (err error) {
126134 cookies := loadCookies()
127135 if len(cookies) > 0 {
128136 u, _ := url.Parse("https://animepahe.pw")
129 SetCookiesForAnimepahe(u, cookies)
137 curdhost.SetCookiesForAnimepahe(u, cookies)
130138
131139 if checkCookiesValid() {
132140 animepaheCookiesBypassed = true
133 Log("Successfully restored Animepahe session from cache.")
141 curdhost.Log("Successfully restored Animepahe session from cache.")
134142 return nil
135143 }
136 Log("Cached Animepahe session expired. Requesting new session...")
144 curdhost.Log("Cached Animepahe session expired. Requesting new session...")
137145 }
138146
139147 return p.refreshBypass()
140148}
141149
142func (p *AnimepaheProvider) refreshBypass() error {
150func (p *Provider) refreshBypass() error {
143151 u, _ := url.Parse("https://animepahe.pw")
144152 animepaheCookiesBypassed = false
145153 if err := os.Remove(getCookieFilePath()); err != nil && !os.IsNotExist(err) {
146 Log(fmt.Sprintf("Failed to remove cached Animepahe cookies: %v", err))
154 curdhost.Log(fmt.Sprintf("Failed to remove cached Animepahe cookies: %v", err))
147155 }
148156
149 CurdOut("Animepahe needs a browser challenge before Curd can search or play. Starting a temporary headless browser...")
157 curdhost.Out("Animepahe needs a browser challenge before Curd can search or play. Starting a temporary headless browser...")
150158 httpCookies, err := solveAnimepaheBrowserChallenge()
151159 if err != nil {
152 CurdOut("Animepahe browser challenge failed. Try again later or switch provider.")
160 curdhost.Out("Animepahe browser challenge failed. Try again later or switch provider.")
153161 return fmt.Errorf("animepahe browser challenge failed: %w", err)
154162 }
155163 if len(httpCookies) == 0 {
156164 return fmt.Errorf("animepahe browser challenge returned no cookies")
157165 }
158 SetCookiesForAnimepahe(u, httpCookies)
166 curdhost.SetCookiesForAnimepahe(u, httpCookies)
159167
160168 if !checkCookiesValid() {
161169 return fmt.Errorf("bypassed cookies are still invalid")
@@ -163,7 +171,7 @@ func (p *AnimepaheProvider) refreshBypass() error {
163171
164172 saveCookies(httpCookies)
165173 animepaheCookiesBypassed = true
166 CurdOut("Successfully bypassed DDoS-Guard.")
174 curdhost.Out("Successfully bypassed DDoS-Guard.")
167175 return nil
168176}
169177
@@ -201,13 +209,14 @@ func solveAnimepaheBrowserChallengeWithRod() (httpCookies []*http.Cookie, err er
201209 return httpCookies, nil
202210}
203211
204type AnimepaheProvider struct{}
212type Provider struct{}
205213
206func (p *AnimepaheProvider) Name() string {
214func (p *Provider) Name() string {
207215 return "animepahe"
208216}
209217
210type AnimepaheSearchItem struct {
218// SearchItem is an animepahe API search result payload.
219type SearchItem struct {
211220 ID int `json:"id"`
212221 Title string `json:"title"`
213222 Type string `json:"type"`
@@ -220,19 +229,19 @@ type AnimepaheSearchItem struct {
220229 Session string `json:"session"`
221230}
222231
223type animepaheAnimeRef struct {
232type AnimeRef struct {
224233 ReleaseID string
225234 Session string
226235}
227236
228func (r animepaheAnimeRef) apiID() string {
237func (r AnimeRef) apiID() string {
229238 if r.Session != "" {
230239 return r.Session
231240 }
232241 return r.ReleaseID
233242}
234243
235func formatAnimepaheProviderID(item AnimepaheSearchItem) string {
244func formatAnimepaheProviderID(item SearchItem) string {
236245 if item.ID > 0 && item.Session != "" {
237246 return fmt.Sprintf("%d:%s", item.ID, item.Session)
238247 }
@@ -245,36 +254,38 @@ func formatAnimepaheProviderID(item AnimepaheSearchItem) string {
245254 return ""
246255}
247256
248func parseAnimepaheProviderID(providerID string) animepaheAnimeRef {
257// ParseProviderID parses a stored animepahe show identifier.
258func ParseProviderID(providerID string) AnimeRef {
249259 providerID = strings.TrimSpace(providerID)
250260 if providerID == "" {
251 return animepaheAnimeRef{}
261 return AnimeRef{}
252262 }
253263
254264 parts := strings.SplitN(providerID, ":", 2)
255265 if len(parts) == 2 && parts[0] != "" && parts[1] != "" {
256266 if _, err := strconv.Atoi(parts[0]); err == nil {
257 return animepaheAnimeRef{ReleaseID: parts[0], Session: parts[1]}
267 return AnimeRef{ReleaseID: parts[0], Session: parts[1]}
258268 }
259269 }
260270
261271 if _, err := strconv.Atoi(providerID); err == nil {
262 return animepaheAnimeRef{ReleaseID: providerID}
272 return AnimeRef{ReleaseID: providerID}
263273 }
264274
265 return animepaheAnimeRef{Session: providerID}
275 return AnimeRef{Session: providerID}
266276}
267277
268func stableAnimepaheProviderID(providerID string) string {
269 animeRef := parseAnimepaheProviderID(providerID)
278// StableProviderID returns the release id portion used for history matching.
279func StableProviderID(providerID string) string {
280 animeRef := ParseProviderID(providerID)
270281 if animeRef.ReleaseID != "" {
271282 return animeRef.ReleaseID
272283 }
273284 return providerID
274285}
275286
276func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string, error) {
277 animeRef := parseAnimepaheProviderID(providerID)
287func (p *Provider) ResolveProviderID(providerID, query string) (string, error) {
288 animeRef := ParseProviderID(providerID)
278289 query = strings.TrimSpace(query)
279290 if query == "" {
280291 if animeRef.Session != "" {
@@ -286,14 +297,14 @@ func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string,
286297 options, err := p.SearchAnime(query, "")
287298 if err != nil {
288299 if animeRef.Session != "" {
289 Log(fmt.Sprintf("Animepahe provider id refresh failed for %q, using existing session: %v", providerID, err))
300 curdhost.Log(fmt.Sprintf("Animepahe provider id refresh failed for %q, using existing session: %v", providerID, err))
290301 return providerID, nil
291302 }
292303 return "", err
293304 }
294305
295306 for _, option := range options {
296 item, ok := option.ExtraData.(AnimepaheSearchItem)
307 item, ok := option.ExtraData.(SearchItem)
297308 if !ok {
298309 continue
299310 }
@@ -307,7 +318,7 @@ func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string,
307318 }
308319
309320 if animeRef.Session != "" {
310 Log(fmt.Sprintf("Animepahe provider id %q was not found in search results for %q, using existing session", providerID, query))
321 curdhost.Log(fmt.Sprintf("Animepahe provider id %q was not found in search results for %q, using existing session", providerID, query))
311322 return providerID, nil
312323 }
313324
@@ -319,10 +330,10 @@ type animepaheSearchResponse struct {
319330 PerPage int `json:"per_page"`
320331 CurrentPage int `json:"current_page"`
321332 LastPage int `json:"last_page"`
322 Data []AnimepaheSearchItem `json:"data"`
333 Data []SearchItem `json:"data"`
323334}
324335
325func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
336func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
326337 if err := p.ensureBypass(); err != nil {
327338 return nil, err
328339 }
@@ -334,7 +345,7 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
334345 return nil, err
335346 }
336347
337 resp, err := sharedHTTPClient.Do(req)
348 resp, err := curdhost.HTTPClient().Do(req)
338349 if err != nil {
339350 return nil, err
340351 }
@@ -344,8 +355,8 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
344355 if err != nil {
345356 return nil, err
346357 }
347 if !httpStatusOK(resp.StatusCode) {
348 return nil, httpStatusError("animepahe search", resp.StatusCode, body)
358 if !curdhost.HTTPStatusOK(resp.StatusCode) {
359 return nil, curdhost.HTTPStatusError("animepahe search", resp.StatusCode, body)
349360 }
350361
351362 var searchResp animepaheSearchResponse
@@ -354,10 +365,10 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
354365 return nil, err
355366 }
356367
357 var result []SelectionOption
368 var result []providers.SelectionOption
358369 for _, item := range searchResp.Data {
359370 label := fmt.Sprintf("%s (%d episodes) [animepahe]", item.Title, item.Episodes)
360 result = append(result, SelectionOption{
371 result = append(result, providers.SelectionOption{
361372 Title: item.Title,
362373 Label: label,
363374 Key: formatAnimepaheProviderID(item),
@@ -382,11 +393,11 @@ type animepaheEpisodesResponse struct {
382393 } `json:"data"`
383394}
384395
385func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error) {
396func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
386397 if err := p.ensureBypass(); err != nil {
387398 return nil, err
388399 }
389 animeRef := parseAnimepaheProviderID(showID)
400 animeRef := ParseProviderID(showID)
390401 apiID := animeRef.apiID()
391402 if apiID == "" {
392403 return nil, fmt.Errorf("animepahe provider id %q is invalid; please reselect this anime", showID)
@@ -403,7 +414,7 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
403414 return nil, err
404415 }
405416
406 resp, err := sharedHTTPClient.Do(req)
417 resp, err := curdhost.HTTPClient().Do(req)
407418 if err != nil {
408419 return nil, err
409420 }
@@ -417,15 +428,15 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
417428 if challengeRetried {
418429 return nil, fmt.Errorf("animepahe episode list is still blocked by DDoS-Guard after refreshing browser session")
419430 }
420 Log("Animepahe episode list returned DDoS-Guard challenge. Refreshing browser session...")
431 curdhost.Log("Animepahe episode list returned DDoS-Guard challenge. Refreshing browser session...")
421432 if err := p.refreshBypass(); err != nil {
422433 return nil, err
423434 }
424435 challengeRetried = true
425436 continue
426437 }
427 if !httpStatusOK(resp.StatusCode) {
428 return nil, httpStatusError("animepahe episode list", resp.StatusCode, body)
438 if !curdhost.HTTPStatusOK(resp.StatusCode) {
439 return nil, curdhost.HTTPStatusError("animepahe episode list", resp.StatusCode, body)
429440 }
430441
431442 var epsResp animepaheEpisodesResponse
@@ -453,15 +464,15 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
453464 return result, nil
454465}
455466
456func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
467func (p *Provider) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
457468 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub)
458469}
459470
460func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, epNo int, mode string) ([]string, error) {
471func (p *Provider) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
461472 if err := p.ensureBypass(); err != nil {
462473 return nil, err
463474 }
464 animeRef := parseAnimepaheProviderID(id)
475 animeRef := ParseProviderID(id)
465476 if animeRef.Session == "" {
466477 return nil, fmt.Errorf("animepahe provider id %q is missing session id; please reselect this anime", id)
467478 }
@@ -492,7 +503,7 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
492503 return nil, err
493504 }
494505
495 resp, err := sharedHTTPClient.Do(req)
506 resp, err := curdhost.HTTPClient().Do(req)
496507 if err != nil {
497508 return nil, err
498509 }
@@ -502,8 +513,8 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
502513 if err != nil {
503514 return nil, err
504515 }
505 if !httpStatusOK(resp.StatusCode) {
506 return nil, httpStatusError("animepahe episode lookup", resp.StatusCode, body)
516 if !curdhost.HTTPStatusOK(resp.StatusCode) {
517 return nil, curdhost.HTTPStatusError("animepahe episode lookup", resp.StatusCode, body)
507518 }
508519
509520 var epsResp animepaheEpisodesResponse
@@ -537,7 +548,7 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
537548 return nil, err
538549 }
539550
540 resp, err := sharedHTTPClient.Do(req)
551 resp, err := curdhost.HTTPClient().Do(req)
541552 if err != nil {
542553 return nil, err
543554 }
@@ -547,8 +558,8 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
547558 if err != nil {
548559 return nil, err
549560 }
550 if !httpStatusOK(resp.StatusCode) {
551 return nil, httpStatusError("animepahe player page", resp.StatusCode, body)
561 if !curdhost.HTTPStatusOK(resp.StatusCode) {
562 return nil, curdhost.HTTPStatusError("animepahe player page", resp.StatusCode, body)
552563 }
553564
554565 bodyStr := string(body)
@@ -606,7 +617,7 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
606617 sortFunc(dubLinks)
607618
608619 var links []string
609 requestedMode := normalizeTranslationType(mode)
620 requestedMode := providers.NormalizeTranslationType(mode)
610621 if requestedMode == "dub" {
611622 for _, l := range dubLinks {
612623 links = append(links, l.url)
@@ -635,13 +646,13 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
635646 return finalLinks, nil
636647}
637648
638func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) {
649func (p *Provider) extractKwikM3u8(kwikUrl string) (string, error) {
639650 req, err := newAnimepahePageRequest(kwikUrl)
640651 if err != nil {
641652 return "", err
642653 }
643654
644 resp, err := sharedHTTPClient.Do(req)
655 resp, err := curdhost.HTTPClient().Do(req)
645656 if err != nil {
646657 return "", err
647658 }
@@ -651,8 +662,8 @@ func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) {
651662 if err != nil {
652663 return "", err
653664 }
654 if !httpStatusOK(resp.StatusCode) {
655 return "", httpStatusError("kwik stream page", resp.StatusCode, body)
665 if !curdhost.HTTPStatusOK(resp.StatusCode) {
666 return "", curdhost.HTTPStatusError("kwik stream page", resp.StatusCode, body)
656667 }
657668 bodyStr := string(body)
658669
internal/provider_animepahe_test.go → internal/providers/animepahe/provider_test.go renamed +31 −13
@@ -1,16 +1,25 @@
1package internal
1package animepahe
22
33import (
44 "io"
55 "net/http"
66 "net/http/cookiejar"
7 "net/url"
78 "os"
89 "strings"
910 "testing"
11
12 "github.com/wraient/curd/internal/curdhost"
1013)
1114
1215const animepaheChallengeHTML = `<!doctype html><html><head><title>DDoS-Guard</title></head><body>Checking your browser</body></html>`
1316
17type roundTripFunc func(*http.Request) (*http.Response, error)
18
19func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
20 return f(req)
21}
22
1423func animepaheTestResponse(req *http.Request, statusCode int, body string, headers map[string]string) *http.Response {
1524 resp := &http.Response{
1625 StatusCode: statusCode,
@@ -27,21 +36,30 @@ func animepaheTestResponse(req *http.Request, statusCode int, body string, heade
2736func withAnimepaheTestHooks(t *testing.T, client *http.Client, solver func() ([]*http.Cookie, error)) {
2837 t.Helper()
2938
30 previousClient := sharedHTTPClient
39 previousClient := curdhost.HTTPClient
40 previousLog := curdhost.Log
41 previousOut := curdhost.Out
42 previousCookies := curdhost.SetCookiesForAnimepahe
3143 previousSolver := solveAnimepaheBrowserChallenge
3244 previousBypassed := animepaheCookiesBypassed
33 previousConfig := GetGlobalConfig()
45 previousStoragePath := curdhost.StoragePath
3446
3547 t.Cleanup(func() {
36 sharedHTTPClient = previousClient
48 curdhost.HTTPClient = previousClient
49 curdhost.Log = previousLog
50 curdhost.Out = previousOut
51 curdhost.SetCookiesForAnimepahe = previousCookies
3752 solveAnimepaheBrowserChallenge = previousSolver
3853 animepaheCookiesBypassed = previousBypassed
39 SetGlobalConfig(previousConfig)
54 curdhost.StoragePath = previousStoragePath
4055 })
4156
42 sharedHTTPClient = client
57 curdhost.HTTPClient = func() *http.Client { return client }
58 curdhost.Log = func(string) {}
59 curdhost.Out = func(string) {}
60 curdhost.SetCookiesForAnimepahe = func(*url.URL, []*http.Cookie) {}
4361 solveAnimepaheBrowserChallenge = solver
44 SetGlobalConfig(&CurdConfig{StoragePath: t.TempDir()})
62 curdhost.StoragePath = func() string { return t.TempDir() }
4563}
4664
4765func TestAnimepaheEpisodesListRefreshesSessionWhenReleaseEndpointReturnsChallenge(t *testing.T) {
@@ -82,7 +100,7 @@ func TestAnimepaheEpisodesListRefreshesSessionWhenReleaseEndpointReturnsChalleng
82100 })
83101 animepaheCookiesBypassed = true
84102
85 episodes, err := (&AnimepaheProvider{}).EpisodesList("4:session-id", "sub")
103 episodes, err := (&Provider{}).EpisodesList("4:session-id", "sub")
86104 if err != nil {
87105 t.Fatalf("expected episode list retry to succeed: %v", err)
88106 }
@@ -129,7 +147,7 @@ func TestAnimepaheEpisodesListReportsPersistentChallengeAfterRefresh(t *testing.
129147 })
130148 animepaheCookiesBypassed = true
131149
132 _, err = (&AnimepaheProvider{}).EpisodesList("4:session-id", "sub")
150 _, err = (&Provider{}).EpisodesList("4:session-id", "sub")
133151 if err == nil {
134152 t.Fatalf("expected persistent DDoS-Guard challenge to fail")
135153 }
@@ -146,16 +164,16 @@ func TestAnimepaheEpisodesListLiveOnePiece(t *testing.T) {
146164 t.Skip("set CURD_LIVE_ANIMEPAHE_TEST=1 to run live Animepahe episode-list verification")
147165 }
148166
149 previousConfig := GetGlobalConfig()
150167 previousBypassed := animepaheCookiesBypassed
168 previousStoragePath := curdhost.StoragePath
151169 t.Cleanup(func() {
152 SetGlobalConfig(previousConfig)
153170 animepaheCookiesBypassed = previousBypassed
171 curdhost.StoragePath = previousStoragePath
154172 })
155 SetGlobalConfig(&CurdConfig{StoragePath: t.TempDir()})
173 curdhost.StoragePath = func() string { return t.TempDir() }
156174 animepaheCookiesBypassed = false
157175
158 episodes, err := (&AnimepaheProvider{}).EpisodesList("4:15a36fc8-73b9-8c2e-ee5f-fb1bcd4fcdc6", "sub")
176 episodes, err := (&Provider{}).EpisodesList("4:15a36fc8-73b9-8c2e-ee5f-fb1bcd4fcdc6", "sub")
159177 if err != nil {
160178 t.Fatalf("live Animepahe One Piece episode list failed: %v", err)
161179 }
internal/providers/animepahe/register.go added +17
@@ -0,0 +1,17 @@
1package animepahe
2
3import "github.com/wraient/curd/internal/providers"
4
5func init() {
6 providers.Register(providers.Meta{
7 Name: "animepahe",
8 Aliases: []string{"pahe"},
9 Referrer: "https://kwik.cx/",
10 DefaultDisabled: true,
11 DisableReason: "Cloudflare/DDoS-Guard protection cannot be bypassed reliably",
12 OptOutToken: "no-animepahe",
13 FallbackPrompt: "Animepahe may require downloading a Chromium browser for DDoS-Guard verification (~500 MB).",
14 }, func() providers.Provider {
15 return &Provider{}
16 })
17}
internal/providers/anineko/bibiemb.go added +110
@@ -0,0 +1,110 @@
1package anineko
2
3import (
4 "fmt"
5 "net/url"
6 "regexp"
7 "strings"
8)
9
10var (
11 bibiembMasterRE = regexp.MustCompile(`const src = "(https?://[^"]+/master\.m3u8)"`)
12 streamInfRE = regexp.MustCompile(`(?m)^#EXT-X-STREAM-INF:.*NAME="([^"]+)".*\r?\n([^\r\n#]+)`)
13)
14
15var bibiembQualityOrder = []string{"1080p", "720p", "480p", "360p"}
16
17type resolvedStream struct {
18 URL string
19 Referrer string
20 Subtitle string
21}
22
23func resolveBibiemb(embedURL string) (resolvedStream, error) {
24 embedURL = strings.TrimSpace(embedURL)
25 if embedURL == "" {
26 return resolvedStream{}, fmt.Errorf("empty bibiemb embed url")
27 }
28
29 html, err := fetchString(embedURL, baseURL+"/")
30 if err != nil {
31 return resolvedStream{}, err
32 }
33
34 match := bibiembMasterRE.FindStringSubmatch(html)
35 if len(match) < 2 {
36 return resolvedStream{}, fmt.Errorf("bibiemb master m3u8 not found")
37 }
38
39 masterURL := match[1]
40 variantURL, err := pickBibiembVariant(masterURL, embedURL)
41 if err != nil {
42 return resolvedStream{}, err
43 }
44
45 return resolvedStream{
46 URL: variantURL,
47 Referrer: embedURL,
48 Subtitle: subtitleFromEmbedURL(embedURL),
49 }, nil
50}
51
52func pickBibiembVariant(masterURL, referer string) (string, error) {
53 playlist, err := fetchString(masterURL, referer)
54 if err != nil {
55 return "", err
56 }
57
58 type variant struct {
59 name string
60 url string
61 }
62 variants := make([]variant, 0)
63 for _, match := range streamInfRE.FindAllStringSubmatch(playlist, -1) {
64 if len(match) < 3 {
65 continue
66 }
67 variants = append(variants, variant{
68 name: strings.TrimSpace(match[1]),
69 url: resolvePlaylistURL(masterURL, strings.TrimSpace(match[2])),
70 })
71 }
72 if len(variants) == 0 {
73 return "", fmt.Errorf("no bibiemb variants in master playlist")
74 }
75
76 byName := map[string]string{}
77 for _, item := range variants {
78 byName[strings.ToLower(item.name)] = item.url
79 }
80 for _, quality := range bibiembQualityOrder {
81 if streamURL, ok := byName[quality]; ok {
82 return streamURL, nil
83 }
84 }
85 return variants[0].url, nil
86}
87
88func resolvePlaylistURL(baseURL, entry string) string {
89 if strings.HasPrefix(entry, "http://") || strings.HasPrefix(entry, "https://") {
90 return entry
91 }
92 parsed, err := url.Parse(baseURL)
93 if err != nil {
94 return entry
95 }
96 if strings.HasPrefix(entry, "/") {
97 parsed.Path = entry
98 parsed.RawQuery = ""
99 parsed.Fragment = ""
100 return parsed.Scheme + "://" + parsed.Host + entry
101 }
102 if idx := strings.LastIndex(parsed.Path, "/"); idx >= 0 {
103 parsed.Path = parsed.Path[:idx+1] + entry
104 } else {
105 parsed.Path = "/" + entry
106 }
107 parsed.RawQuery = ""
108 parsed.Fragment = ""
109 return parsed.String()
110}
internal/providers/anineko/client.go added +92
@@ -0,0 +1,92 @@
1package anineko
2
3import (
4 "fmt"
5 "io"
6 "net/http"
7 "strings"
8
9 "github.com/wraient/curd/internal/curdhost"
10)
11
12const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
13
14var baseURL = "https://anineko.to"
15
16func newRequest(method, rawURL, referer string) (*http.Request, error) {
17 req, err := http.NewRequest(method, rawURL, nil)
18 if err != nil {
19 return nil, err
20 }
21 req.Header.Set("User-Agent", userAgent)
22 if referer != "" {
23 req.Header.Set("Referer", referer)
24 }
25 return req, nil
26}
27
28func fetchString(rawURL, referer string) (string, error) {
29 req, err := newRequest(http.MethodGet, rawURL, referer)
30 if err != nil {
31 return "", err
32 }
33 resp, err := curdhost.HTTPClient().Do(req)
34 if err != nil {
35 return "", err
36 }
37 defer resp.Body.Close()
38
39 body, err := io.ReadAll(resp.Body)
40 if err != nil {
41 return "", err
42 }
43 if !curdhost.HTTPStatusOK(resp.StatusCode) {
44 return "", curdhost.HTTPStatusError("anineko request", resp.StatusCode, body)
45 }
46 return string(body), nil
47}
48
49func fetchBytes(rawURL, referer string) ([]byte, error) {
50 req, err := newRequest(http.MethodGet, rawURL, referer)
51 if err != nil {
52 return nil, err
53 }
54 resp, err := curdhost.HTTPClient().Do(req)
55 if err != nil {
56 return nil, err
57 }
58 defer resp.Body.Close()
59
60 body, err := io.ReadAll(resp.Body)
61 if err != nil {
62 return nil, err
63 }
64 if !curdhost.HTTPStatusOK(resp.StatusCode) {
65 return nil, curdhost.HTTPStatusError("anineko request", resp.StatusCode, body)
66 }
67 return body, nil
68}
69
70func absoluteURL(path string) string {
71 path = strings.TrimSpace(path)
72 if path == "" {
73 return ""
74 }
75 if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
76 return path
77 }
78 if strings.HasPrefix(path, "//") {
79 return "https:" + path
80 }
81 if !strings.HasPrefix(path, "/") {
82 path = "/" + path
83 }
84 return baseURL + path
85}
86
87func watchURL(slug string, epNo int) string {
88 if epNo > 0 {
89 return fmt.Sprintf("%s/watch/%s/ep-%d", baseURL, slug, epNo)
90 }
91 return fmt.Sprintf("%s/watch/%s", baseURL, slug)
92}
internal/providers/anineko/episodes.go added +50
@@ -0,0 +1,50 @@
1package anineko
2
3import (
4 "fmt"
5 "regexp"
6 "sort"
7 "strconv"
8 "strings"
9)
10
11var episodePathRE = regexp.MustCompile(`/ep-(\d+)`)
12
13func episodesList(showID, mode string) ([]string, error) {
14 slug := strings.TrimSpace(showID)
15 if slug == "" {
16 return nil, fmt.Errorf("empty show id")
17 }
18
19 html, err := fetchString(watchURL(slug, 0), baseURL+"/")
20 if err != nil {
21 return nil, err
22 }
23
24 seen := map[int]struct{}{}
25 for _, match := range episodePathRE.FindAllStringSubmatch(html, -1) {
26 if len(match) < 2 {
27 continue
28 }
29 epNo, err := strconv.Atoi(match[1])
30 if err != nil || epNo <= 0 {
31 continue
32 }
33 seen[epNo] = struct{}{}
34 }
35 if len(seen) == 0 {
36 return nil, fmt.Errorf("no episodes found for %q", slug)
37 }
38
39 episodes := make([]int, 0, len(seen))
40 for epNo := range seen {
41 episodes = append(episodes, epNo)
42 }
43 sort.Ints(episodes)
44
45 result := make([]string, 0, len(episodes))
46 for _, epNo := range episodes {
47 result = append(result, strconv.Itoa(epNo))
48 }
49 return result, nil
50}
internal/providers/anineko/provider.go added +34
@@ -0,0 +1,34 @@
1package anineko
2
3import "github.com/wraient/curd/internal/providers"
4
5// Provider implements anineko.to catalog search and stream resolution.
6type Provider struct{}
7
8func (p *Provider) Name() string {
9 return "anineko"
10}
11
12func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
13 return searchAnime(query, mode)
14}
15
16func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
17 return episodesList(showID, mode)
18}
19
20func (p *Provider) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
21 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, config.SubOrDub)
22 return links, err
23}
24
25func (p *Provider) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
26 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, mode)
27 return links, err
28}
29
30func (p *Provider) GetEpisodeURLForModeWithHints(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, map[string]providers.StreamPlaybackHint, error) {
31 playback := config
32 playback.SubOrDub = providers.NormalizeTranslationType(mode)
33 return getEpisodeStreamsForMode(id, playback, epNo)
34}
internal/providers/anineko/provider_test.go added +314
@@ -0,0 +1,314 @@
1package anineko
2
3import (
4 "io"
5 "net/http"
6 "net/http/httptest"
7 "strings"
8 "testing"
9
10 "github.com/wraient/curd/internal/curdhost"
11)
12
13type roundTripFunc func(*http.Request) (*http.Response, error)
14
15func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
16 return f(req)
17}
18
19func testResponse(req *http.Request, statusCode int, body string, headers map[string]string) *http.Response {
20 resp := &http.Response{
21 StatusCode: statusCode,
22 Header: make(http.Header),
23 Body: io.NopCloser(strings.NewReader(body)),
24 Request: req,
25 }
26 for key, value := range headers {
27 resp.Header.Set(key, value)
28 }
29 return resp
30}
31
32func withAninekoTestClient(t *testing.T, client *http.Client) {
33 t.Helper()
34 previous := curdhost.HTTPClient
35 t.Cleanup(func() {
36 curdhost.HTTPClient = previous
37 resetVibeProxyForTest()
38 resetSubStyleForTest()
39 })
40 curdhost.HTTPClient = func() *http.Client { return client }
41}
42
43func TestSearchAnimeParsesResults(t *testing.T) {
44 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
45 if r.URL.Path != "/ajax/search" {
46 http.NotFound(w, r)
47 return
48 }
49 _, _ = io.WriteString(w, `{"success":true,"results":[{"title":"One Piece","url":"/watch/one-piece","image":"/img/op.jpg","meta":"TV"}]}`)
50 }))
51 defer server.Close()
52
53 withAninekoTestClient(t, server.Client())
54
55 originalBase := baseURL
56 t.Cleanup(func() { baseURL = originalBase })
57 baseURL = server.URL
58
59 options, err := searchAnime("one piece", "sub")
60 if err != nil {
61 t.Fatalf("searchAnime: %v", err)
62 }
63 if len(options) != 1 {
64 t.Fatalf("expected 1 option, got %d", len(options))
65 }
66 if options[0].Key != "one-piece" {
67 t.Fatalf("unexpected key %q", options[0].Key)
68 }
69 if options[0].Thumbnail != server.URL+"/img/op.jpg" {
70 t.Fatalf("unexpected thumbnail %q", options[0].Thumbnail)
71 }
72}
73
74func TestEpisodesListParsesEpisodeLinks(t *testing.T) {
75 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
76 _, _ = io.WriteString(w, `<a href="/watch/frieren/ep-1">1</a><a href="/watch/frieren/ep-12">12</a>`)
77 }))
78 defer server.Close()
79
80 withAninekoTestClient(t, server.Client())
81 originalBase := baseURL
82 t.Cleanup(func() { baseURL = originalBase })
83 baseURL = server.URL
84
85 episodes, err := episodesList("frieren", "sub")
86 if err != nil {
87 t.Fatalf("episodesList: %v", err)
88 }
89 if strings.Join(episodes, ",") != "1,12" {
90 t.Fatalf("unexpected episodes %v", episodes)
91 }
92}
93
94func TestExtractLangEmbedURLs(t *testing.T) {
95 html := `
96<div class="server-items" data-id="sub">
97 <div data-video="https://bibiemb.xyz/aaa"></div>
98 <div data-video="https://vibeplayer.site/bbb?sub=https://cdn.example/sub.vtt"></div>
99</div>
100<div class="server-items" data-id="dub">
101 <div data-video="https://bibiemb.xyz/ccc"></div>
102</div>`
103
104 groups := extractLangEmbedURLs(html)
105 if len(groups["sub"]) != 2 {
106 t.Fatalf("expected 2 sub urls, got %d", len(groups["sub"]))
107 }
108 if len(groups["dub"]) != 1 {
109 t.Fatalf("expected 1 dub url, got %d", len(groups["dub"]))
110 }
111 subURLs := embedURLsForSubStyle(groups, "soft")
112 if len(subURLs) != 2 {
113 t.Fatalf("expected 2 soft sub urls, got %d", len(subURLs))
114 }
115 if subtitleFromEmbedURL(subURLs[1]) != "https://cdn.example/sub.vtt" {
116 t.Fatalf("unexpected subtitle %q", subtitleFromEmbedURL(subURLs[1]))
117 }
118}
119
120func TestChooseSubStyleRespectsPreference(t *testing.T) {
121 groups := map[string][]string{
122 "hsub": {"https://vibeplayer.site/hard"},
123 "sub": {"https://vibeplayer.site/soft?sub=https://cdn.example/sub.vtt"},
124 "dub": {"https://vibeplayer.site/dub"},
125 }
126
127 style, err := chooseSubStyle(groups, "soft")
128 if err != nil || style != "soft" {
129 t.Fatalf("chooseSubStyle soft: style=%q err=%v", style, err)
130 }
131
132 style, err = chooseSubStyle(groups, "hard")
133 if err != nil || style != "hard" {
134 t.Fatalf("chooseSubStyle hard: style=%q err=%v", style, err)
135 }
136}
137
138func TestChooseSubStylePromptSelectOnce(t *testing.T) {
139 groups := map[string][]string{
140 "hsub": {"https://vibeplayer.site/hard"},
141 "sub": {"https://vibeplayer.site/soft?sub=https://cdn.example/sub.vtt"},
142 }
143
144 prompts := 0
145 previousPrompt := curdhost.PromptSelect
146 previousOut := curdhost.Out
147 previousPersist := curdhost.PersistSubStylePreference
148 previousCurrent := curdhost.CurrentSubStyle
149 curdhost.PromptSelect = func(options []curdhost.PromptOption) (curdhost.PromptOption, error) {
150 prompts++
151 return curdhost.PromptOption{Key: "hard", Label: "Hard sub"}, nil
152 }
153 curdhost.Out = func(string) {}
154 saved := ""
155 curdhost.PersistSubStylePreference = func(style string) error {
156 saved = style
157 return nil
158 }
159 curdhost.CurrentSubStyle = func() string { return saved }
160 t.Cleanup(func() {
161 curdhost.PromptSelect = previousPrompt
162 curdhost.Out = previousOut
163 curdhost.PersistSubStylePreference = previousPersist
164 curdhost.CurrentSubStyle = previousCurrent
165 resetSubStyleForTest()
166 })
167
168 for i := 0; i < 2; i++ {
169 style, err := chooseSubStyle(groups, "ask")
170 if err != nil || style != "hard" {
171 t.Fatalf("iteration %d: style=%q err=%v", i, style, err)
172 }
173 }
174 if prompts != 1 {
175 t.Fatalf("expected 1 prompt, got %d", prompts)
176 }
177 if saved != "hard" {
178 t.Fatalf("expected saved preference hard, got %q", saved)
179 }
180}
181
182func TestResolveBibiembPicks1080pVariant(t *testing.T) {
183 const hash = "agdeadbeef"
184
185 var server *httptest.Server
186 server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
187 switch {
188 case r.URL.Path == "/"+hash:
189 _, _ = io.WriteString(w, `const src = "`+server.URL+`/`+hash+`/master.m3u8"`)
190 case r.URL.Path == "/"+hash+"/master.m3u8":
191 _, _ = io.WriteString(w, `#EXTM3U
192#EXT-X-STREAM-INF:BANDWIDTH=1,NAME="720p"
193`+server.URL+`/`+hash+`/720p/index.m3u8
194#EXT-X-STREAM-INF:BANDWIDTH=2,NAME="1080p"
195`+server.URL+`/`+hash+`/1080p/index.m3u8`)
196 default:
197 http.NotFound(w, r)
198 }
199 }))
200 defer server.Close()
201
202 withAninekoTestClient(t, server.Client())
203
204 stream, err := resolveBibiemb(server.URL + "/" + hash)
205 if err != nil {
206 t.Fatalf("resolveBibiemb: %v", err)
207 }
208 if !strings.HasSuffix(stream.URL, "/1080p/index.m3u8") {
209 t.Fatalf("expected 1080p variant, got %q", stream.URL)
210 }
211}
212
213func TestStripPNGWrapper(t *testing.T) {
214 png := []byte{
215 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
216 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
217 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
218 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
219 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41,
220 0x54, 0x78, 0xda, 0x63, 0x64, 0xf8, 0xcf, 0x50,
221 0x0f, 0x00, 0x03, 0x86, 0x01, 0x80, 0x5a, 0x34,
222 0x7d, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
223 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
224 }
225 payload := []byte{0x47, 0x01, 0x02, 0x03}
226 data := append(append([]byte{}, png...), payload...)
227 if got := stripPNGWrapper(data); string(got) != string(payload) {
228 t.Fatalf("unexpected stripped payload %v", got)
229 }
230}
231
232func TestVibeProxyRewritesAndStripsSegments(t *testing.T) {
233 const (
234 id = "abc123"
235 variant = "1720.m3u8"
236 )
237
238 png := []byte{
239 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
240 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
241 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
242 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
243 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41,
244 0x54, 0x78, 0xda, 0x63, 0x64, 0xf8, 0xcf, 0x50,
245 0x0f, 0x00, 0x03, 0x86, 0x01, 0x80, 0x5a, 0x34,
246 0x7d, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
247 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, 0x47, 0x11,
248 }
249
250 remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
251 switch r.URL.Path {
252 case "/public/stream/" + id + "/master.m3u8":
253 _, _ = io.WriteString(w, "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1,NAME=\"720p\"\n"+variant+"\n")
254 case "/public/stream/" + id + "/" + variant:
255 _, _ = io.WriteString(w, "#EXTM3U\n#EXTINF:10.0,\n/public/segment.bin\n")
256 case "/public/segment.bin":
257 _, _ = w.Write(png)
258 default:
259 http.NotFound(w, r)
260 }
261 }))
262 defer remote.Close()
263
264 withAninekoTestClient(t, remote.Client())
265 resetVibeProxyForTest()
266
267 masterURL := remote.URL + "/public/stream/" + id + "/master.m3u8"
268 proxyURL, err := registerVibeStream(masterURL, remote.URL+"/"+id)
269 if err != nil {
270 t.Fatalf("registerVibeStream: %v", err)
271 }
272
273 resp, err := http.Get(proxyURL)
274 if err != nil {
275 t.Fatalf("get master: %v", err)
276 }
277 body, _ := io.ReadAll(resp.Body)
278 resp.Body.Close()
279 if !strings.Contains(string(body), "/1720.m3u8") {
280 t.Fatalf("master not rewritten: %s", body)
281 }
282
283 variantURL := ""
284 for _, line := range strings.Split(strings.ReplaceAll(string(body), "\r\n", "\n"), "\n") {
285 line = strings.TrimSpace(line)
286 if line != "" && !strings.HasPrefix(line, "#") {
287 variantURL = line
288 break
289 }
290 }
291 resp, err = http.Get(variantURL)
292 if err != nil {
293 t.Fatalf("get variant: %v", err)
294 }
295 body, _ = io.ReadAll(resp.Body)
296 resp.Body.Close()
297 segURL := ""
298 for _, line := range strings.Split(strings.TrimSpace(string(body)), "\n") {
299 line = strings.TrimSpace(line)
300 if line != "" && !strings.HasPrefix(line, "#") {
301 segURL = line
302 }
303 }
304
305 resp, err = http.Get(segURL)
306 if err != nil {
307 t.Fatalf("get segment: %v", err)
308 }
309 segBody, _ := io.ReadAll(resp.Body)
310 resp.Body.Close()
311 if len(segBody) != 2 || segBody[0] != 0x47 {
312 t.Fatalf("expected stripped mpeg-ts payload, got %v", segBody)
313 }
314}
internal/providers/anineko/register.go added +13
@@ -0,0 +1,13 @@
1package anineko
2
3import "github.com/wraient/curd/internal/providers"
4
5func init() {
6 providers.Register(providers.Meta{
7 Name: "anineko",
8 Aliases: []string{"ani-neko", "ani neko"},
9 Referrer: "https://anineko.to/",
10 }, func() providers.Provider {
11 return &Provider{}
12 })
13}
internal/providers/anineko/scrape.go added +107
@@ -0,0 +1,107 @@
1package anineko
2
3import (
4 "net/url"
5 "regexp"
6 "strings"
7)
8
9var (
10 dataVideoRE = regexp.MustCompile(`data-video="([^"]+)"`)
11 subtitleRE = regexp.MustCompile(`[?&](?:sub|caption_1|c1_file)=([^&"]+)`)
12)
13
14func extractLangEmbedURLs(html string) map[string][]string {
15 groups := map[string][]string{
16 "hsub": {},
17 "sub": {},
18 "dub": {},
19 }
20 markers := regexp.MustCompile(`data-id="(hsub|sub|dub)"`).FindAllStringSubmatchIndex(html, -1)
21 for i, marker := range markers {
22 if len(marker) < 4 {
23 continue
24 }
25 lang := html[marker[2]:marker[3]]
26 start := marker[1]
27 end := len(html)
28 if i+1 < len(markers) {
29 end = markers[i+1][0]
30 }
31 block := html[start:end]
32 seen := map[string]struct{}{}
33 for _, videoMatch := range dataVideoRE.FindAllStringSubmatch(block, -1) {
34 if len(videoMatch) < 2 {
35 continue
36 }
37 embedURL := strings.TrimSpace(videoMatch[1])
38 if embedURL == "" {
39 continue
40 }
41 if _, ok := seen[embedURL]; ok {
42 continue
43 }
44 seen[embedURL] = struct{}{}
45 groups[lang] = append(groups[lang], embedURL)
46 }
47 }
48 return groups
49}
50
51func partitionByHost(embedURLs []string) (bibiemb, vibeplayer, other []string) {
52 for _, embedURL := range embedURLs {
53 host := strings.ToLower(hostFromURL(embedURL))
54 switch {
55 case strings.Contains(host, "bibiemb."):
56 bibiemb = append(bibiemb, embedURL)
57 case strings.Contains(host, "vibeplayer."):
58 vibeplayer = append(vibeplayer, embedURL)
59 default:
60 other = append(other, embedURL)
61 }
62 }
63 return bibiemb, vibeplayer, other
64}
65
66func subtitleFromEmbedURL(embedURL string) string {
67 parsed, err := url.Parse(embedURL)
68 if err != nil {
69 return ""
70 }
71 for key, values := range parsed.Query() {
72 switch strings.ToLower(key) {
73 case "sub", "caption_1", "c1_file":
74 if len(values) > 0 {
75 if decoded, err := url.QueryUnescape(values[0]); err == nil {
76 return decoded
77 }
78 return values[0]
79 }
80 }
81 }
82 match := subtitleRE.FindStringSubmatch(embedURL)
83 if len(match) < 2 {
84 return ""
85 }
86 if decoded, err := url.QueryUnescape(match[1]); err == nil {
87 return decoded
88 }
89 return match[1]
90}
91
92func hostFromURL(rawURL string) string {
93 parsed, err := url.Parse(rawURL)
94 if err != nil {
95 return ""
96 }
97 return parsed.Host
98}
99
100func containsString(items []string, target string) bool {
101 for _, item := range items {
102 if item == target {
103 return true
104 }
105 }
106 return false
107}
internal/providers/anineko/search.go added +74
@@ -0,0 +1,74 @@
1package anineko
2
3import (
4 "encoding/json"
5 "fmt"
6 "net/url"
7 "regexp"
8 "strings"
9
10 "github.com/wraient/curd/internal/providers"
11)
12
13type searchResponse struct {
14 Success bool `json:"success"`
15 Results []struct {
16 Title string `json:"title"`
17 URL string `json:"url"`
18 Image string `json:"image"`
19 Meta string `json:"meta"`
20 } `json:"results"`
21}
22
23var slugFromPathRE = regexp.MustCompile(`/watch/([^/?#]+)`)
24
25func searchAnime(query, mode string) ([]providers.SelectionOption, error) {
26 query = strings.TrimSpace(query)
27 if query == "" {
28 return nil, fmt.Errorf("empty search query")
29 }
30
31 rawURL := fmt.Sprintf("%s/ajax/search?q=%s", baseURL, url.QueryEscape(query))
32 body, err := fetchString(rawURL, baseURL+"/")
33 if err != nil {
34 return nil, err
35 }
36
37 var payload searchResponse
38 if err := json.Unmarshal([]byte(body), &payload); err != nil {
39 return nil, fmt.Errorf("parse anineko search response: %w", err)
40 }
41 if !payload.Success {
42 return nil, fmt.Errorf("anineko search failed")
43 }
44
45 options := make([]providers.SelectionOption, 0, len(payload.Results))
46 for _, result := range payload.Results {
47 slug := slugFromWatchURL(result.URL)
48 if slug == "" {
49 continue
50 }
51 label := strings.TrimSpace(result.Title)
52 if meta := strings.TrimSpace(result.Meta); meta != "" {
53 label = label + " — " + meta
54 }
55 options = append(options, providers.SelectionOption{
56 Key: slug,
57 Label: label,
58 Title: strings.TrimSpace(result.Title),
59 Thumbnail: absoluteURL(result.Image),
60 })
61 }
62 if len(options) == 0 {
63 return nil, fmt.Errorf("no results for %q", query)
64 }
65 return options, nil
66}
67
68func slugFromWatchURL(watchPath string) string {
69 match := slugFromPathRE.FindStringSubmatch(watchPath)
70 if len(match) < 2 {
71 return ""
72 }
73 return strings.TrimSpace(match[1])
74}
internal/providers/anineko/streams.go added +66
@@ -0,0 +1,66 @@
1package anineko
2
3import (
4 "fmt"
5 "strings"
6
7 "github.com/wraient/curd/internal/providers"
8)
9
10func getEpisodeStreamsForMode(slug string, config providers.PlaybackConfig, epNo int) ([]string, map[string]providers.StreamPlaybackHint, error) {
11 slug = strings.TrimSpace(slug)
12 if slug == "" {
13 return nil, nil, fmt.Errorf("empty show id")
14 }
15 if epNo <= 0 {
16 return nil, nil, fmt.Errorf("invalid episode number %d", epNo)
17 }
18
19 mode := providers.NormalizeTranslationType(config.SubOrDub)
20 html, err := fetchString(watchURL(slug, epNo), baseURL+"/")
21 if err != nil {
22 return nil, nil, err
23 }
24
25 groups := extractLangEmbedURLs(html)
26 embedURLs, err := embedURLsForMode(groups, mode, config.SubStyle)
27 if err != nil {
28 return nil, nil, err
29 }
30 if len(embedURLs) == 0 {
31 return nil, nil, fmt.Errorf("no %s streams found for episode %d", mode, epNo)
32 }
33
34 bibiembURLs, vibeplayerURLs, _ := partitionByHost(embedURLs)
35
36 for _, embedURL := range bibiembURLs {
37 stream, err := resolveBibiemb(embedURL)
38 if err != nil {
39 continue
40 }
41 return singleStreamResult(stream)
42 }
43
44 for _, embedURL := range vibeplayerURLs {
45 stream, err := resolveVibeplayer(embedURL)
46 if err != nil {
47 continue
48 }
49 return singleStreamResult(stream)
50 }
51
52 return nil, nil, fmt.Errorf("no playable streams resolved for episode %d", epNo)
53}
54
55func singleStreamResult(stream resolvedStream) ([]string, map[string]providers.StreamPlaybackHint, error) {
56 if strings.TrimSpace(stream.URL) == "" {
57 return nil, nil, fmt.Errorf("empty stream url")
58 }
59 hints := map[string]providers.StreamPlaybackHint{
60 stream.URL: {
61 Referrer: stream.Referrer,
62 Subtitle: stream.Subtitle,
63 },
64 }
65 return []string{stream.URL}, hints, nil
66}
internal/providers/anineko/substyle.go added +138
@@ -0,0 +1,138 @@
1package anineko
2
3import (
4 "fmt"
5 "strings"
6 "sync"
7
8 "github.com/wraient/curd/internal/curdhost"
9)
10
11var (
12 subStyleChoiceMu sync.Mutex
13 subStyleChosen string
14)
15
16func normalizeSubStyle(style string) string {
17 switch strings.ToLower(strings.TrimSpace(style)) {
18 case "soft":
19 return "soft"
20 case "hard":
21 return "hard"
22 default:
23 return "ask"
24 }
25}
26
27func resolveSubStylePreference(fallback string) string {
28 if curdhost.CurrentSubStyle != nil {
29 if live := normalizeSubStyle(curdhost.CurrentSubStyle()); live != "ask" {
30 return live
31 }
32 }
33
34 subStyleChoiceMu.Lock()
35 defer subStyleChoiceMu.Unlock()
36 if subStyleChosen != "" {
37 return subStyleChosen
38 }
39 return normalizeSubStyle(fallback)
40}
41
42func rememberSubStyleChoice(style string) {
43 style = normalizeSubStyle(style)
44 if style != "soft" && style != "hard" {
45 return
46 }
47
48 subStyleChoiceMu.Lock()
49 subStyleChosen = style
50 subStyleChoiceMu.Unlock()
51
52 if curdhost.PersistSubStylePreference != nil {
53 _ = curdhost.PersistSubStylePreference(style)
54 }
55}
56
57func chooseSubStyle(groups map[string][]string, preference string) (string, error) {
58 preference = resolveSubStylePreference(preference)
59 hasSoft := len(groups["sub"]) > 0
60 hasHard := len(groups["hsub"]) > 0
61
62 switch preference {
63 case "soft":
64 if hasSoft {
65 return "soft", nil
66 }
67 if hasHard {
68 return "hard", nil
69 }
70 case "hard":
71 if hasHard {
72 return "hard", nil
73 }
74 if hasSoft {
75 return "soft", nil
76 }
77 case "ask":
78 if hasSoft && hasHard {
79 if curdhost.PromptSelect == nil {
80 rememberSubStyleChoice("soft")
81 return "soft", nil
82 }
83 if curdhost.Out != nil {
84 curdhost.Out("Both soft-sub and hard-sub streams are available.")
85 }
86 selected, err := curdhost.PromptSelect([]curdhost.PromptOption{
87 {Key: "soft", Label: "Soft sub (external subtitles)"},
88 {Key: "hard", Label: "Hard sub (burned-in subtitles)"},
89 })
90 if err != nil {
91 return "", err
92 }
93 chosen := "soft"
94 if selected.Key == "hard" {
95 chosen = "hard"
96 }
97 rememberSubStyleChoice(chosen)
98 return chosen, nil
99 }
100 if hasSoft {
101 return "soft", nil
102 }
103 if hasHard {
104 return "hard", nil
105 }
106 }
107
108 return "", fmt.Errorf("no sub streams found")
109}
110
111func embedURLsForSubStyle(groups map[string][]string, style string) []string {
112 switch style {
113 case "soft":
114 return append([]string{}, groups["sub"]...)
115 case "hard":
116 return append([]string{}, groups["hsub"]...)
117 default:
118 return nil
119 }
120}
121
122func embedURLsForMode(groups map[string][]string, mode, subStyle string) ([]string, error) {
123 if strings.EqualFold(mode, "dub") {
124 return groups["dub"], nil
125 }
126
127 chosen, err := chooseSubStyle(groups, subStyle)
128 if err != nil {
129 return nil, err
130 }
131 return embedURLsForSubStyle(groups, chosen), nil
132}
133
134func resetSubStyleForTest() {
135 subStyleChoiceMu.Lock()
136 subStyleChosen = ""
137 subStyleChoiceMu.Unlock()
138}
internal/providers/anineko/vibeplayer.go added +37
@@ -0,0 +1,37 @@
1package anineko
2
3import (
4 "fmt"
5 "regexp"
6 "strings"
7)
8
9var vibeplayerMasterRE = regexp.MustCompile(`const src = "(https://vibeplayer\.site/public/stream/[^"]+/master\.m3u8)"`)
10
11func resolveVibeplayer(embedURL string) (resolvedStream, error) {
12 embedURL = strings.TrimSpace(embedURL)
13 if embedURL == "" {
14 return resolvedStream{}, fmt.Errorf("empty vibeplayer embed url")
15 }
16
17 html, err := fetchString(embedURL, baseURL+"/")
18 if err != nil {
19 return resolvedStream{}, err
20 }
21
22 match := vibeplayerMasterRE.FindStringSubmatch(html)
23 if len(match) < 2 {
24 return resolvedStream{}, fmt.Errorf("vibeplayer master m3u8 not found")
25 }
26
27 proxyURL, err := registerVibeStream(match[1], embedURL)
28 if err != nil {
29 return resolvedStream{}, err
30 }
31
32 return resolvedStream{
33 URL: proxyURL,
34 Referrer: embedURL,
35 Subtitle: subtitleFromEmbedURL(embedURL),
36 }, nil
37}
internal/providers/anineko/vibeproxy.go added +242
@@ -0,0 +1,242 @@
1package anineko
2
3import (
4 "bytes"
5 "crypto/rand"
6 "encoding/hex"
7 "fmt"
8 "io"
9 "net"
10 "net/http"
11 "strconv"
12 "strings"
13 "sync"
14)
15
16var pngIENDMarker = []byte{0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}
17
18var (
19 vibeProxyMu sync.Mutex
20 vibeProxyServer *vibeProxy
21)
22
23type vibeSession struct {
24 masterURL string
25 referer string
26 variants map[string][]vibeSegment
27}
28
29type vibeSegment struct {
30 duration float64
31 url string
32}
33
34type vibeProxy struct {
35 baseURL string
36 server *http.Server
37 sessions map[string]*vibeSession
38}
39
40func registerVibeStream(masterURL, referer string) (string, error) {
41 proxy, err := getVibeProxy()
42 if err != nil {
43 return "", err
44 }
45 return proxy.register(masterURL, referer)
46}
47
48func getVibeProxy() (*vibeProxy, error) {
49 vibeProxyMu.Lock()
50 defer vibeProxyMu.Unlock()
51
52 if vibeProxyServer != nil {
53 return vibeProxyServer, nil
54 }
55
56 proxy := &vibeProxy{sessions: map[string]*vibeSession{}}
57 mux := http.NewServeMux()
58 mux.HandleFunc("/stream/", proxy.handle)
59 server := &http.Server{Handler: mux}
60
61 listener, err := net.Listen("tcp", "127.0.0.1:0")
62 if err != nil {
63 return nil, fmt.Errorf("start vibe proxy listener: %w", err)
64 }
65 proxy.server = server
66 proxy.baseURL = "http://" + listener.Addr().String()
67
68 go func() {
69 _ = server.Serve(listener)
70 }()
71
72 vibeProxyServer = proxy
73 return proxy, nil
74}
75
76func (p *vibeProxy) register(masterURL, referer string) (string, error) {
77 id, err := randomSessionID()
78 if err != nil {
79 return "", err
80 }
81 vibeProxyMu.Lock()
82 p.sessions[id] = &vibeSession{
83 masterURL: masterURL,
84 referer: referer,
85 variants: map[string][]vibeSegment{},
86 }
87 vibeProxyMu.Unlock()
88 return p.baseURL + "/stream/" + id + "/master.m3u8", nil
89}
90
91func (p *vibeProxy) handle(w http.ResponseWriter, r *http.Request) {
92 path := strings.TrimPrefix(r.URL.Path, "/stream/")
93 parts := strings.Split(path, "/")
94 if len(parts) < 2 {
95 http.NotFound(w, r)
96 return
97 }
98 sessionID := parts[0]
99
100 vibeProxyMu.Lock()
101 session, ok := p.sessions[sessionID]
102 vibeProxyMu.Unlock()
103 if !ok {
104 http.NotFound(w, r)
105 return
106 }
107
108 switch {
109 case len(parts) == 2 && parts[1] == "master.m3u8":
110 p.serveMaster(w, sessionID, session, parts[1])
111 case len(parts) == 2 && strings.HasSuffix(parts[1], ".m3u8"):
112 p.serveVariant(w, sessionID, session, parts[1])
113 case len(parts) == 4 && parts[2] == "seg":
114 p.serveSegment(w, r, session, parts[1], parts[3])
115 default:
116 http.NotFound(w, r)
117 }
118}
119
120func (p *vibeProxy) serveMaster(w http.ResponseWriter, sessionID string, session *vibeSession, _ string) {
121 body, err := fetchString(session.masterURL, session.referer)
122 if err != nil {
123 http.Error(w, err.Error(), http.StatusBadGateway)
124 return
125 }
126 rewritten := rewritePlaylistLines(body, func(line string) string {
127 line = strings.TrimSpace(line)
128 if line == "" || strings.HasPrefix(line, "#") {
129 return line
130 }
131 return p.baseURL + "/stream/" + sessionID + "/" + line
132 })
133 writePlaylist(w, rewritten)
134}
135
136func (p *vibeProxy) serveVariant(w http.ResponseWriter, sessionID string, session *vibeSession, variantName string) {
137 variantURL := resolvePlaylistURL(session.masterURL, variantName)
138 body, err := fetchString(variantURL, session.referer)
139 if err != nil {
140 http.Error(w, err.Error(), http.StatusBadGateway)
141 return
142 }
143
144 segments := make([]vibeSegment, 0)
145 var currentDuration float64
146 rewritten := rewritePlaylistLines(body, func(line string) string {
147 line = strings.TrimSpace(line)
148 if strings.HasPrefix(line, "#EXTINF:") {
149 currentDuration = parseExtInfDuration(line)
150 return line
151 }
152 if line == "" || strings.HasPrefix(line, "#") {
153 return line
154 }
155 segmentURL := resolvePlaylistURL(variantURL, line)
156 index := len(segments)
157 segments = append(segments, vibeSegment{duration: currentDuration, url: segmentURL})
158 return fmt.Sprintf("%s/stream/%s/%s/seg/%d", p.baseURL, sessionID, variantName, index)
159 })
160
161 vibeProxyMu.Lock()
162 session.variants[variantName] = segments
163 vibeProxyMu.Unlock()
164
165 writePlaylist(w, rewritten)
166}
167
168func (p *vibeProxy) serveSegment(w http.ResponseWriter, r *http.Request, session *vibeSession, variantName, indexText string) {
169 index, err := strconv.Atoi(indexText)
170 if err != nil || index < 0 {
171 http.NotFound(w, r)
172 return
173 }
174
175 vibeProxyMu.Lock()
176 segments := session.variants[variantName]
177 vibeProxyMu.Unlock()
178 if index >= len(segments) {
179 http.NotFound(w, r)
180 return
181 }
182
183 data, err := fetchBytes(segments[index].url, session.referer)
184 if err != nil {
185 http.Error(w, err.Error(), http.StatusBadGateway)
186 return
187 }
188 body := stripPNGWrapper(data)
189 w.Header().Set("Content-Type", "video/mp2t")
190 w.Header().Set("Content-Length", strconv.Itoa(len(body)))
191 _, _ = w.Write(body)
192}
193
194func rewritePlaylistLines(playlist string, mapLine func(string) string) string {
195 lines := strings.Split(strings.ReplaceAll(playlist, "\r\n", "\n"), "\n")
196 for i, line := range lines {
197 lines[i] = mapLine(line)
198 }
199 return strings.Join(lines, "\n")
200}
201
202func parseExtInfDuration(line string) float64 {
203 line = strings.TrimPrefix(strings.TrimSpace(line), "#EXTINF:")
204 if idx := strings.Index(line, ","); idx >= 0 {
205 line = line[:idx]
206 }
207 value, err := strconv.ParseFloat(strings.TrimSpace(line), 64)
208 if err != nil {
209 return 0
210 }
211 return value
212}
213
214func stripPNGWrapper(data []byte) []byte {
215 idx := bytes.Index(data, pngIENDMarker)
216 if idx < 0 {
217 return data
218 }
219 return data[idx+len(pngIENDMarker):]
220}
221
222func writePlaylist(w http.ResponseWriter, body string) {
223 w.Header().Set("Content-Type", "application/vnd.apple.mpegurl")
224 _, _ = io.WriteString(w, body)
225}
226
227func randomSessionID() (string, error) {
228 buf := make([]byte, 8)
229 if _, err := rand.Read(buf); err != nil {
230 return "", err
231 }
232 return hex.EncodeToString(buf), nil
233}
234
235func resetVibeProxyForTest() {
236 vibeProxyMu.Lock()
237 defer vibeProxyMu.Unlock()
238 if vibeProxyServer != nil && vibeProxyServer.server != nil {
239 _ = vibeProxyServer.server.Close()
240 }
241 vibeProxyServer = nil
242}
internal/providers/lang.go added +17
@@ -0,0 +1,17 @@
1package providers
2
3import "strings"
4
5func NormalizeTranslationType(mode string) string {
6 if strings.EqualFold(strings.TrimSpace(mode), "dub") {
7 return "dub"
8 }
9 return "sub"
10}
11
12func AlternateTranslationType(mode string) string {
13 if NormalizeTranslationType(mode) == "dub" {
14 return "sub"
15 }
16 return "dub"
17}
internal/providers/registry.go added +170
@@ -0,0 +1,170 @@
1package providers
2
3import (
4 "fmt"
5 "sort"
6 "strings"
7 "sync"
8)
9
10// Meta describes a registered streaming provider.
11type Meta struct {
12 Name string
13 Aliases []string
14 Referrer string
15 DefaultDisabled bool
16 DisableReason string
17 // OptOutToken excludes a provider from automatic fallback prompts, e.g. "no-animepahe".
18 OptOutToken string
19 // FallbackPrompt is shown when the host offers this provider as a fallback.
20 FallbackPrompt string
21}
22
23type entry struct {
24 meta Meta
25 factory func() Provider
26}
27
28var (
29 registryMu sync.RWMutex
30 registry = map[string]entry{}
31 aliases = map[string]string{}
32)
33
34// Register adds a provider factory to the global registry.
35func Register(meta Meta, factory func() Provider) {
36 registryMu.Lock()
37 defer registryMu.Unlock()
38
39 meta.Name = strings.ToLower(strings.Trim(strings.TrimSpace(meta.Name), "\"'[]"))
40 if meta.Name == "" {
41 panic("providers.Register: Name is required")
42 }
43 if factory == nil {
44 panic("providers.Register: factory is required")
45 }
46
47 meta.Name = strings.ReplaceAll(strings.ReplaceAll(meta.Name, "-", ""), " ", "")
48 if meta.Name == "" {
49 panic("providers.Register: Name is required")
50 }
51
52 registry[meta.Name] = entry{meta: meta, factory: factory}
53 registerAlias(meta.Name, meta.Name)
54 for _, alias := range meta.Aliases {
55 registerAlias(alias, meta.Name)
56 }
57}
58
59func registerAlias(alias, canonical string) {
60 alias = strings.Trim(strings.TrimSpace(alias), "\"'[]")
61 if alias == "" {
62 return
63 }
64 aliases[strings.ToLower(strings.Join(strings.Fields(alias), " "))] = canonical
65 compact := strings.ToLower(alias)
66 compact = strings.ReplaceAll(compact, "-", "")
67 compact = strings.ReplaceAll(compact, "_", "")
68 compact = strings.ReplaceAll(compact, " ", "")
69 if compact != "" {
70 aliases[compact] = canonical
71 }
72}
73
74// NormalizeName maps user/config input to a canonical provider name.
75func NormalizeName(name string) string {
76 registryMu.RLock()
77 defer registryMu.RUnlock()
78 return normalizeName(name)
79}
80
81func normalizeName(name string) string {
82 name = strings.Trim(strings.TrimSpace(name), "\"'[]")
83 if name == "" {
84 return ""
85 }
86 key := strings.ToLower(strings.Join(strings.Fields(name), " "))
87 if canonical, ok := aliases[key]; ok {
88 return canonical
89 }
90 key = strings.ReplaceAll(key, "-", "")
91 key = strings.ReplaceAll(key, "_", "")
92 key = strings.ReplaceAll(key, " ", "")
93 if canonical, ok := aliases[key]; ok {
94 return canonical
95 }
96 return ""
97}
98
99// MetaFor returns registration metadata for a provider name.
100func MetaFor(name string) (Meta, bool) {
101 registryMu.RLock()
102 defer registryMu.RUnlock()
103
104 name = normalizeName(name)
105 if name == "" {
106 return Meta{}, false
107 }
108 entry, ok := registry[name]
109 if !ok {
110 return Meta{}, false
111 }
112 return entry.meta, true
113}
114
115// RegisteredNames returns sorted canonical provider names.
116func RegisteredNames() []string {
117 registryMu.RLock()
118 defer registryMu.RUnlock()
119
120 names := make([]string, 0, len(registry))
121 for name := range registry {
122 names = append(names, name)
123 }
124 sort.Strings(names)
125 return names
126}
127
128// New creates a provider instance by canonical name.
129func New(name string) (Provider, error) {
130 registryMu.RLock()
131 defer registryMu.RUnlock()
132
133 name = normalizeName(name)
134 if name == "" {
135 return nil, fmt.Errorf("unknown provider %q", name)
136 }
137 entry, ok := registry[name]
138 if !ok {
139 return nil, fmt.Errorf("unknown provider %q", name)
140 }
141 return entry.factory(), nil
142}
143
144// Referrer returns the stream referrer for a provider, if configured.
145func Referrer(name string) string {
146 meta, ok := MetaFor(name)
147 if !ok {
148 return ""
149 }
150 return meta.Referrer
151}
152
153// SetFactoryForTest overrides a provider factory for the duration of a test.
154func SetFactoryForTest(name string, factory func() Provider) (restore func()) {
155 registryMu.Lock()
156 defer registryMu.Unlock()
157
158 name = normalizeName(name)
159 previous, ok := registry[name]
160 if !ok {
161 panic(fmt.Sprintf("providers.SetFactoryForTest: unknown provider %q", name))
162 }
163
164 registry[name] = entry{meta: previous.meta, factory: factory}
165 return func() {
166 registryMu.Lock()
167 registry[name] = previous
168 registryMu.Unlock()
169 }
170}
internal/providers/types.go added +46
@@ -0,0 +1,46 @@
1package providers
2
3// SelectionOption is a provider search or menu result item.
4type SelectionOption struct {
5 Key string
6 Label string
7 Title string
8 Thumbnail string
9 ExtraData any
10}
11
12// PlaybackConfig carries playback preferences passed into providers.
13type PlaybackConfig struct {
14 SubOrDub string
15 // SubStyle controls anineko subtitle stream tabs: ask, soft, or hard.
16 SubStyle string
17}
18
19// StreamPlaybackHint carries MPV playback metadata for a resolved stream URL.
20type StreamPlaybackHint struct {
21 Referrer string
22 Subtitle string
23}
24
25// Provider resolves catalog search, episode lists, and stream URLs.
26type Provider interface {
27 Name() string
28 SearchAnime(query, mode string) ([]SelectionOption, error)
29 EpisodesList(showID, mode string) ([]string, error)
30 GetEpisodeURL(config PlaybackConfig, id string, epNo int) ([]string, error)
31}
32
33// ModeResolver resolves episode URLs for an explicit sub/dub mode.
34type ModeResolver interface {
35 GetEpisodeURLForMode(config PlaybackConfig, id string, epNo int, mode string) ([]string, error)
36}
37
38// HintResolver resolves episode URLs with MPV playback hints.
39type HintResolver interface {
40 GetEpisodeURLForModeWithHints(config PlaybackConfig, id string, epNo int, mode string) ([]string, map[string]StreamPlaybackHint, error)
41}
42
43// IDResolver refreshes or validates a provider-specific show ID.
44type IDResolver interface {
45 ResolveProviderID(providerID, query string) (string, error)
46}
internal/structs.go +10 −2
@@ -71,6 +71,12 @@ type NextEpisode struct {
7171 Mode string
7272}
7373
74// StreamPlaybackHint carries MPV playback metadata for a resolved stream URL.
75type StreamPlaybackHint struct {
76 Referrer string
77 Subtitle string
78}
79
7480type playingVideo struct {
7581 Url string
7682 Speed float64 `json:"speed"`
@@ -98,8 +104,9 @@ func GetGlobalUser() *User {
98104
99105// AniListAnime is the struct for the API response
100106type AniListAnime struct {
101 ID int `json:"id"`
102 Title struct {
107 ID int `json:"id"`
108 Episodes int `json:"episodes"`
109 Title struct {
103110 Romaji string `json:"romaji"`
104111 English string `json:"english"`
105112 Native string `json:"native"`
@@ -122,6 +129,7 @@ type ResponseData struct {
122129type Media struct {
123130 Duration int `json:"duration"`
124131 Episodes int `json:"episodes"`
132 Format string `json:"format"`
125133 ID int `json:"id"`
126134 MalID int `json:"mal_id"`
127135 Title AnimeTitle `json:"title"`
internal/user_intent_regression_test.go +8 −1
@@ -141,6 +141,7 @@ func TestGetProviderTotalEpisodesReturnsLookupErrorsWhenNoEpisodesFound(t *testi
141141}
142142
143143func TestGetAllAnimeEpisodesListUsesValidGraphQLVariableSyntax(t *testing.T) {
144 withAllProvidersEnabledForTest(t)
144145 previousClient := sharedHTTPClient
145146 t.Cleanup(func() {
146147 sharedHTTPClient = previousClient
@@ -163,7 +164,13 @@ func TestGetAllAnimeEpisodesListUsesValidGraphQLVariableSyntax(t *testing.T) {
163164 return testHTTPResponse(req, http.StatusOK, `{"data":{"show":{"_id":"show-id","availableEpisodesDetail":{"sub":[1,2,12]}}}}`), nil
164165 })}
165166
166 episodes, err := getAllAnimeEpisodesList("show-id", "sub")
167 episodes, err := func() ([]string, error) {
168 provider, err := ProviderByName("allanime")
169 if err != nil {
170 return nil, err
171 }
172 return provider.EpisodesList("show-id", "sub")
173 }()
167174 if err != nil {
168175 t.Fatalf("expected allanime episode list lookup to succeed: %v", err)
169176 }