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