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) {
69 } 69 }
70} 70}
71 71
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
89func BenchmarkLevenshteinAnimeTitles(b *testing.B) { 72func BenchmarkLevenshteinAnimeTitles(b *testing.B) {
90 for i := 0; i < b.N; i++ { 73 for i := 0; i < b.N; i++ {
91 _ = levenshtein("Sousou no Frieren Beyond Journey's End", "Frieren Beyond Journey's End") 74 _ = 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) {
10 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" { 10 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" {
11 t.Skip("set CURD_LIVE_ALLANIME_TEST=1") 11 t.Skip("set CURD_LIVE_ALLANIME_TEST=1")
12 } 12 }
13 withAllProvidersEnabledForTest(t)
13 14
14 showID := "NPpCgzb2MbnpiyxZ3" 15 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")
16 if err == nil { 25 if err == nil {
17 for _, link := range links { 26 for _, link := range links {
18 if strings.Contains(link, "fast4speed.rsvp") { 27 if strings.Contains(link, "fast4speed.rsvp") {
@@ -27,9 +36,18 @@ func TestAllanimeMarchLionSubEp1Live(t *testing.T) {
27 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" { 36 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" {
28 t.Skip("set CURD_LIVE_ALLANIME_TEST=1") 37 t.Skip("set CURD_LIVE_ALLANIME_TEST=1")
29 } 38 }
39 withAllProvidersEnabledForTest(t)
30 40
31 showID := "NPpCgzb2MbnpiyxZ3" 41 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")
33 if err != nil { 51 if err != nil {
34 t.Fatalf("sub episode link lookup failed: %v", err) 52 t.Fatalf("sub episode link lookup failed: %v", err)
35 } 53 }
internal/links.go +20
@@ -42,3 +42,23 @@ func linkSelectionScore(link string) int {
42 score += wixmpQualityScore(link) 42 score += wixmpQualityScore(link)
43 return score 43 return score
44} 44}
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) {
219 CurrentProvider = nil 219 CurrentProvider = nil
220 SetGlobalConfig(&CurdConfig{Provider: " AllAnime "}) 220 SetGlobalConfig(&CurdConfig{Provider: " AllAnime "})
221 221
222 if got := GetProvider().Name(); got != "allanime" { 222 if got := GetProvider().Name(); got != "anineko" {
223 t.Fatalf("expected allanime provider, got %q", got) 223 t.Fatalf("expected anineko provider when allanime is disabled, got %q", got)
224 } 224 }
225} 225}
226 226
@@ -235,8 +235,8 @@ func TestGetProviderFallsBackWhenConfiguredProviderDisabled(t *testing.T) {
235 CurrentProvider = nil 235 CurrentProvider = nil
236 SetGlobalConfig(&CurdConfig{Provider: " AnimePahe "}) 236 SetGlobalConfig(&CurdConfig{Provider: " AnimePahe "})
237 237
238 if got := GetProvider().Name(); got != "allanime" { 238 if got := GetProvider().Name(); got != "anineko" {
239 t.Fatalf("expected allanime fallback for disabled provider, got %q", got) 239 t.Fatalf("expected anineko fallback for disabled provider, got %q", got)
240 } 240 }
241} 241}
242 242
internal/player.go +4 −2
@@ -12,6 +12,8 @@ import (
12 "strings" 12 "strings"
13 "sync" 13 "sync"
14 "time" 14 "time"
15
16 "github.com/wraient/curd/internal/providers"
15) 17)
16 18
17var logFile = "debug.log" 19var logFile = "debug.log"
@@ -23,8 +25,8 @@ func streamReferrerForLink(link, provider string) string {
23 if strings.Contains(strings.ToLower(link), "tools.fast4speed.rsvp") { 25 if strings.Contains(strings.ToLower(link), "tools.fast4speed.rsvp") {
24 return "https://allanime.to" 26 return "https://allanime.to"
25 } 27 }
26 if provider == "animepahe" { 28 if referrer := providers.Referrer(provider); referrer != "" {
27 return "https://kwik.cx/" 29 return referrer
28 } 30 }
29 return defaultStreamReferrer 31 return defaultStreamReferrer
30} 32}
internal/provider.go +49 −30
@@ -4,6 +4,9 @@ import (
4 "fmt" 4 "fmt"
5 "strconv" 5 "strconv"
6 "strings" 6 "strings"
7
8 "github.com/wraient/curd/internal/providers"
9 "github.com/wraient/curd/internal/providers/animepahe"
7) 10)
8 11
9// Provider interface defines methods for an anime provider. 12// Provider interface defines methods for an anime provider.
@@ -27,26 +30,12 @@ type ProviderEpisodeResult struct {
27} 30}
28 31
29const providerIDSeparator = "::" 32const providerIDSeparator = "::"
30const animepaheOptOutProvider = "no-animepahe"
31 33
32// Global variable to keep the current provider 34// Global variable to keep the current provider
33var CurrentProvider Provider 35var CurrentProvider Provider
34 36
35var providerFactories = map[string]func() Provider{
36 "allanime": func() Provider { return &AllanimeProvider{} },
37 "animepahe": func() Provider { return &AnimepaheProvider{} },
38}
39
40func normalizeProviderName(providerName string) string { 37func normalizeProviderName(providerName string) string {
41 providerName = strings.Trim(strings.TrimSpace(providerName), "\"'[]") 38 return providers.NormalizeName(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 }
50} 39}
51 40
52func normalizeProviderConfigToken(token string) string { 41func normalizeProviderConfigToken(token string) string {
@@ -69,7 +58,7 @@ func parseProviderConfigParts(rawProvider string) []string {
69func parseProviderConfig(rawProvider string) ([]string, bool) { 58func parseProviderConfig(rawProvider string) ([]string, bool) {
70 rawProvider = strings.TrimSpace(rawProvider) 59 rawProvider = strings.TrimSpace(rawProvider)
71 if rawProvider == "" { 60 if rawProvider == "" {
72 rawProvider = "allanime" 61 rawProvider = firstEnabledProviderName()
73 } 62 }
74 63
75 normalizedRaw := strings.ToLower(rawProvider) 64 normalizedRaw := strings.ToLower(rawProvider)
@@ -83,7 +72,7 @@ func parseProviderConfig(rawProvider string) ([]string, bool) {
83 animepaheDeclined := false 72 animepaheDeclined := false
84 73
85 for _, part := range parts { 74 for _, part := range parts {
86 if normalizeProviderConfigToken(part) == animepaheOptOutProvider { 75 if isProviderOptOutToken(part) {
87 animepaheDeclined = true 76 animepaheDeclined = true
88 continue 77 continue
89 } 78 }
@@ -112,14 +101,14 @@ func parseProviderConfig(rawProvider string) ([]string, bool) {
112 } 101 }
113 102
114 if len(providers) == 0 { 103 if len(providers) == 0 {
115 providers = []string{"allanime"} 104 providers = []string{firstEnabledProviderName()}
116 } 105 }
117 106
118 return providers, animepaheDeclined 107 return providers, animepaheDeclined
119} 108}
120 109
121func configuredProviderNames(config *CurdConfig) []string { 110func configuredProviderNames(config *CurdConfig) []string {
122 rawProvider := "allanime" 111 rawProvider := firstEnabledProviderName()
123 if config != nil && strings.TrimSpace(config.Provider) != "" { 112 if config != nil && strings.TrimSpace(config.Provider) != "" {
124 rawProvider = config.Provider 113 rawProvider = config.Provider
125 } 114 }
@@ -143,11 +132,38 @@ func formatProviderConfigValue(names []string, animepaheDeclined bool) string {
143 quotedNames = append(quotedNames, fmt.Sprintf("%q", name)) 132 quotedNames = append(quotedNames, fmt.Sprintf("%q", name))
144 } 133 }
145 if animepaheDeclined { 134 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 }
147 } 138 }
148 return "[" + strings.Join(quotedNames, ",") + "]" 139 return "[" + strings.Join(quotedNames, ",") + "]"
149} 140}
150 141
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
151func animepaheDeclinedInConfig(config *CurdConfig) bool { 167func animepaheDeclinedInConfig(config *CurdConfig) bool {
152 if config == nil { 168 if config == nil {
153 return false 169 return false
@@ -174,11 +190,11 @@ func ProviderByName(providerName string) (Provider, error) {
174 if reason := providerDisabledReason(providerName); reason != "" { 190 if reason := providerDisabledReason(providerName); reason != "" {
175 return nil, fmt.Errorf("provider %q is disabled: %s", providerName, reason) 191 return nil, fmt.Errorf("provider %q is disabled: %s", providerName, reason)
176 } 192 }
177 factory, ok := providerFactories[providerName] 193 provider, err := providers.New(providerName)
178 if !ok { 194 if err != nil {
179 return nil, fmt.Errorf("unknown provider %q", providerName) 195 return nil, err
180 } 196 }
181 return factory(), nil 197 return wrapProvider(provider), nil
182} 198}
183 199
184func GetProvider() Provider { 200func GetProvider() Provider {
@@ -190,8 +206,11 @@ func GetProvider() Provider {
190 primaryProviderName := providerNames[0] 206 primaryProviderName := providerNames[0]
191 provider, err := ProviderByName(primaryProviderName) 207 provider, err := ProviderByName(primaryProviderName)
192 if err != nil { 208 if err != nil {
193 CurrentProvider = &AllanimeProvider{} 209 if fallback, fallbackErr := ProviderByName(firstEnabledProviderName()); fallbackErr == nil {
194 return CurrentProvider 210 CurrentProvider = fallback
211 return CurrentProvider
212 }
213 return provider
195 } 214 }
196 CurrentProvider = provider 215 CurrentProvider = provider
197 return CurrentProvider 216 return CurrentProvider
@@ -280,7 +299,7 @@ func providerNamesForAnime(config *CurdConfig, anime *Anime) []string {
280 } 299 }
281 } 300 }
282 if len(result) == 0 { 301 if len(result) == 0 {
283 return []string{"allanime"} 302 return []string{firstEnabledProviderName()}
284 } 303 }
285 return result 304 return result
286} 305}
@@ -425,7 +444,7 @@ func appendProviderName(providerNames []string, providerName string) []string {
425 } 444 }
426 } 445 }
427 if len(result) == 0 { 446 if len(result) == 0 {
428 return []string{"allanime"} 447 return []string{firstEnabledProviderName()}
429 } 448 }
430 return result 449 return result
431} 450}
@@ -635,7 +654,7 @@ func episodeModeResult(config CurdConfig, anime *Anime, epNo int, mode string) (
635func episodeModeResultWithProviders(config CurdConfig, anime *Anime, epNo int, mode string, providerNames []string) (ProviderEpisodeResult, error) { 654func episodeModeResultWithProviders(config CurdConfig, anime *Anime, epNo int, mode string, providerNames []string) (ProviderEpisodeResult, error) {
636 mode = normalizeTranslationType(mode) 655 mode = normalizeTranslationType(mode)
637 if len(providerNames) == 0 { 656 if len(providerNames) == 0 {
638 providerNames = []string{"allanime"} 657 providerNames = []string{firstEnabledProviderName()}
639 } 658 }
640 659
641 var errors []string 660 var errors []string
@@ -832,7 +851,7 @@ func scoreProviderSearchOption(option SelectionOption, anime *Anime, query strin
832 if anime.TotalEpisodes > 0 && strings.Contains(option.Label, fmt.Sprintf("(%d episodes)", anime.TotalEpisodes)) { 851 if anime.TotalEpisodes > 0 && strings.Contains(option.Label, fmt.Sprintf("(%d episodes)", anime.TotalEpisodes)) {
833 score += 20 852 score += 20
834 } 853 }
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 {
836 score += 20 855 score += 20
837 } 856 }
838 return score 857 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
2 2
3import ( 3import (
4 "sort" 4 "sort"
5 "strings"
5 "testing" 6 "testing"
6)
7 7
8// disabledProviders lists providers kept in source but excluded from runtime use. 8 "github.com/wraient/curd/internal/providers"
9// Remove a provider from this map to re-enable it without restoring deleted code. 9)
10var disabledProviders = map[string]string{
11 "animepahe": "Cloudflare/DDoS-Guard protection cannot be bypassed reliably",
12}
13 10
14var disabledProviderReasonForTest func(string) string 11var disabledProviderReasonForTest func(string) string
15 12
@@ -21,7 +18,56 @@ func providerDisabledReason(name string) string {
21 if disabledProviderReasonForTest != nil { 18 if disabledProviderReasonForTest != nil {
22 return disabledProviderReasonForTest(name) 19 return disabledProviderReasonForTest(name)
23 } 20 }
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
25} 71}
26 72
27// ProviderEnabled reports whether a provider may be used at runtime. 73// ProviderEnabled reports whether a provider may be used at runtime.
@@ -55,11 +101,7 @@ func filterEnabledProviders(names []string) []string {
55} 101}
56 102
57func defaultEnabledProviderStack() []string { 103func defaultEnabledProviderStack() []string {
58 names := make([]string, 0, len(providerFactories)) 104 names := providers.RegisteredNames()
59 for name := range providerFactories {
60 names = append(names, name)
61 }
62 sort.Strings(names)
63 return filterEnabledProviders(names) 105 return filterEnabledProviders(names)
64} 106}
65 107
@@ -87,12 +129,32 @@ func providerSelectionOptions() []SelectionOption {
87 return options 129 return options
88} 130}
89 131
132func firstEnabledProviderName() string {
133 enabled := defaultEnabledProviderStack()
134 if len(enabled) > 0 {
135 return enabled[0]
136 }
137 return "anineko"
138}
139
90func ensureEnabledProviderNames(names []string) []string { 140func ensureEnabledProviderNames(names []string) []string {
91 enabled := filterEnabledProviders(names) 141 enabled := filterEnabledProviders(names)
92 if len(enabled) > 0 { 142 if len(enabled) > 0 {
93 return enabled 143 return enabled
94 } 144 }
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()}
96} 158}
97 159
98func withAllProvidersEnabledForTest(t *testing.T) { 160func withAllProvidersEnabledForTest(t *testing.T) {
@@ -103,3 +165,10 @@ func withAllProvidersEnabledForTest(t *testing.T) {
103 disabledProviderReasonForTest = previous 165 disabledProviderReasonForTest = previous
104 }) 166 })
105} 167}
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
2 2
3import "testing" 3import "testing"
4 4
5func TestProviderEnabledDisablesAnimepaheByDefault(t *testing.T) { 5func TestProviderEnabledDisablesAllanimeAndAnimepaheByDefault(t *testing.T) {
6 if ProviderEnabled("allanime") != true { 6 if ProviderEnabled("allanime") != false {
7 t.Fatal("expected allanime to stay enabled") 7 t.Fatal("expected allanime to be disabled by default")
8 } 8 }
9 if ProviderEnabled("animepahe") != false { 9 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")
11 } 17 }
12 if reason := ProviderDisabledReason("animepahe"); reason == "" { 18 if reason := ProviderDisabledReason("animepahe"); reason == "" {
13 t.Fatal("expected animepahe disable reason") 19 t.Fatal("expected animepahe disable reason")
@@ -20,10 +26,11 @@ func TestConfiguredProviderNamesFiltersDisabledProviders(t *testing.T) {
20 cfg *CurdConfig 26 cfg *CurdConfig
21 want []string 27 want []string
22 }{ 28 }{
23 {name: "empty", cfg: &CurdConfig{}, want: []string{"allanime"}}, 29 {name: "empty", cfg: &CurdConfig{}, want: []string{"anineko"}},
24 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"allanime"}}, 30 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"anineko"}},
25 {name: "animepahe only", cfg: &CurdConfig{Provider: `["animepahe"]`}, want: []string{"allanime"}}, 31 {name: "animepahe only", cfg: &CurdConfig{Provider: `["animepahe"]`}, want: []string{"anineko"}},
26 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"allanime"}}, 32 {name: "allanime only", cfg: &CurdConfig{Provider: `["allanime"]`}, want: []string{"anineko"}},
33 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"anineko"}},
27 } 34 }
28 35
29 for _, tc := range cases { 36 for _, tc := range cases {
@@ -50,19 +57,23 @@ func TestConfiguredProviderNamesHonorsEnabledProvidersWhenOverridden(t *testing.
50} 57}
51 58
52func TestProviderByNameRejectsDisabledProvider(t *testing.T) { 59func TestProviderByNameRejectsDisabledProvider(t *testing.T) {
53 if _, err := ProviderByName("animepahe"); err == nil { 60 for _, name := range []string{"animepahe", "allanime"} {
54 t.Fatal("expected disabled provider error") 61 if _, err := ProviderByName(name); err == nil {
62 t.Fatalf("expected disabled provider error for %s", name)
63 }
55 } 64 }
56} 65}
57 66
58func TestProviderByNameAllowsDisabledProviderWhenOverridden(t *testing.T) { 67func TestProviderByNameAllowsDisabledProviderWhenOverridden(t *testing.T) {
59 withAllProvidersEnabledForTest(t) 68 withAllProvidersEnabledForTest(t)
60 69
61 provider, err := ProviderByName("animepahe") 70 for _, name := range []string{"animepahe", "allanime"} {
62 if err != nil { 71 provider, err := ProviderByName(name)
63 t.Fatalf("expected animepahe provider: %v", err) 72 if err != nil {
64 } 73 t.Fatalf("expected %s provider: %v", name, err)
65 if provider.Name() != "animepahe" { 74 }
66 t.Fatalf("got provider %q", provider.Name()) 75 if provider.Name() != name {
76 t.Fatalf("got provider %q", provider.Name())
77 }
67 } 78 }
68} 79}
internal/provider_stack_test.go +35 −10
@@ -6,6 +6,8 @@ import (
6 "path/filepath" 6 "path/filepath"
7 "strings" 7 "strings"
8 "testing" 8 "testing"
9
10 "github.com/wraient/curd/internal/providers"
9) 11)
10 12
11type stackStubProvider struct { 13type stackStubProvider struct {
@@ -47,21 +49,44 @@ func (s *stackStubProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
47 return nil, nil 49 return nil, nil
48} 50}
49 51
50func withProviderFactories(t *testing.T, providers ...*stackStubProvider) { 52func withProviderFactories(t *testing.T, stubs ...*stackStubProvider) {
51 t.Helper() 53 t.Helper()
52 withAllProvidersEnabledForTest(t) 54 withAllProvidersEnabledForTest(t)
53 previousAllanime := providerFactories["allanime"] 55 restores := make([]func(), 0, len(stubs))
54 previousAnimepahe := providerFactories["animepahe"] 56 for _, stub := range stubs {
55 for _, provider := range providers { 57 stub := stub
56 provider := provider 58 restores = append(restores, providers.SetFactoryForTest(stub.name, func() providers.Provider {
57 providerFactories[provider.name] = func() Provider { return provider } 59 return &stackStubProviderBridge{stub}
60 }))
58 } 61 }
59 t.Cleanup(func() { 62 t.Cleanup(func() {
60 providerFactories["allanime"] = previousAllanime 63 for i := len(restores) - 1; i >= 0; i-- {
61 providerFactories["animepahe"] = previousAnimepahe 64 restores[i]()
65 }
62 }) 66 })
63} 67}
64 68
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
65func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) { 90func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) {
66 withAllProvidersEnabledForTest(t) 91 withAllProvidersEnabledForTest(t)
67 92
@@ -74,7 +99,7 @@ func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) {
74 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"allanime", "animepahe"}}, 99 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"allanime", "animepahe"}},
75 {name: "comma list", cfg: &CurdConfig{Provider: "animepahe,allanime"}, want: []string{"animepahe", "allanime"}}, 100 {name: "comma list", cfg: &CurdConfig{Provider: "animepahe,allanime"}, want: []string{"animepahe", "allanime"}},
76 {name: "plus list", cfg: &CurdConfig{Provider: "allanime+animepahe"}, want: []string{"allanime", "animepahe"}}, 101 {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"}},
78 } 103 }
79 104
80 for _, tc := range cases { 105 for _, tc := range cases {
@@ -100,7 +125,7 @@ func TestCanonicalProviderConfigValueMigratesLegacyValuesWithoutAddingAnimepahe(
100 {name: "legacy animepahe", raw: "animepahe", want: `["animepahe"]`}, 125 {name: "legacy animepahe", raw: "animepahe", want: `["animepahe"]`},
101 {name: "ordered stack", raw: "animepahe,allanime", want: `["animepahe","allanime"]`}, 126 {name: "ordered stack", raw: "animepahe,allanime", want: `["animepahe","allanime"]`},
102 {name: "animepahe opt out", raw: "allanime,no-animepahe", want: `["allanime","no-animepahe"]`}, 127 {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"]`},
104 } 129 }
105 130
106 for _, tc := range cases { 131 for _, tc := range cases {
internal/episode_list.go → internal/providers/allanime/episodes.go renamed +11 −8
@@ -1,4 +1,4 @@
1package internal 1package allanime
2 2
3import ( 3import (
4 "bytes" 4 "bytes"
@@ -8,6 +8,9 @@ import (
8 "net/http" 8 "net/http"
9 "sort" 9 "sort"
10 "strconv" 10 "strconv"
11
12 "github.com/wraient/curd/internal/curdhost"
13 "github.com/wraient/curd/internal/providers"
11) 14)
12 15
13type episodesResponse struct { 16type episodesResponse struct {
@@ -33,7 +36,7 @@ type episodesResponse struct {
33 36
34// episodesList performs the API call and fetches the episodes list 37// episodesList performs the API call and fetches the episodes list
35func getAllAnimeEpisodesList(showID, mode string) ([]string, error) { 38func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
36 preferredMode := normalizeTranslationType(mode) 39 preferredMode := providers.NormalizeTranslationType(mode)
37 40
38 episodesListGql := `query ($showId: String!) { show( _id: $showId ) { _id availableEpisodesDetail }}` 41 episodesListGql := `query ($showId: String!) { show( _id: $showId ) { _id availableEpisodesDetail }}`
39 42
@@ -56,27 +59,27 @@ func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
56 req.Header.Set("Referer", "https://allanime.to") 59 req.Header.Set("Referer", "https://allanime.to")
57 req.Header.Set("Origin", "https://allanime.to") 60 req.Header.Set("Origin", "https://allanime.to")
58 61
59 resp, err := sharedHTTPClient.Do(req) 62 resp, err := curdhost.HTTPClient().Do(req)
60 if err != nil { 63 if err != nil {
61 Log(fmt.Sprint("Error making HTTP request:", err)) 64 curdhost.Log(fmt.Sprint("Error making HTTP request:", err))
62 return nil, err 65 return nil, err
63 } 66 }
64 defer resp.Body.Close() 67 defer resp.Body.Close()
65 68
66 body, err := io.ReadAll(resp.Body) 69 body, err := io.ReadAll(resp.Body)
67 if err != nil { 70 if err != nil {
68 Log(fmt.Sprint("Error reading response body:", err)) 71 curdhost.Log(fmt.Sprint("Error reading response body:", err))
69 return nil, err 72 return nil, err
70 } 73 }
71 if !httpStatusOK(resp.StatusCode) { 74 if !curdhost.HTTPStatusOK(resp.StatusCode) {
72 return nil, httpStatusError("allanime episode list", resp.StatusCode, body) 75 return nil, curdhost.HTTPStatusError("allanime episode list", resp.StatusCode, body)
73 } 76 }
74 77
75 // Parse the JSON response 78 // Parse the JSON response
76 var response episodesResponse 79 var response episodesResponse
77 err = json.Unmarshal(body, &response) 80 err = json.Unmarshal(body, &response)
78 if err != nil { 81 if err != nil {
79 Log(fmt.Sprint("Error parsing JSON:", err)) 82 curdhost.Log(fmt.Sprint("Error parsing JSON:", err))
80 return nil, err 83 return nil, err
81 } 84 }
82 85
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
2 2
3import ( 3import (
4 "bytes" 4 "bytes"
@@ -6,8 +6,9 @@ import (
6 "fmt" 6 "fmt"
7 "io" 7 "io"
8 "net/http" 8 "net/http"
9 "path/filepath" 9
10 "strings" 10 "github.com/wraient/curd/internal/curdhost"
11 "github.com/wraient/curd/internal/providers"
11) 12)
12 13
13type anime struct { 14type anime struct {
@@ -26,20 +27,6 @@ type response struct {
26 } `json:"data"` 27 } `json:"data"`
27} 28}
28 29
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
43// func main() { 30// func main() {
44// // Get environment variables 31// // Get environment variables
45// mode := "sub" 32// mode := "sub"
@@ -55,14 +42,12 @@ func alternateTranslationType(mode string) string {
55// fmt.Println(animeList) 42// fmt.Println(animeList)
56// } 43// }
57 44
58func searchAllAnime(query, mode string) ([]SelectionOption, error) { 45func searchAllAnime(query, mode string) ([]providers.SelectionOption, error) {
59 preferredMode := normalizeTranslationType(mode) 46 preferredMode := providers.NormalizeTranslationType(mode)
60 return searchAnimeByMode(query, preferredMode, preferredMode) 47 return searchAnimeByMode(query, preferredMode, preferredMode)
61} 48}
62 49
63func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, error) { 50func searchAnimeByMode(query, mode, preferredMode string) ([]providers.SelectionOption, error) {
64 userCurdConfig := GetGlobalConfig()
65 logFile = filepath.Join(GetStoragePath(), "debug.log")
66 const ( 51 const (
67 agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0" 52 agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
68 allanimeRef = "https://allanime.to" 53 allanimeRef = "https://allanime.to"
@@ -70,10 +55,10 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
70 allanimeAPI = "https://api." + allanimeBase + "/api" 55 allanimeAPI = "https://api." + allanimeBase + "/api"
71 ) 56 )
72 57
73 mode = normalizeTranslationType(mode) 58 mode = providers.NormalizeTranslationType(mode)
74 preferredMode = normalizeTranslationType(preferredMode) 59 preferredMode = providers.NormalizeTranslationType(preferredMode)
75 60
76 animeList := make([]SelectionOption, 0) 61 animeList := make([]providers.SelectionOption, 0)
77 62
78 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) { 63 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) {
79 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) { 64 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) {
@@ -107,14 +92,14 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
107 "variables": variables, 92 "variables": variables,
108 }) 93 })
109 if err != nil { 94 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))
111 return animeList, err 96 return animeList, err
112 } 97 }
113 98
114 // Make the HTTP POST request 99 // Make the HTTP POST request
115 req, err := http.NewRequest("POST", allanimeAPI, bytes.NewBuffer(requestBody)) 100 req, err := http.NewRequest("POST", allanimeAPI, bytes.NewBuffer(requestBody))
116 if err != nil { 101 if err != nil {
117 Log(fmt.Sprintf("Error creating HTTP request: %v", err)) 102 curdhost.Log(fmt.Sprintf("Error creating HTTP request: %v", err))
118 return animeList, err 103 return animeList, err
119 } 104 }
120 req.Header.Set("Content-Type", "application/json") 105 req.Header.Set("Content-Type", "application/json")
@@ -122,9 +107,9 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
122 req.Header.Set("Referer", allanimeRef) 107 req.Header.Set("Referer", allanimeRef)
123 req.Header.Set("Origin", allanimeRef) 108 req.Header.Set("Origin", allanimeRef)
124 109
125 resp, err := sharedHTTPClient.Do(req) 110 resp, err := curdhost.HTTPClient().Do(req)
126 if err != nil { 111 if err != nil {
127 Log(fmt.Sprintf("Error making HTTP request: %v", err)) 112 curdhost.Log(fmt.Sprintf("Error making HTTP request: %v", err))
128 return animeList, err 113 return animeList, err
129 } 114 }
130 defer resp.Body.Close() 115 defer resp.Body.Close()
@@ -132,16 +117,16 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
132 // Read the response body 117 // Read the response body
133 body, err := io.ReadAll(resp.Body) 118 body, err := io.ReadAll(resp.Body)
134 if err != nil { 119 if err != nil {
135 Log(fmt.Sprintf("Error reading response body: %v", err)) 120 curdhost.Log(fmt.Sprintf("Error reading response body: %v", err))
136 return animeList, err 121 return animeList, err
137 } 122 }
138 123
139 // Debug: Log the response status and first part of the body 124 // Debug: Log the response status and first part of the body
140 Log(fmt.Sprintf("Response Status: %s", resp.Status)) 125 curdhost.Log(fmt.Sprintf("Response Status: %s", resp.Status))
141 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)]))) 126 curdhost.Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
142 if !httpStatusOK(resp.StatusCode) { 127 if !curdhost.HTTPStatusOK(resp.StatusCode) {
143 err := httpStatusError("allanime search", resp.StatusCode, body) 128 err := curdhost.HTTPStatusError("allanime search", resp.StatusCode, body)
144 Log(err) 129 curdhost.Log(err.Error())
145 return animeList, err 130 return animeList, err
146 } 131 }
147 132
@@ -149,7 +134,7 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
149 var response response 134 var response response
150 err = json.Unmarshal(body, &response) 135 err = json.Unmarshal(body, &response)
151 if err != nil { 136 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)))
153 return animeList, err 138 return animeList, err
154 } 139 }
155 140
@@ -167,7 +152,7 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
167 152
168 // Use English name if available and configured, otherwise use default name 153 // Use English name if available and configured, otherwise use default name
169 displayName := anime.Name 154 displayName := anime.Name
170 if anime.EnglishName != "" && userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" { 155 if anime.EnglishName != "" && curdhost.AnimeNameLanguage != nil && curdhost.AnimeNameLanguage() == "english" {
171 displayName = anime.EnglishName 156 displayName = anime.EnglishName
172 } 157 }
173 158
@@ -176,7 +161,7 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
176 label = fmt.Sprintf("%s [%s]", label, mode) 161 label = fmt.Sprintf("%s [%s]", label, mode)
177 } 162 }
178 163
179 animeList = append(animeList, SelectionOption{ 164 animeList = append(animeList, providers.SelectionOption{
180 Title: displayName, 165 Title: displayName,
181 Key: anime.ID, 166 Key: anime.ID,
182 Label: label, 167 Label: label,
internal/episode_url_anicli.go → internal/providers/allanime/streams.go renamed +18 −35
@@ -1,4 +1,4 @@
1package internal 1package allanime
2 2
3import ( 3import (
4 "encoding/json" 4 "encoding/json"
@@ -12,16 +12,13 @@ import (
12 "strings" 12 "strings"
13 "sync" 13 "sync"
14 "time" 14 "time"
15
16 "github.com/wraient/curd/internal/curdhost"
17 "github.com/wraient/curd/internal/providers"
15) 18)
16 19
17const allanimeUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0" 20const allanimeUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
18 21
19// StreamPlaybackHint carries MPV playback metadata extracted from AllAnime clock.json.
20type StreamPlaybackHint struct {
21 Referrer string
22 Subtitle string
23}
24
25type allanimeResolvedStream struct { 22type allanimeResolvedStream struct {
26 URL string 23 URL string
27 Referrer string 24 Referrer string
@@ -36,7 +33,7 @@ var (
36 allanimeStreamBandwidthPattern = regexp.MustCompile(`BANDWIDTH=(\d+)`) 33 allanimeStreamBandwidthPattern = regexp.MustCompile(`BANDWIDTH=(\d+)`)
37) 34)
38 35
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) {
40 sourceUrls, err := fetchEpisodeSourcesForMode(id, mode, epNo) 37 sourceUrls, err := fetchEpisodeSourcesForMode(id, mode, epNo)
41 if err != nil { 38 if err != nil {
42 return nil, nil, err 39 return nil, nil, err
@@ -44,7 +41,7 @@ func getAllanimeEpisodeStreamsForMode(id, mode string, epNo int) ([]string, map[
44 return getLinksFromEncodedSourceUrls(sourceUrls) 41 return getLinksFromEncodedSourceUrls(sourceUrls)
45} 42}
46 43
47func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[string]StreamPlaybackHint, error) { 44func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[string]providers.StreamPlaybackHint, error) {
48 type providerJob struct { 45 type providerJob struct {
49 index int 46 index int
50 name string 47 name string
@@ -84,7 +81,7 @@ func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[s
84 go func(idx int, providerName, encodedURL string) { 81 go func(idx int, providerName, encodedURL string) {
85 defer wg.Done() 82 defer wg.Done()
86 decodedProviderID := decodeProviderID(encodedURL[2:]) 83 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))
88 streams, err := resolveAllanimeClockProvider(providerName, decodedProviderID) 85 streams, err := resolveAllanimeClockProvider(providerName, decodedProviderID)
89 results <- streamResult{index: idx, streams: streams, err: err} 86 results <- streamResult{index: idx, streams: streams, err: err}
90 }(job.index, job.name, job.url) 87 }(job.index, job.name, job.url)
@@ -108,14 +105,14 @@ func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[s
108 } 105 }
109 completedCount++ 106 completedCount++
110 if res.err != nil { 107 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))
112 collectedErrors = append(collectedErrors, fmt.Errorf("%s: %w", jobs[res.index].name, res.err)) 109 collectedErrors = append(collectedErrors, fmt.Errorf("%s: %w", jobs[res.index].name, res.err))
113 continue 110 continue
114 } 111 }
115 if len(res.streams) > 0 { 112 if len(res.streams) > 0 {
116 orderedStreams[res.index] = res.streams 113 orderedStreams[res.index] = res.streams
117 successCount++ 114 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)))
119 } 116 }
120 case <-timeout: 117 case <-timeout:
121 if successCount > 0 { 118 if successCount > 0 {
@@ -131,7 +128,7 @@ func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[s
131 return buildAllanimeLinkResult(orderedStreams) 128 return buildAllanimeLinkResult(orderedStreams)
132} 129}
133 130
134func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]string, map[string]StreamPlaybackHint, error) { 131func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]string, map[string]providers.StreamPlaybackHint, error) {
135 allStreams := make([]allanimeResolvedStream, 0) 132 allStreams := make([]allanimeResolvedStream, 0)
136 for _, streams := range orderedStreams { 133 for _, streams := range orderedStreams {
137 allStreams = append(allStreams, streams...) 134 allStreams = append(allStreams, streams...)
@@ -141,7 +138,7 @@ func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]strin
141 }) 138 })
142 139
143 links := make([]string, 0, len(allStreams)) 140 links := make([]string, 0, len(allStreams))
144 hints := make(map[string]StreamPlaybackHint) 141 hints := make(map[string]providers.StreamPlaybackHint)
145 seen := make(map[string]struct{}) 142 seen := make(map[string]struct{})
146 for _, stream := range allStreams { 143 for _, stream := range allStreams {
147 if stream.URL == "" || isUnreliableAllanimeDirectURL(stream.URL) { 144 if stream.URL == "" || isUnreliableAllanimeDirectURL(stream.URL) {
@@ -156,7 +153,7 @@ func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]strin
156 if referrer == "" { 153 if referrer == "" {
157 referrer = allanimeGraphQLReferer 154 referrer = allanimeGraphQLReferer
158 } 155 }
159 hints[stream.URL] = StreamPlaybackHint{ 156 hints[stream.URL] = providers.StreamPlaybackHint{
160 Referrer: referrer, 157 Referrer: referrer,
161 Subtitle: stream.SubtitleURL, 158 Subtitle: stream.SubtitleURL,
162 } 159 }
@@ -242,7 +239,7 @@ func fetchAllanimeClockResponse(providerPath string) ([]byte, map[string]interfa
242 req.Header.Set("Referer", allanimeGraphQLReferer) 239 req.Header.Set("Referer", allanimeGraphQLReferer)
243 req.Header.Set("User-Agent", allanimeUserAgent) 240 req.Header.Set("User-Agent", allanimeUserAgent)
244 241
245 resp, err := sharedHTTPClient.Do(req) 242 resp, err := curdhost.HTTPClient().Do(req)
246 if err != nil { 243 if err != nil {
247 return nil, nil, err 244 return nil, nil, err
248 } 245 }
@@ -252,8 +249,8 @@ func fetchAllanimeClockResponse(providerPath string) ([]byte, map[string]interfa
252 if err != nil { 249 if err != nil {
253 return nil, nil, err 250 return nil, nil, err
254 } 251 }
255 if !httpStatusOK(resp.StatusCode) { 252 if !curdhost.HTTPStatusOK(resp.StatusCode) {
256 return nil, nil, httpStatusError("allanime source extractor", resp.StatusCode, body) 253 return nil, nil, curdhost.HTTPStatusError("allanime source extractor", resp.StatusCode, body)
257 } 254 }
258 255
259 var videoData map[string]interface{} 256 var videoData map[string]interface{}
@@ -303,7 +300,7 @@ func fetchAllanimeM3U8VariantStreams(masterURL, referrer, subtitleURL string) ([
303 req.Header.Set("Referer", referrer) 300 req.Header.Set("Referer", referrer)
304 req.Header.Set("User-Agent", allanimeUserAgent) 301 req.Header.Set("User-Agent", allanimeUserAgent)
305 302
306 resp, err := sharedHTTPClient.Do(req) 303 resp, err := curdhost.HTTPClient().Do(req)
307 if err != nil { 304 if err != nil {
308 return nil, err 305 return nil, err
309 } 306 }
@@ -312,8 +309,8 @@ func fetchAllanimeM3U8VariantStreams(masterURL, referrer, subtitleURL string) ([
312 if err != nil { 309 if err != nil {
313 return nil, err 310 return nil, err
314 } 311 }
315 if !httpStatusOK(resp.StatusCode) { 312 if !curdhost.HTTPStatusOK(resp.StatusCode) {
316 return nil, httpStatusError("allanime m3u8 master playlist", resp.StatusCode, body) 313 return nil, curdhost.HTTPStatusError("allanime m3u8 master playlist", resp.StatusCode, body)
317 } 314 }
318 315
319 playlist := string(body) 316 playlist := string(body)
@@ -449,17 +446,3 @@ func streamsFromPlainURLs(urls []string, referrer, subtitleURL string, qualitySc
449 } 446 }
450 return streams 447 return streams
451} 448}
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
2 2
3import ( 3import (
4 "bytes" 4 "bytes"
@@ -17,6 +17,9 @@ import (
17 "sort" 17 "sort"
18 "strconv" 18 "strconv"
19 "strings" 19 "strings"
20
21 "github.com/wraient/curd/internal/curdhost"
22 "github.com/wraient/curd/internal/providers"
20) 23)
21 24
22type allanimeSource struct { 25type allanimeSource struct {
@@ -231,13 +234,13 @@ func decodeBase64URLRaw(input string) ([]byte, error) {
231func extractFilemoonLinks(videoData map[string]interface{}) []string { 234func extractFilemoonLinks(videoData map[string]interface{}) []string {
232 raw, err := json.Marshal(videoData) 235 raw, err := json.Marshal(videoData)
233 if err != nil { 236 if err != nil {
234 Log(fmt.Sprintf("Error marshaling filemoon payload: %v", err)) 237 curdhost.Log(fmt.Sprintf("Error marshaling filemoon payload: %v", err))
235 return nil 238 return nil
236 } 239 }
237 240
238 var payload filemoonResponse 241 var payload filemoonResponse
239 if err := json.Unmarshal(raw, &payload); err != nil { 242 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))
241 return nil 244 return nil
242 } 245 }
243 246
@@ -247,30 +250,30 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
247 250
248 keyPart1, err := decodeBase64URLRaw(payload.KeyParts[0]) 251 keyPart1, err := decodeBase64URLRaw(payload.KeyParts[0])
249 if err != nil { 252 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))
251 return nil 254 return nil
252 } 255 }
253 256
254 keyPart2, err := decodeBase64URLRaw(payload.KeyParts[1]) 257 keyPart2, err := decodeBase64URLRaw(payload.KeyParts[1])
255 if err != nil { 258 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))
257 return nil 260 return nil
258 } 261 }
259 262
260 iv, err := decodeBase64URLRaw(payload.IV) 263 iv, err := decodeBase64URLRaw(payload.IV)
261 if err != nil { 264 if err != nil {
262 Log(fmt.Sprintf("Error decoding filemoon IV: %v", err)) 265 curdhost.Log(fmt.Sprintf("Error decoding filemoon IV: %v", err))
263 return nil 266 return nil
264 } 267 }
265 268
266 ciphertext, err := decodeBase64URLRaw(payload.Payload) 269 ciphertext, err := decodeBase64URLRaw(payload.Payload)
267 if err != nil { 270 if err != nil {
268 Log(fmt.Sprintf("Error decoding filemoon ciphertext: %v", err)) 271 curdhost.Log(fmt.Sprintf("Error decoding filemoon ciphertext: %v", err))
269 return nil 272 return nil
270 } 273 }
271 274
272 if len(ciphertext) <= 16 { 275 if len(ciphertext) <= 16 {
273 Log("Filemoon ciphertext is too short") 276 curdhost.Log("Filemoon ciphertext is too short")
274 return nil 277 return nil
275 } 278 }
276 279
@@ -280,25 +283,25 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
280 keyHex := hex.EncodeToString(append(keyPart1, keyPart2...)) 283 keyHex := hex.EncodeToString(append(keyPart1, keyPart2...))
281 key, err := hex.DecodeString(keyHex) 284 key, err := hex.DecodeString(keyHex)
282 if err != nil { 285 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))
284 return nil 287 return nil
285 } 288 }
286 289
287 ctrIVHex := hex.EncodeToString(iv) + "00000002" 290 ctrIVHex := hex.EncodeToString(iv) + "00000002"
288 ctrIV, err := hex.DecodeString(ctrIVHex) 291 ctrIV, err := hex.DecodeString(ctrIVHex)
289 if err != nil { 292 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))
291 return nil 294 return nil
292 } 295 }
293 296
294 if len(ctrIV) != aes.BlockSize { 297 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)))
296 return nil 299 return nil
297 } 300 }
298 301
299 block, err := aes.NewCipher(key) 302 block, err := aes.NewCipher(key)
300 if err != nil { 303 if err != nil {
301 Log(fmt.Sprintf("Error creating filemoon cipher: %v", err)) 304 curdhost.Log(fmt.Sprintf("Error creating filemoon cipher: %v", err))
302 return nil 305 return nil
303 } 306 }
304 307
@@ -359,7 +362,7 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
359 } 362 }
360 363
361 if len(links) > 0 { 364 if len(links) > 0 {
362 Log("Filemoon links fetched") 365 curdhost.Log("Filemoon links fetched")
363 } 366 }
364 367
365 return links 368 return links
@@ -376,17 +379,17 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
376// Returns: 379// Returns:
377// - []string: a list of links for specified episode. 380// - []string: a list of links for specified episode.
378// - error: an error if the episode is not found or if there is an issue during the search. 381// - 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) { 382func getAllanimeEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
380 preferredMode := normalizeTranslationType(config.SubOrDub) 383 preferredMode := providers.NormalizeTranslationType(config.SubOrDub)
381 return getAllanimeEpisodeURLForMode(id, preferredMode, epNo) 384 return getAllanimeEpisodeURLForMode(id, preferredMode, epNo)
382} 385}
383 386
384func getAllanimeEpisodeURLForMode(id, mode string, epNo int) ([]string, error) { 387func getAllanimeEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
385 return getEpisodeURLForMode(id, normalizeTranslationType(mode), epNo) 388 return getEpisodeURLForMode(id, providers.NormalizeTranslationType(mode), epNo)
386} 389}
387 390
388func fetchAllanimeEpisodeSources(id, mode string, epNo int) ([]allanimeSource, error) { 391func fetchAllanimeEpisodeSources(id, mode string, epNo int) ([]allanimeSource, error) {
389 return fetchEpisodeSourcesForMode(id, normalizeTranslationType(mode), epNo) 392 return fetchEpisodeSourcesForMode(id, providers.NormalizeTranslationType(mode), epNo)
390} 393}
391 394
392func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, error) { 395func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, error) {
@@ -398,7 +401,7 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
398 401
399 variables := map[string]interface{}{ 402 variables := map[string]interface{}{
400 "showId": id, 403 "showId": id,
401 "translationType": normalizeTranslationType(mode), 404 "translationType": providers.NormalizeTranslationType(mode),
402 "episodeString": fmt.Sprintf("%d", epNo), 405 "episodeString": fmt.Sprintf("%d", epNo),
403 } 406 }
404 407
@@ -429,7 +432,7 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
429 req.Header.Set("Referer", allanimePersistedQueryReferer) 432 req.Header.Set("Referer", allanimePersistedQueryReferer)
430 req.Header.Set("Origin", allanimePersistedQueryReferer) 433 req.Header.Set("Origin", allanimePersistedQueryReferer)
431 434
432 resp, err := sharedHTTPClient.Do(req) 435 resp, err := curdhost.HTTPClient().Do(req)
433 if err != nil { 436 if err != nil {
434 return nil, fmt.Errorf("failed to send persisted query request: %w", err) 437 return nil, fmt.Errorf("failed to send persisted query request: %w", err)
435 } 438 }
@@ -438,13 +441,13 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
438 if err != nil { 441 if err != nil {
439 return nil, fmt.Errorf("failed to read persisted query response: %w", err) 442 return nil, fmt.Errorf("failed to read persisted query response: %w", err)
440 } 443 }
441 if !httpStatusOK(resp.StatusCode) { 444 if !curdhost.HTTPStatusOK(resp.StatusCode) {
442 return nil, httpStatusError("allanime episode persisted query", resp.StatusCode, body) 445 return nil, curdhost.HTTPStatusError("allanime episode persisted query", resp.StatusCode, body)
443 } 446 }
444 447
445 var response allanimeResponse 448 var response allanimeResponse
446 if err := json.Unmarshal(body, &response); err != nil { 449 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))
448 } 451 }
449 452
450 useFallback := response.Data.Tobeparsed == "" && len(response.Data.Episode.SourceUrls) == 0 453 useFallback := response.Data.Tobeparsed == "" && len(response.Data.Episode.SourceUrls) == 0
@@ -473,7 +476,7 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
473 req.Header.Set("Referer", allanimeGraphQLReferer) 476 req.Header.Set("Referer", allanimeGraphQLReferer)
474 req.Header.Set("Origin", allanimeGraphQLReferer) 477 req.Header.Set("Origin", allanimeGraphQLReferer)
475 478
476 resp, err := sharedHTTPClient.Do(req) 479 resp, err := curdhost.HTTPClient().Do(req)
477 if err != nil { 480 if err != nil {
478 return nil, fmt.Errorf("failed to send request: %w", err) 481 return nil, fmt.Errorf("failed to send request: %w", err)
479 } 482 }
@@ -483,24 +486,24 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
483 if err != nil { 486 if err != nil {
484 return nil, fmt.Errorf("failed to read response body: %w", err) 487 return nil, fmt.Errorf("failed to read response body: %w", err)
485 } 488 }
486 if !httpStatusOK(resp.StatusCode) { 489 if !curdhost.HTTPStatusOK(resp.StatusCode) {
487 return nil, httpStatusError("allanime episode fallback query", resp.StatusCode, body) 490 return nil, curdhost.HTTPStatusError("allanime episode fallback query", resp.StatusCode, body)
488 } 491 }
489 492
490 if err := json.Unmarshal(body, &response); err != nil { 493 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))
492 return nil, err 495 return nil, err
493 } 496 }
494 } 497 }
495 498
496 if response.Data.Tobeparsed != "" { 499 if response.Data.Tobeparsed != "" {
497 Log("Found tobeparsed field, decoding source URLs") 500 curdhost.Log("Found tobeparsed field, decoding source URLs")
498 decodedSources, err := decodeTobeparsed(response.Data.Tobeparsed) 501 decodedSources, err := decodeTobeparsed(response.Data.Tobeparsed)
499 if err != nil { 502 if err != nil {
500 return nil, err 503 return nil, err
501 } 504 }
502 505
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)))
504 return decodedSources, nil 507 return decodedSources, nil
505 } 508 }
506 509
internal/episode_url_test.go → internal/providers/allanime/streams_test.go renamed +1 −1
@@ -1,4 +1,4 @@
1package internal 1package allanime
2 2
3import ( 3import (
4 "strings" 4 "strings"
internal/provider_animepahe.go → internal/providers/animepahe/provider.go renamed +69 −58
@@ -1,4 +1,4 @@
1package internal 1package animepahe
2 2
3import ( 3import (
4 "encoding/json" 4 "encoding/json"
@@ -16,13 +16,16 @@ import (
16 16
17 "github.com/go-rod/rod" 17 "github.com/go-rod/rod"
18 "github.com/go-rod/rod/lib/launcher" 18 "github.com/go-rod/rod/lib/launcher"
19
20 "github.com/wraient/curd/internal/curdhost"
21 "github.com/wraient/curd/internal/providers"
19) 22)
20 23
21var animepaheCookiesBypassed bool 24var animepaheCookiesBypassed bool
22var solveAnimepaheBrowserChallenge = solveAnimepaheBrowserChallengeWithRod 25var solveAnimepaheBrowserChallenge = solveAnimepaheBrowserChallengeWithRod
23 26
24func getCookieFilePath() string { 27func getCookieFilePath() string {
25 return filepath.Join(GetStoragePath(), "animepahe_cookies.json") 28 return filepath.Join(curdhost.StoragePath(), "animepahe_cookies.json")
26} 29}
27 30
28func saveCookies(cookies []*http.Cookie) { 31func saveCookies(cookies []*http.Cookie) {
@@ -57,6 +60,11 @@ func newAnimepaheAPIRequest(rawURL string) (*http.Request, error) {
57 return req, nil 60 return req, nil
58} 61}
59 62
63// NewPageRequest builds an HTTP request for animepahe HTML pages.
64func NewPageRequest(rawURL string) (*http.Request, error) {
65 return newAnimepahePageRequest(rawURL)
66}
67
60func newAnimepahePageRequest(rawURL string) (*http.Request, error) { 68func newAnimepahePageRequest(rawURL string) (*http.Request, error) {
61 req, err := http.NewRequest("GET", rawURL, nil) 69 req, err := http.NewRequest("GET", rawURL, nil)
62 if err != nil { 70 if err != nil {
@@ -74,7 +82,7 @@ func checkCookiesValid() bool {
74 return false 82 return false
75 } 83 }
76 84
77 resp, err := sharedHTTPClient.Do(req) 85 resp, err := curdhost.HTTPClient().Do(req)
78 if err != nil { 86 if err != nil {
79 return false 87 return false
80 } 88 }
@@ -112,7 +120,7 @@ func isAnimepaheChallengeBody(body []byte) bool {
112 strings.Contains(normalized, "checking your browser") 120 strings.Contains(normalized, "checking your browser")
113} 121}
114 122
115func (p *AnimepaheProvider) ensureBypass() (err error) { 123func (p *Provider) ensureBypass() (err error) {
116 defer func() { 124 defer func() {
117 if recovered := recover(); recovered != nil { 125 if recovered := recover(); recovered != nil {
118 err = fmt.Errorf("failed to solve Animepahe DDoS-Guard challenge: %v", recovered) 126 err = fmt.Errorf("failed to solve Animepahe DDoS-Guard challenge: %v", recovered)
@@ -126,36 +134,36 @@ func (p *AnimepaheProvider) ensureBypass() (err error) {
126 cookies := loadCookies() 134 cookies := loadCookies()
127 if len(cookies) > 0 { 135 if len(cookies) > 0 {
128 u, _ := url.Parse("https://animepahe.pw") 136 u, _ := url.Parse("https://animepahe.pw")
129 SetCookiesForAnimepahe(u, cookies) 137 curdhost.SetCookiesForAnimepahe(u, cookies)
130 138
131 if checkCookiesValid() { 139 if checkCookiesValid() {
132 animepaheCookiesBypassed = true 140 animepaheCookiesBypassed = true
133 Log("Successfully restored Animepahe session from cache.") 141 curdhost.Log("Successfully restored Animepahe session from cache.")
134 return nil 142 return nil
135 } 143 }
136 Log("Cached Animepahe session expired. Requesting new session...") 144 curdhost.Log("Cached Animepahe session expired. Requesting new session...")
137 } 145 }
138 146
139 return p.refreshBypass() 147 return p.refreshBypass()
140} 148}
141 149
142func (p *AnimepaheProvider) refreshBypass() error { 150func (p *Provider) refreshBypass() error {
143 u, _ := url.Parse("https://animepahe.pw") 151 u, _ := url.Parse("https://animepahe.pw")
144 animepaheCookiesBypassed = false 152 animepaheCookiesBypassed = false
145 if err := os.Remove(getCookieFilePath()); err != nil && !os.IsNotExist(err) { 153 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))
147 } 155 }
148 156
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...")
150 httpCookies, err := solveAnimepaheBrowserChallenge() 158 httpCookies, err := solveAnimepaheBrowserChallenge()
151 if err != nil { 159 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.")
153 return fmt.Errorf("animepahe browser challenge failed: %w", err) 161 return fmt.Errorf("animepahe browser challenge failed: %w", err)
154 } 162 }
155 if len(httpCookies) == 0 { 163 if len(httpCookies) == 0 {
156 return fmt.Errorf("animepahe browser challenge returned no cookies") 164 return fmt.Errorf("animepahe browser challenge returned no cookies")
157 } 165 }
158 SetCookiesForAnimepahe(u, httpCookies) 166 curdhost.SetCookiesForAnimepahe(u, httpCookies)
159 167
160 if !checkCookiesValid() { 168 if !checkCookiesValid() {
161 return fmt.Errorf("bypassed cookies are still invalid") 169 return fmt.Errorf("bypassed cookies are still invalid")
@@ -163,7 +171,7 @@ func (p *AnimepaheProvider) refreshBypass() error {
163 171
164 saveCookies(httpCookies) 172 saveCookies(httpCookies)
165 animepaheCookiesBypassed = true 173 animepaheCookiesBypassed = true
166 CurdOut("Successfully bypassed DDoS-Guard.") 174 curdhost.Out("Successfully bypassed DDoS-Guard.")
167 return nil 175 return nil
168} 176}
169 177
@@ -201,13 +209,14 @@ func solveAnimepaheBrowserChallengeWithRod() (httpCookies []*http.Cookie, err er
201 return httpCookies, nil 209 return httpCookies, nil
202} 210}
203 211
204type AnimepaheProvider struct{} 212type Provider struct{}
205 213
206func (p *AnimepaheProvider) Name() string { 214func (p *Provider) Name() string {
207 return "animepahe" 215 return "animepahe"
208} 216}
209 217
210type AnimepaheSearchItem struct { 218// SearchItem is an animepahe API search result payload.
219type SearchItem struct {
211 ID int `json:"id"` 220 ID int `json:"id"`
212 Title string `json:"title"` 221 Title string `json:"title"`
213 Type string `json:"type"` 222 Type string `json:"type"`
@@ -220,19 +229,19 @@ type AnimepaheSearchItem struct {
220 Session string `json:"session"` 229 Session string `json:"session"`
221} 230}
222 231
223type animepaheAnimeRef struct { 232type AnimeRef struct {
224 ReleaseID string 233 ReleaseID string
225 Session string 234 Session string
226} 235}
227 236
228func (r animepaheAnimeRef) apiID() string { 237func (r AnimeRef) apiID() string {
229 if r.Session != "" { 238 if r.Session != "" {
230 return r.Session 239 return r.Session
231 } 240 }
232 return r.ReleaseID 241 return r.ReleaseID
233} 242}
234 243
235func formatAnimepaheProviderID(item AnimepaheSearchItem) string { 244func formatAnimepaheProviderID(item SearchItem) string {
236 if item.ID > 0 && item.Session != "" { 245 if item.ID > 0 && item.Session != "" {
237 return fmt.Sprintf("%d:%s", item.ID, item.Session) 246 return fmt.Sprintf("%d:%s", item.ID, item.Session)
238 } 247 }
@@ -245,36 +254,38 @@ func formatAnimepaheProviderID(item AnimepaheSearchItem) string {
245 return "" 254 return ""
246} 255}
247 256
248func parseAnimepaheProviderID(providerID string) animepaheAnimeRef { 257// ParseProviderID parses a stored animepahe show identifier.
258func ParseProviderID(providerID string) AnimeRef {
249 providerID = strings.TrimSpace(providerID) 259 providerID = strings.TrimSpace(providerID)
250 if providerID == "" { 260 if providerID == "" {
251 return animepaheAnimeRef{} 261 return AnimeRef{}
252 } 262 }
253 263
254 parts := strings.SplitN(providerID, ":", 2) 264 parts := strings.SplitN(providerID, ":", 2)
255 if len(parts) == 2 && parts[0] != "" && parts[1] != "" { 265 if len(parts) == 2 && parts[0] != "" && parts[1] != "" {
256 if _, err := strconv.Atoi(parts[0]); err == nil { 266 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]}
258 } 268 }
259 } 269 }
260 270
261 if _, err := strconv.Atoi(providerID); err == nil { 271 if _, err := strconv.Atoi(providerID); err == nil {
262 return animepaheAnimeRef{ReleaseID: providerID} 272 return AnimeRef{ReleaseID: providerID}
263 } 273 }
264 274
265 return animepaheAnimeRef{Session: providerID} 275 return AnimeRef{Session: providerID}
266} 276}
267 277
268func stableAnimepaheProviderID(providerID string) string { 278// StableProviderID returns the release id portion used for history matching.
269 animeRef := parseAnimepaheProviderID(providerID) 279func StableProviderID(providerID string) string {
280 animeRef := ParseProviderID(providerID)
270 if animeRef.ReleaseID != "" { 281 if animeRef.ReleaseID != "" {
271 return animeRef.ReleaseID 282 return animeRef.ReleaseID
272 } 283 }
273 return providerID 284 return providerID
274} 285}
275 286
276func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string, error) { 287func (p *Provider) ResolveProviderID(providerID, query string) (string, error) {
277 animeRef := parseAnimepaheProviderID(providerID) 288 animeRef := ParseProviderID(providerID)
278 query = strings.TrimSpace(query) 289 query = strings.TrimSpace(query)
279 if query == "" { 290 if query == "" {
280 if animeRef.Session != "" { 291 if animeRef.Session != "" {
@@ -286,14 +297,14 @@ func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string,
286 options, err := p.SearchAnime(query, "") 297 options, err := p.SearchAnime(query, "")
287 if err != nil { 298 if err != nil {
288 if animeRef.Session != "" { 299 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))
290 return providerID, nil 301 return providerID, nil
291 } 302 }
292 return "", err 303 return "", err
293 } 304 }
294 305
295 for _, option := range options { 306 for _, option := range options {
296 item, ok := option.ExtraData.(AnimepaheSearchItem) 307 item, ok := option.ExtraData.(SearchItem)
297 if !ok { 308 if !ok {
298 continue 309 continue
299 } 310 }
@@ -307,7 +318,7 @@ func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string,
307 } 318 }
308 319
309 if animeRef.Session != "" { 320 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))
311 return providerID, nil 322 return providerID, nil
312 } 323 }
313 324
@@ -319,10 +330,10 @@ type animepaheSearchResponse struct {
319 PerPage int `json:"per_page"` 330 PerPage int `json:"per_page"`
320 CurrentPage int `json:"current_page"` 331 CurrentPage int `json:"current_page"`
321 LastPage int `json:"last_page"` 332 LastPage int `json:"last_page"`
322 Data []AnimepaheSearchItem `json:"data"` 333 Data []SearchItem `json:"data"`
323} 334}
324 335
325func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption, error) { 336func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
326 if err := p.ensureBypass(); err != nil { 337 if err := p.ensureBypass(); err != nil {
327 return nil, err 338 return nil, err
328 } 339 }
@@ -334,7 +345,7 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
334 return nil, err 345 return nil, err
335 } 346 }
336 347
337 resp, err := sharedHTTPClient.Do(req) 348 resp, err := curdhost.HTTPClient().Do(req)
338 if err != nil { 349 if err != nil {
339 return nil, err 350 return nil, err
340 } 351 }
@@ -344,8 +355,8 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
344 if err != nil { 355 if err != nil {
345 return nil, err 356 return nil, err
346 } 357 }
347 if !httpStatusOK(resp.StatusCode) { 358 if !curdhost.HTTPStatusOK(resp.StatusCode) {
348 return nil, httpStatusError("animepahe search", resp.StatusCode, body) 359 return nil, curdhost.HTTPStatusError("animepahe search", resp.StatusCode, body)
349 } 360 }
350 361
351 var searchResp animepaheSearchResponse 362 var searchResp animepaheSearchResponse
@@ -354,10 +365,10 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
354 return nil, err 365 return nil, err
355 } 366 }
356 367
357 var result []SelectionOption 368 var result []providers.SelectionOption
358 for _, item := range searchResp.Data { 369 for _, item := range searchResp.Data {
359 label := fmt.Sprintf("%s (%d episodes) [animepahe]", item.Title, item.Episodes) 370 label := fmt.Sprintf("%s (%d episodes) [animepahe]", item.Title, item.Episodes)
360 result = append(result, SelectionOption{ 371 result = append(result, providers.SelectionOption{
361 Title: item.Title, 372 Title: item.Title,
362 Label: label, 373 Label: label,
363 Key: formatAnimepaheProviderID(item), 374 Key: formatAnimepaheProviderID(item),
@@ -382,11 +393,11 @@ type animepaheEpisodesResponse struct {
382 } `json:"data"` 393 } `json:"data"`
383} 394}
384 395
385func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error) { 396func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
386 if err := p.ensureBypass(); err != nil { 397 if err := p.ensureBypass(); err != nil {
387 return nil, err 398 return nil, err
388 } 399 }
389 animeRef := parseAnimepaheProviderID(showID) 400 animeRef := ParseProviderID(showID)
390 apiID := animeRef.apiID() 401 apiID := animeRef.apiID()
391 if apiID == "" { 402 if apiID == "" {
392 return nil, fmt.Errorf("animepahe provider id %q is invalid; please reselect this anime", showID) 403 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)
403 return nil, err 414 return nil, err
404 } 415 }
405 416
406 resp, err := sharedHTTPClient.Do(req) 417 resp, err := curdhost.HTTPClient().Do(req)
407 if err != nil { 418 if err != nil {
408 return nil, err 419 return nil, err
409 } 420 }
@@ -417,15 +428,15 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
417 if challengeRetried { 428 if challengeRetried {
418 return nil, fmt.Errorf("animepahe episode list is still blocked by DDoS-Guard after refreshing browser session") 429 return nil, fmt.Errorf("animepahe episode list is still blocked by DDoS-Guard after refreshing browser session")
419 } 430 }
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...")
421 if err := p.refreshBypass(); err != nil { 432 if err := p.refreshBypass(); err != nil {
422 return nil, err 433 return nil, err
423 } 434 }
424 challengeRetried = true 435 challengeRetried = true
425 continue 436 continue
426 } 437 }
427 if !httpStatusOK(resp.StatusCode) { 438 if !curdhost.HTTPStatusOK(resp.StatusCode) {
428 return nil, httpStatusError("animepahe episode list", resp.StatusCode, body) 439 return nil, curdhost.HTTPStatusError("animepahe episode list", resp.StatusCode, body)
429 } 440 }
430 441
431 var epsResp animepaheEpisodesResponse 442 var epsResp animepaheEpisodesResponse
@@ -453,15 +464,15 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
453 return result, nil 464 return result, nil
454} 465}
455 466
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) {
457 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub) 468 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub)
458} 469}
459 470
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) {
461 if err := p.ensureBypass(); err != nil { 472 if err := p.ensureBypass(); err != nil {
462 return nil, err 473 return nil, err
463 } 474 }
464 animeRef := parseAnimepaheProviderID(id) 475 animeRef := ParseProviderID(id)
465 if animeRef.Session == "" { 476 if animeRef.Session == "" {
466 return nil, fmt.Errorf("animepahe provider id %q is missing session id; please reselect this anime", id) 477 return nil, fmt.Errorf("animepahe provider id %q is missing session id; please reselect this anime", id)
467 } 478 }
@@ -492,7 +503,7 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
492 return nil, err 503 return nil, err
493 } 504 }
494 505
495 resp, err := sharedHTTPClient.Do(req) 506 resp, err := curdhost.HTTPClient().Do(req)
496 if err != nil { 507 if err != nil {
497 return nil, err 508 return nil, err
498 } 509 }
@@ -502,8 +513,8 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
502 if err != nil { 513 if err != nil {
503 return nil, err 514 return nil, err
504 } 515 }
505 if !httpStatusOK(resp.StatusCode) { 516 if !curdhost.HTTPStatusOK(resp.StatusCode) {
506 return nil, httpStatusError("animepahe episode lookup", resp.StatusCode, body) 517 return nil, curdhost.HTTPStatusError("animepahe episode lookup", resp.StatusCode, body)
507 } 518 }
508 519
509 var epsResp animepaheEpisodesResponse 520 var epsResp animepaheEpisodesResponse
@@ -537,7 +548,7 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
537 return nil, err 548 return nil, err
538 } 549 }
539 550
540 resp, err := sharedHTTPClient.Do(req) 551 resp, err := curdhost.HTTPClient().Do(req)
541 if err != nil { 552 if err != nil {
542 return nil, err 553 return nil, err
543 } 554 }
@@ -547,8 +558,8 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
547 if err != nil { 558 if err != nil {
548 return nil, err 559 return nil, err
549 } 560 }
550 if !httpStatusOK(resp.StatusCode) { 561 if !curdhost.HTTPStatusOK(resp.StatusCode) {
551 return nil, httpStatusError("animepahe player page", resp.StatusCode, body) 562 return nil, curdhost.HTTPStatusError("animepahe player page", resp.StatusCode, body)
552 } 563 }
553 564
554 bodyStr := string(body) 565 bodyStr := string(body)
@@ -606,7 +617,7 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
606 sortFunc(dubLinks) 617 sortFunc(dubLinks)
607 618
608 var links []string 619 var links []string
609 requestedMode := normalizeTranslationType(mode) 620 requestedMode := providers.NormalizeTranslationType(mode)
610 if requestedMode == "dub" { 621 if requestedMode == "dub" {
611 for _, l := range dubLinks { 622 for _, l := range dubLinks {
612 links = append(links, l.url) 623 links = append(links, l.url)
@@ -635,13 +646,13 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
635 return finalLinks, nil 646 return finalLinks, nil
636} 647}
637 648
638func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) { 649func (p *Provider) extractKwikM3u8(kwikUrl string) (string, error) {
639 req, err := newAnimepahePageRequest(kwikUrl) 650 req, err := newAnimepahePageRequest(kwikUrl)
640 if err != nil { 651 if err != nil {
641 return "", err 652 return "", err
642 } 653 }
643 654
644 resp, err := sharedHTTPClient.Do(req) 655 resp, err := curdhost.HTTPClient().Do(req)
645 if err != nil { 656 if err != nil {
646 return "", err 657 return "", err
647 } 658 }
@@ -651,8 +662,8 @@ func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) {
651 if err != nil { 662 if err != nil {
652 return "", err 663 return "", err
653 } 664 }
654 if !httpStatusOK(resp.StatusCode) { 665 if !curdhost.HTTPStatusOK(resp.StatusCode) {
655 return "", httpStatusError("kwik stream page", resp.StatusCode, body) 666 return "", curdhost.HTTPStatusError("kwik stream page", resp.StatusCode, body)
656 } 667 }
657 bodyStr := string(body) 668 bodyStr := string(body)
658 669
internal/provider_animepahe_test.go → internal/providers/animepahe/provider_test.go renamed +31 −13
@@ -1,16 +1,25 @@
1package internal 1package animepahe
2 2
3import ( 3import (
4 "io" 4 "io"
5 "net/http" 5 "net/http"
6 "net/http/cookiejar" 6 "net/http/cookiejar"
7 "net/url"
7 "os" 8 "os"
8 "strings" 9 "strings"
9 "testing" 10 "testing"
11
12 "github.com/wraient/curd/internal/curdhost"
10) 13)
11 14
12const animepaheChallengeHTML = `<!doctype html><html><head><title>DDoS-Guard</title></head><body>Checking your browser</body></html>` 15const animepaheChallengeHTML = `<!doctype html><html><head><title>DDoS-Guard</title></head><body>Checking your browser</body></html>`
13 16
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
14func animepaheTestResponse(req *http.Request, statusCode int, body string, headers map[string]string) *http.Response { 23func animepaheTestResponse(req *http.Request, statusCode int, body string, headers map[string]string) *http.Response {
15 resp := &http.Response{ 24 resp := &http.Response{
16 StatusCode: statusCode, 25 StatusCode: statusCode,
@@ -27,21 +36,30 @@ func animepaheTestResponse(req *http.Request, statusCode int, body string, heade
27func withAnimepaheTestHooks(t *testing.T, client *http.Client, solver func() ([]*http.Cookie, error)) { 36func withAnimepaheTestHooks(t *testing.T, client *http.Client, solver func() ([]*http.Cookie, error)) {
28 t.Helper() 37 t.Helper()
29 38
30 previousClient := sharedHTTPClient 39 previousClient := curdhost.HTTPClient
40 previousLog := curdhost.Log
41 previousOut := curdhost.Out
42 previousCookies := curdhost.SetCookiesForAnimepahe
31 previousSolver := solveAnimepaheBrowserChallenge 43 previousSolver := solveAnimepaheBrowserChallenge
32 previousBypassed := animepaheCookiesBypassed 44 previousBypassed := animepaheCookiesBypassed
33 previousConfig := GetGlobalConfig() 45 previousStoragePath := curdhost.StoragePath
34 46
35 t.Cleanup(func() { 47 t.Cleanup(func() {
36 sharedHTTPClient = previousClient 48 curdhost.HTTPClient = previousClient
49 curdhost.Log = previousLog
50 curdhost.Out = previousOut
51 curdhost.SetCookiesForAnimepahe = previousCookies
37 solveAnimepaheBrowserChallenge = previousSolver 52 solveAnimepaheBrowserChallenge = previousSolver
38 animepaheCookiesBypassed = previousBypassed 53 animepaheCookiesBypassed = previousBypassed
39 SetGlobalConfig(previousConfig) 54 curdhost.StoragePath = previousStoragePath
40 }) 55 })
41 56
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) {}
43 solveAnimepaheBrowserChallenge = solver 61 solveAnimepaheBrowserChallenge = solver
44 SetGlobalConfig(&CurdConfig{StoragePath: t.TempDir()}) 62 curdhost.StoragePath = func() string { return t.TempDir() }
45} 63}
46 64
47func TestAnimepaheEpisodesListRefreshesSessionWhenReleaseEndpointReturnsChallenge(t *testing.T) { 65func TestAnimepaheEpisodesListRefreshesSessionWhenReleaseEndpointReturnsChallenge(t *testing.T) {
@@ -82,7 +100,7 @@ func TestAnimepaheEpisodesListRefreshesSessionWhenReleaseEndpointReturnsChalleng
82 }) 100 })
83 animepaheCookiesBypassed = true 101 animepaheCookiesBypassed = true
84 102
85 episodes, err := (&AnimepaheProvider{}).EpisodesList("4:session-id", "sub") 103 episodes, err := (&Provider{}).EpisodesList("4:session-id", "sub")
86 if err != nil { 104 if err != nil {
87 t.Fatalf("expected episode list retry to succeed: %v", err) 105 t.Fatalf("expected episode list retry to succeed: %v", err)
88 } 106 }
@@ -129,7 +147,7 @@ func TestAnimepaheEpisodesListReportsPersistentChallengeAfterRefresh(t *testing.
129 }) 147 })
130 animepaheCookiesBypassed = true 148 animepaheCookiesBypassed = true
131 149
132 _, err = (&AnimepaheProvider{}).EpisodesList("4:session-id", "sub") 150 _, err = (&Provider{}).EpisodesList("4:session-id", "sub")
133 if err == nil { 151 if err == nil {
134 t.Fatalf("expected persistent DDoS-Guard challenge to fail") 152 t.Fatalf("expected persistent DDoS-Guard challenge to fail")
135 } 153 }
@@ -146,16 +164,16 @@ func TestAnimepaheEpisodesListLiveOnePiece(t *testing.T) {
146 t.Skip("set CURD_LIVE_ANIMEPAHE_TEST=1 to run live Animepahe episode-list verification") 164 t.Skip("set CURD_LIVE_ANIMEPAHE_TEST=1 to run live Animepahe episode-list verification")
147 } 165 }
148 166
149 previousConfig := GetGlobalConfig()
150 previousBypassed := animepaheCookiesBypassed 167 previousBypassed := animepaheCookiesBypassed
168 previousStoragePath := curdhost.StoragePath
151 t.Cleanup(func() { 169 t.Cleanup(func() {
152 SetGlobalConfig(previousConfig)
153 animepaheCookiesBypassed = previousBypassed 170 animepaheCookiesBypassed = previousBypassed
171 curdhost.StoragePath = previousStoragePath
154 }) 172 })
155 SetGlobalConfig(&CurdConfig{StoragePath: t.TempDir()}) 173 curdhost.StoragePath = func() string { return t.TempDir() }
156 animepaheCookiesBypassed = false 174 animepaheCookiesBypassed = false
157 175
158 episodes, err := (&AnimepaheProvider{}).EpisodesList("4:15a36fc8-73b9-8c2e-ee5f-fb1bcd4fcdc6", "sub") 176 episodes, err := (&Provider{}).EpisodesList("4:15a36fc8-73b9-8c2e-ee5f-fb1bcd4fcdc6", "sub")
159 if err != nil { 177 if err != nil {
160 t.Fatalf("live Animepahe One Piece episode list failed: %v", err) 178 t.Fatalf("live Animepahe One Piece episode list failed: %v", err)
161 } 179 }
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 {
71 Mode string 71 Mode string
72} 72}
73 73
74// StreamPlaybackHint carries MPV playback metadata for a resolved stream URL.
75type StreamPlaybackHint struct {
76 Referrer string
77 Subtitle string
78}
79
74type playingVideo struct { 80type playingVideo struct {
75 Url string 81 Url string
76 Speed float64 `json:"speed"` 82 Speed float64 `json:"speed"`
@@ -98,8 +104,9 @@ func GetGlobalUser() *User {
98 104
99// AniListAnime is the struct for the API response 105// AniListAnime is the struct for the API response
100type AniListAnime struct { 106type AniListAnime struct {
101 ID int `json:"id"` 107 ID int `json:"id"`
102 Title struct { 108 Episodes int `json:"episodes"`
109 Title struct {
103 Romaji string `json:"romaji"` 110 Romaji string `json:"romaji"`
104 English string `json:"english"` 111 English string `json:"english"`
105 Native string `json:"native"` 112 Native string `json:"native"`
@@ -122,6 +129,7 @@ type ResponseData struct {
122type Media struct { 129type Media struct {
123 Duration int `json:"duration"` 130 Duration int `json:"duration"`
124 Episodes int `json:"episodes"` 131 Episodes int `json:"episodes"`
132 Format string `json:"format"`
125 ID int `json:"id"` 133 ID int `json:"id"`
126 MalID int `json:"mal_id"` 134 MalID int `json:"mal_id"`
127 Title AnimeTitle `json:"title"` 135 Title AnimeTitle `json:"title"`
internal/user_intent_regression_test.go +8 −1
@@ -141,6 +141,7 @@ func TestGetProviderTotalEpisodesReturnsLookupErrorsWhenNoEpisodesFound(t *testi
141} 141}
142 142
143func TestGetAllAnimeEpisodesListUsesValidGraphQLVariableSyntax(t *testing.T) { 143func TestGetAllAnimeEpisodesListUsesValidGraphQLVariableSyntax(t *testing.T) {
144 withAllProvidersEnabledForTest(t)
144 previousClient := sharedHTTPClient 145 previousClient := sharedHTTPClient
145 t.Cleanup(func() { 146 t.Cleanup(func() {
146 sharedHTTPClient = previousClient 147 sharedHTTPClient = previousClient
@@ -163,7 +164,13 @@ func TestGetAllAnimeEpisodesListUsesValidGraphQLVariableSyntax(t *testing.T) {
163 return testHTTPResponse(req, http.StatusOK, `{"data":{"show":{"_id":"show-id","availableEpisodesDetail":{"sub":[1,2,12]}}}}`), nil 164 return testHTTPResponse(req, http.StatusOK, `{"data":{"show":{"_id":"show-id","availableEpisodesDetail":{"sub":[1,2,12]}}}}`), nil
164 })} 165 })}
165 166
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 }()
167 if err != nil { 174 if err != nil {
168 t.Fatalf("expected allanime episode list lookup to succeed: %v", err) 175 t.Fatalf("expected allanime episode list lookup to succeed: %v", err)
169 } 176 }