Commit 40a931ea11

40a931ea117ba1cf4572683d520f6b51fc3a807d

parent: d0c088ce23

Unregistered key

Rushikesh Gaikwad <81632222+Wraient@users.noreply.github.com> · 2026-06-22 13:56 UTC
committer: <noreply@github.com>

v2.0.0: provider registry, AniNeko, and search UX fixes (#103)

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

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

* fix: provider search UX, auth recovery, remap menu, and anineko defaults

Add manual provider search with episode hints, search recovery menus,
provider remap flow, and invalid-token browser re-auth for AniList/MAL.
Default to anineko with allanime and animepahe disabled, plus SubStyle
flags and REMAP_PROVIDER menu entry.

Layout: unified · split

Build/curd-windows-build.iss +1 −1
@@ -1,6 +1,6 @@
11[Setup]
22AppName=Curd Installer
3AppVersion=1.5.1
3AppVersion=1.5.3
44DefaultDirName={userappdata}\Curd
55PrivilegesRequired=lowest
66AllowNoIcons=yes
README.md +8 −3
@@ -24,7 +24,7 @@ https://github.com/user-attachments/assets/cbf799bc-9fdd-4402-ab61-b4e31f1e264d
2424
2525
2626## Features
27- Multiple Content Providers (AllAnime and Animepahe) with ordered fallback and up to 1080p support
27- Multiple Content Providers (AllAnime, AniNeko, and Animepahe) with ordered fallback and up to 1080p support
2828- Built-in headless browser to bypass Cloudflare/DDoS-Guard protections
2929- Stream anime online
3030- Track anime locally, on AniList, or on MyAnimeList
@@ -299,6 +299,8 @@ curd [options]
299299| `-change-token` | Change your authentication token | - |
300300| `-dub` | Watch the dubbed version of the anime | - |
301301| `-sub` | Watch the subbed version of the anime | - |
302| `-softsub` | Prefer soft subtitles when available (AniNeko) | - |
303| `-hardsub` | Prefer hard subtitles when available (AniNeko) | - |
302304| `-new` | Add a new anime to your list | - |
303305| `-e` | Edit the configuration file | - |
304306| `-skip-op` | Automatically skip the opening section of each episode | `true` |
@@ -381,6 +383,7 @@ If the browser reaches the localhost callback page but curd does not continue au
381383| `PercentageToMarkComplete`| Integer | `0` to `100` | Sets the percentage of an episode watched to consider it as completed. |
382384| `StoragePath` | String | Any valid path (Environment variables accepted) | Specifies the directory where Curd stores its data. |
383385| `SubOrDub` | Enum | `sub`, `dub` | Sets the preferred format for anime audio. |
386| `SubStyle` | Enum | `ask`, `soft`, `hard` | For AniNeko sub streams: `ask` prompts once when both soft-sub and hard-sub servers exist, then saves your choice here; `soft` uses external `.vtt` subtitles via mpv; `hard` uses burned-in subs. Default: `ask` |
384387| `NextEpisodePrompt` | Boolean | `true`, `false` | Prompts the user before automatically playing the next episode. |
385388| `SubsLanguage` | String | `english` (redundant rn) | Sets the preferred subtitle language. |
386389| `ScoreOnCompletion` | Boolean | `true`, `false` | Automatically prompts the user to rate the anime upon completion. |
@@ -391,8 +394,9 @@ If the browser reaches the localhost callback page but curd does not continue au
391394| `Player` | String | any mpv-compatible binary (e.g. `mpv`, `iina`) | Player binary used for playback. If not found, Curd falls back to `mpv`. |
392395| `SaveMpvSpeed` | Boolean | `true`, `false` | Retains the playback speed set in MPV for next episode. |
393396| `SkipFiller` | Boolean | `true`, `false` | Skips filler episodes when supported. |
394| `MenuOrder` | String | Comma-separated list | Controls which menu items appear and their order. Available options: `CURRENT`, `ALL`, `UNTRACKED`, `UPDATE`, `CONTINUE_LAST`, `PLANNING`, `COMPLETED`, `PAUSED`, `DROPPED`, `REWATCHING`, `TRACKER`, `PROVIDER`. Only listed items will be shown. Default: `CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,TRACKER,PROVIDER` |
395| `Provider` | List | `["allanime"]`, `["animepahe"]`, `["allanime","animepahe"]`, `["allanime","no-animepahe"]` | Sets the ordered content-provider fallback list. Curd tries providers from left to right for the requested stream. If AllAnime has no search results or the requested episode stream is unavailable and Animepahe is not configured, Curd asks before enabling Animepahe and warns that DDoS-Guard verification may require a ~500 MB chromium download. Declining stores `no-animepahe` so Curd does not ask again. Legacy single values like `allanime` are migrated to list form. Default: `["allanime"]` |
397| `MenuOrder` | String | Comma-separated list | Controls which menu items appear and their order. Available options: `CURRENT`, `ALL`, `UNTRACKED`, `UPDATE`, `REMAP_PROVIDER`, `CONTINUE_LAST`, `PLANNING`, `COMPLETED`, `PAUSED`, `DROPPED`, `REWATCHING`, `TRACKER`, `PROVIDER`. Only listed items will be shown. Default: `CURRENT,ALL,UNTRACKED,UPDATE,REMAP_PROVIDER,CONTINUE_LAST,TRACKER,PROVIDER` |
398| `Provider` | List | `["anineko"]`, `["allanime"]`, `["animepahe"]`, `["anineko","allanime"]`, `["allanime","animepahe"]`, `["allanime","no-animepahe"]`, `stacked` | Sets the ordered content-provider fallback list. Curd tries providers from left to right for the requested stream. `stacked` / `all` uses every enabled provider. AllAnime and Animepahe are disabled by default; include them in `Provider` to enable. If the primary provider has no search results or stream and Animepahe is not configured, Curd may ask before enabling Animepahe. Default: `["anineko"]` |
399| `ManualProviderSearch` | Boolean | `true`, `false` | Skip automatic provider matching and always show provider search results for manual selection. Displays a hint with the tracker title, format (TV/Movie/etc.), episode count, and sub/dub mode. Default: `false` |
396400| `TrackingLocal` | Boolean | `true` | Legacy compatibility flag. Local playback history is always enabled. |
397401| `TrackingRemote` | Enum | `none`, `anilist`, `myanimelist`, `anilist+myanimelist` | Selects which remote tracker curd syncs with. |
398402| `TrackingConfigured` | Boolean | `true`, `false` | Internal flag used to remember that the startup tracking prompt has already been completed. |
@@ -416,6 +420,7 @@ If the browser reaches the localhost callback page but curd does not continue au
416420- [MyAnimeList API](https://myanimelist.net/apiconfig/references/api/v2) - MyAnimeList OAuth and tracking sync
417421- [AniSkip API](https://api.aniskip.com/api-docs) - Get anime intro and outro timings
418422- [AllAnime Content](https://allanime.to/) - Fetch anime url
423- [AniNeko Content](https://anineko.to/) - Alternative provider with soft/hard sub stream selection
419424- [Animepahe Content](https://animepahe.pw/) - Alternative provider for 1080p streams
420425- [Jikan](https://jikan.moe/) - Get filler episode number
421426
cmd/curd/main.go +7
@@ -82,6 +82,8 @@ func main() {
8282 editConfig := flag.Bool("e", false, "Edit config")
8383 subFlag := flag.Bool("sub", false, "Watch sub version")
8484 dubFlag := flag.Bool("dub", false, "Watch dub version")
85 softSubFlag := flag.Bool("softsub", false, "Prefer soft subtitles when available (anineko)")
86 hardSubFlag := flag.Bool("hardsub", false, "Prefer hard subtitles when available (anineko)")
8587 versionFlag := flag.Bool("v", false, "Print version information")
8688
8789 // Custom help/usage function
@@ -183,6 +185,11 @@ func main() {
183185 } else if *dubFlag {
184186 userCurdConfig.SubOrDub = "dub"
185187 }
188 if *softSubFlag {
189 userCurdConfig.SubStyle = "soft"
190 } else if *hardSubFlag {
191 userCurdConfig.SubStyle = "hard"
192 }
186193
187194 // Get the token from the token file for the configured remote tracker.
188195 if internal.UsesRemoteTracking(&userCurdConfig) {
docs/providers.md added +358
@@ -0,0 +1,358 @@
1# Curd streaming providers
2
3Curd separates **what you watch** (AniList / local history) from **where streams come from** (providers). Providers are compile-time modules that implement a small interface and register themselves at startup. The host application handles menus, tracking, mpv playback, and provider stack fallback — providers only answer search, episode list, and stream URL questions.
4
5This document explains the intent of the design, how to add a provider, how users enable or disable providers, and what to do when a new provider needs something the current contract does not cover.
6
7---
8
9## Design intent
10
11### Goals
12
131. **Adding a provider should be mechanical** — new package, implement three methods, register in `init()`, add one import line. No edits to central maps, name switches, or `curd.go` provider-specific branches.
142. **Disabling a broken provider should not require a release** — users can turn providers off in `curd.conf` without rebuilding.
153. **Keep one binary** — providers ship inside the curd repo (or as Go packages imported at build time). We are not using runtime plugin binaries or `.so` loading.
164. **Host owns orchestration** — ordered fallback, sub/dub prompts, AniList → provider matching, and mpv IPC stay in `internal/`. Providers return data; they do not drive the watch loop.
17
18### Non-goals (for now)
19
20- Installable third-party plugin binaries
21- Providers replacing AniList search or the TUI/Rofi selector
22- Providers running arbitrary host code or reading OAuth tokens
23
24### Architecture (high level)
25
26```
27┌─────────────────────────────────────────────────────────┐
28│ internal/ (host) │
29│ SetupCurd · provider stack · mpv · tracking · config │
30│ │ uses providers.New() + adapter │
31│ │ wires curdhost.* hooks for HTTP, log, storage │
32└───────┼─────────────────────────────────────────────────┘
33 │
34 ▼
35┌─────────────────────────────────────────────────────────┐
36│ internal/providers/ │
37│ registry · types · Provider interface │
38├─────────────────────────────────────────────────────────┤
39│ allanime/ animepahe/ yourprovider/ │
40│ search · episodes · streams · register.go │
41└─────────────────────────────────────────────────────────┘
42```
43
44Providers **must not** import `internal` (that would create an import cycle). They use `curdhost` for shared services and `providers` for types and registration.
45
46---
47
48## Provider contract
49
50### Required interface
51
52Defined in `internal/providers/types.go`:
53
54```go
55type Provider interface {
56 Name() string
57 SearchAnime(query, mode string) ([]SelectionOption, error)
58 EpisodesList(showID, mode string) ([]string, error)
59 GetEpisodeURL(config PlaybackConfig, id string, epNo int) ([]string, error)
60}
61```
62
63| Method | Purpose |
64|--------|---------|
65| `Name()` | Canonical provider id (e.g. `allanime`). Must match `Meta.Name` from registration. |
66| `SearchAnime` | Find shows on the streaming site. `mode` is `sub` or `dub` where relevant. |
67| `EpisodesList` | Return episode numbers as strings for a provider show id. |
68| `GetEpisodeURL` | Resolve playable URLs for episode `epNo` (1-based, aligned with AniList progress). |
69
70### Shared types
71
72```go
73type SelectionOption struct {
74 Key string // provider show id (stored in history / ProviderId)
75 Label string // menu line
76 Title string // plain title for matching
77 Thumbnail string // optional cover URL
78 ExtraData any // optional provider-specific payload (e.g. metadata for matching)
79}
80
81type PlaybackConfig struct {
82 SubOrDub string // "sub" or "dub"
83}
84```
85
86Use `providers.NormalizeTranslationType(mode)` and `providers.AlternateTranslationType(mode)` from `internal/providers/lang.go` for sub/dub handling.
87
88### Optional interfaces
89
90Implement only when the default behavior is not enough:
91
92| Interface | When to implement |
93|-----------|-------------------|
94| `ModeResolver` | Sub and dub use different APIs or URLs; host calls `GetEpisodeURLForMode` explicitly during fallback. |
95| `HintResolver` | Streams need per-URL mpv metadata (Referer header, external subtitle URL). Used by AllAnime. |
96| `IDResolver` | Stored show ids go stale and must be refreshed via search (Animepahe sessions). |
97
98The host discovers these via type assertion on the registered provider — no extra registration step.
99
100### Show IDs and the provider stack
101
102- Configured stack: `Provider = ["allanime", "animepahe"]` — tried left to right for search and playback.
103- Qualified ids in menus when multiple providers are active: `allanime::ShowIdHere`.
104- Host qualifies ids with `providername::id` when merging stacked search results.
105
106Your `Key` in `SearchAnime` should be the **raw** provider id. The host adds the `provider::` prefix when needed.
107
108---
109
110## Adding a new provider
111
112### 1. Create the package
113
114```
115internal/providers/yoursite/
116 register.go # providers.Register in init()
117 provider.go # Provider struct + interface methods
118 search.go # HTTP / API search (optional split)
119 episodes.go
120 streams.go
121 provider_test.go
122```
123
124Use `allanime` as a reference for a GraphQL/REST provider, `animepahe` for cookie/browser-heavy sites.
125
126### 2. Implement `Provider`
127
128```go
129package yoursite
130
131import "github.com/wraient/curd/internal/providers"
132
133type Provider struct{}
134
135func (p *Provider) Name() string { return "yoursite" }
136
137func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
138 // ...
139}
140
141func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
142 // ...
143}
144
145func (p *Provider) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
146 // ...
147}
148```
149
150### 3. Register in `init()`
151
152```go
153func init() {
154 providers.Register(providers.Meta{
155 Name: "yoursite",
156 Aliases: []string{"ys"}, // optional config/menu aliases
157 Referrer: "https://yoursite.example/", // mpv Referer for streams
158 }, func() providers.Provider {
159 return &Provider{}
160 })
161}
162```
163
164`Meta` fields:
165
166| Field | Meaning |
167|-------|---------|
168| `Name` | Canonical name (lowercase, no spaces; normalized to compact form e.g. `allanime`). |
169| `Aliases` | Alternate names accepted in config. |
170| `Referrer` | Default HTTP Referer for mpv when playing this provider's links. |
171| `DefaultDisabled` | If true, provider is off until user enables it (see Animepahe). |
172| `DisableReason` | Shown when a disabled provider is requested. |
173| `OptOutToken` | Config token to permanently skip fallback prompts (e.g. `no-animepahe`). |
174| `FallbackPrompt` | Reserved for host fallback UX (Animepahe chromium warning). |
175
176### 4. Wire the package into the binary
177
178Add a blank import in `internal/loadproviders/load.go`:
179
180```go
181import (
182 _ "github.com/wraient/curd/internal/providers/allanime"
183 _ "github.com/wraient/curd/internal/providers/animepahe"
184 _ "github.com/wraient/curd/internal/providers/yoursite"
185)
186```
187
188`internal` already imports `loadproviders` from `provider_bridge.go`, so registration runs on startup.
189
190### 5. Use `curdhost` for host services
191
192Providers must not call `internal` helpers directly. Use hooks in `internal/curdhost/host.go`:
193
194| Hook | Use |
195|------|-----|
196| `curdhost.HTTPClient()` | Shared cookie jar HTTP client |
197| `curdhost.Log(string)` | Debug log (`debug.log` in storage path) |
198| `curdhost.Out(string)` | User-visible terminal message |
199| `curdhost.StoragePath()` | `~/.local/share/curd` (or configured path) |
200| `curdhost.AnimeNameLanguage()` | `"english"` or `"romaji"` for search result labels |
201| `curdhost.HTTPStatusOK` / `HTTPStatusError` | Consistent HTTP error formatting |
202
203Example:
204
205```go
206resp, err := curdhost.HTTPClient().Do(req)
207if err != nil {
208 return nil, err
209}
210body, _ := io.ReadAll(resp.Body)
211resp.Body.Close()
212if !curdhost.HTTPStatusOK(resp.StatusCode) {
213 return nil, curdhost.HTTPStatusError("yoursite search", resp.StatusCode, body)
214}
215```
216
217### 6. Tests
218
219- Unit tests live in the provider package (`httptest` transport, no live site).
220- Use `curdhost` hooks in test setup (see `animepahe/provider_test.go`).
221- Host-level stack tests use `providers.SetFactoryForTest` via `withProviderFactories` in `provider_stack_test.go`.
222- Live tests: gate behind env vars (e.g. `CURD_LIVE_ALLANIME_TEST=1`).
223
224### 7. User configuration
225
226Users add the provider to their stack in `~/.config/curd/curd.conf`:
227
228```ini
229Provider=["yoursite"]
230# or fallback stack:
231Provider=["yoursite","allanime"]
232```
233
234---
235
236## Enabling and disabling providers
237
238Disable order (first match wins):
239
2401. **Test override** — `withAllProvidersEnabledForTest` in tests only.
2412. **`DisabledProviders` in config** — runtime kill switch, no rebuild:
242
243 ```ini
244 DisabledProviders=["animepahe","yoursite"]
245 ```
246
2473. **`DefaultDisabled` in `Meta`** — compile-time default (Animepahe ships disabled with a reason).
248
249To ship a provider that is **off by default** but opt-in capable, set `DefaultDisabled: true` and a clear `DisableReason`. Users remove it from `DisabledProviders` or we can add a menu entry later to toggle it.
250
251---
252
253## When a provider needs something new
254
255Follow this order — prefer extending the contract over special-casing in `curd.go`.
256
257### A. Needs fit an optional interface
258
259| Need | Action |
260|------|--------|
261| Explicit sub/dub resolution | Implement `ModeResolver` |
262| Per-stream Referer / subtitles | Implement `HintResolver` |
263| Stale show id refresh | Implement `IDResolver` |
264
265No registry or host changes required beyond what the interface already supports.
266
267### B. Needs a new `Meta` field
268
269Examples: capability flags (`RequiresBrowser: true`), max quality, consent text.
270
2711. Add the field to `providers.Meta`.
2722. Teach the host to read it via `providers.MetaFor(name)` (config UI, fallback prompts, doctor command).
2733. Do **not** hardcode the provider name in `curd.go`.
274
275### C. Needs a new host hook (in `curdhost`)
276
277Examples: headless browser factory, shared rate limiter, proxy setting.
278
2791. Add a function variable to `internal/curdhost/host.go`.
2802. Wire it in `internal/provider_bridge.go` `init()` from existing `internal` infrastructure.
2813. Document it in this file.
2824. Use it only from provider packages that need it.
283
284Avoid importing `internal` from providers.
285
286### D. Needs new `PlaybackConfig` fields
287
288If every provider needs a new playback preference (e.g. subtitle language on resolve):
289
2901. Add the field to `providers.PlaybackConfig`.
2912. Map it in `toPlaybackConfig()` in `provider_bridge.go`.
2923. Update existing providers if the field is required; otherwise ignore in providers that do not care.
293
294### E. Needs AniList matching behavior
295
296Prefer putting provider-specific match data in `SelectionOption.ExtraData` and scoring in the host (see `scoreProviderSearchOption` in `provider.go`).
297
298If matching is truly provider-specific and complex, implement `IDResolver` or export small helpers from your provider package (as `animepahe.ParseProviderID` does) and call them from the host through interfaces — **never** `if providerName == "yoursite"` in `curd.go`.
299
300### F. Needs runtime install without rebuild
301
302That is outside the current model. Options for a future iteration:
303
304- External JSON/script providers invoked via subprocess
305- Separate Go module imported at build time (`go install` with build tags)
306
307Document the decision in a short ADR before building. The compile-time registry is intentional for reliability and packaging.
308
309---
310
311## Checklist for a new provider PR
312
313- [ ] Package under `internal/providers/<name>/`
314- [ ] `register.go` with `providers.Register` and complete `Meta`
315- [ ] Blank import added in `internal/loadproviders/load.go`
316- [ ] Uses `curdhost` only (no `internal` import)
317- [ ] `provider_test.go` with HTTP mocks
318- [ ] Episode numbers compatible with AniList 1-based progress
319- [ ] Stream URLs return formats mpv can play (m3u8, mp4, etc.)
320- [ ] `Referrer` set correctly if the CDN checks Referer
321- [ ] No provider-specific branches added to `curd.go`
322- [ ] README or this doc updated if new config keys or hooks were added
323
324---
325
326## Reference implementations
327
328| Provider | Package | Notes |
329|----------|---------|-------|
330| AllAnime | `internal/providers/allanime` | GraphQL search/episodes, parallel stream resolution, `HintResolver` |
331| Animepahe | `internal/providers/animepahe` | DDoS-Guard + rod browser, `IDResolver`, `DefaultDisabled`, `OptOutToken` |
332
333Key host files:
334
335| File | Role |
336|------|------|
337| `internal/providers/registry.go` | Registration and lookup |
338| `internal/providers/types.go` | Interfaces and DTOs |
339| `internal/loadproviders/load.go` | Built-in provider imports |
340| `internal/provider_bridge.go` | Host hooks + internal adapter |
341| `internal/provider.go` | Stack, search, resolve orchestration |
342| `internal/provider_disabled.go` | Enable/disable logic |
343
344---
345
346## FAQ
347
348**Why not dynamic plugins?**
349Curd is a single-session CLI binary. Compile-time modules give fast startup, simple packaging (AUR, nix, releases), and easy debugging. Config-based disable covers “site is broken right now” without a plugin marketplace.
350
351**Can providers live in another repo?**
352Yes, as a Go module that imports `github.com/wraient/curd/internal/providers` and `curdhost`, calls `Register` in `init()`, and is blank-imported from a fork or custom `loadproviders` package. Same binary model, different import path.
353
354**What if episode URL resolution is slow?**
355That is expected for some sites. Do heavy work inside the provider (parallel HTTP, caching cookies on disk under `curdhost.StoragePath()`). The host already prefetches the next episode in a goroutine during playback.
356
357**Who owns breaking site changes?**
358The provider package. Fix the provider, release curd. Users can disable a broken provider with `DisabledProviders` until a fix ships.
internal/anilist.go +74 −11
@@ -141,6 +141,28 @@ func min3(a, b, c int) int {
141141}
142142
143143func doAniListSearchRequest(url string, requestBody []byte, token string) ([]byte, error) {
144 for authAttempt := 0; authAttempt < 2; authAttempt++ {
145 body, err := doAniListSearchRequestAttempt(url, requestBody, token)
146 if err == nil {
147 return body, nil
148 }
149 if authAttempt == 0 && isInvalidTokenError(err) {
150 newToken, renewed, renewErr := tryRenewAniListTokenForAPI(token, "invalid token")
151 if renewErr != nil {
152 return nil, renewErr
153 }
154 if renewed {
155 token = newToken
156 continue
157 }
158 }
159 return nil, err
160 }
161
162 return nil, fmt.Errorf("AniList search failed after token renewal")
163}
164
165func doAniListSearchRequestAttempt(url string, requestBody []byte, token string) ([]byte, error) {
144166 client := sharedHTTPClient
145167 if client == nil {
146168 client = &http.Client{Timeout: 15 * time.Second}
@@ -197,6 +219,7 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
197219 Page(page: 1, perPage: 50) {
198220 media(search: $search, type: ANIME) {
199221 id
222 episodes
200223 title {
201224 romaji
202225 english
@@ -233,10 +256,11 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
233256 animeDict := make(map[string]RofiSelectPreview)
234257
235258 type scoredAnime struct {
236 id string
237 title string
238 cover string
239 score int
259 id string
260 title string
261 cover string
262 episodes int
263 score int
240264 }
241265 var scored []scoredAnime
242266 for _, anime := range animeList {
@@ -247,7 +271,7 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
247271 }
248272 cover := anime.CoverImage.Large
249273 score := levenshtein(title, query)
250 scored = append(scored, scoredAnime{idStr, title, cover, score})
274 scored = append(scored, scoredAnime{idStr, title, cover, anime.Episodes, score})
251275 }
252276 sort.Slice(scored, func(i, j int) bool {
253277 return scored[i].score < scored[j].score
@@ -257,7 +281,7 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
257281 break
258282 }
259283 animeDict[s.id] = RofiSelectPreview{
260 Title: s.title,
284 Title: FormatAnimeSearchLabel(s.title, s.episodes),
261285 CoverImage: s.cover,
262286 }
263287 }
@@ -273,6 +297,7 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
273297 Page(page: 1, perPage: 50) {
274298 media(search: $search, type: ANIME) {
275299 id
300 episodes
276301 title {
277302 romaji
278303 english
@@ -306,9 +331,10 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
306331 var results []SelectionOption
307332
308333 type scoredAnime struct {
309 id string
310 title string
311 score int
334 id string
335 title string
336 episodes int
337 score int
312338 }
313339 var scored []scoredAnime
314340 for _, anime := range animeList {
@@ -318,7 +344,7 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
318344 title = anime.Title.Romaji
319345 }
320346 score := levenshtein(title, query)
321 scored = append(scored, scoredAnime{idStr, title, score})
347 scored = append(scored, scoredAnime{idStr, title, anime.Episodes, score})
322348 }
323349 sort.Slice(scored, func(i, j int) bool {
324350 return scored[i].score < scored[j].score
@@ -329,7 +355,8 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
329355 }
330356 results = append(results, SelectionOption{
331357 Key: s.id,
332 Label: s.title,
358 Label: FormatAnimeSearchLabel(s.title, s.episodes),
359 Title: s.title,
333360 })
334361 }
335362 return results, nil
@@ -497,6 +524,7 @@ func GetUserData(token string, userID int) (map[string]interface{}, error) {
497524 idMal
498525 episodes
499526 duration
527 format
500528 title {
501529 romaji
502530 english
@@ -554,6 +582,7 @@ func GetUserDataPreview(token string, userID int) (map[string]interface{}, error
554582 idMal
555583 episodes
556584 duration
585 format
557586 coverImage {
558587 large
559588 }
@@ -872,6 +901,39 @@ func makePostRequest(url, query string, variables map[string]interface{}, header
872901 return nil, fmt.Errorf("failed to marshal request body: %w", err)
873902 }
874903
904 token := ""
905 if headers != nil {
906 if authHeader := headers["Authorization"]; strings.HasPrefix(authHeader, "Bearer ") {
907 token = strings.TrimPrefix(authHeader, "Bearer ")
908 }
909 }
910
911 for authAttempt := 0; authAttempt < 2; authAttempt++ {
912 response, err := makePostRequestAttempt(url, requestBody, headers)
913 if err == nil {
914 return response, nil
915 }
916 if authAttempt == 0 && isInvalidTokenError(err) && token != "" {
917 newToken, renewed, renewErr := tryRenewAniListTokenForAPI(token, "invalid token")
918 if renewErr != nil {
919 return nil, renewErr
920 }
921 if renewed {
922 token = newToken
923 if headers == nil {
924 headers = map[string]string{}
925 }
926 headers["Authorization"] = "Bearer " + newToken
927 continue
928 }
929 }
930 return nil, err
931 }
932
933 return nil, fmt.Errorf("AniList request failed after token renewal")
934}
935
936func makePostRequestAttempt(url string, requestBody []byte, headers map[string]string) (map[string]interface{}, error) {
875937 client := sharedHTTPClient
876938 if client == nil {
877939 client = &http.Client{Timeout: 15 * time.Second}
@@ -1016,6 +1078,7 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
10161078 Media: Media{
10171079 Duration: toInt(media["duration"]),
10181080 Episodes: toInt(media["episodes"]),
1081 Format: safeString(media["format"]),
10191082 ID: toInt(media["id"]),
10201083 MalID: toInt(media["idMal"]),
10211084 Title: AnimeTitle{
internal/auth_token.go added +83
@@ -0,0 +1,83 @@
1package internal
2
3import (
4 "fmt"
5 "net/http"
6 "os"
7 "path/filepath"
8 "strings"
9)
10
11func isInvalidTokenResponse(statusCode int, body []byte) bool {
12 lower := strings.ToLower(string(body))
13 if strings.Contains(lower, "invalid token") || strings.Contains(lower, "invalid_token") {
14 return true
15 }
16 return statusCode == http.StatusUnauthorized
17}
18
19func isInvalidTokenError(err error) bool {
20 if err == nil {
21 return false
22 }
23 lower := strings.ToLower(err.Error())
24 return strings.Contains(lower, "invalid token") || strings.Contains(lower, "invalid_token")
25}
26
27func anilistTokenPath(config *CurdConfig) string {
28 return filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")
29}
30
31func ReauthenticateAniList(config *CurdConfig, user *User, reason string) (string, error) {
32 if config == nil {
33 config = GetGlobalConfig()
34 }
35 if config == nil {
36 return "", fmt.Errorf("missing config for AniList reauthentication")
37 }
38
39 tokenPath := anilistTokenPath(config)
40 if reason != "" {
41 CurdOut(fmt.Sprintf("AniList sign-in required (%s). Opening browser...", reason))
42 Log(fmt.Sprintf("AniList token invalid (%s), starting browser authentication", reason))
43 } else {
44 CurdOut("AniList sign-in required. Opening browser...")
45 Log("AniList token invalid, starting browser authentication")
46 }
47
48 if err := os.Remove(tokenPath); err != nil && !os.IsNotExist(err) {
49 Log(fmt.Sprintf("Failed to clear stale AniList token file: %v", err))
50 }
51
52 accessToken, err := authenticateWithBrowser(tokenPath)
53 if err != nil {
54 return "", err
55 }
56
57 if user != nil {
58 user.Token = accessToken
59 } else if globalUser := GetGlobalUser(); globalUser != nil {
60 globalUser.Token = accessToken
61 }
62
63 return accessToken, nil
64}
65
66func tryRenewAniListTokenForAPI(currentToken string, reason string) (string, bool, error) {
67 config := GetGlobalConfig()
68 if config == nil {
69 return currentToken, false, nil
70 }
71
72 newToken, err := ReauthenticateAniList(config, GetGlobalUser(), reason)
73 if err != nil {
74 return currentToken, false, err
75 }
76 return newToken, true, nil
77}
78
79func clearStoredTokenFile(tokenPath string) {
80 if err := os.Remove(tokenPath); err != nil && !os.IsNotExist(err) {
81 Log(fmt.Sprintf("Failed to clear stale token file %s: %v", tokenPath, err))
82 }
83}
internal/bench_test.go −17
@@ -69,23 +69,6 @@ func BenchmarkMergeAnimeLists(b *testing.B) {
6969 }
7070}
7171
72func BenchmarkSortAllanimeSourcesByPriority(b *testing.B) {
73 sources := make([]allanimeSource, 0, 1000)
74 for i := 0; i < 1000; i++ {
75 sources = append(sources, allanimeSource{
76 SourceUrl: fmt.Sprintf("https://example.com/%d.mp4", i),
77 SourceName: "Yt-mp4",
78 Priority: float64((i * 37) % 100),
79 })
80 }
81
82 b.ReportAllocs()
83 b.ResetTimer()
84 for i := 0; i < b.N; i++ {
85 _ = sortAllanimeSourcesByPriority(sources)
86 }
87}
88
8972func BenchmarkLevenshteinAnimeTitles(b *testing.B) {
9073 for i := 0; i < b.N; i++ {
9174 _ = levenshtein("Sousou no Frieren Beyond Journey's End", "Frieren Beyond Journey's End")
internal/config.go +34 −8
@@ -42,6 +42,7 @@ type CurdConfig struct {
4242 MpvArgs []string `config:"MpvArgs"`
4343 SubsLanguage string `config:"SubsLanguage"`
4444 SubOrDub string `config:"SubOrDub"`
45 SubStyle string `config:"SubStyle"`
4546 StoragePath string `config:"StoragePath"`
4647 AnimeNameLanguage string `config:"AnimeNameLanguage"`
4748 MenuOrder string `config:"MenuOrder"`
@@ -61,6 +62,8 @@ type CurdConfig struct {
6162 DiscordPresence bool `config:"DiscordPresence"`
6263 DiscordClientId string `config:"DiscordClientId"`
6364 Provider string `config:"Provider"`
65 DisabledProviders string `config:"DisabledProviders"`
66 ManualProviderSearch bool `config:"ManualProviderSearch"`
6467 TrackingLocal bool `config:"TrackingLocal"`
6568 TrackingRemote string `config:"TrackingRemote"`
6669 TrackingConfigured bool `config:"TrackingConfigured"`
@@ -85,8 +88,9 @@ func defaultConfigMap() map[string]string {
8588 "StoragePath": "$HOME/.local/share/curd",
8689 "AnimeNameLanguage": "english",
8790 "SubsLanguage": "english",
88 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,TRACKER,PROVIDER",
91 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,REMAP_PROVIDER,CONTINUE_LAST,TRACKER,PROVIDER",
8992 "SubOrDub": "sub",
93 "SubStyle": "ask",
9094 "PercentageToMarkComplete": "85",
9195 "NextEpisodePrompt": "false",
9296 "SkipOp": "true",
@@ -101,7 +105,9 @@ func defaultConfigMap() map[string]string {
101105 "AlternateScreen": "true",
102106 "DiscordPresence": "true",
103107 "DiscordClientId": "1287457464148820089",
104 "Provider": "[\"allanime\"]",
108 "Provider": "[\"anineko\"]",
109 "DisabledProviders": "[]",
110 "ManualProviderSearch": "false",
105111 "TrackingLocal": "true",
106112 "TrackingRemote": "anilist",
107113 "TrackingConfigured": "false",
@@ -164,6 +170,25 @@ func parseStringArray(value string) []string {
164170
165171var GlobalConfigPath string
166172
173func persistSubStylePreference(style string) error {
174 style = strings.ToLower(strings.TrimSpace(style))
175 if style != "soft" && style != "hard" {
176 return nil
177 }
178 if cfg := GetGlobalConfig(); cfg != nil {
179 cfg.SubStyle = style
180 }
181 if strings.TrimSpace(GlobalConfigPath) == "" {
182 return nil
183 }
184 configMap, err := LoadConfigFromFile(GlobalConfigPath)
185 if err != nil {
186 return err
187 }
188 configMap["SubStyle"] = style
189 return SaveConfigToFile(GlobalConfigPath, configMap)
190}
191
167192// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct
168193func LoadConfig(configPath string) (CurdConfig, error) {
169194 configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME
@@ -687,13 +712,14 @@ func normalizeTrackingConfig(config *CurdConfig) {
687712
688713func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption {
689714 // Define the default categories and all available labels
690 defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "CONTINUE_LAST", "TRACKER", "PROVIDER"}
715 defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "REMAP_PROVIDER", "CONTINUE_LAST", "TRACKER", "PROVIDER"}
691716 availableLabels := map[string]string{
692 "CURRENT": "Currently Watching",
693 "ALL": "Show All",
694 "UNTRACKED": "Untracked Watching",
695 "UPDATE": "Update (Episode, Status, Score)",
696 "CONTINUE_LAST": "Continue Last Session",
717 "CURRENT": "Currently Watching",
718 "ALL": "Show All",
719 "UNTRACKED": "Untracked Watching",
720 "UPDATE": "Update (Episode, Status, Score)",
721 "REMAP_PROVIDER": "Remap Provider",
722 "CONTINUE_LAST": "Continue Last Session",
697723 "PLANNING": "Plan to Watch",
698724 "COMPLETED": "Completed",
699725 "PAUSED": "Paused",
internal/curd.go +79 −342
@@ -735,6 +735,11 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
735735 // If WatchUntracked returns, user pressed back OR watched is done- continue to category selection
736736 ClearScreen()
737737 continue categorySelectionLoop
738 } else if categorySelection.Key == "REMAP_PROVIDER" {
739 ClearScreen()
740 RemapProviderAnime(userCurdConfig, user, databaseAnimes)
741 ClearScreen()
742 continue categorySelectionLoop
738743 } else if categorySelection.Key == "CONTINUE_LAST" {
739744 anime.Ep.ContinueLast = true
740745 }
@@ -915,7 +920,6 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
915920 anime.StartedAt = selectedAnilistAnime.StartedAt
916921 anime.CompletedAt = selectedAnilistAnime.CompletedAt
917922 anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
918 var animeList []SelectionOption
919923 userQuery = anime.Title.Romaji
920924
921925 if selectedAnilistAnime.Status == "COMPLETED" {
@@ -988,293 +992,21 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
988992 // if anime not found in database or provider changed, find it in animeList
989993 if needsProviderSearch {
990994 Log("Anime not found in database for current provider, searching in animeList...")
991 // Get Anime list (All anime)
992 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
993
994 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
995 if err != nil {
996 Log(fmt.Sprintf("Failed to select anime: %v", err))
997 ExitCurd(fmt.Errorf("Failed to select anime"))
998 }
999 // Prompt user for manual query only when no results were found
1000 if len(animeList) == 0 {
1001 for {
1002 var manualQuery string
1003 manualQuery, err = promptText(userCurdConfig, fmt.Sprintf("No results found for '%s'. Press Enter to search with AniList name, or enter a custom name to search on configured providers.", userQuery), true)
1004 if err != nil {
1005 Log("Error getting user input: " + err.Error())
1006 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1007 }
1008
1009 // If empty, use original AniList name
1010 if manualQuery == "" {
1011 manualQuery = string(userQuery)
1012 }
1013
1014 animeList, err = SearchAnime(manualQuery, userCurdConfig.SubOrDub)
1015 if err != nil {
1016 Log(fmt.Sprintf("Failed to search anime with query '%s': %v", manualQuery, err))
1017 ExitCurd(fmt.Errorf("Failed to search anime"))
1018 }
1019
1020 if len(animeList) > 0 {
1021 break
1022 }
1023 }
1024 }
1025
1026 // Automatic mapping using Thumbnail clues
1027 // 1. Try AniList and MAL thumbnail matching
1028 found := false
1029 anilistIDStr := strconv.Itoa(anime.AnilistId)
1030 var jikanUrls []string
1031 fetchedJikan := false
1032
1033 // Helper regex
1034 // AniList regex extracts ID from strings like "bx155348-" or "/155348.jpg"
1035 anilistRegex := regexp.MustCompile(`anilistcdn/media/anime/cover/(?:large|medium)/(?:bx)?(\d+)`)
1036 // MyAnimeList regex extracts the filename like "120128.jpg"
1037 malRegex := regexp.MustCompile(`myanimelist\.net/images/anime/[^/]+/([^/]+\.jpg)`)
1038
1039 for i, option := range animeList {
1040 Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s', Thumbnail='%s'", i, option.Key, option.Label, option.Thumbnail))
1041
1042 if strings.Contains(option.Thumbnail, "anilist.co") {
1043 matches := anilistRegex.FindStringSubmatch(option.Thumbnail)
1044 if len(matches) > 1 && matches[1] == anilistIDStr {
1045 anime.ProviderId = option.Key
1046 Log(fmt.Sprintf("Found Anilist Thumbnail match! Setting ProviderId to: %s", anime.ProviderId))
1047 found = true
1048 break
1049 }
1050 } else if strings.Contains(option.Thumbnail, "myanimelist.net") {
1051 matches := malRegex.FindStringSubmatch(option.Thumbnail)
1052 if len(matches) > 1 {
1053 fileName := matches[1]
1054
1055 // Fetch Jikan pictures lazily (only once)
1056 if !fetchedJikan {
1057 if anime.MalId == 0 {
1058 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
1059 }
1060 if anime.MalId != 0 {
1061 urls, err := FetchJikanPictures(anime.MalId)
1062 if err != nil {
1063 Log(fmt.Sprintf("Failed to fetch Jikan pictures: %v", err))
1064 } else {
1065 jikanUrls = urls
1066 }
1067 }
1068 fetchedJikan = true
1069 }
1070
1071 for _, url := range jikanUrls {
1072 if strings.HasSuffix(url, "/"+fileName) || strings.Contains(url, fileName) {
1073 anime.ProviderId = option.Key
1074 Log(fmt.Sprintf("Found MyAnimeList Thumbnail match (%s)! Setting ProviderId to: %s", fileName, anime.ProviderId))
1075 found = true
1076 break
1077 }
1078 }
1079 }
1080 if found {
1081 break
1082 }
1083 }
995 mappingOutcome, mappingErr := ResolveAnimeProviderMapping(userCurdConfig, anime, string(userQuery), selectedAnilistAnime)
996 if mappingErr != nil {
997 Log(fmt.Sprintf("Provider mapping failed: %v", mappingErr))
998 ExitCurd(mappingErr)
1084999 }
1085
1086 // 1b. Title/thumbnail scoring (AllAnime englishName vs AniList romaji query, etc.)
1087 if !found {
1088 if bestMatch, ok := confidentProviderSearchMatch(animeList, anime, userQuery); ok {
1089 anime.ProviderId = bestMatch.Key
1090 Log(fmt.Sprintf("Found confident provider title match! Setting ProviderId to: %s (%s)", anime.ProviderId, bestMatch.Label))
1091 found = true
1092 }
1093 }
1094
1095 // 2. Jikan Metadata & Exact Anilist Meta Tag Matching (for animepahe)
1096 if !found && ProviderEnabled("animepahe") && ProviderStackContains(userCurdConfig, "animepahe") {
1097 Log("Attempting deep metadata matching and exact AniList meta tag check for Animepahe...")
1098
1099 targetAnilistID := strconv.Itoa(anime.AnilistId)
1100 var bestMatch *SelectionOption
1101 var highestScore int
1102
1103 if anime.MalId == 0 {
1104 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
1105 }
1106
1107 var malData *JikanAnimeData
1108 if anime.MalId != 0 {
1109 malData, _ = FetchJikanAnimeData(anime.MalId)
1110 }
1111
1112 for i := range animeList {
1113 opt := &animeList[i]
1114 optionProviderName, rawProviderID, ok := ParseProviderQualifiedID(opt.Key)
1115 if ok {
1116 if optionProviderName != "animepahe" {
1117 continue
1118 }
1119 } else {
1120 rawProviderID = opt.Key
1121 if configuredProviderNames(userCurdConfig)[0] != "animepahe" {
1122 continue
1123 }
1124 }
1125 score := 0
1126
1127 if malData != nil && opt.ExtraData != nil {
1128 if paheData, ok := opt.ExtraData.(AnimepaheSearchItem); ok {
1129 paheTitleLower := strings.ToLower(paheData.Title)
1130 malTitleLower := strings.ToLower(malData.Title)
1131 malTitleEngLower := strings.ToLower(malData.TitleEnglish)
1132 malTitleJapLower := strings.ToLower(malData.TitleJapanese)
1133
1134 if paheTitleLower == malTitleLower || (malTitleEngLower != "" && paheTitleLower == malTitleEngLower) || (malTitleJapLower != "" && paheTitleLower == malTitleJapLower) {
1135 score += 5
1136 } else if strings.Contains(paheTitleLower, malTitleLower) || strings.Contains(malTitleLower, paheTitleLower) ||
1137 (malTitleEngLower != "" && (strings.Contains(paheTitleLower, malTitleEngLower) || strings.Contains(malTitleEngLower, paheTitleLower))) {
1138 score += 2
1139 }
1140
1141 if paheData.Year > 0 && malData.Year > 0 && paheData.Year == malData.Year {
1142 score += 3
1143 }
1144 if paheData.Season != "" && malData.Season != "" && strings.EqualFold(paheData.Season, malData.Season) {
1145 score += 2
1146 }
1147 if paheData.Type != "" && malData.Type != "" && strings.EqualFold(paheData.Type, malData.Type) {
1148 score += 2
1149 }
1150 if paheData.Episodes > 0 && malData.Episodes > 0 && paheData.Episodes == malData.Episodes {
1151 score += 2
1152 } else if (paheData.Episodes == 0 && malData.Status == "Currently Airing") || (malData.Episodes == 0 && paheData.Status == "Currently Airing") {
1153 score += 2
1154 }
1155 if strings.EqualFold(paheData.Status, malData.Status) {
1156 score += 1
1157 }
1158 }
1159 } else {
1160 if strings.Contains(strings.ToLower(opt.Title), strings.ToLower(string(userQuery))) {
1161 score += 2
1162 }
1163 }
1164
1165 // If it has a decent score (or there are very few options), let's verify with the exact AniList meta tag
1166 if score >= 2 || len(animeList) <= 3 {
1167 animeRef := parseAnimepaheProviderID(rawProviderID)
1168 if animeRef.Session == "" {
1169 continue
1170 }
1171 animeUrl := fmt.Sprintf("https://animepahe.pw/anime/%s", animeRef.Session)
1172 Log(fmt.Sprintf("Fetching %s to check exact AniList meta tag...", animeUrl))
1173 req, err := newAnimepahePageRequest(animeUrl)
1174 if err != nil {
1175 Log(fmt.Sprintf("Failed to build animepahe detail request %s: %v", animeUrl, err))
1176 continue
1177 }
1178
1179 resp, err := sharedHTTPClient.Do(req)
1180 if err != nil {
1181 Log(fmt.Sprintf("Failed to fetch animepahe detail page %s: %v", animeUrl, err))
1182 continue
1183 }
1184 body, readErr := io.ReadAll(resp.Body)
1185 resp.Body.Close()
1186 if readErr != nil {
1187 Log(fmt.Sprintf("Failed to read animepahe detail page %s: %v", animeUrl, readErr))
1188 continue
1189 }
1190 if resp.StatusCode == http.StatusOK {
1191 bodyStr := string(body)
1192
1193 metaTag := fmt.Sprintf(`<meta name="anilist" content="%s">`, targetAnilistID)
1194 if strings.Contains(bodyStr, metaTag) {
1195 Log(fmt.Sprintf("FOUND EXACT ANILIST META TAG MATCH in %s!", opt.Title))
1196 bestMatch = opt
1197 highestScore = 100 // Guarantee selection
1198 break
1199 } else {
1200 malMetaTag := fmt.Sprintf(`<meta name="mal" content="%d">`, anime.MalId)
1201 if anime.MalId != 0 && strings.Contains(bodyStr, malMetaTag) {
1202 Log(fmt.Sprintf("FOUND EXACT MAL META TAG MATCH in %s!", opt.Title))
1203 bestMatch = opt
1204 highestScore = 100
1205 break
1206 }
1207 }
1208 }
1209 }
1210
1211 if score > highestScore {
1212 highestScore = score
1213 bestMatch = opt
1214 }
1215 }
1216
1217 if bestMatch != nil && highestScore == 100 {
1218 anime.ProviderId = bestMatch.Key
1219 Log(fmt.Sprintf("Found EXACT meta tag match! Score: %d. Setting ProviderId to: %s", highestScore, anime.ProviderId))
1220 found = true
1221 } else if bestMatch != nil {
1222 Log(fmt.Sprintf("Highest match score was %d (needed 100 for Animepahe exact meta tag match). Not selecting automatically to prevent false positives.", highestScore))
1223 if confirmProviderMatch(*bestMatch, "Animepahe metadata") {
1224 anime.ProviderId = bestMatch.Key
1225 Log(fmt.Sprintf("User confirmed Animepahe match. Setting ProviderId to: %s", anime.ProviderId))
1226 found = true
1227 }
1228 }
1229 }
1230
1231 // 3. Fallback to naive title/episode match
1232 if !found {
1233 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes)
1234 for _, option := range animeList {
1235 if fmt.Sprintf("%s (%d episodes)", option.Title, selectedAnilistAnime.Media.Episodes) == targetLabel {
1236 if confirmProviderMatch(option, "title and episode count") {
1237 anime.ProviderId = option.Key
1238 Log(fmt.Sprintf("User confirmed exact text match. Setting ProviderId to: %s", anime.ProviderId))
1239 found = true
1240 }
1241 break
1242 }
1243 }
1244 if !found {
1245 Log(fmt.Sprintf("No exact match found for label '%s'. Will require manual selection.", targetLabel))
1246 }
1247 }
1248
1249 // If unable to get Allanime id automatically get manually
1250 if anime.ProviderId == "" {
1251 CurdOut("We didn't find any matches. Please select manually.")
1252 selectedAllanimeAnime, err := DynamicSelect(animeList)
1253 if err != nil {
1254 ExitCurd(fmt.Errorf("No anime available"))
1255 }
1256
1257 if selectedAllanimeAnime.Key == "-1" {
1258 ExitCurd(nil)
1259 }
1260
1261 // Handle back button - go back to main menu
1262 if selectedAllanimeAnime.Key == "-2" {
1263 CurdOut("Going back to main menu...")
1264 RestoreScreen()
1265 if anime.Ep.ContinueLast {
1266 anime.Ep.ContinueLast = false
1267 }
1268 continue
1000 switch mappingOutcome {
1001 case ProviderMappingBack:
1002 CurdOut("Going back to main menu...")
1003 RestoreScreen()
1004 if anime.Ep.ContinueLast {
1005 anime.Ep.ContinueLast = false
12691006 }
1270
1271 anime.ProviderId = selectedAllanimeAnime.Key
1272 }
1273 if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
1274 anime.ProviderName = providerName
1275 anime.ProviderId = rawProviderID
1276 } else {
1277 anime.ProviderName = configuredProviderNames(userCurdConfig)[0]
1007 continue
1008 case ProviderMappingQuit:
1009 ExitCurd(nil)
12781010 }
12791011 }
12801012
@@ -1560,27 +1292,6 @@ func handleUnreleasedAnime(userCurdConfig *CurdConfig, user *User, anime *Anime,
15601292 anime.Ep.ContinueLast = false
15611293}
15621294
1563func confirmProviderMatch(option SelectionOption, reason string) bool {
1564 label := option.Label
1565 if label == "" {
1566 label = option.Title
1567 }
1568 if label == "" {
1569 label = option.Key
1570 }
1571
1572 CurdOut(fmt.Sprintf("Provider match found by %s: %s", reason, label))
1573 selected, err := promptSelect([]SelectionOption{
1574 {Key: "use", Label: "Use this match"},
1575 {Key: "manual", Label: "Select manually"},
1576 })
1577 if err != nil {
1578 Log(fmt.Sprintf("Error confirming provider match: %v", err))
1579 return false
1580 }
1581 return selected.Key == "use"
1582}
1583
15841295func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
15851296 if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil {
15861297 Log(fmt.Sprintf("Failed to resolve provider id: %v", err))
@@ -1628,34 +1339,59 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
16281339 linkErr = err
16291340 Log(fmt.Sprintf("ResolveEpisodeURL still failed after provider reselect: %v", linkErr))
16301341 }
1631 // If unable to get episode link automatically get manually
1632 episodeProviderName, episodeProviderID := AnimeProviderID(anime)
1633 episodeList, listErr := EpisodesList(QualifyProviderID(episodeProviderName, episodeProviderID), userCurdConfig.SubOrDub)
1634 if listErr != nil {
1635 CurdOut("No episode list found: " + listErr.Error())
1636 Log(fmt.Sprintf("EpisodesList failed: %v", listErr))
1637 RestoreScreen()
1638 os.Exit(1)
1639 }
1640 if len(episodeList) == 0 {
1641 CurdOut("No episodes were returned by the current provider for this anime.")
1642 Log(fmt.Sprintf("EpisodesList returned no episodes for provider %s and id %s after ResolveEpisodeURL error: %v", episodeProviderName, episodeProviderID, linkErr))
1643 RestoreScreen()
1644 os.Exit(1)
1645 }
1646 episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1647 if err != nil {
1648 Log("Invalid episode input: " + err.Error())
1649 CurdOut("Invalid episode number")
1650 RestoreScreen()
1651 os.Exit(1)
1652 }
1653 anime.Ep.Number = episodeNumber
1654 episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1655 link = episodeResult.Links
1656 if err != nil {
1657 CurdOut("Failed to get episode link")
1658 os.Exit(1)
1342 for {
1343 switch promptEpisodeLinkFailureRecovery(userCurdConfig) {
1344 case "remap":
1345 if RemapAnimeProviderOnEpisodeFailure(userCurdConfig, anime, nil) {
1346 episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1347 link = episodeResult.Links
1348 if err == nil && len(link) > 0 {
1349 anime.Ep.Links = link
1350 applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1351 goto episodeLinksReady
1352 }
1353 if err != nil {
1354 linkErr = err
1355 Log(fmt.Sprintf("ResolveEpisodeURL failed after provider remap: %v", linkErr))
1356 }
1357 }
1358 case "episode":
1359 episodeProviderName, episodeProviderID := AnimeProviderID(anime)
1360 episodeList, listErr := EpisodesList(QualifyProviderID(episodeProviderName, episodeProviderID), userCurdConfig.SubOrDub)
1361 if listErr != nil {
1362 CurdOut("No episode list found: " + listErr.Error())
1363 Log(fmt.Sprintf("EpisodesList failed: %v", listErr))
1364 continue
1365 }
1366 if len(episodeList) == 0 {
1367 CurdOut("No episodes were returned by the current provider for this anime.")
1368 Log(fmt.Sprintf("EpisodesList returned no episodes for provider %s and id %s after ResolveEpisodeURL error: %v", episodeProviderName, episodeProviderID, linkErr))
1369 continue
1370 }
1371 episodeNumber, promptErr := promptPositiveEpisodeNumber(userCurdConfig, fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1372 if promptErr != nil {
1373 Log("Invalid episode input: " + promptErr.Error())
1374 CurdOut("Invalid episode number")
1375 continue
1376 }
1377 anime.Ep.Number = episodeNumber
1378 episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1379 link = episodeResult.Links
1380 if err == nil && len(link) > 0 {
1381 anime.Ep.Links = link
1382 applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1383 goto episodeLinksReady
1384 }
1385 if err != nil {
1386 linkErr = err
1387 Log(fmt.Sprintf("ResolveEpisodeURL failed for episode %d: %v", anime.Ep.Number, linkErr))
1388 } else {
1389 CurdOut("Failed to get episode link")
1390 }
1391 default:
1392 RestoreScreen()
1393 return ""
1394 }
16591395 }
16601396 } else {
16611397 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link on first try. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link)))
@@ -1667,7 +1403,8 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
16671403episodeLinksReady:
16681404 if len(anime.Ep.Links) == 0 {
16691405 CurdOut("No episode links found")
1670 os.Exit(1)
1406 RestoreScreen()
1407 return ""
16711408 } else {
16721409 Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links)))
16731410 }
@@ -1763,10 +1500,6 @@ func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
17631500 if err != nil {
17641501 return err
17651502 }
1766 animepaheProvider, ok := provider.(*AnimepaheProvider)
1767 if !ok {
1768 return nil
1769 }
17701503
17711504 query := GetAnimeName(*anime)
17721505 if query == "" {
@@ -1776,7 +1509,7 @@ func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
17761509 query = anime.Title.English
17771510 }
17781511
1779 resolved, err := animepaheProvider.ResolveProviderID(providerID, query)
1512 resolved, err := resolveProviderID(provider, providerID, query)
17801513 if err != nil {
17811514 return err
17821515 }
@@ -1821,7 +1554,11 @@ func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason erro
18211554 }
18221555
18231556 CurdOut("The saved Animepahe mapping is stale. Please select the anime again.")
1824 selected, err := promptSelect(options)
1557 var trackerEntry *Entry
1558 if anime.TotalEpisodes > 0 {
1559 trackerEntry = &Entry{Media: Media{Episodes: anime.TotalEpisodes}}
1560 }
1561 selected, err := promptProviderSearchSelection(userCurdConfig, options, trackerEntry)
18251562 if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" {
18261563 if err != nil {
18271564 Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err))
internal/curdhost/host.go added +42
@@ -0,0 +1,42 @@
1package curdhost
2
3import (
4 "fmt"
5 "net/http"
6 "net/url"
7 "strings"
8)
9
10// PromptOption is a minimal menu item for provider-driven prompts.
11type PromptOption struct {
12 Key string
13 Label string
14}
15
16// Host hooks are wired from the main application package during init.
17var (
18 HTTPClient func() *http.Client
19 Log func(string)
20 Out func(string)
21 PromptSelect func(options []PromptOption) (PromptOption, error)
22 CurrentSubStyle func() string
23 PersistSubStylePreference func(style string) error
24 StoragePath func() string
25 AnimeNameLanguage func() string
26 SetCookiesForAnimepahe func(u *url.URL, cookies []*http.Cookie)
27)
28
29func HTTPStatusOK(statusCode int) bool {
30 return statusCode >= http.StatusOK && statusCode < http.StatusMultipleChoices
31}
32
33func HTTPStatusError(context string, statusCode int, body []byte) error {
34 snippet := strings.TrimSpace(string(body))
35 if len(snippet) > 300 {
36 snippet = snippet[:300] + "..."
37 }
38 if snippet != "" {
39 return fmt.Errorf("%s failed with status %d: %s", context, statusCode, snippet)
40 }
41 return fmt.Errorf("%s failed with status %d", context, statusCode)
42}
internal/episode_url_live_test.go +20 −2
@@ -10,9 +10,18 @@ func TestAllanimeMarchLionDubEp1Live(t *testing.T) {
1010 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" {
1111 t.Skip("set CURD_LIVE_ALLANIME_TEST=1")
1212 }
13 withAllProvidersEnabledForTest(t)
1314
1415 showID := "NPpCgzb2MbnpiyxZ3"
15 links, err := getAllanimeEpisodeURLForMode(showID, "dub", 1)
16 provider, err := ProviderByName("allanime")
17 if err != nil {
18 t.Fatalf("allanime provider: %v", err)
19 }
20 resolver, ok := provider.(ProviderModeResolver)
21 if !ok {
22 t.Fatal("expected allanime provider to implement ProviderModeResolver")
23 }
24 links, err := resolver.GetEpisodeURLForMode(CurdConfig{SubOrDub: "dub"}, showID, 1, "dub")
1625 if err == nil {
1726 for _, link := range links {
1827 if strings.Contains(link, "fast4speed.rsvp") {
@@ -27,9 +36,18 @@ func TestAllanimeMarchLionSubEp1Live(t *testing.T) {
2736 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" {
2837 t.Skip("set CURD_LIVE_ALLANIME_TEST=1")
2938 }
39 withAllProvidersEnabledForTest(t)
3040
3141 showID := "NPpCgzb2MbnpiyxZ3"
32 links, err := getAllanimeEpisodeURLForMode(showID, "sub", 1)
42 provider, err := ProviderByName("allanime")
43 if err != nil {
44 t.Fatalf("allanime provider: %v", err)
45 }
46 resolver, ok := provider.(ProviderModeResolver)
47 if !ok {
48 t.Fatal("expected allanime provider to implement ProviderModeResolver")
49 }
50 links, err := resolver.GetEpisodeURLForMode(CurdConfig{SubOrDub: "sub"}, showID, 1, "sub")
3351 if err != nil {
3452 t.Fatalf("sub episode link lookup failed: %v", err)
3553 }
internal/links.go +20
@@ -42,3 +42,23 @@ func linkSelectionScore(link string) int {
4242 score += wixmpQualityScore(link)
4343 return score
4444}
45
46func wixmpQualityScore(link string) int {
47 for _, quality := range []string{"1080p", "720p", "480p", "360p", "240p"} {
48 if strings.Contains(link, quality) {
49 switch quality {
50 case "1080p":
51 return 1080
52 case "720p":
53 return 720
54 case "480p":
55 return 480
56 case "360p":
57 return 360
58 case "240p":
59 return 240
60 }
61 }
62 }
63 return 0
64}
internal/loadproviders/load.go added +8
@@ -0,0 +1,8 @@
1// Package loadproviders registers built-in streaming providers via init side effects.
2package loadproviders
3
4import (
5 _ "github.com/wraient/curd/internal/providers/allanime"
6 _ "github.com/wraient/curd/internal/providers/animepahe"
7 _ "github.com/wraient/curd/internal/providers/anineko"
8)
internal/localTracking.go +105 −61
@@ -8,6 +8,8 @@ import (
88 "strconv"
99 "strings"
1010 "time"
11
12 "github.com/wraient/curd/internal/providers/animepahe"
1113)
1214
1315// Function to add an anime entry
@@ -54,7 +56,7 @@ func normalizeLocalProviderID(providerName, providerID, animeName string) string
5456 return ""
5557 }
5658
57 stableID := stableAnimepaheProviderID(providerID)
59 stableID := animepahe.StableProviderID(providerID)
5860 if stableID != "" {
5961 return stableID
6062 }
@@ -343,9 +345,82 @@ func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime
343345 return bestMatch
344346}
345347
348func LocalRemapAnimeProvider(databaseFile string, anilistID int, providerName, providerID, animeName string, watchingEpisode, playbackTime, animeDuration int) error {
349 providerID = normalizeLocalProviderID(providerName, providerID, animeName)
350 animeList := LocalGetAllAnime(databaseFile)
351
352 target := LocalFindAnime(animeList, anilistID, "")
353 if target == nil {
354 newAnime := Anime{
355 AnilistId: anilistID,
356 ProviderId: providerID,
357 ProviderName: providerName,
358 Ep: Episode{
359 Number: watchingEpisode,
360 Player: playingVideo{PlaybackTime: playbackTime},
361 Duration: animeDuration,
362 },
363 Title: AnimeTitle{
364 English: animeName,
365 Romaji: animeName,
366 },
367 }
368 animeList = append(animeList, newAnime)
369 } else {
370 oldProviderID := normalizeLocalProviderID(target.ProviderName, target.ProviderId, GetAnimeName(*target))
371 updated := false
372 for i := range animeList {
373 entry := &animeList[i]
374 if entry.AnilistId != anilistID {
375 continue
376 }
377 entryProviderID := normalizeLocalProviderID(entry.ProviderName, entry.ProviderId, GetAnimeName(*entry))
378 if entryProviderID != oldProviderID {
379 continue
380 }
381 entry.ProviderId = providerID
382 entry.ProviderName = providerName
383 entry.Ep.Number = watchingEpisode
384 entry.Ep.Player.PlaybackTime = playbackTime
385 entry.Ep.Duration = animeDuration
386 if animeName != "" {
387 entry.Title.English = animeName
388 entry.Title.Romaji = animeName
389 }
390 updated = true
391 }
392 if !updated {
393 return fmt.Errorf("failed to update local history for AniList ID %d", anilistID)
394 }
395 }
396
397 file, err := os.Create(databaseFile)
398 if err != nil {
399 return fmt.Errorf("create local history file: %w", err)
400 }
401 defer file.Close()
402
403 writer := csv.NewWriter(file)
404 for _, anime := range animeList {
405 record := []string{
406 strconv.Itoa(anime.AnilistId),
407 normalizeLocalProviderID(anime.ProviderName, anime.ProviderId, GetAnimeName(anime)),
408 strconv.Itoa(anime.Ep.Number),
409 strconv.Itoa(anime.Ep.Player.PlaybackTime),
410 strconv.Itoa(anime.Ep.Duration),
411 anime.ProviderName,
412 GetAnimeName(anime),
413 }
414 if err := writer.Write(record); err != nil {
415 return fmt.Errorf("write local history: %w", err)
416 }
417 }
418 writer.Flush()
419 return writer.Error()
420}
421
346422func WatchUntracked(userCurdConfig *CurdConfig) {
347423 var query string
348 var animeList []SelectionOption
349424 var err error
350425 var anime Anime
351426
@@ -358,70 +433,22 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
358433 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
359434 }
360435
361 // Search for the anime
362 animeList, err = SearchAnime(query, userCurdConfig.SubOrDub)
363 if err != nil {
364 Log(fmt.Sprintf("Failed to search anime: %v", err))
436 providerID, providerName, back, searchErr := ResolveUntrackedProviderSearch(userCurdConfig, query)
437 if searchErr != nil {
438 Log(fmt.Sprintf("Failed to search anime: %v", searchErr))
365439 ExitCurd(fmt.Errorf("Failed to search anime"))
366440 }
367
368 if len(animeList) == 0 {
369 // Prompt user for manual query
370 for {
371 var manualQuery string
372 manualQuery, err = promptText(userCurdConfig, fmt.Sprintf("No results found for '%s'. Press Enter to search with the original name, or enter a custom name to search on AllAnime.", query), true)
373 if err != nil {
374 Log("Error getting user input: " + err.Error())
375 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
376 }
377
378 // If empty, use original query name
379 if manualQuery == "" {
380 manualQuery = query
381 }
382
383 animeList, err = SearchAnime(manualQuery, userCurdConfig.SubOrDub)
384 if err != nil {
385 Log(fmt.Sprintf("Failed to search anime with query '%s': %v", manualQuery, err))
386 ExitCurd(fmt.Errorf("Failed to search anime"))
387 }
388
389 if len(animeList) > 0 {
390 break
391 }
392 }
441 if back {
442 return
393443 }
394
395 // Select anime from search results
396 selectedAnime, err := DynamicSelect(animeList)
397 if err != nil {
398 Log(fmt.Sprintf("Failed to select anime: %v", err))
399 ExitCurd(fmt.Errorf("Failed to select anime"))
400 }
401
402 if selectedAnime.Key == "-1" {
444 if providerID == "" {
403445 ExitCurd(nil)
404446 }
405447
406 // Back goes to home menu
407 if selectedAnime.Key == "-2" {
408 return // Return to caller (home menu)
409 }
410
411 anime.ProviderId = selectedAnime.Key
412 if providerName, rawProviderID, ok := ParseProviderQualifiedID(selectedAnime.Key); ok {
413 anime.ProviderName = providerName
414 anime.ProviderId = rawProviderID
415 } else {
416 anime.ProviderName = configuredProviderNames(userCurdConfig)[0]
417 }
418 if selectedAnime.Title != "" {
419 anime.Title.English = selectedAnime.Title
420 anime.Title.Romaji = selectedAnime.Title
421 } else {
422 anime.Title.English = selectedAnime.Label
423 anime.Title.Romaji = selectedAnime.Label
424 }
448 anime.ProviderId = providerID
449 anime.ProviderName = providerName
450 anime.Title.English = query
451 anime.Title.Romaji = query
425452 break
426453 }
427454
@@ -439,7 +466,24 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
439466 resolvedLink, err := ResolveEpisodeURLForPlayback(*userCurdConfig, &anime, anime.Ep.Number)
440467 if err != nil {
441468 Log(fmt.Sprintf("Failed to get episode link: %v", err))
442 ExitCurd(fmt.Errorf("Failed to get episode link"))
469 switch promptEpisodeLinkFailureRecovery(userCurdConfig) {
470 case "remap":
471 if RemapAnimeProviderOnEpisodeFailure(userCurdConfig, &anime, nil) {
472 continue
473 }
474 case "episode":
475 episodeNumber, promptErr := promptPositiveEpisodeNumber(userCurdConfig, "Enter the episode number")
476 if promptErr != nil {
477 Log(fmt.Sprintf("Invalid episode number: %v", promptErr))
478 CurdOut("Invalid episode number")
479 continue
480 }
481 anime.Ep.Number = episodeNumber
482 continue
483 default:
484 ExitCurd(nil)
485 }
486 continue
443487 }
444488 link := resolvedLink.Links
445489 applyStreamPlaybackHints(&anime, link, resolvedLink.LinkHints)
internal/logic_regression_test.go +4 −4
@@ -219,8 +219,8 @@ func TestGetProviderNormalizesConfiguredProviderName(t *testing.T) {
219219 CurrentProvider = nil
220220 SetGlobalConfig(&CurdConfig{Provider: " AllAnime "})
221221
222 if got := GetProvider().Name(); got != "allanime" {
223 t.Fatalf("expected allanime provider, got %q", got)
222 if got := GetProvider().Name(); got != "anineko" {
223 t.Fatalf("expected anineko provider when allanime is disabled, got %q", got)
224224 }
225225}
226226
@@ -235,8 +235,8 @@ func TestGetProviderFallsBackWhenConfiguredProviderDisabled(t *testing.T) {
235235 CurrentProvider = nil
236236 SetGlobalConfig(&CurdConfig{Provider: " AnimePahe "})
237237
238 if got := GetProvider().Name(); got != "allanime" {
239 t.Fatalf("expected allanime fallback for disabled provider, got %q", got)
238 if got := GetProvider().Name(); got != "anineko" {
239 t.Fatalf("expected anineko fallback for disabled provider, got %q", got)
240240 }
241241}
242242
internal/myanimelist.go +24 −15
@@ -454,6 +454,10 @@ func renewMyAnimeListAccessToken(config *CurdConfig, tokenPath string, token *OA
454454 Log(fmt.Sprintf("Failed to refresh MyAnimeList token after %s: %v", reason, refreshErr))
455455 }
456456
457 CurdOut("MyAnimeList sign-in required. Opening browser...")
458 Log(fmt.Sprintf("Starting MyAnimeList browser authentication after %s", reason))
459 clearStoredTokenFile(tokenPath)
460
457461 accessToken, authErr := authenticateMyAnimeList(config, tokenPath)
458462 if authErr != nil {
459463 return "", authErr
@@ -547,24 +551,26 @@ func myAnimeListRequest(config *CurdConfig, method, requestURL string, form url.
547551 return readErr
548552 }
549553
550 if resp.StatusCode == http.StatusUnauthorized && attempt == 0 {
551 tokenPath := myAnimeListTokenPath(config)
552 storedToken, tokenErr := loadToken(tokenPath)
553 if tokenErr != nil {
554 Log(fmt.Sprintf("Failed to load MyAnimeList token after unauthorized response, starting login: %v", tokenErr))
555 accessToken, authErr := renewMyAnimeListAccessToken(config, tokenPath, nil, "unauthorized API response")
556 if authErr != nil {
557 return authErr
554 if resp.StatusCode == http.StatusUnauthorized || isInvalidTokenResponse(resp.StatusCode, body) {
555 if attempt == 0 {
556 tokenPath := myAnimeListTokenPath(config)
557 storedToken, tokenErr := loadToken(tokenPath)
558 if tokenErr != nil {
559 Log(fmt.Sprintf("Failed to load MyAnimeList token after unauthorized response, starting login: %v", tokenErr))
560 accessToken, authErr := renewMyAnimeListAccessToken(config, tokenPath, nil, "unauthorized API response")
561 if authErr != nil {
562 return authErr
563 }
564 token = accessToken
565 continue
566 }
567 accessToken, renewErr := renewMyAnimeListAccessToken(config, tokenPath, storedToken, "unauthorized API response")
568 if renewErr != nil {
569 return renewErr
558570 }
559571 token = accessToken
560572 continue
561573 }
562 accessToken, renewErr := renewMyAnimeListAccessToken(config, tokenPath, storedToken, "unauthorized API response")
563 if renewErr != nil {
564 return renewErr
565 }
566 token = accessToken
567 continue
568574 }
569575
570576 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
@@ -724,6 +730,7 @@ func lookupAniListMediaByMalID(malID int) (Media, string, error) {
724730 episodes
725731 duration
726732 status
733 format
727734 title {
728735 romaji
729736 english
@@ -760,6 +767,7 @@ func lookupAniListMediaByMalID(malID int) (Media, string, error) {
760767 Episodes: 0,
761768 Duration: 0,
762769 Status: safeAniListString(mediaData["status"]),
770 Format: safeAniListString(mediaData["format"]),
763771 Title: AnimeTitle{
764772 Romaji: safeAniListTitle(mediaData, "romaji"),
765773 English: safeAniListTitle(mediaData, "english"),
@@ -833,7 +841,7 @@ func lookupAniListMediaByMalIDs(malIDs []int) (map[int]aniListMediaLookupResult,
833841 var query strings.Builder
834842 query.WriteString("query {")
835843 for idx, malID := range malIDs {
836 fmt.Fprintf(&query, " m%d: Media(idMal: %d, type: ANIME) { id idMal episodes duration status title { romaji english native } coverImage { large } }", idx, malID)
844 fmt.Fprintf(&query, " m%d: Media(idMal: %d, type: ANIME) { id idMal episodes duration status format title { romaji english native } coverImage { large } }", idx, malID)
837845 }
838846 query.WriteString(" }")
839847
@@ -876,6 +884,7 @@ func lookupAniListMediaByMalIDs(malIDs []int) (map[int]aniListMediaLookupResult,
876884 Episodes: 0,
877885 Duration: 0,
878886 Status: safeAniListString(rawMedia["status"]),
887 Format: safeAniListString(rawMedia["format"]),
879888 Title: AnimeTitle{
880889 Romaji: safeAniListTitle(rawMedia, "romaji"),
881890 English: safeAniListTitle(rawMedia, "english"),
internal/player.go +4 −2
@@ -12,6 +12,8 @@ import (
1212 "strings"
1313 "sync"
1414 "time"
15
16 "github.com/wraient/curd/internal/providers"
1517)
1618
1719var logFile = "debug.log"
@@ -23,8 +25,8 @@ func streamReferrerForLink(link, provider string) string {
2325 if strings.Contains(strings.ToLower(link), "tools.fast4speed.rsvp") {
2426 return "https://allanime.to"
2527 }
26 if provider == "animepahe" {
27 return "https://kwik.cx/"
28 if referrer := providers.Referrer(provider); referrer != "" {
29 return referrer
2830 }
2931 return defaultStreamReferrer
3032}
internal/provider.go +49 −30
@@ -4,6 +4,9 @@ import (
44 "fmt"
55 "strconv"
66 "strings"
7
8 "github.com/wraient/curd/internal/providers"
9 "github.com/wraient/curd/internal/providers/animepahe"
710)
811
912// Provider interface defines methods for an anime provider.
@@ -27,26 +30,12 @@ type ProviderEpisodeResult struct {
2730}
2831
2932const providerIDSeparator = "::"
30const animepaheOptOutProvider = "no-animepahe"
3133
3234// Global variable to keep the current provider
3335var CurrentProvider Provider
3436
35var providerFactories = map[string]func() Provider{
36 "allanime": func() Provider { return &AllanimeProvider{} },
37 "animepahe": func() Provider { return &AnimepaheProvider{} },
38}
39
4037func normalizeProviderName(providerName string) string {
41 providerName = strings.Trim(strings.TrimSpace(providerName), "\"'[]")
42 switch strings.ToLower(strings.TrimSpace(providerName)) {
43 case "allanime", "all-anime", "all anime":
44 return "allanime"
45 case "animepahe", "pahe":
46 return "animepahe"
47 default:
48 return ""
49 }
38 return providers.NormalizeName(providerName)
5039}
5140
5241func normalizeProviderConfigToken(token string) string {
@@ -69,7 +58,7 @@ func parseProviderConfigParts(rawProvider string) []string {
6958func parseProviderConfig(rawProvider string) ([]string, bool) {
7059 rawProvider = strings.TrimSpace(rawProvider)
7160 if rawProvider == "" {
72 rawProvider = "allanime"
61 rawProvider = firstEnabledProviderName()
7362 }
7463
7564 normalizedRaw := strings.ToLower(rawProvider)
@@ -83,7 +72,7 @@ func parseProviderConfig(rawProvider string) ([]string, bool) {
8372 animepaheDeclined := false
8473
8574 for _, part := range parts {
86 if normalizeProviderConfigToken(part) == animepaheOptOutProvider {
75 if isProviderOptOutToken(part) {
8776 animepaheDeclined = true
8877 continue
8978 }
@@ -112,14 +101,14 @@ func parseProviderConfig(rawProvider string) ([]string, bool) {
112101 }
113102
114103 if len(providers) == 0 {
115 providers = []string{"allanime"}
104 providers = []string{firstEnabledProviderName()}
116105 }
117106
118107 return providers, animepaheDeclined
119108}
120109
121110func configuredProviderNames(config *CurdConfig) []string {
122 rawProvider := "allanime"
111 rawProvider := firstEnabledProviderName()
123112 if config != nil && strings.TrimSpace(config.Provider) != "" {
124113 rawProvider = config.Provider
125114 }
@@ -143,11 +132,38 @@ func formatProviderConfigValue(names []string, animepaheDeclined bool) string {
143132 quotedNames = append(quotedNames, fmt.Sprintf("%q", name))
144133 }
145134 if animepaheDeclined {
146 quotedNames = append(quotedNames, fmt.Sprintf("%q", animepaheOptOutProvider))
135 if token := providerOptOutTokenForName("animepahe"); token != "" {
136 quotedNames = append(quotedNames, fmt.Sprintf("%q", token))
137 }
147138 }
148139 return "[" + strings.Join(quotedNames, ",") + "]"
149140}
150141
142func isProviderOptOutToken(token string) bool {
143 token = normalizeProviderConfigToken(token)
144 if token == "" {
145 return false
146 }
147 for _, name := range providers.RegisteredNames() {
148 meta, ok := providers.MetaFor(name)
149 if !ok || meta.OptOutToken == "" {
150 continue
151 }
152 if token == normalizeProviderConfigToken(meta.OptOutToken) {
153 return true
154 }
155 }
156 return false
157}
158
159func providerOptOutTokenForName(providerName string) string {
160 meta, ok := providers.MetaFor(providerName)
161 if !ok {
162 return ""
163 }
164 return meta.OptOutToken
165}
166
151167func animepaheDeclinedInConfig(config *CurdConfig) bool {
152168 if config == nil {
153169 return false
@@ -174,11 +190,11 @@ func ProviderByName(providerName string) (Provider, error) {
174190 if reason := providerDisabledReason(providerName); reason != "" {
175191 return nil, fmt.Errorf("provider %q is disabled: %s", providerName, reason)
176192 }
177 factory, ok := providerFactories[providerName]
178 if !ok {
179 return nil, fmt.Errorf("unknown provider %q", providerName)
193 provider, err := providers.New(providerName)
194 if err != nil {
195 return nil, err
180196 }
181 return factory(), nil
197 return wrapProvider(provider), nil
182198}
183199
184200func GetProvider() Provider {
@@ -190,8 +206,11 @@ func GetProvider() Provider {
190206 primaryProviderName := providerNames[0]
191207 provider, err := ProviderByName(primaryProviderName)
192208 if err != nil {
193 CurrentProvider = &AllanimeProvider{}
194 return CurrentProvider
209 if fallback, fallbackErr := ProviderByName(firstEnabledProviderName()); fallbackErr == nil {
210 CurrentProvider = fallback
211 return CurrentProvider
212 }
213 return provider
195214 }
196215 CurrentProvider = provider
197216 return CurrentProvider
@@ -280,7 +299,7 @@ func providerNamesForAnime(config *CurdConfig, anime *Anime) []string {
280299 }
281300 }
282301 if len(result) == 0 {
283 return []string{"allanime"}
302 return []string{firstEnabledProviderName()}
284303 }
285304 return result
286305}
@@ -425,7 +444,7 @@ func appendProviderName(providerNames []string, providerName string) []string {
425444 }
426445 }
427446 if len(result) == 0 {
428 return []string{"allanime"}
447 return []string{firstEnabledProviderName()}
429448 }
430449 return result
431450}
@@ -635,7 +654,7 @@ func episodeModeResult(config CurdConfig, anime *Anime, epNo int, mode string) (
635654func episodeModeResultWithProviders(config CurdConfig, anime *Anime, epNo int, mode string, providerNames []string) (ProviderEpisodeResult, error) {
636655 mode = normalizeTranslationType(mode)
637656 if len(providerNames) == 0 {
638 providerNames = []string{"allanime"}
657 providerNames = []string{firstEnabledProviderName()}
639658 }
640659
641660 var errors []string
@@ -832,7 +851,7 @@ func scoreProviderSearchOption(option SelectionOption, anime *Anime, query strin
832851 if anime.TotalEpisodes > 0 && strings.Contains(option.Label, fmt.Sprintf("(%d episodes)", anime.TotalEpisodes)) {
833852 score += 20
834853 }
835 if item, ok := option.ExtraData.(AnimepaheSearchItem); ok && anime.TotalEpisodes > 0 && item.Episodes == anime.TotalEpisodes {
854 if item, ok := option.ExtraData.(animepahe.SearchItem); ok && anime.TotalEpisodes > 0 && item.Episodes == anime.TotalEpisodes {
836855 score += 20
837856 }
838857 return score
internal/provider_allanime.go deleted −28
@@ -1,28 +0,0 @@
1package internal
2
3type AllanimeProvider struct{}
4
5func (p *AllanimeProvider) Name() string {
6 return "allanime"
7}
8
9func (p *AllanimeProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
10 return searchAllAnime(query, mode)
11}
12
13func (p *AllanimeProvider) EpisodesList(showID, mode string) ([]string, error) {
14 return getAllAnimeEpisodesList(showID, mode)
15}
16
17func (p *AllanimeProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
18 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub)
19}
20
21func (p *AllanimeProvider) GetEpisodeURLForMode(config CurdConfig, id string, epNo int, mode string) ([]string, error) {
22 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, mode)
23 return links, err
24}
25
26func (p *AllanimeProvider) GetEpisodeURLForModeWithHints(config CurdConfig, id string, epNo int, mode string) ([]string, map[string]StreamPlaybackHint, error) {
27 return getAllanimeEpisodeStreamsForMode(id, mode, epNo)
28}
internal/provider_bridge.go added +181
@@ -0,0 +1,181 @@
1package internal
2
3import (
4 "net/http"
5
6 _ "github.com/wraient/curd/internal/loadproviders"
7
8 "github.com/wraient/curd/internal/curdhost"
9 "github.com/wraient/curd/internal/providers"
10)
11
12func init() {
13 curdhost.HTTPClient = func() *http.Client { return sharedHTTPClient }
14 curdhost.Log = func(msg string) { _ = Log(msg) }
15 curdhost.Out = func(msg string) { CurdOut(msg) }
16 curdhost.PromptSelect = func(options []curdhost.PromptOption) (curdhost.PromptOption, error) {
17 mapped := make([]SelectionOption, 0, len(options))
18 for _, option := range options {
19 mapped = append(mapped, SelectionOption{
20 Key: option.Key,
21 Label: option.Label,
22 })
23 }
24 selected, err := promptSelect(mapped)
25 if err != nil {
26 return curdhost.PromptOption{}, err
27 }
28 return curdhost.PromptOption{Key: selected.Key, Label: selected.Label}, nil
29 }
30 curdhost.PersistSubStylePreference = persistSubStylePreference
31 curdhost.CurrentSubStyle = func() string {
32 if cfg := GetGlobalConfig(); cfg != nil {
33 return cfg.SubStyle
34 }
35 return ""
36 }
37 curdhost.StoragePath = GetStoragePath
38 curdhost.AnimeNameLanguage = func() string {
39 if cfg := GetGlobalConfig(); cfg != nil {
40 return cfg.AnimeNameLanguage
41 }
42 return "english"
43 }
44 curdhost.SetCookiesForAnimepahe = SetCookiesForAnimepahe
45}
46
47func normalizeTranslationType(mode string) string {
48 return providers.NormalizeTranslationType(mode)
49}
50
51func alternateTranslationType(mode string) string {
52 return providers.AlternateTranslationType(mode)
53}
54
55func toInternalSelectionOptions(options []providers.SelectionOption) []SelectionOption {
56 if len(options) == 0 {
57 return nil
58 }
59 result := make([]SelectionOption, 0, len(options))
60 for _, option := range options {
61 result = append(result, SelectionOption{
62 Key: option.Key,
63 Label: option.Label,
64 Title: option.Title,
65 Thumbnail: option.Thumbnail,
66 ExtraData: option.ExtraData,
67 })
68 }
69 return result
70}
71
72func toProviderSelectionOptions(options []SelectionOption) []providers.SelectionOption {
73 if len(options) == 0 {
74 return nil
75 }
76 result := make([]providers.SelectionOption, 0, len(options))
77 for _, option := range options {
78 result = append(result, providers.SelectionOption{
79 Key: option.Key,
80 Label: option.Label,
81 Title: option.Title,
82 Thumbnail: option.Thumbnail,
83 ExtraData: option.ExtraData,
84 })
85 }
86 return result
87}
88
89func toPlaybackConfig(config CurdConfig) providers.PlaybackConfig {
90 return providers.PlaybackConfig{
91 SubOrDub: config.SubOrDub,
92 SubStyle: config.SubStyle,
93 }
94}
95
96func fromStreamHints(hints map[string]providers.StreamPlaybackHint) map[string]StreamPlaybackHint {
97 if len(hints) == 0 {
98 return nil
99 }
100 result := make(map[string]StreamPlaybackHint, len(hints))
101 for key, hint := range hints {
102 result[key] = StreamPlaybackHint{
103 Referrer: hint.Referrer,
104 Subtitle: hint.Subtitle,
105 }
106 }
107 return result
108}
109
110type providerAdapter struct {
111 inner providers.Provider
112}
113
114func (a *providerAdapter) Name() string {
115 return a.inner.Name()
116}
117
118func (a *providerAdapter) SearchAnime(query, mode string) ([]SelectionOption, error) {
119 options, err := a.inner.SearchAnime(query, mode)
120 return toInternalSelectionOptions(options), err
121}
122
123func (a *providerAdapter) EpisodesList(showID, mode string) ([]string, error) {
124 return a.inner.EpisodesList(showID, mode)
125}
126
127func (a *providerAdapter) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
128 return a.inner.GetEpisodeURL(toPlaybackConfig(config), id, epNo)
129}
130
131func (a *providerAdapter) GetEpisodeURLForMode(config CurdConfig, id string, epNo int, mode string) ([]string, error) {
132 if resolver, ok := a.inner.(providers.ModeResolver); ok {
133 return resolver.GetEpisodeURLForMode(toPlaybackConfig(config), id, epNo, mode)
134 }
135 return a.inner.GetEpisodeURL(toPlaybackConfig(config), id, epNo)
136}
137
138func (a *providerAdapter) GetEpisodeURLForModeWithHints(config CurdConfig, id string, epNo int, mode string) ([]string, map[string]StreamPlaybackHint, error) {
139 if resolver, ok := a.inner.(providers.HintResolver); ok {
140 links, hints, err := resolver.GetEpisodeURLForModeWithHints(toPlaybackConfig(config), id, epNo, mode)
141 return links, fromStreamHints(hints), err
142 }
143 links, err := a.GetEpisodeURLForMode(config, id, epNo, mode)
144 return links, nil, err
145}
146
147func resolveProviderID(provider Provider, providerID, query string) (string, error) {
148 inner := unwrapProvider(provider)
149 if inner == nil {
150 return providerID, nil
151 }
152 if resolver, ok := inner.(providers.IDResolver); ok {
153 return resolver.ResolveProviderID(providerID, query)
154 }
155 return providerID, nil
156}
157
158func wrapProvider(provider providers.Provider) Provider {
159 return &providerAdapter{inner: provider}
160}
161
162func unwrapProvider(provider Provider) providers.Provider {
163 if adapter, ok := provider.(*providerAdapter); ok {
164 return adapter.inner
165 }
166 return nil
167}
168
169func applyStreamPlaybackHints(anime *Anime, links []string, hints map[string]StreamPlaybackHint) {
170 if anime == nil || len(links) == 0 {
171 return
172 }
173 selected := PrioritizeLink(links)
174 if hint, ok := hints[selected]; ok {
175 anime.Ep.StreamReferrer = hint.Referrer
176 anime.Ep.SubtitleURL = hint.Subtitle
177 return
178 }
179 anime.Ep.StreamReferrer = ""
180 anime.Ep.SubtitleURL = ""
181}
internal/provider_disabled.go +82 −13
@@ -2,14 +2,11 @@ package internal
22
33import (
44 "sort"
5 "strings"
56 "testing"
6)
77
8// disabledProviders lists providers kept in source but excluded from runtime use.
9// Remove a provider from this map to re-enable it without restoring deleted code.
10var disabledProviders = map[string]string{
11 "animepahe": "Cloudflare/DDoS-Guard protection cannot be bypassed reliably",
12}
8 "github.com/wraient/curd/internal/providers"
9)
1310
1411var disabledProviderReasonForTest func(string) string
1512
@@ -21,7 +18,56 @@ func providerDisabledReason(name string) string {
2118 if disabledProviderReasonForTest != nil {
2219 return disabledProviderReasonForTest(name)
2320 }
24 return disabledProviders[name]
21 if reason := configDisabledProviderReason(name); reason != "" {
22 return reason
23 }
24 meta, ok := providers.MetaFor(name)
25 if !ok {
26 return ""
27 }
28 if meta.DefaultDisabled {
29 return meta.DisableReason
30 }
31 return ""
32}
33
34func configDisabledProviderReason(name string) string {
35 config := GetGlobalConfig()
36 if config == nil {
37 return ""
38 }
39 for _, disabledName := range parseDisabledProviderNames(config.DisabledProviders) {
40 if disabledName == name {
41 if meta, ok := providers.MetaFor(name); ok && meta.DisableReason != "" {
42 return meta.DisableReason
43 }
44 return "disabled in config"
45 }
46 }
47 return ""
48}
49
50func parseDisabledProviderNames(raw string) []string {
51 parts := parseStringArray(raw)
52 if len(parts) == 0 {
53 parts = strings.FieldsFunc(raw, func(r rune) bool {
54 return r == ',' || r == '+' || r == '|' || r == ';'
55 })
56 }
57 names := make([]string, 0, len(parts))
58 seen := make(map[string]struct{})
59 for _, part := range parts {
60 name := normalizeProviderName(part)
61 if name == "" {
62 continue
63 }
64 if _, exists := seen[name]; exists {
65 continue
66 }
67 seen[name] = struct{}{}
68 names = append(names, name)
69 }
70 return names
2571}
2672
2773// ProviderEnabled reports whether a provider may be used at runtime.
@@ -55,11 +101,7 @@ func filterEnabledProviders(names []string) []string {
55101}
56102
57103func defaultEnabledProviderStack() []string {
58 names := make([]string, 0, len(providerFactories))
59 for name := range providerFactories {
60 names = append(names, name)
61 }
62 sort.Strings(names)
104 names := providers.RegisteredNames()
63105 return filterEnabledProviders(names)
64106}
65107
@@ -87,12 +129,32 @@ func providerSelectionOptions() []SelectionOption {
87129 return options
88130}
89131
132func firstEnabledProviderName() string {
133 enabled := defaultEnabledProviderStack()
134 if len(enabled) > 0 {
135 return enabled[0]
136 }
137 return "anineko"
138}
139
90140func ensureEnabledProviderNames(names []string) []string {
91141 enabled := filterEnabledProviders(names)
92142 if len(enabled) > 0 {
93143 return enabled
94144 }
95 return []string{"allanime"}
145 fallback := filterEnabledProviders([]string{firstEnabledProviderName()})
146 if len(fallback) > 0 {
147 return fallback
148 }
149 if registered := providers.RegisteredNames(); len(registered) > 0 {
150 for _, name := range registered {
151 if ProviderEnabled(name) {
152 return []string{name}
153 }
154 }
155 return []string{registered[0]}
156 }
157 return []string{firstEnabledProviderName()}
96158}
97159
98160func withAllProvidersEnabledForTest(t *testing.T) {
@@ -103,3 +165,10 @@ func withAllProvidersEnabledForTest(t *testing.T) {
103165 disabledProviderReasonForTest = previous
104166 })
105167}
168
169// RegisteredProviderNames returns sorted registered provider names.
170func RegisteredProviderNames() []string {
171 names := providers.RegisteredNames()
172 sort.Strings(names)
173 return names
174}
internal/provider_disabled_test.go +27 −16
@@ -2,12 +2,18 @@ package internal
22
33import "testing"
44
5func TestProviderEnabledDisablesAnimepaheByDefault(t *testing.T) {
6 if ProviderEnabled("allanime") != true {
7 t.Fatal("expected allanime to stay enabled")
5func TestProviderEnabledDisablesAllanimeAndAnimepaheByDefault(t *testing.T) {
6 if ProviderEnabled("allanime") != false {
7 t.Fatal("expected allanime to be disabled by default")
88 }
99 if ProviderEnabled("animepahe") != false {
10 t.Fatal("expected animepahe to be disabled")
10 t.Fatal("expected animepahe to be disabled by default")
11 }
12 if ProviderEnabled("anineko") != true {
13 t.Fatal("expected anineko to stay enabled")
14 }
15 if reason := ProviderDisabledReason("allanime"); reason == "" {
16 t.Fatal("expected allanime disable reason")
1117 }
1218 if reason := ProviderDisabledReason("animepahe"); reason == "" {
1319 t.Fatal("expected animepahe disable reason")
@@ -20,10 +26,11 @@ func TestConfiguredProviderNamesFiltersDisabledProviders(t *testing.T) {
2026 cfg *CurdConfig
2127 want []string
2228 }{
23 {name: "empty", cfg: &CurdConfig{}, want: []string{"allanime"}},
24 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"allanime"}},
25 {name: "animepahe only", cfg: &CurdConfig{Provider: `["animepahe"]`}, want: []string{"allanime"}},
26 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"allanime"}},
29 {name: "empty", cfg: &CurdConfig{}, want: []string{"anineko"}},
30 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"anineko"}},
31 {name: "animepahe only", cfg: &CurdConfig{Provider: `["animepahe"]`}, want: []string{"anineko"}},
32 {name: "allanime only", cfg: &CurdConfig{Provider: `["allanime"]`}, want: []string{"anineko"}},
33 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"anineko"}},
2734 }
2835
2936 for _, tc := range cases {
@@ -50,19 +57,23 @@ func TestConfiguredProviderNamesHonorsEnabledProvidersWhenOverridden(t *testing.
5057}
5158
5259func TestProviderByNameRejectsDisabledProvider(t *testing.T) {
53 if _, err := ProviderByName("animepahe"); err == nil {
54 t.Fatal("expected disabled provider error")
60 for _, name := range []string{"animepahe", "allanime"} {
61 if _, err := ProviderByName(name); err == nil {
62 t.Fatalf("expected disabled provider error for %s", name)
63 }
5564 }
5665}
5766
5867func TestProviderByNameAllowsDisabledProviderWhenOverridden(t *testing.T) {
5968 withAllProvidersEnabledForTest(t)
6069
61 provider, err := ProviderByName("animepahe")
62 if err != nil {
63 t.Fatalf("expected animepahe provider: %v", err)
64 }
65 if provider.Name() != "animepahe" {
66 t.Fatalf("got provider %q", provider.Name())
70 for _, name := range []string{"animepahe", "allanime"} {
71 provider, err := ProviderByName(name)
72 if err != nil {
73 t.Fatalf("expected %s provider: %v", name, err)
74 }
75 if provider.Name() != name {
76 t.Fatalf("got provider %q", provider.Name())
77 }
6778 }
6879}
internal/provider_mapping.go added +837
@@ -0,0 +1,837 @@
1package internal
2
3import (
4 "fmt"
5 "io"
6 "net/http"
7 "os"
8 "path/filepath"
9 "regexp"
10 "strconv"
11 "strings"
12
13 "github.com/wraient/curd/internal/providers/animepahe"
14)
15
16type ProviderMappingOutcome int
17
18const (
19 ProviderMappingOK ProviderMappingOutcome = iota
20 ProviderMappingBack
21 ProviderMappingQuit
22)
23
24type providerMappingSearchState struct {
25 query string
26 allProviders []string
27 sequential bool
28 providerIndex int
29}
30
31func (s *providerMappingSearchState) activeProviders() []string {
32 if !s.sequential {
33 return s.allProviders
34 }
35 if s.providerIndex >= len(s.allProviders) {
36 return nil
37 }
38 return []string{s.allProviders[s.providerIndex]}
39}
40
41func (s *providerMappingSearchState) currentProviderLabel() string {
42 if !s.sequential {
43 return "all configured providers"
44 }
45 if s.providerIndex >= len(s.allProviders) {
46 return ""
47 }
48 return s.allProviders[s.providerIndex]
49}
50
51func (s *providerMappingSearchState) nextProviderLabel() string {
52 if !s.sequential {
53 if len(s.allProviders) > 0 {
54 return s.allProviders[0]
55 }
56 return ""
57 }
58 next := s.providerIndex + 1
59 if next < len(s.allProviders) {
60 return s.allProviders[next]
61 }
62 return ""
63}
64
65func (s *providerMappingSearchState) advanceToNextProvider() bool {
66 if !s.sequential {
67 s.sequential = true
68 s.providerIndex = 0
69 return len(s.allProviders) > 0
70 }
71 s.providerIndex++
72 return s.providerIndex < len(s.allProviders)
73}
74
75func (s *providerMappingSearchState) resetToAllProviders() {
76 s.sequential = false
77 s.providerIndex = 0
78}
79
80func searchAnimeForMapping(config *CurdConfig, state *providerMappingSearchState, mode string) ([]SelectionOption, error) {
81 providers := state.activeProviders()
82 if len(providers) == 0 {
83 return nil, nil
84 }
85 if !state.sequential && len(providers) == len(state.allProviders) {
86 return SearchAnime(state.query, mode)
87 }
88 return searchAnimeWithProviders(providers, state.query, mode)
89}
90
91func confirmProviderMatch(option SelectionOption, reason string) bool {
92 label := option.Label
93 if label == "" {
94 label = option.Title
95 }
96 if label == "" {
97 label = option.Key
98 }
99
100 CurdOut(fmt.Sprintf("Provider match found by %s: %s", reason, label))
101 selected, err := promptSelect([]SelectionOption{
102 {Key: "use", Label: "Use this match"},
103 {Key: "manual", Label: "Select manually"},
104 })
105 if err != nil {
106 Log(fmt.Sprintf("Error confirming provider match: %v", err))
107 return false
108 }
109 return selected.Key == "use"
110}
111
112func autoMatchProviderListing(config *CurdConfig, anime *Anime, animeList []SelectionOption, userQuery string, anilistEntry *Entry) bool {
113 anilistIDStr := strconv.Itoa(anime.AnilistId)
114 var jikanUrls []string
115 fetchedJikan := false
116
117 anilistRegex := regexp.MustCompile(`anilistcdn/media/anime/cover/(?:large|medium)/(?:bx)?(\d+)`)
118 malRegex := regexp.MustCompile(`myanimelist\.net/images/anime/[^/]+/([^/]+\.jpg)`)
119
120 for i, option := range animeList {
121 Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s', Thumbnail='%s'", i, option.Key, option.Label, option.Thumbnail))
122
123 if strings.Contains(option.Thumbnail, "anilist.co") {
124 matches := anilistRegex.FindStringSubmatch(option.Thumbnail)
125 if len(matches) > 1 && matches[1] == anilistIDStr {
126 anime.ProviderId = option.Key
127 Log(fmt.Sprintf("Found Anilist Thumbnail match! Setting ProviderId to: %s", anime.ProviderId))
128 return true
129 }
130 } else if strings.Contains(option.Thumbnail, "myanimelist.net") {
131 matches := malRegex.FindStringSubmatch(option.Thumbnail)
132 if len(matches) > 1 {
133 fileName := matches[1]
134
135 if !fetchedJikan {
136 if anime.MalId == 0 {
137 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
138 }
139 if anime.MalId != 0 {
140 urls, err := FetchJikanPictures(anime.MalId)
141 if err != nil {
142 Log(fmt.Sprintf("Failed to fetch Jikan pictures: %v", err))
143 } else {
144 jikanUrls = urls
145 }
146 }
147 fetchedJikan = true
148 }
149
150 for _, url := range jikanUrls {
151 if strings.HasSuffix(url, "/"+fileName) || strings.Contains(url, fileName) {
152 anime.ProviderId = option.Key
153 Log(fmt.Sprintf("Found MyAnimeList Thumbnail match (%s)! Setting ProviderId to: %s", fileName, anime.ProviderId))
154 return true
155 }
156 }
157 }
158 }
159 }
160
161 if bestMatch, ok := confidentProviderSearchMatch(animeList, anime, userQuery); ok {
162 anime.ProviderId = bestMatch.Key
163 Log(fmt.Sprintf("Found confident provider title match! Setting ProviderId to: %s (%s)", anime.ProviderId, bestMatch.Label))
164 return true
165 }
166
167 if ProviderEnabled("animepahe") && ProviderStackContains(config, "animepahe") {
168 Log("Attempting deep metadata matching and exact AniList meta tag check for Animepahe...")
169
170 targetAnilistID := strconv.Itoa(anime.AnilistId)
171 var bestMatch *SelectionOption
172 var highestScore int
173
174 if anime.MalId == 0 {
175 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
176 }
177
178 var malData *JikanAnimeData
179 if anime.MalId != 0 {
180 malData, _ = FetchJikanAnimeData(anime.MalId)
181 }
182
183 for i := range animeList {
184 opt := &animeList[i]
185 optionProviderName, rawProviderID, ok := ParseProviderQualifiedID(opt.Key)
186 if ok {
187 if optionProviderName != "animepahe" {
188 continue
189 }
190 } else {
191 rawProviderID = opt.Key
192 if configuredProviderNames(config)[0] != "animepahe" {
193 continue
194 }
195 }
196 score := 0
197
198 if malData != nil && opt.ExtraData != nil {
199 if paheData, ok := opt.ExtraData.(animepahe.SearchItem); ok {
200 paheTitleLower := strings.ToLower(paheData.Title)
201 malTitleLower := strings.ToLower(malData.Title)
202 malTitleEngLower := strings.ToLower(malData.TitleEnglish)
203 malTitleJapLower := strings.ToLower(malData.TitleJapanese)
204
205 if paheTitleLower == malTitleLower || (malTitleEngLower != "" && paheTitleLower == malTitleEngLower) || (malTitleJapLower != "" && paheTitleLower == malTitleJapLower) {
206 score += 5
207 } else if strings.Contains(paheTitleLower, malTitleLower) || strings.Contains(malTitleLower, paheTitleLower) ||
208 (malTitleEngLower != "" && (strings.Contains(paheTitleLower, malTitleEngLower) || strings.Contains(malTitleEngLower, paheTitleLower))) {
209 score += 2
210 }
211
212 if paheData.Year > 0 && malData.Year > 0 && paheData.Year == malData.Year {
213 score += 3
214 }
215 if paheData.Season != "" && malData.Season != "" && strings.EqualFold(paheData.Season, malData.Season) {
216 score += 2
217 }
218 if paheData.Type != "" && malData.Type != "" && strings.EqualFold(paheData.Type, malData.Type) {
219 score += 2
220 }
221 if paheData.Episodes > 0 && malData.Episodes > 0 && paheData.Episodes == malData.Episodes {
222 score += 2
223 } else if (paheData.Episodes == 0 && malData.Status == "Currently Airing") || (malData.Episodes == 0 && paheData.Status == "Currently Airing") {
224 score += 2
225 }
226 if strings.EqualFold(paheData.Status, malData.Status) {
227 score += 1
228 }
229 }
230 } else if strings.Contains(strings.ToLower(opt.Title), strings.ToLower(string(userQuery))) {
231 score += 2
232 }
233
234 if score >= 2 || len(animeList) <= 3 {
235 animeRef := animepahe.ParseProviderID(rawProviderID)
236 if animeRef.Session == "" {
237 continue
238 }
239 animeUrl := fmt.Sprintf("https://animepahe.pw/anime/%s", animeRef.Session)
240 Log(fmt.Sprintf("Fetching %s to check exact AniList meta tag...", animeUrl))
241 req, err := animepahe.NewPageRequest(animeUrl)
242 if err != nil {
243 Log(fmt.Sprintf("Failed to build animepahe detail request %s: %v", animeUrl, err))
244 continue
245 }
246
247 resp, err := sharedHTTPClient.Do(req)
248 if err != nil {
249 Log(fmt.Sprintf("Failed to fetch animepahe detail page %s: %v", animeUrl, err))
250 continue
251 }
252 body, readErr := io.ReadAll(resp.Body)
253 resp.Body.Close()
254 if readErr != nil {
255 Log(fmt.Sprintf("Failed to read animepahe detail page %s: %v", animeUrl, readErr))
256 continue
257 }
258 if resp.StatusCode == http.StatusOK {
259 bodyStr := string(body)
260
261 metaTag := fmt.Sprintf(`<meta name="anilist" content="%s">`, targetAnilistID)
262 if strings.Contains(bodyStr, metaTag) {
263 Log(fmt.Sprintf("FOUND EXACT ANILIST META TAG MATCH in %s!", opt.Title))
264 bestMatch = opt
265 highestScore = 100
266 break
267 }
268
269 malMetaTag := fmt.Sprintf(`<meta name="mal" content="%d">`, anime.MalId)
270 if anime.MalId != 0 && strings.Contains(bodyStr, malMetaTag) {
271 Log(fmt.Sprintf("FOUND EXACT MAL META TAG MATCH in %s!", opt.Title))
272 bestMatch = opt
273 highestScore = 100
274 break
275 }
276 }
277 }
278
279 if score > highestScore {
280 highestScore = score
281 bestMatch = opt
282 }
283 }
284
285 if bestMatch != nil && highestScore == 100 {
286 anime.ProviderId = bestMatch.Key
287 Log(fmt.Sprintf("Found EXACT meta tag match! Score: %d. Setting ProviderId to: %s", highestScore, anime.ProviderId))
288 return true
289 }
290 if bestMatch != nil {
291 Log(fmt.Sprintf("Highest match score was %d (needed 100 for Animepahe exact meta tag match). Not selecting automatically to prevent false positives.", highestScore))
292 if confirmProviderMatch(*bestMatch, "Animepahe metadata") {
293 anime.ProviderId = bestMatch.Key
294 Log(fmt.Sprintf("User confirmed Animepahe match. Setting ProviderId to: %s", anime.ProviderId))
295 return true
296 }
297 }
298 }
299
300 if anilistEntry != nil {
301 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, anilistEntry.Media.Episodes)
302 for _, option := range animeList {
303 if fmt.Sprintf("%s (%d episodes)", option.Title, anilistEntry.Media.Episodes) == targetLabel {
304 if confirmProviderMatch(option, "title and episode count") {
305 anime.ProviderId = option.Key
306 Log(fmt.Sprintf("User confirmed exact text match. Setting ProviderId to: %s", anime.ProviderId))
307 return true
308 }
309 break
310 }
311 }
312 Log(fmt.Sprintf("No exact match found for label '%s'. Will require manual selection.", targetLabel))
313 }
314
315 return anime.ProviderId != ""
316}
317
318func promptProviderSearchRecovery(config *CurdConfig, state *providerMappingSearchState, reason string) (action string, err error) {
319 options := []SelectionOption{
320 {Key: "custom", Label: "Search with a different name"},
321 }
322 if next := state.nextProviderLabel(); next != "" {
323 options = append(options, SelectionOption{
324 Key: "next_provider",
325 Label: fmt.Sprintf("Try next provider (%s)", next),
326 })
327 }
328 options = append(options, SelectionOption{Key: "back", Label: "Back to menu"})
329
330 message := reason
331 if message == "" {
332 message = fmt.Sprintf("No results found for '%s' on %s.", state.query, state.currentProviderLabel())
333 }
334 CurdOut(message)
335
336 selected, err := promptSelect(options)
337 if err != nil {
338 return "", err
339 }
340 if selected.Key == "-1" {
341 return "quit", nil
342 }
343 if selected.Key == "-2" {
344 return "back", nil
345 }
346 return selected.Key, nil
347}
348
349func promptProviderMatchRecovery(config *CurdConfig, state *providerMappingSearchState) (action string, err error) {
350 options := []SelectionOption{
351 {Key: "pick", Label: "Pick from search results"},
352 {Key: "custom", Label: "Search with a different name"},
353 }
354 if next := state.nextProviderLabel(); next != "" {
355 options = append(options, SelectionOption{
356 Key: "next_provider",
357 Label: fmt.Sprintf("Try next provider (%s)", next),
358 })
359 }
360 options = append(options, SelectionOption{Key: "back", Label: "Back to menu"})
361
362 CurdOut("We didn't find an automatic provider match.")
363 selected, err := promptSelect(options)
364 if err != nil {
365 return "", err
366 }
367 if selected.Key == "-1" {
368 return "quit", nil
369 }
370 if selected.Key == "-2" {
371 return "back", nil
372 }
373 return selected.Key, nil
374}
375
376func applySelectedProviderMapping(config *CurdConfig, anime *Anime, selected SelectionOption) {
377 anime.ProviderId = selected.Key
378 if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
379 anime.ProviderName = providerName
380 anime.ProviderId = rawProviderID
381 } else {
382 anime.ProviderName = configuredProviderNames(config)[0]
383 }
384}
385
386func promptCustomProviderSearchQuery(config *CurdConfig, currentQuery, hint string) (string, bool, bool, error) {
387 manualQuery, err := promptText(config, hint, true)
388 if err != nil {
389 return "", false, false, err
390 }
391 if manualQuery == "" {
392 manualQuery = currentQuery
393 }
394 return manualQuery, false, false, nil
395}
396
397func ResolveAnimeProviderMapping(config *CurdConfig, anime *Anime, query string, anilistEntry *Entry) (ProviderMappingOutcome, error) {
398 return resolveAnimeProviderMapping(config, anime, query, anilistEntry, ManualProviderSearchEnabled(config))
399}
400
401func resolveAnimeProviderMapping(config *CurdConfig, anime *Anime, query string, anilistEntry *Entry, manualOnly bool) (ProviderMappingOutcome, error) {
402 state := &providerMappingSearchState{
403 query: query,
404 allProviders: configuredProviderNames(config),
405 }
406
407 for {
408 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s, scope: %s", state.query, config.SubOrDub, state.currentProviderLabel()))
409
410 animeList, err := searchAnimeForMapping(config, state, config.SubOrDub)
411 if err != nil {
412 Log(fmt.Sprintf("Provider search failed: %v", err))
413 action, actionErr := promptProviderSearchRecovery(config, state, fmt.Sprintf("Provider search failed for '%s': %v", state.query, err))
414 if actionErr != nil {
415 return ProviderMappingQuit, actionErr
416 }
417 outcome, cont, actionErr := handleProviderMappingAction(config, state, action, query)
418 if actionErr != nil {
419 return ProviderMappingQuit, actionErr
420 }
421 if !cont {
422 return outcome, nil
423 }
424 continue
425 }
426
427 if len(animeList) == 0 {
428 action, actionErr := promptProviderSearchRecovery(config, state, "")
429 if actionErr != nil {
430 return ProviderMappingQuit, actionErr
431 }
432 outcome, cont, actionErr := handleProviderMappingAction(config, state, action, query)
433 if actionErr != nil {
434 return ProviderMappingQuit, actionErr
435 }
436 if !cont {
437 return outcome, nil
438 }
439 continue
440 }
441
442 anime.ProviderId = ""
443 if !manualOnly && autoMatchProviderListing(config, anime, animeList, state.query, anilistEntry) {
444 if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
445 anime.ProviderName = providerName
446 anime.ProviderId = rawProviderID
447 } else {
448 anime.ProviderName = configuredProviderNames(config)[0]
449 }
450 return ProviderMappingOK, nil
451 }
452
453 if manualOnly {
454 for {
455 hint := ManualProviderSearchHint(config, anilistEntry, state.query, config.SubOrDub)
456 selected, selectErr := promptProviderSearchSelectionWithHint(config, animeList, anilistEntry, hint)
457 if selectErr != nil {
458 Log(fmt.Sprintf("Failed to select anime: %v", selectErr))
459 } else {
460 switch selected.Key {
461 case "-1":
462 // fall through to recovery menu
463 case "-2":
464 return ProviderMappingBack, nil
465 default:
466 applySelectedProviderMapping(config, anime, selected)
467 return ProviderMappingOK, nil
468 }
469 }
470
471 action, actionErr := promptProviderMatchRecovery(config, state)
472 if actionErr != nil {
473 return ProviderMappingQuit, actionErr
474 }
475 switch action {
476 case "pick":
477 continue
478 case "custom", "next_provider":
479 outcome, cont, handleErr := handleProviderMappingAction(config, state, action, query)
480 if handleErr != nil {
481 return ProviderMappingQuit, handleErr
482 }
483 if !cont {
484 return outcome, nil
485 }
486 break
487 case "back":
488 return ProviderMappingBack, nil
489 case "quit":
490 return ProviderMappingQuit, nil
491 default:
492 continue
493 }
494 break
495 }
496 continue
497 }
498
499 for {
500 action, actionErr := promptProviderMatchRecovery(config, state)
501 if actionErr != nil {
502 return ProviderMappingQuit, actionErr
503 }
504
505 switch action {
506 case "pick":
507 CurdOut("Select the correct anime from the search results.")
508 selected, selectErr := promptProviderSearchSelection(config, animeList, anilistEntry)
509 if selectErr != nil {
510 Log(fmt.Sprintf("Failed to select anime: %v", selectErr))
511 continue
512 }
513 switch selected.Key {
514 case "-1":
515 continue
516 case "-2":
517 return ProviderMappingBack, nil
518 default:
519 applySelectedProviderMapping(config, anime, selected)
520 return ProviderMappingOK, nil
521 }
522 case "custom", "next_provider":
523 outcome, cont, handleErr := handleProviderMappingAction(config, state, action, query)
524 if handleErr != nil {
525 return ProviderMappingQuit, handleErr
526 }
527 if !cont {
528 return outcome, nil
529 }
530 break
531 case "back":
532 return ProviderMappingBack, nil
533 case "quit":
534 return ProviderMappingQuit, nil
535 default:
536 continue
537 }
538 break
539 }
540 }
541}
542
543func RemapProviderAnime(userCurdConfig *CurdConfig, user *User, databaseAnimes *[]Anime) {
544 if userCurdConfig == nil || user == nil {
545 return
546 }
547
548 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
549 Log(fmt.Sprintf("Failed to refresh anime list before provider remap: %v", err))
550 }
551
552 if user.ListSync != nil {
553 user.AnimeList = user.ListSync.Current()
554 }
555
556 options := buildCategorySelectionOptions(user.AnimeList, "ALL")
557 if len(options) == 0 {
558 CurdOut("No anime found in your lists.")
559 return
560 }
561
562 var selected SelectionOption
563 var err error
564 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
565 preview := buildCategoryPreviewOptions(user.AnimeList, "ALL")
566 selected, err = DynamicSelectPreview(preview, false)
567 } else {
568 selected, err = DynamicSelect(options)
569 }
570 if err != nil {
571 Log(fmt.Sprintf("Failed to select anime for provider remap: %v", err))
572 return
573 }
574 if selected.Key == "-1" || selected.Key == "-2" {
575 return
576 }
577
578 anilistEntry, err := FindAnimeByAnilistID(user.AnimeList, selected.Key)
579 if err != nil {
580 Log(fmt.Sprintf("Failed to resolve selected anime: %v", err))
581 CurdOut("Could not find the selected anime in your lists.")
582 return
583 }
584
585 historyPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_history.txt")
586 if databaseAnimes != nil {
587 if existing := LocalFindAnime(*databaseAnimes, anilistEntry.Media.ID, ""); existing != nil {
588 CurdOut(fmt.Sprintf("Current provider mapping: %s (%s)", CurrentAnimeProviderName(existing), existing.ProviderId))
589 } else {
590 CurdOut("No saved provider mapping in local history yet.")
591 }
592 }
593
594 query := mediaDisplayTitle(anilistEntry.Media, userCurdConfig)
595 anime := Anime{
596 AnilistId: anilistEntry.Media.ID,
597 MalId: anilistEntry.Media.MalID,
598 Title: anilistEntry.Media.Title,
599 TotalEpisodes: anilistEntry.Media.Episodes,
600 CoverImage: anilistEntry.CoverImage,
601 }
602
603 outcome, mappingErr := resolveAnimeProviderMapping(userCurdConfig, &anime, query, anilistEntry, true)
604 if mappingErr != nil {
605 Log(fmt.Sprintf("Provider remap failed: %v", mappingErr))
606 CurdOut("Failed to update provider mapping.")
607 return
608 }
609 switch outcome {
610 case ProviderMappingBack, ProviderMappingQuit:
611 return
612 case ProviderMappingOK:
613 if err := persistRemappedProvider(historyPath, databaseAnimes, anilistEntry, &anime, query); err != nil {
614 Log(fmt.Sprintf("Failed to save remapped provider: %v", err))
615 CurdOut("Provider selected, but failed to save mapping to local history.")
616 return
617 }
618 CurdOut(fmt.Sprintf("Updated provider mapping to %s (%s).", anime.ProviderName, anime.ProviderId))
619 }
620}
621
622func persistRemappedProvider(historyPath string, databaseAnimes *[]Anime, anilistEntry *Entry, anime *Anime, animeName string) error {
623 if anime == nil || anilistEntry == nil {
624 return fmt.Errorf("missing anime data")
625 }
626
627 episode := 1
628 playbackTime := 0
629 duration := 0
630 if databaseAnimes != nil {
631 if existing := LocalFindAnime(*databaseAnimes, anime.AnilistId, ""); existing != nil {
632 episode = existing.Ep.Number
633 playbackTime = existing.Ep.Player.PlaybackTime
634 duration = existing.Ep.Duration
635 if savedName := GetAnimeName(*existing); savedName != "" {
636 animeName = savedName
637 }
638 }
639 }
640 if episode <= 0 {
641 episode = nextEpisodeFromProgress(anilistEntry.Progress)
642 if episode <= 0 {
643 episode = 1
644 }
645 }
646
647 if err := LocalRemapAnimeProvider(historyPath, anime.AnilistId, anime.ProviderName, anime.ProviderId, animeName, episode, playbackTime, duration); err != nil {
648 return err
649 }
650 if databaseAnimes != nil {
651 *databaseAnimes = LocalGetAllAnime(historyPath)
652 }
653 return nil
654}
655
656func handleProviderMappingAction(config *CurdConfig, state *providerMappingSearchState, action, defaultQuery string) (ProviderMappingOutcome, bool, error) {
657 switch action {
658 case "custom":
659 hint := fmt.Sprintf("Enter a search name for configured providers (current: '%s').", state.query)
660 newQuery, _, _, err := promptCustomProviderSearchQuery(config, state.query, hint)
661 if err != nil {
662 return ProviderMappingQuit, false, err
663 }
664 state.query = newQuery
665 state.resetToAllProviders()
666 return ProviderMappingOK, true, nil
667 case "next_provider":
668 if !state.advanceToNextProvider() {
669 CurdOut("No more providers left to try.")
670 action, err := promptProviderSearchRecovery(config, state, "No more providers left to try.")
671 if err != nil {
672 return ProviderMappingQuit, false, err
673 }
674 return handleProviderMappingAction(config, state, action, defaultQuery)
675 }
676 return ProviderMappingOK, true, nil
677 case "back":
678 return ProviderMappingBack, false, nil
679 case "quit":
680 return ProviderMappingQuit, false, nil
681 default:
682 return ProviderMappingOK, true, nil
683 }
684}
685
686func untrackedProviderSearchSelection(config *CurdConfig, query string, animeList []SelectionOption) (SelectionOption, error) {
687 if ManualProviderSearchEnabled(config) {
688 hint := ManualProviderSearchHint(config, nil, query, config.SubOrDub)
689 return promptProviderSearchSelectionWithHint(config, animeList, nil, hint)
690 }
691 return promptProviderSearchSelection(config, animeList, nil)
692}
693
694func RemapAnimeProviderOnEpisodeFailure(config *CurdConfig, anime *Anime, anilistEntry *Entry) bool {
695 query := GetAnimeName(*anime)
696 if query == "" {
697 query = anime.Title.Romaji
698 }
699 if query == "" {
700 query = anime.Title.English
701 }
702 if query == "" {
703 return false
704 }
705
706 CurdOut("Could not get an episode link with the current provider mapping.")
707 anime.ProviderId = ""
708 anime.ProviderName = ""
709 anime.Ep.NextEpisode = NextEpisode{}
710
711 outcome, err := ResolveAnimeProviderMapping(config, anime, query, anilistEntry)
712 if err != nil {
713 Log(fmt.Sprintf("Provider remap failed: %v", err))
714 return false
715 }
716 return outcome == ProviderMappingOK
717}
718
719func promptEpisodeLinkFailureRecovery(config *CurdConfig) string {
720 selected, err := promptSelect([]SelectionOption{
721 {Key: "remap", Label: "Search providers again"},
722 {Key: "episode", Label: "Try a different episode number"},
723 {Key: "quit", Label: "Cancel playback"},
724 })
725 if err != nil {
726 return "quit"
727 }
728 if selected.Key == "-1" || selected.Key == "-2" {
729 return "quit"
730 }
731 return selected.Key
732}
733
734func ResolveUntrackedProviderSearch(config *CurdConfig, initialQuery string) (providerID, providerName string, back bool, err error) {
735 state := &providerMappingSearchState{
736 query: initialQuery,
737 allProviders: configuredProviderNames(config),
738 }
739
740 for {
741 animeList, searchErr := searchAnimeForMapping(config, state, config.SubOrDub)
742 if searchErr != nil {
743 Log(fmt.Sprintf("Provider search failed: %v", searchErr))
744 action, actionErr := promptProviderSearchRecovery(config, state, fmt.Sprintf("Provider search failed for '%s': %v", state.query, searchErr))
745 if actionErr != nil {
746 return "", "", false, actionErr
747 }
748 if action == "back" {
749 return "", "", true, nil
750 }
751 if action == "quit" {
752 return "", "", false, nil
753 }
754 _, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
755 if handleErr != nil {
756 return "", "", false, handleErr
757 }
758 if !cont {
759 return "", "", false, nil
760 }
761 continue
762 }
763
764 if len(animeList) == 0 {
765 action, actionErr := promptProviderSearchRecovery(config, state, "")
766 if actionErr != nil {
767 return "", "", false, actionErr
768 }
769 if action == "back" {
770 return "", "", true, nil
771 }
772 if action == "quit" {
773 return "", "", false, nil
774 }
775 _, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
776 if handleErr != nil {
777 return "", "", false, handleErr
778 }
779 if !cont {
780 return "", "", false, nil
781 }
782 continue
783 }
784
785 selected, selectErr := untrackedProviderSearchSelection(config, state.query, animeList)
786 if selectErr != nil {
787 Log(fmt.Sprintf("Failed to select anime: %v", selectErr))
788 action, actionErr := promptProviderMatchRecovery(config, state)
789 if actionErr != nil {
790 return "", "", false, actionErr
791 }
792 if action == "back" {
793 return "", "", true, nil
794 }
795 if action == "quit" {
796 return "", "", false, nil
797 }
798 _, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
799 if handleErr != nil {
800 return "", "", false, handleErr
801 }
802 if !cont {
803 return "", "", false, nil
804 }
805 continue
806 }
807
808 switch selected.Key {
809 case "-1":
810 action, actionErr := promptProviderMatchRecovery(config, state)
811 if actionErr != nil {
812 return "", "", false, actionErr
813 }
814 if action == "back" {
815 return "", "", true, nil
816 }
817 if action == "quit" {
818 return "", "", false, nil
819 }
820 _, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
821 if handleErr != nil {
822 return "", "", false, handleErr
823 }
824 if !cont {
825 return "", "", false, nil
826 }
827 continue
828 case "-2":
829 return "", "", true, nil
830 default:
831 if name, rawID, ok := ParseProviderQualifiedID(selected.Key); ok {
832 return rawID, name, false, nil
833 }
834 return selected.Key, configuredProviderNames(config)[0], false, nil
835 }
836 }
837}
internal/provider_stack_test.go +35 −10
@@ -6,6 +6,8 @@ import (
66 "path/filepath"
77 "strings"
88 "testing"
9
10 "github.com/wraient/curd/internal/providers"
911)
1012
1113type stackStubProvider struct {
@@ -47,21 +49,44 @@ func (s *stackStubProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
4749 return nil, nil
4850}
4951
50func withProviderFactories(t *testing.T, providers ...*stackStubProvider) {
52func withProviderFactories(t *testing.T, stubs ...*stackStubProvider) {
5153 t.Helper()
5254 withAllProvidersEnabledForTest(t)
53 previousAllanime := providerFactories["allanime"]
54 previousAnimepahe := providerFactories["animepahe"]
55 for _, provider := range providers {
56 provider := provider
57 providerFactories[provider.name] = func() Provider { return provider }
55 restores := make([]func(), 0, len(stubs))
56 for _, stub := range stubs {
57 stub := stub
58 restores = append(restores, providers.SetFactoryForTest(stub.name, func() providers.Provider {
59 return &stackStubProviderBridge{stub}
60 }))
5861 }
5962 t.Cleanup(func() {
60 providerFactories["allanime"] = previousAllanime
61 providerFactories["animepahe"] = previousAnimepahe
63 for i := len(restores) - 1; i >= 0; i-- {
64 restores[i]()
65 }
6266 })
6367}
6468
69type stackStubProviderBridge struct {
70 *stackStubProvider
71}
72
73func (s *stackStubProviderBridge) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
74 options, err := s.stackStubProvider.SearchAnime(query, mode)
75 return toProviderSelectionOptions(options), err
76}
77
78func (s *stackStubProviderBridge) EpisodesList(showID, mode string) ([]string, error) {
79 return s.stackStubProvider.EpisodesList(showID, mode)
80}
81
82func (s *stackStubProviderBridge) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
83 return s.stackStubProvider.GetEpisodeURL(CurdConfig{SubOrDub: config.SubOrDub}, id, epNo)
84}
85
86func (s *stackStubProviderBridge) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
87 return s.stackStubProvider.GetEpisodeURLForMode(CurdConfig{SubOrDub: config.SubOrDub}, id, epNo, mode)
88}
89
6590func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) {
6691 withAllProvidersEnabledForTest(t)
6792
@@ -74,7 +99,7 @@ func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) {
7499 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"allanime", "animepahe"}},
75100 {name: "comma list", cfg: &CurdConfig{Provider: "animepahe,allanime"}, want: []string{"animepahe", "allanime"}},
76101 {name: "plus list", cfg: &CurdConfig{Provider: "allanime+animepahe"}, want: []string{"allanime", "animepahe"}},
77 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"allanime", "animepahe"}},
102 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"allanime", "animepahe", "anineko"}},
78103 }
79104
80105 for _, tc := range cases {
@@ -100,7 +125,7 @@ func TestCanonicalProviderConfigValueMigratesLegacyValuesWithoutAddingAnimepahe(
100125 {name: "legacy animepahe", raw: "animepahe", want: `["animepahe"]`},
101126 {name: "ordered stack", raw: "animepahe,allanime", want: `["animepahe","allanime"]`},
102127 {name: "animepahe opt out", raw: "allanime,no-animepahe", want: `["allanime","no-animepahe"]`},
103 {name: "empty default", raw: "", want: `["allanime"]`},
128 {name: "empty default", raw: "", want: `["anineko"]`},
104129 }
105130
106131 for _, tc := range cases {
internal/episode_list.go → internal/providers/allanime/episodes.go renamed +11 −8
@@ -1,4 +1,4 @@
1package internal
1package allanime
22
33import (
44 "bytes"
@@ -8,6 +8,9 @@ import (
88 "net/http"
99 "sort"
1010 "strconv"
11
12 "github.com/wraient/curd/internal/curdhost"
13 "github.com/wraient/curd/internal/providers"
1114)
1215
1316type episodesResponse struct {
@@ -33,7 +36,7 @@ type episodesResponse struct {
3336
3437// episodesList performs the API call and fetches the episodes list
3538func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
36 preferredMode := normalizeTranslationType(mode)
39 preferredMode := providers.NormalizeTranslationType(mode)
3740
3841 episodesListGql := `query ($showId: String!) { show( _id: $showId ) { _id availableEpisodesDetail }}`
3942
@@ -56,27 +59,27 @@ func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
5659 req.Header.Set("Referer", "https://allanime.to")
5760 req.Header.Set("Origin", "https://allanime.to")
5861
59 resp, err := sharedHTTPClient.Do(req)
62 resp, err := curdhost.HTTPClient().Do(req)
6063 if err != nil {
61 Log(fmt.Sprint("Error making HTTP request:", err))
64 curdhost.Log(fmt.Sprint("Error making HTTP request:", err))
6265 return nil, err
6366 }
6467 defer resp.Body.Close()
6568
6669 body, err := io.ReadAll(resp.Body)
6770 if err != nil {
68 Log(fmt.Sprint("Error reading response body:", err))
71 curdhost.Log(fmt.Sprint("Error reading response body:", err))
6972 return nil, err
7073 }
71 if !httpStatusOK(resp.StatusCode) {
72 return nil, httpStatusError("allanime episode list", resp.StatusCode, body)
74 if !curdhost.HTTPStatusOK(resp.StatusCode) {
75 return nil, curdhost.HTTPStatusError("allanime episode list", resp.StatusCode, body)
7376 }
7477
7578 // Parse the JSON response
7679 var response episodesResponse
7780 err = json.Unmarshal(body, &response)
7881 if err != nil {
79 Log(fmt.Sprint("Error parsing JSON:", err))
82 curdhost.Log(fmt.Sprint("Error parsing JSON:", err))
8083 return nil, err
8184 }
8285
internal/providers/allanime/provider.go added +33
@@ -0,0 +1,33 @@
1package allanime
2
3import (
4 "github.com/wraient/curd/internal/providers"
5)
6
7// Provider implements AllAnime catalog search and stream resolution.
8type Provider struct{}
9
10func (p *Provider) Name() string {
11 return "allanime"
12}
13
14func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
15 return searchAllAnime(query, mode)
16}
17
18func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
19 return getAllAnimeEpisodesList(showID, mode)
20}
21
22func (p *Provider) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
23 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub)
24}
25
26func (p *Provider) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
27 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, mode)
28 return links, err
29}
30
31func (p *Provider) GetEpisodeURLForModeWithHints(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, map[string]providers.StreamPlaybackHint, error) {
32 return getAllanimeEpisodeStreamsForMode(id, mode, epNo)
33}
internal/providers/allanime/register.go added +15
@@ -0,0 +1,15 @@
1package allanime
2
3import "github.com/wraient/curd/internal/providers"
4
5func init() {
6 providers.Register(providers.Meta{
7 Name: "allanime",
8 Aliases: []string{"all-anime", "all anime"},
9 Referrer: "https://allanime.day/",
10 DefaultDisabled: true,
11 DisableReason: "disabled by default; set Provider to include allanime to enable",
12 }, func() providers.Provider {
13 return &Provider{}
14 })
15}
internal/anime_list.go → internal/providers/allanime/search.go renamed +23 −38
@@ -1,4 +1,4 @@
1package internal
1package allanime
22
33import (
44 "bytes"
@@ -6,8 +6,9 @@ import (
66 "fmt"
77 "io"
88 "net/http"
9 "path/filepath"
10 "strings"
9
10 "github.com/wraient/curd/internal/curdhost"
11 "github.com/wraient/curd/internal/providers"
1112)
1213
1314type anime struct {
@@ -26,20 +27,6 @@ type response struct {
2627 } `json:"data"`
2728}
2829
29func normalizeTranslationType(mode string) string {
30 if strings.EqualFold(strings.TrimSpace(mode), "dub") {
31 return "dub"
32 }
33 return "sub"
34}
35
36func alternateTranslationType(mode string) string {
37 if normalizeTranslationType(mode) == "dub" {
38 return "sub"
39 }
40 return "dub"
41}
42
4330// func main() {
4431// // Get environment variables
4532// mode := "sub"
@@ -55,14 +42,12 @@ func alternateTranslationType(mode string) string {
5542// fmt.Println(animeList)
5643// }
5744
58func searchAllAnime(query, mode string) ([]SelectionOption, error) {
59 preferredMode := normalizeTranslationType(mode)
45func searchAllAnime(query, mode string) ([]providers.SelectionOption, error) {
46 preferredMode := providers.NormalizeTranslationType(mode)
6047 return searchAnimeByMode(query, preferredMode, preferredMode)
6148}
6249
63func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, error) {
64 userCurdConfig := GetGlobalConfig()
65 logFile = filepath.Join(GetStoragePath(), "debug.log")
50func searchAnimeByMode(query, mode, preferredMode string) ([]providers.SelectionOption, error) {
6651 const (
6752 agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
6853 allanimeRef = "https://allanime.to"
@@ -70,10 +55,10 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
7055 allanimeAPI = "https://api." + allanimeBase + "/api"
7156 )
7257
73 mode = normalizeTranslationType(mode)
74 preferredMode = normalizeTranslationType(preferredMode)
58 mode = providers.NormalizeTranslationType(mode)
59 preferredMode = providers.NormalizeTranslationType(preferredMode)
7560
76 animeList := make([]SelectionOption, 0)
61 animeList := make([]providers.SelectionOption, 0)
7762
7863 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) {
7964 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) {
@@ -107,14 +92,14 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
10792 "variables": variables,
10893 })
10994 if err != nil {
110 Log(fmt.Sprintf("Error encoding request body to JSON: %v", err))
95 curdhost.Log(fmt.Sprintf("Error encoding request body to JSON: %v", err))
11196 return animeList, err
11297 }
11398
11499 // Make the HTTP POST request
115100 req, err := http.NewRequest("POST", allanimeAPI, bytes.NewBuffer(requestBody))
116101 if err != nil {
117 Log(fmt.Sprintf("Error creating HTTP request: %v", err))
102 curdhost.Log(fmt.Sprintf("Error creating HTTP request: %v", err))
118103 return animeList, err
119104 }
120105 req.Header.Set("Content-Type", "application/json")
@@ -122,9 +107,9 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
122107 req.Header.Set("Referer", allanimeRef)
123108 req.Header.Set("Origin", allanimeRef)
124109
125 resp, err := sharedHTTPClient.Do(req)
110 resp, err := curdhost.HTTPClient().Do(req)
126111 if err != nil {
127 Log(fmt.Sprintf("Error making HTTP request: %v", err))
112 curdhost.Log(fmt.Sprintf("Error making HTTP request: %v", err))
128113 return animeList, err
129114 }
130115 defer resp.Body.Close()
@@ -132,16 +117,16 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
132117 // Read the response body
133118 body, err := io.ReadAll(resp.Body)
134119 if err != nil {
135 Log(fmt.Sprintf("Error reading response body: %v", err))
120 curdhost.Log(fmt.Sprintf("Error reading response body: %v", err))
136121 return animeList, err
137122 }
138123
139124 // Debug: Log the response status and first part of the body
140 Log(fmt.Sprintf("Response Status: %s", resp.Status))
141 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
142 if !httpStatusOK(resp.StatusCode) {
143 err := httpStatusError("allanime search", resp.StatusCode, body)
144 Log(err)
125 curdhost.Log(fmt.Sprintf("Response Status: %s", resp.Status))
126 curdhost.Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
127 if !curdhost.HTTPStatusOK(resp.StatusCode) {
128 err := curdhost.HTTPStatusError("allanime search", resp.StatusCode, body)
129 curdhost.Log(err.Error())
145130 return animeList, err
146131 }
147132
@@ -149,7 +134,7 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
149134 var response response
150135 err = json.Unmarshal(body, &response)
151136 if err != nil {
152 Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)))
137 curdhost.Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)))
153138 return animeList, err
154139 }
155140
@@ -167,7 +152,7 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
167152
168153 // Use English name if available and configured, otherwise use default name
169154 displayName := anime.Name
170 if anime.EnglishName != "" && userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" {
155 if anime.EnglishName != "" && curdhost.AnimeNameLanguage != nil && curdhost.AnimeNameLanguage() == "english" {
171156 displayName = anime.EnglishName
172157 }
173158
@@ -176,7 +161,7 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
176161 label = fmt.Sprintf("%s [%s]", label, mode)
177162 }
178163
179 animeList = append(animeList, SelectionOption{
164 animeList = append(animeList, providers.SelectionOption{
180165 Title: displayName,
181166 Key: anime.ID,
182167 Label: label,
internal/episode_url_anicli.go → internal/providers/allanime/streams.go renamed +18 −35
@@ -1,4 +1,4 @@
1package internal
1package allanime
22
33import (
44 "encoding/json"
@@ -12,16 +12,13 @@ import (
1212 "strings"
1313 "sync"
1414 "time"
15
16 "github.com/wraient/curd/internal/curdhost"
17 "github.com/wraient/curd/internal/providers"
1518)
1619
1720const allanimeUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
1821
19// StreamPlaybackHint carries MPV playback metadata extracted from AllAnime clock.json.
20type StreamPlaybackHint struct {
21 Referrer string
22 Subtitle string
23}
24
2522type allanimeResolvedStream struct {
2623 URL string
2724 Referrer string
@@ -36,7 +33,7 @@ var (
3633 allanimeStreamBandwidthPattern = regexp.MustCompile(`BANDWIDTH=(\d+)`)
3734)
3835
39func getAllanimeEpisodeStreamsForMode(id, mode string, epNo int) ([]string, map[string]StreamPlaybackHint, error) {
36func getAllanimeEpisodeStreamsForMode(id, mode string, epNo int) ([]string, map[string]providers.StreamPlaybackHint, error) {
4037 sourceUrls, err := fetchEpisodeSourcesForMode(id, mode, epNo)
4138 if err != nil {
4239 return nil, nil, err
@@ -44,7 +41,7 @@ func getAllanimeEpisodeStreamsForMode(id, mode string, epNo int) ([]string, map[
4441 return getLinksFromEncodedSourceUrls(sourceUrls)
4542}
4643
47func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[string]StreamPlaybackHint, error) {
44func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[string]providers.StreamPlaybackHint, error) {
4845 type providerJob struct {
4946 index int
5047 name string
@@ -84,7 +81,7 @@ func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[s
8481 go func(idx int, providerName, encodedURL string) {
8582 defer wg.Done()
8683 decodedProviderID := decodeProviderID(encodedURL[2:])
87 Log(fmt.Sprintf("Fetching Allanime provider %s via %s", providerName, decodedProviderID))
84 curdhost.Log(fmt.Sprintf("Fetching Allanime provider %s via %s", providerName, decodedProviderID))
8885 streams, err := resolveAllanimeClockProvider(providerName, decodedProviderID)
8986 results <- streamResult{index: idx, streams: streams, err: err}
9087 }(job.index, job.name, job.url)
@@ -108,14 +105,14 @@ func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[s
108105 }
109106 completedCount++
110107 if res.err != nil {
111 Log(fmt.Sprintf("Allanime provider %s failed: %v", jobs[res.index].name, res.err))
108 curdhost.Log(fmt.Sprintf("Allanime provider %s failed: %v", jobs[res.index].name, res.err))
112109 collectedErrors = append(collectedErrors, fmt.Errorf("%s: %w", jobs[res.index].name, res.err))
113110 continue
114111 }
115112 if len(res.streams) > 0 {
116113 orderedStreams[res.index] = res.streams
117114 successCount++
118 Log(fmt.Sprintf("Allanime provider %s returned %d stream(s)", jobs[res.index].name, len(res.streams)))
115 curdhost.Log(fmt.Sprintf("Allanime provider %s returned %d stream(s)", jobs[res.index].name, len(res.streams)))
119116 }
120117 case <-timeout:
121118 if successCount > 0 {
@@ -131,7 +128,7 @@ func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[s
131128 return buildAllanimeLinkResult(orderedStreams)
132129}
133130
134func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]string, map[string]StreamPlaybackHint, error) {
131func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]string, map[string]providers.StreamPlaybackHint, error) {
135132 allStreams := make([]allanimeResolvedStream, 0)
136133 for _, streams := range orderedStreams {
137134 allStreams = append(allStreams, streams...)
@@ -141,7 +138,7 @@ func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]strin
141138 })
142139
143140 links := make([]string, 0, len(allStreams))
144 hints := make(map[string]StreamPlaybackHint)
141 hints := make(map[string]providers.StreamPlaybackHint)
145142 seen := make(map[string]struct{})
146143 for _, stream := range allStreams {
147144 if stream.URL == "" || isUnreliableAllanimeDirectURL(stream.URL) {
@@ -156,7 +153,7 @@ func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]strin
156153 if referrer == "" {
157154 referrer = allanimeGraphQLReferer
158155 }
159 hints[stream.URL] = StreamPlaybackHint{
156 hints[stream.URL] = providers.StreamPlaybackHint{
160157 Referrer: referrer,
161158 Subtitle: stream.SubtitleURL,
162159 }
@@ -242,7 +239,7 @@ func fetchAllanimeClockResponse(providerPath string) ([]byte, map[string]interfa
242239 req.Header.Set("Referer", allanimeGraphQLReferer)
243240 req.Header.Set("User-Agent", allanimeUserAgent)
244241
245 resp, err := sharedHTTPClient.Do(req)
242 resp, err := curdhost.HTTPClient().Do(req)
246243 if err != nil {
247244 return nil, nil, err
248245 }
@@ -252,8 +249,8 @@ func fetchAllanimeClockResponse(providerPath string) ([]byte, map[string]interfa
252249 if err != nil {
253250 return nil, nil, err
254251 }
255 if !httpStatusOK(resp.StatusCode) {
256 return nil, nil, httpStatusError("allanime source extractor", resp.StatusCode, body)
252 if !curdhost.HTTPStatusOK(resp.StatusCode) {
253 return nil, nil, curdhost.HTTPStatusError("allanime source extractor", resp.StatusCode, body)
257254 }
258255
259256 var videoData map[string]interface{}
@@ -303,7 +300,7 @@ func fetchAllanimeM3U8VariantStreams(masterURL, referrer, subtitleURL string) ([
303300 req.Header.Set("Referer", referrer)
304301 req.Header.Set("User-Agent", allanimeUserAgent)
305302
306 resp, err := sharedHTTPClient.Do(req)
303 resp, err := curdhost.HTTPClient().Do(req)
307304 if err != nil {
308305 return nil, err
309306 }
@@ -312,8 +309,8 @@ func fetchAllanimeM3U8VariantStreams(masterURL, referrer, subtitleURL string) ([
312309 if err != nil {
313310 return nil, err
314311 }
315 if !httpStatusOK(resp.StatusCode) {
316 return nil, httpStatusError("allanime m3u8 master playlist", resp.StatusCode, body)
312 if !curdhost.HTTPStatusOK(resp.StatusCode) {
313 return nil, curdhost.HTTPStatusError("allanime m3u8 master playlist", resp.StatusCode, body)
317314 }
318315
319316 playlist := string(body)
@@ -449,17 +446,3 @@ func streamsFromPlainURLs(urls []string, referrer, subtitleURL string, qualitySc
449446 }
450447 return streams
451448}
452
453func applyStreamPlaybackHints(anime *Anime, links []string, hints map[string]StreamPlaybackHint) {
454 if anime == nil || len(links) == 0 {
455 return
456 }
457 selected := PrioritizeLink(links)
458 if hint, ok := hints[selected]; ok {
459 anime.Ep.StreamReferrer = hint.Referrer
460 anime.Ep.SubtitleURL = hint.Subtitle
461 return
462 }
463 anime.Ep.StreamReferrer = ""
464 anime.Ep.SubtitleURL = ""
465}
internal/episode_url.go → internal/providers/allanime/streams_legacy.go renamed +31 −28
@@ -1,4 +1,4 @@
1package internal
1package allanime
22
33import (
44 "bytes"
@@ -17,6 +17,9 @@ import (
1717 "sort"
1818 "strconv"
1919 "strings"
20
21 "github.com/wraient/curd/internal/curdhost"
22 "github.com/wraient/curd/internal/providers"
2023)
2124
2225type allanimeSource struct {
@@ -231,13 +234,13 @@ func decodeBase64URLRaw(input string) ([]byte, error) {
231234func extractFilemoonLinks(videoData map[string]interface{}) []string {
232235 raw, err := json.Marshal(videoData)
233236 if err != nil {
234 Log(fmt.Sprintf("Error marshaling filemoon payload: %v", err))
237 curdhost.Log(fmt.Sprintf("Error marshaling filemoon payload: %v", err))
235238 return nil
236239 }
237240
238241 var payload filemoonResponse
239242 if err := json.Unmarshal(raw, &payload); err != nil {
240 Log(fmt.Sprintf("Error parsing filemoon payload: %v", err))
243 curdhost.Log(fmt.Sprintf("Error parsing filemoon payload: %v", err))
241244 return nil
242245 }
243246
@@ -247,30 +250,30 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
247250
248251 keyPart1, err := decodeBase64URLRaw(payload.KeyParts[0])
249252 if err != nil {
250 Log(fmt.Sprintf("Error decoding filemoon key part 1: %v", err))
253 curdhost.Log(fmt.Sprintf("Error decoding filemoon key part 1: %v", err))
251254 return nil
252255 }
253256
254257 keyPart2, err := decodeBase64URLRaw(payload.KeyParts[1])
255258 if err != nil {
256 Log(fmt.Sprintf("Error decoding filemoon key part 2: %v", err))
259 curdhost.Log(fmt.Sprintf("Error decoding filemoon key part 2: %v", err))
257260 return nil
258261 }
259262
260263 iv, err := decodeBase64URLRaw(payload.IV)
261264 if err != nil {
262 Log(fmt.Sprintf("Error decoding filemoon IV: %v", err))
265 curdhost.Log(fmt.Sprintf("Error decoding filemoon IV: %v", err))
263266 return nil
264267 }
265268
266269 ciphertext, err := decodeBase64URLRaw(payload.Payload)
267270 if err != nil {
268 Log(fmt.Sprintf("Error decoding filemoon ciphertext: %v", err))
271 curdhost.Log(fmt.Sprintf("Error decoding filemoon ciphertext: %v", err))
269272 return nil
270273 }
271274
272275 if len(ciphertext) <= 16 {
273 Log("Filemoon ciphertext is too short")
276 curdhost.Log("Filemoon ciphertext is too short")
274277 return nil
275278 }
276279
@@ -280,25 +283,25 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
280283 keyHex := hex.EncodeToString(append(keyPart1, keyPart2...))
281284 key, err := hex.DecodeString(keyHex)
282285 if err != nil {
283 Log(fmt.Sprintf("Error decoding filemoon key hex: %v", err))
286 curdhost.Log(fmt.Sprintf("Error decoding filemoon key hex: %v", err))
284287 return nil
285288 }
286289
287290 ctrIVHex := hex.EncodeToString(iv) + "00000002"
288291 ctrIV, err := hex.DecodeString(ctrIVHex)
289292 if err != nil {
290 Log(fmt.Sprintf("Error decoding filemoon CTR IV: %v", err))
293 curdhost.Log(fmt.Sprintf("Error decoding filemoon CTR IV: %v", err))
291294 return nil
292295 }
293296
294297 if len(ctrIV) != aes.BlockSize {
295 Log(fmt.Sprintf("Invalid filemoon CTR IV size: %d", len(ctrIV)))
298 curdhost.Log(fmt.Sprintf("Invalid filemoon CTR IV size: %d", len(ctrIV)))
296299 return nil
297300 }
298301
299302 block, err := aes.NewCipher(key)
300303 if err != nil {
301 Log(fmt.Sprintf("Error creating filemoon cipher: %v", err))
304 curdhost.Log(fmt.Sprintf("Error creating filemoon cipher: %v", err))
302305 return nil
303306 }
304307
@@ -359,7 +362,7 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
359362 }
360363
361364 if len(links) > 0 {
362 Log("Filemoon links fetched")
365 curdhost.Log("Filemoon links fetched")
363366 }
364367
365368 return links
@@ -376,17 +379,17 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
376379// Returns:
377380// - []string: a list of links for specified episode.
378381// - error: an error if the episode is not found or if there is an issue during the search.
379func getAllanimeEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
380 preferredMode := normalizeTranslationType(config.SubOrDub)
382func getAllanimeEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
383 preferredMode := providers.NormalizeTranslationType(config.SubOrDub)
381384 return getAllanimeEpisodeURLForMode(id, preferredMode, epNo)
382385}
383386
384387func getAllanimeEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
385 return getEpisodeURLForMode(id, normalizeTranslationType(mode), epNo)
388 return getEpisodeURLForMode(id, providers.NormalizeTranslationType(mode), epNo)
386389}
387390
388391func fetchAllanimeEpisodeSources(id, mode string, epNo int) ([]allanimeSource, error) {
389 return fetchEpisodeSourcesForMode(id, normalizeTranslationType(mode), epNo)
392 return fetchEpisodeSourcesForMode(id, providers.NormalizeTranslationType(mode), epNo)
390393}
391394
392395func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, error) {
@@ -398,7 +401,7 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
398401
399402 variables := map[string]interface{}{
400403 "showId": id,
401 "translationType": normalizeTranslationType(mode),
404 "translationType": providers.NormalizeTranslationType(mode),
402405 "episodeString": fmt.Sprintf("%d", epNo),
403406 }
404407
@@ -429,7 +432,7 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
429432 req.Header.Set("Referer", allanimePersistedQueryReferer)
430433 req.Header.Set("Origin", allanimePersistedQueryReferer)
431434
432 resp, err := sharedHTTPClient.Do(req)
435 resp, err := curdhost.HTTPClient().Do(req)
433436 if err != nil {
434437 return nil, fmt.Errorf("failed to send persisted query request: %w", err)
435438 }
@@ -438,13 +441,13 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
438441 if err != nil {
439442 return nil, fmt.Errorf("failed to read persisted query response: %w", err)
440443 }
441 if !httpStatusOK(resp.StatusCode) {
442 return nil, httpStatusError("allanime episode persisted query", resp.StatusCode, body)
444 if !curdhost.HTTPStatusOK(resp.StatusCode) {
445 return nil, curdhost.HTTPStatusError("allanime episode persisted query", resp.StatusCode, body)
443446 }
444447
445448 var response allanimeResponse
446449 if err := json.Unmarshal(body, &response); err != nil {
447 Log(fmt.Sprint("Error parsing persisted query JSON: ", err))
450 curdhost.Log(fmt.Sprint("Error parsing persisted query JSON: ", err))
448451 }
449452
450453 useFallback := response.Data.Tobeparsed == "" && len(response.Data.Episode.SourceUrls) == 0
@@ -473,7 +476,7 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
473476 req.Header.Set("Referer", allanimeGraphQLReferer)
474477 req.Header.Set("Origin", allanimeGraphQLReferer)
475478
476 resp, err := sharedHTTPClient.Do(req)
479 resp, err := curdhost.HTTPClient().Do(req)
477480 if err != nil {
478481 return nil, fmt.Errorf("failed to send request: %w", err)
479482 }
@@ -483,24 +486,24 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
483486 if err != nil {
484487 return nil, fmt.Errorf("failed to read response body: %w", err)
485488 }
486 if !httpStatusOK(resp.StatusCode) {
487 return nil, httpStatusError("allanime episode fallback query", resp.StatusCode, body)
489 if !curdhost.HTTPStatusOK(resp.StatusCode) {
490 return nil, curdhost.HTTPStatusError("allanime episode fallback query", resp.StatusCode, body)
488491 }
489492
490493 if err := json.Unmarshal(body, &response); err != nil {
491 Log(fmt.Sprint("Error parsing fallback JSON: ", err))
494 curdhost.Log(fmt.Sprint("Error parsing fallback JSON: ", err))
492495 return nil, err
493496 }
494497 }
495498
496499 if response.Data.Tobeparsed != "" {
497 Log("Found tobeparsed field, decoding source URLs")
500 curdhost.Log("Found tobeparsed field, decoding source URLs")
498501 decodedSources, err := decodeTobeparsed(response.Data.Tobeparsed)
499502 if err != nil {
500503 return nil, err
501504 }
502505
503 Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources)))
506 curdhost.Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources)))
504507 return decodedSources, nil
505508 }
506509
internal/episode_url_test.go → internal/providers/allanime/streams_test.go renamed +1 −1
@@ -1,4 +1,4 @@
1package internal
1package allanime
22
33import (
44 "strings"
internal/provider_animepahe.go → internal/providers/animepahe/provider.go renamed +69 −58
@@ -1,4 +1,4 @@
1package internal
1package animepahe
22
33import (
44 "encoding/json"
@@ -16,13 +16,16 @@ import (
1616
1717 "github.com/go-rod/rod"
1818 "github.com/go-rod/rod/lib/launcher"
19
20 "github.com/wraient/curd/internal/curdhost"
21 "github.com/wraient/curd/internal/providers"
1922)
2023
2124var animepaheCookiesBypassed bool
2225var solveAnimepaheBrowserChallenge = solveAnimepaheBrowserChallengeWithRod
2326
2427func getCookieFilePath() string {
25 return filepath.Join(GetStoragePath(), "animepahe_cookies.json")
28 return filepath.Join(curdhost.StoragePath(), "animepahe_cookies.json")
2629}
2730
2831func saveCookies(cookies []*http.Cookie) {
@@ -57,6 +60,11 @@ func newAnimepaheAPIRequest(rawURL string) (*http.Request, error) {
5760 return req, nil
5861}
5962
63// NewPageRequest builds an HTTP request for animepahe HTML pages.
64func NewPageRequest(rawURL string) (*http.Request, error) {
65 return newAnimepahePageRequest(rawURL)
66}
67
6068func newAnimepahePageRequest(rawURL string) (*http.Request, error) {
6169 req, err := http.NewRequest("GET", rawURL, nil)
6270 if err != nil {
@@ -74,7 +82,7 @@ func checkCookiesValid() bool {
7482 return false
7583 }
7684
77 resp, err := sharedHTTPClient.Do(req)
85 resp, err := curdhost.HTTPClient().Do(req)
7886 if err != nil {
7987 return false
8088 }
@@ -112,7 +120,7 @@ func isAnimepaheChallengeBody(body []byte) bool {
112120 strings.Contains(normalized, "checking your browser")
113121}
114122
115func (p *AnimepaheProvider) ensureBypass() (err error) {
123func (p *Provider) ensureBypass() (err error) {
116124 defer func() {
117125 if recovered := recover(); recovered != nil {
118126 err = fmt.Errorf("failed to solve Animepahe DDoS-Guard challenge: %v", recovered)
@@ -126,36 +134,36 @@ func (p *AnimepaheProvider) ensureBypass() (err error) {
126134 cookies := loadCookies()
127135 if len(cookies) > 0 {
128136 u, _ := url.Parse("https://animepahe.pw")
129 SetCookiesForAnimepahe(u, cookies)
137 curdhost.SetCookiesForAnimepahe(u, cookies)
130138
131139 if checkCookiesValid() {
132140 animepaheCookiesBypassed = true
133 Log("Successfully restored Animepahe session from cache.")
141 curdhost.Log("Successfully restored Animepahe session from cache.")
134142 return nil
135143 }
136 Log("Cached Animepahe session expired. Requesting new session...")
144 curdhost.Log("Cached Animepahe session expired. Requesting new session...")
137145 }
138146
139147 return p.refreshBypass()
140148}
141149
142func (p *AnimepaheProvider) refreshBypass() error {
150func (p *Provider) refreshBypass() error {
143151 u, _ := url.Parse("https://animepahe.pw")
144152 animepaheCookiesBypassed = false
145153 if err := os.Remove(getCookieFilePath()); err != nil && !os.IsNotExist(err) {
146 Log(fmt.Sprintf("Failed to remove cached Animepahe cookies: %v", err))
154 curdhost.Log(fmt.Sprintf("Failed to remove cached Animepahe cookies: %v", err))
147155 }
148156
149 CurdOut("Animepahe needs a browser challenge before Curd can search or play. Starting a temporary headless browser...")
157 curdhost.Out("Animepahe needs a browser challenge before Curd can search or play. Starting a temporary headless browser...")
150158 httpCookies, err := solveAnimepaheBrowserChallenge()
151159 if err != nil {
152 CurdOut("Animepahe browser challenge failed. Try again later or switch provider.")
160 curdhost.Out("Animepahe browser challenge failed. Try again later or switch provider.")
153161 return fmt.Errorf("animepahe browser challenge failed: %w", err)
154162 }
155163 if len(httpCookies) == 0 {
156164 return fmt.Errorf("animepahe browser challenge returned no cookies")
157165 }
158 SetCookiesForAnimepahe(u, httpCookies)
166 curdhost.SetCookiesForAnimepahe(u, httpCookies)
159167
160168 if !checkCookiesValid() {
161169 return fmt.Errorf("bypassed cookies are still invalid")
@@ -163,7 +171,7 @@ func (p *AnimepaheProvider) refreshBypass() error {
163171
164172 saveCookies(httpCookies)
165173 animepaheCookiesBypassed = true
166 CurdOut("Successfully bypassed DDoS-Guard.")
174 curdhost.Out("Successfully bypassed DDoS-Guard.")
167175 return nil
168176}
169177
@@ -201,13 +209,14 @@ func solveAnimepaheBrowserChallengeWithRod() (httpCookies []*http.Cookie, err er
201209 return httpCookies, nil
202210}
203211
204type AnimepaheProvider struct{}
212type Provider struct{}
205213
206func (p *AnimepaheProvider) Name() string {
214func (p *Provider) Name() string {
207215 return "animepahe"
208216}
209217
210type AnimepaheSearchItem struct {
218// SearchItem is an animepahe API search result payload.
219type SearchItem struct {
211220 ID int `json:"id"`
212221 Title string `json:"title"`
213222 Type string `json:"type"`
@@ -220,19 +229,19 @@ type AnimepaheSearchItem struct {
220229 Session string `json:"session"`
221230}
222231
223type animepaheAnimeRef struct {
232type AnimeRef struct {
224233 ReleaseID string
225234 Session string
226235}
227236
228func (r animepaheAnimeRef) apiID() string {
237func (r AnimeRef) apiID() string {
229238 if r.Session != "" {
230239 return r.Session
231240 }
232241 return r.ReleaseID
233242}
234243
235func formatAnimepaheProviderID(item AnimepaheSearchItem) string {
244func formatAnimepaheProviderID(item SearchItem) string {
236245 if item.ID > 0 && item.Session != "" {
237246 return fmt.Sprintf("%d:%s", item.ID, item.Session)
238247 }
@@ -245,36 +254,38 @@ func formatAnimepaheProviderID(item AnimepaheSearchItem) string {
245254 return ""
246255}
247256
248func parseAnimepaheProviderID(providerID string) animepaheAnimeRef {
257// ParseProviderID parses a stored animepahe show identifier.
258func ParseProviderID(providerID string) AnimeRef {
249259 providerID = strings.TrimSpace(providerID)
250260 if providerID == "" {
251 return animepaheAnimeRef{}
261 return AnimeRef{}
252262 }
253263
254264 parts := strings.SplitN(providerID, ":", 2)
255265 if len(parts) == 2 && parts[0] != "" && parts[1] != "" {
256266 if _, err := strconv.Atoi(parts[0]); err == nil {
257 return animepaheAnimeRef{ReleaseID: parts[0], Session: parts[1]}
267 return AnimeRef{ReleaseID: parts[0], Session: parts[1]}
258268 }
259269 }
260270
261271 if _, err := strconv.Atoi(providerID); err == nil {
262 return animepaheAnimeRef{ReleaseID: providerID}
272 return AnimeRef{ReleaseID: providerID}
263273 }
264274
265 return animepaheAnimeRef{Session: providerID}
275 return AnimeRef{Session: providerID}
266276}
267277
268func stableAnimepaheProviderID(providerID string) string {
269 animeRef := parseAnimepaheProviderID(providerID)
278// StableProviderID returns the release id portion used for history matching.
279func StableProviderID(providerID string) string {
280 animeRef := ParseProviderID(providerID)
270281 if animeRef.ReleaseID != "" {
271282 return animeRef.ReleaseID
272283 }
273284 return providerID
274285}
275286
276func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string, error) {
277 animeRef := parseAnimepaheProviderID(providerID)
287func (p *Provider) ResolveProviderID(providerID, query string) (string, error) {
288 animeRef := ParseProviderID(providerID)
278289 query = strings.TrimSpace(query)
279290 if query == "" {
280291 if animeRef.Session != "" {
@@ -286,14 +297,14 @@ func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string,
286297 options, err := p.SearchAnime(query, "")
287298 if err != nil {
288299 if animeRef.Session != "" {
289 Log(fmt.Sprintf("Animepahe provider id refresh failed for %q, using existing session: %v", providerID, err))
300 curdhost.Log(fmt.Sprintf("Animepahe provider id refresh failed for %q, using existing session: %v", providerID, err))
290301 return providerID, nil
291302 }
292303 return "", err
293304 }
294305
295306 for _, option := range options {
296 item, ok := option.ExtraData.(AnimepaheSearchItem)
307 item, ok := option.ExtraData.(SearchItem)
297308 if !ok {
298309 continue
299310 }
@@ -307,7 +318,7 @@ func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string,
307318 }
308319
309320 if animeRef.Session != "" {
310 Log(fmt.Sprintf("Animepahe provider id %q was not found in search results for %q, using existing session", providerID, query))
321 curdhost.Log(fmt.Sprintf("Animepahe provider id %q was not found in search results for %q, using existing session", providerID, query))
311322 return providerID, nil
312323 }
313324
@@ -319,10 +330,10 @@ type animepaheSearchResponse struct {
319330 PerPage int `json:"per_page"`
320331 CurrentPage int `json:"current_page"`
321332 LastPage int `json:"last_page"`
322 Data []AnimepaheSearchItem `json:"data"`
333 Data []SearchItem `json:"data"`
323334}
324335
325func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
336func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
326337 if err := p.ensureBypass(); err != nil {
327338 return nil, err
328339 }
@@ -334,7 +345,7 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
334345 return nil, err
335346 }
336347
337 resp, err := sharedHTTPClient.Do(req)
348 resp, err := curdhost.HTTPClient().Do(req)
338349 if err != nil {
339350 return nil, err
340351 }
@@ -344,8 +355,8 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
344355 if err != nil {
345356 return nil, err
346357 }
347 if !httpStatusOK(resp.StatusCode) {
348 return nil, httpStatusError("animepahe search", resp.StatusCode, body)
358 if !curdhost.HTTPStatusOK(resp.StatusCode) {
359 return nil, curdhost.HTTPStatusError("animepahe search", resp.StatusCode, body)
349360 }
350361
351362 var searchResp animepaheSearchResponse
@@ -354,10 +365,10 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
354365 return nil, err
355366 }
356367
357 var result []SelectionOption
368 var result []providers.SelectionOption
358369 for _, item := range searchResp.Data {
359370 label := fmt.Sprintf("%s (%d episodes) [animepahe]", item.Title, item.Episodes)
360 result = append(result, SelectionOption{
371 result = append(result, providers.SelectionOption{
361372 Title: item.Title,
362373 Label: label,
363374 Key: formatAnimepaheProviderID(item),
@@ -382,11 +393,11 @@ type animepaheEpisodesResponse struct {
382393 } `json:"data"`
383394}
384395
385func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error) {
396func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
386397 if err := p.ensureBypass(); err != nil {
387398 return nil, err
388399 }
389 animeRef := parseAnimepaheProviderID(showID)
400 animeRef := ParseProviderID(showID)
390401 apiID := animeRef.apiID()
391402 if apiID == "" {
392403 return nil, fmt.Errorf("animepahe provider id %q is invalid; please reselect this anime", showID)
@@ -403,7 +414,7 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
403414 return nil, err
404415 }
405416
406 resp, err := sharedHTTPClient.Do(req)
417 resp, err := curdhost.HTTPClient().Do(req)
407418 if err != nil {
408419 return nil, err
409420 }
@@ -417,15 +428,15 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
417428 if challengeRetried {
418429 return nil, fmt.Errorf("animepahe episode list is still blocked by DDoS-Guard after refreshing browser session")
419430 }
420 Log("Animepahe episode list returned DDoS-Guard challenge. Refreshing browser session...")
431 curdhost.Log("Animepahe episode list returned DDoS-Guard challenge. Refreshing browser session...")
421432 if err := p.refreshBypass(); err != nil {
422433 return nil, err
423434 }
424435 challengeRetried = true
425436 continue
426437 }
427 if !httpStatusOK(resp.StatusCode) {
428 return nil, httpStatusError("animepahe episode list", resp.StatusCode, body)
438 if !curdhost.HTTPStatusOK(resp.StatusCode) {
439 return nil, curdhost.HTTPStatusError("animepahe episode list", resp.StatusCode, body)
429440 }
430441
431442 var epsResp animepaheEpisodesResponse
@@ -453,15 +464,15 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
453464 return result, nil
454465}
455466
456func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
467func (p *Provider) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
457468 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub)
458469}
459470
460func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, epNo int, mode string) ([]string, error) {
471func (p *Provider) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
461472 if err := p.ensureBypass(); err != nil {
462473 return nil, err
463474 }
464 animeRef := parseAnimepaheProviderID(id)
475 animeRef := ParseProviderID(id)
465476 if animeRef.Session == "" {
466477 return nil, fmt.Errorf("animepahe provider id %q is missing session id; please reselect this anime", id)
467478 }
@@ -492,7 +503,7 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
492503 return nil, err
493504 }
494505
495 resp, err := sharedHTTPClient.Do(req)
506 resp, err := curdhost.HTTPClient().Do(req)
496507 if err != nil {
497508 return nil, err
498509 }
@@ -502,8 +513,8 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
502513 if err != nil {
503514 return nil, err
504515 }
505 if !httpStatusOK(resp.StatusCode) {
506 return nil, httpStatusError("animepahe episode lookup", resp.StatusCode, body)
516 if !curdhost.HTTPStatusOK(resp.StatusCode) {
517 return nil, curdhost.HTTPStatusError("animepahe episode lookup", resp.StatusCode, body)
507518 }
508519
509520 var epsResp animepaheEpisodesResponse
@@ -537,7 +548,7 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
537548 return nil, err
538549 }
539550
540 resp, err := sharedHTTPClient.Do(req)
551 resp, err := curdhost.HTTPClient().Do(req)
541552 if err != nil {
542553 return nil, err
543554 }
@@ -547,8 +558,8 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
547558 if err != nil {
548559 return nil, err
549560 }
550 if !httpStatusOK(resp.StatusCode) {
551 return nil, httpStatusError("animepahe player page", resp.StatusCode, body)
561 if !curdhost.HTTPStatusOK(resp.StatusCode) {
562 return nil, curdhost.HTTPStatusError("animepahe player page", resp.StatusCode, body)
552563 }
553564
554565 bodyStr := string(body)
@@ -606,7 +617,7 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
606617 sortFunc(dubLinks)
607618
608619 var links []string
609 requestedMode := normalizeTranslationType(mode)
620 requestedMode := providers.NormalizeTranslationType(mode)
610621 if requestedMode == "dub" {
611622 for _, l := range dubLinks {
612623 links = append(links, l.url)
@@ -635,13 +646,13 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
635646 return finalLinks, nil
636647}
637648
638func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) {
649func (p *Provider) extractKwikM3u8(kwikUrl string) (string, error) {
639650 req, err := newAnimepahePageRequest(kwikUrl)
640651 if err != nil {
641652 return "", err
642653 }
643654
644 resp, err := sharedHTTPClient.Do(req)
655 resp, err := curdhost.HTTPClient().Do(req)
645656 if err != nil {
646657 return "", err
647658 }
@@ -651,8 +662,8 @@ func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) {
651662 if err != nil {
652663 return "", err
653664 }
654 if !httpStatusOK(resp.StatusCode) {
655 return "", httpStatusError("kwik stream page", resp.StatusCode, body)
665 if !curdhost.HTTPStatusOK(resp.StatusCode) {
666 return "", curdhost.HTTPStatusError("kwik stream page", resp.StatusCode, body)
656667 }
657668 bodyStr := string(body)
658669
internal/provider_animepahe_test.go → internal/providers/animepahe/provider_test.go renamed +31 −13
@@ -1,16 +1,25 @@
1package internal
1package animepahe
22
33import (
44 "io"
55 "net/http"
66 "net/http/cookiejar"
7 "net/url"
78 "os"
89 "strings"
910 "testing"
11
12 "github.com/wraient/curd/internal/curdhost"
1013)
1114
1215const animepaheChallengeHTML = `<!doctype html><html><head><title>DDoS-Guard</title></head><body>Checking your browser</body></html>`
1316
17type roundTripFunc func(*http.Request) (*http.Response, error)
18
19func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
20 return f(req)
21}
22
1423func animepaheTestResponse(req *http.Request, statusCode int, body string, headers map[string]string) *http.Response {
1524 resp := &http.Response{
1625 StatusCode: statusCode,
@@ -27,21 +36,30 @@ func animepaheTestResponse(req *http.Request, statusCode int, body string, heade
2736func withAnimepaheTestHooks(t *testing.T, client *http.Client, solver func() ([]*http.Cookie, error)) {
2837 t.Helper()
2938
30 previousClient := sharedHTTPClient
39 previousClient := curdhost.HTTPClient
40 previousLog := curdhost.Log
41 previousOut := curdhost.Out
42 previousCookies := curdhost.SetCookiesForAnimepahe
3143 previousSolver := solveAnimepaheBrowserChallenge
3244 previousBypassed := animepaheCookiesBypassed
33 previousConfig := GetGlobalConfig()
45 previousStoragePath := curdhost.StoragePath
3446
3547 t.Cleanup(func() {
36 sharedHTTPClient = previousClient
48 curdhost.HTTPClient = previousClient
49 curdhost.Log = previousLog
50 curdhost.Out = previousOut
51 curdhost.SetCookiesForAnimepahe = previousCookies
3752 solveAnimepaheBrowserChallenge = previousSolver
3853 animepaheCookiesBypassed = previousBypassed
39 SetGlobalConfig(previousConfig)
54 curdhost.StoragePath = previousStoragePath
4055 })
4156
42 sharedHTTPClient = client
57 curdhost.HTTPClient = func() *http.Client { return client }
58 curdhost.Log = func(string) {}
59 curdhost.Out = func(string) {}
60 curdhost.SetCookiesForAnimepahe = func(*url.URL, []*http.Cookie) {}
4361 solveAnimepaheBrowserChallenge = solver
44 SetGlobalConfig(&CurdConfig{StoragePath: t.TempDir()})
62 curdhost.StoragePath = func() string { return t.TempDir() }
4563}
4664
4765func TestAnimepaheEpisodesListRefreshesSessionWhenReleaseEndpointReturnsChallenge(t *testing.T) {
@@ -82,7 +100,7 @@ func TestAnimepaheEpisodesListRefreshesSessionWhenReleaseEndpointReturnsChalleng
82100 })
83101 animepaheCookiesBypassed = true
84102
85 episodes, err := (&AnimepaheProvider{}).EpisodesList("4:session-id", "sub")
103 episodes, err := (&Provider{}).EpisodesList("4:session-id", "sub")
86104 if err != nil {
87105 t.Fatalf("expected episode list retry to succeed: %v", err)
88106 }
@@ -129,7 +147,7 @@ func TestAnimepaheEpisodesListReportsPersistentChallengeAfterRefresh(t *testing.
129147 })
130148 animepaheCookiesBypassed = true
131149
132 _, err = (&AnimepaheProvider{}).EpisodesList("4:session-id", "sub")
150 _, err = (&Provider{}).EpisodesList("4:session-id", "sub")
133151 if err == nil {
134152 t.Fatalf("expected persistent DDoS-Guard challenge to fail")
135153 }
@@ -146,16 +164,16 @@ func TestAnimepaheEpisodesListLiveOnePiece(t *testing.T) {
146164 t.Skip("set CURD_LIVE_ANIMEPAHE_TEST=1 to run live Animepahe episode-list verification")
147165 }
148166
149 previousConfig := GetGlobalConfig()
150167 previousBypassed := animepaheCookiesBypassed
168 previousStoragePath := curdhost.StoragePath
151169 t.Cleanup(func() {
152 SetGlobalConfig(previousConfig)
153170 animepaheCookiesBypassed = previousBypassed
171 curdhost.StoragePath = previousStoragePath
154172 })
155 SetGlobalConfig(&CurdConfig{StoragePath: t.TempDir()})
173 curdhost.StoragePath = func() string { return t.TempDir() }
156174 animepaheCookiesBypassed = false
157175
158 episodes, err := (&AnimepaheProvider{}).EpisodesList("4:15a36fc8-73b9-8c2e-ee5f-fb1bcd4fcdc6", "sub")
176 episodes, err := (&Provider{}).EpisodesList("4:15a36fc8-73b9-8c2e-ee5f-fb1bcd4fcdc6", "sub")
159177 if err != nil {
160178 t.Fatalf("live Animepahe One Piece episode list failed: %v", err)
161179 }
internal/providers/animepahe/register.go added +17
@@ -0,0 +1,17 @@
1package animepahe
2
3import "github.com/wraient/curd/internal/providers"
4
5func init() {
6 providers.Register(providers.Meta{
7 Name: "animepahe",
8 Aliases: []string{"pahe"},
9 Referrer: "https://kwik.cx/",
10 DefaultDisabled: true,
11 DisableReason: "Cloudflare/DDoS-Guard protection cannot be bypassed reliably",
12 OptOutToken: "no-animepahe",
13 FallbackPrompt: "Animepahe may require downloading a Chromium browser for DDoS-Guard verification (~500 MB).",
14 }, func() providers.Provider {
15 return &Provider{}
16 })
17}
internal/providers/anineko/bibiemb.go added +110
@@ -0,0 +1,110 @@
1package anineko
2
3import (
4 "fmt"
5 "net/url"
6 "regexp"
7 "strings"
8)
9
10var (
11 bibiembMasterRE = regexp.MustCompile(`const src = "(https?://[^"]+/master\.m3u8)"`)
12 streamInfRE = regexp.MustCompile(`(?m)^#EXT-X-STREAM-INF:.*NAME="([^"]+)".*\r?\n([^\r\n#]+)`)
13)
14
15var bibiembQualityOrder = []string{"1080p", "720p", "480p", "360p"}
16
17type resolvedStream struct {
18 URL string
19 Referrer string
20 Subtitle string
21}
22
23func resolveBibiemb(embedURL string) (resolvedStream, error) {
24 embedURL = strings.TrimSpace(embedURL)
25 if embedURL == "" {
26 return resolvedStream{}, fmt.Errorf("empty bibiemb embed url")
27 }
28
29 html, err := fetchString(embedURL, baseURL+"/")
30 if err != nil {
31 return resolvedStream{}, err
32 }
33
34 match := bibiembMasterRE.FindStringSubmatch(html)
35 if len(match) < 2 {
36 return resolvedStream{}, fmt.Errorf("bibiemb master m3u8 not found")
37 }
38
39 masterURL := match[1]
40 variantURL, err := pickBibiembVariant(masterURL, embedURL)
41 if err != nil {
42 return resolvedStream{}, err
43 }
44
45 return resolvedStream{
46 URL: variantURL,
47 Referrer: embedURL,
48 Subtitle: subtitleFromEmbedURL(embedURL),
49 }, nil
50}
51
52func pickBibiembVariant(masterURL, referer string) (string, error) {
53 playlist, err := fetchString(masterURL, referer)
54 if err != nil {
55 return "", err
56 }
57
58 type variant struct {
59 name string
60 url string
61 }
62 variants := make([]variant, 0)
63 for _, match := range streamInfRE.FindAllStringSubmatch(playlist, -1) {
64 if len(match) < 3 {
65 continue
66 }
67 variants = append(variants, variant{
68 name: strings.TrimSpace(match[1]),
69 url: resolvePlaylistURL(masterURL, strings.TrimSpace(match[2])),
70 })
71 }
72 if len(variants) == 0 {
73 return "", fmt.Errorf("no bibiemb variants in master playlist")
74 }
75
76 byName := map[string]string{}
77 for _, item := range variants {
78 byName[strings.ToLower(item.name)] = item.url
79 }
80 for _, quality := range bibiembQualityOrder {
81 if streamURL, ok := byName[quality]; ok {
82 return streamURL, nil
83 }
84 }
85 return variants[0].url, nil
86}
87
88func resolvePlaylistURL(baseURL, entry string) string {
89 if strings.HasPrefix(entry, "http://") || strings.HasPrefix(entry, "https://") {
90 return entry
91 }
92 parsed, err := url.Parse(baseURL)
93 if err != nil {
94 return entry
95 }
96 if strings.HasPrefix(entry, "/") {
97 parsed.Path = entry
98 parsed.RawQuery = ""
99 parsed.Fragment = ""
100 return parsed.Scheme + "://" + parsed.Host + entry
101 }
102 if idx := strings.LastIndex(parsed.Path, "/"); idx >= 0 {
103 parsed.Path = parsed.Path[:idx+1] + entry
104 } else {
105 parsed.Path = "/" + entry
106 }
107 parsed.RawQuery = ""
108 parsed.Fragment = ""
109 return parsed.String()
110}
internal/providers/anineko/client.go added +92
@@ -0,0 +1,92 @@
1package anineko
2
3import (
4 "fmt"
5 "io"
6 "net/http"
7 "strings"
8
9 "github.com/wraient/curd/internal/curdhost"
10)
11
12const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
13
14var baseURL = "https://anineko.to"
15
16func newRequest(method, rawURL, referer string) (*http.Request, error) {
17 req, err := http.NewRequest(method, rawURL, nil)
18 if err != nil {
19 return nil, err
20 }
21 req.Header.Set("User-Agent", userAgent)
22 if referer != "" {
23 req.Header.Set("Referer", referer)
24 }
25 return req, nil
26}
27
28func fetchString(rawURL, referer string) (string, error) {
29 req, err := newRequest(http.MethodGet, rawURL, referer)
30 if err != nil {
31 return "", err
32 }
33 resp, err := curdhost.HTTPClient().Do(req)
34 if err != nil {
35 return "", err
36 }
37 defer resp.Body.Close()
38
39 body, err := io.ReadAll(resp.Body)
40 if err != nil {
41 return "", err
42 }
43 if !curdhost.HTTPStatusOK(resp.StatusCode) {
44 return "", curdhost.HTTPStatusError("anineko request", resp.StatusCode, body)
45 }
46 return string(body), nil
47}
48
49func fetchBytes(rawURL, referer string) ([]byte, error) {
50 req, err := newRequest(http.MethodGet, rawURL, referer)
51 if err != nil {
52 return nil, err
53 }
54 resp, err := curdhost.HTTPClient().Do(req)
55 if err != nil {
56 return nil, err
57 }
58 defer resp.Body.Close()
59
60 body, err := io.ReadAll(resp.Body)
61 if err != nil {
62 return nil, err
63 }
64 if !curdhost.HTTPStatusOK(resp.StatusCode) {
65 return nil, curdhost.HTTPStatusError("anineko request", resp.StatusCode, body)
66 }
67 return body, nil
68}
69
70func absoluteURL(path string) string {
71 path = strings.TrimSpace(path)
72 if path == "" {
73 return ""
74 }
75 if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
76 return path
77 }
78 if strings.HasPrefix(path, "//") {
79 return "https:" + path
80 }
81 if !strings.HasPrefix(path, "/") {
82 path = "/" + path
83 }
84 return baseURL + path
85}
86
87func watchURL(slug string, epNo int) string {
88 if epNo > 0 {
89 return fmt.Sprintf("%s/watch/%s/ep-%d", baseURL, slug, epNo)
90 }
91 return fmt.Sprintf("%s/watch/%s", baseURL, slug)
92}
internal/providers/anineko/episodes.go added +50
@@ -0,0 +1,50 @@
1package anineko
2
3import (
4 "fmt"
5 "regexp"
6 "sort"
7 "strconv"
8 "strings"
9)
10
11var episodePathRE = regexp.MustCompile(`/ep-(\d+)`)
12
13func episodesList(showID, mode string) ([]string, error) {
14 slug := strings.TrimSpace(showID)
15 if slug == "" {
16 return nil, fmt.Errorf("empty show id")
17 }
18
19 html, err := fetchString(watchURL(slug, 0), baseURL+"/")
20 if err != nil {
21 return nil, err
22 }
23
24 seen := map[int]struct{}{}
25 for _, match := range episodePathRE.FindAllStringSubmatch(html, -1) {
26 if len(match) < 2 {
27 continue
28 }
29 epNo, err := strconv.Atoi(match[1])
30 if err != nil || epNo <= 0 {
31 continue
32 }
33 seen[epNo] = struct{}{}
34 }
35 if len(seen) == 0 {
36 return nil, fmt.Errorf("no episodes found for %q", slug)
37 }
38
39 episodes := make([]int, 0, len(seen))
40 for epNo := range seen {
41 episodes = append(episodes, epNo)
42 }
43 sort.Ints(episodes)
44
45 result := make([]string, 0, len(episodes))
46 for _, epNo := range episodes {
47 result = append(result, strconv.Itoa(epNo))
48 }
49 return result, nil
50}
internal/providers/anineko/provider.go added +34
@@ -0,0 +1,34 @@
1package anineko
2
3import "github.com/wraient/curd/internal/providers"
4
5// Provider implements anineko.to catalog search and stream resolution.
6type Provider struct{}
7
8func (p *Provider) Name() string {
9 return "anineko"
10}
11
12func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
13 return searchAnime(query, mode)
14}
15
16func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
17 return episodesList(showID, mode)
18}
19
20func (p *Provider) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
21 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, config.SubOrDub)
22 return links, err
23}
24
25func (p *Provider) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
26 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, mode)
27 return links, err
28}
29
30func (p *Provider) GetEpisodeURLForModeWithHints(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, map[string]providers.StreamPlaybackHint, error) {
31 playback := config
32 playback.SubOrDub = providers.NormalizeTranslationType(mode)
33 return getEpisodeStreamsForMode(id, playback, epNo)
34}
internal/providers/anineko/provider_test.go added +314
@@ -0,0 +1,314 @@
1package anineko
2
3import (
4 "io"
5 "net/http"
6 "net/http/httptest"
7 "strings"
8 "testing"
9
10 "github.com/wraient/curd/internal/curdhost"
11)
12
13type roundTripFunc func(*http.Request) (*http.Response, error)
14
15func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
16 return f(req)
17}
18
19func testResponse(req *http.Request, statusCode int, body string, headers map[string]string) *http.Response {
20 resp := &http.Response{
21 StatusCode: statusCode,
22 Header: make(http.Header),
23 Body: io.NopCloser(strings.NewReader(body)),
24 Request: req,
25 }
26 for key, value := range headers {
27 resp.Header.Set(key, value)
28 }
29 return resp
30}
31
32func withAninekoTestClient(t *testing.T, client *http.Client) {
33 t.Helper()
34 previous := curdhost.HTTPClient
35 t.Cleanup(func() {
36 curdhost.HTTPClient = previous
37 resetVibeProxyForTest()
38 resetSubStyleForTest()
39 })
40 curdhost.HTTPClient = func() *http.Client { return client }
41}
42
43func TestSearchAnimeParsesResults(t *testing.T) {
44 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
45 if r.URL.Path != "/ajax/search" {
46 http.NotFound(w, r)
47 return
48 }
49 _, _ = io.WriteString(w, `{"success":true,"results":[{"title":"One Piece","url":"/watch/one-piece","image":"/img/op.jpg","meta":"TV"}]}`)
50 }))
51 defer server.Close()
52
53 withAninekoTestClient(t, server.Client())
54
55 originalBase := baseURL
56 t.Cleanup(func() { baseURL = originalBase })
57 baseURL = server.URL
58
59 options, err := searchAnime("one piece", "sub")
60 if err != nil {
61 t.Fatalf("searchAnime: %v", err)
62 }
63 if len(options) != 1 {
64 t.Fatalf("expected 1 option, got %d", len(options))
65 }
66 if options[0].Key != "one-piece" {
67 t.Fatalf("unexpected key %q", options[0].Key)
68 }
69 if options[0].Thumbnail != server.URL+"/img/op.jpg" {
70 t.Fatalf("unexpected thumbnail %q", options[0].Thumbnail)
71 }
72}
73
74func TestEpisodesListParsesEpisodeLinks(t *testing.T) {
75 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
76 _, _ = io.WriteString(w, `<a href="/watch/frieren/ep-1">1</a><a href="/watch/frieren/ep-12">12</a>`)
77 }))
78 defer server.Close()
79
80 withAninekoTestClient(t, server.Client())
81 originalBase := baseURL
82 t.Cleanup(func() { baseURL = originalBase })
83 baseURL = server.URL
84
85 episodes, err := episodesList("frieren", "sub")
86 if err != nil {
87 t.Fatalf("episodesList: %v", err)
88 }
89 if strings.Join(episodes, ",") != "1,12" {
90 t.Fatalf("unexpected episodes %v", episodes)
91 }
92}
93
94func TestExtractLangEmbedURLs(t *testing.T) {
95 html := `
96<div class="server-items" data-id="sub">
97 <div data-video="https://bibiemb.xyz/aaa"></div>
98 <div data-video="https://vibeplayer.site/bbb?sub=https://cdn.example/sub.vtt"></div>
99</div>
100<div class="server-items" data-id="dub">
101 <div data-video="https://bibiemb.xyz/ccc"></div>
102</div>`
103
104 groups := extractLangEmbedURLs(html)
105 if len(groups["sub"]) != 2 {
106 t.Fatalf("expected 2 sub urls, got %d", len(groups["sub"]))
107 }
108 if len(groups["dub"]) != 1 {
109 t.Fatalf("expected 1 dub url, got %d", len(groups["dub"]))
110 }
111 subURLs := embedURLsForSubStyle(groups, "soft")
112 if len(subURLs) != 2 {
113 t.Fatalf("expected 2 soft sub urls, got %d", len(subURLs))
114 }
115 if subtitleFromEmbedURL(subURLs[1]) != "https://cdn.example/sub.vtt" {
116 t.Fatalf("unexpected subtitle %q", subtitleFromEmbedURL(subURLs[1]))
117 }
118}
119
120func TestChooseSubStyleRespectsPreference(t *testing.T) {
121 groups := map[string][]string{
122 "hsub": {"https://vibeplayer.site/hard"},
123 "sub": {"https://vibeplayer.site/soft?sub=https://cdn.example/sub.vtt"},
124 "dub": {"https://vibeplayer.site/dub"},
125 }
126
127 style, err := chooseSubStyle(groups, "soft")
128 if err != nil || style != "soft" {
129 t.Fatalf("chooseSubStyle soft: style=%q err=%v", style, err)
130 }
131
132 style, err = chooseSubStyle(groups, "hard")
133 if err != nil || style != "hard" {
134 t.Fatalf("chooseSubStyle hard: style=%q err=%v", style, err)
135 }
136}
137
138func TestChooseSubStylePromptSelectOnce(t *testing.T) {
139 groups := map[string][]string{
140 "hsub": {"https://vibeplayer.site/hard"},
141 "sub": {"https://vibeplayer.site/soft?sub=https://cdn.example/sub.vtt"},
142 }
143
144 prompts := 0
145 previousPrompt := curdhost.PromptSelect
146 previousOut := curdhost.Out
147 previousPersist := curdhost.PersistSubStylePreference
148 previousCurrent := curdhost.CurrentSubStyle
149 curdhost.PromptSelect = func(options []curdhost.PromptOption) (curdhost.PromptOption, error) {
150 prompts++
151 return curdhost.PromptOption{Key: "hard", Label: "Hard sub"}, nil
152 }
153 curdhost.Out = func(string) {}
154 saved := ""
155 curdhost.PersistSubStylePreference = func(style string) error {
156 saved = style
157 return nil
158 }
159 curdhost.CurrentSubStyle = func() string { return saved }
160 t.Cleanup(func() {
161 curdhost.PromptSelect = previousPrompt
162 curdhost.Out = previousOut
163 curdhost.PersistSubStylePreference = previousPersist
164 curdhost.CurrentSubStyle = previousCurrent
165 resetSubStyleForTest()
166 })
167
168 for i := 0; i < 2; i++ {
169 style, err := chooseSubStyle(groups, "ask")
170 if err != nil || style != "hard" {
171 t.Fatalf("iteration %d: style=%q err=%v", i, style, err)
172 }
173 }
174 if prompts != 1 {
175 t.Fatalf("expected 1 prompt, got %d", prompts)
176 }
177 if saved != "hard" {
178 t.Fatalf("expected saved preference hard, got %q", saved)
179 }
180}
181
182func TestResolveBibiembPicks1080pVariant(t *testing.T) {
183 const hash = "agdeadbeef"
184
185 var server *httptest.Server
186 server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
187 switch {
188 case r.URL.Path == "/"+hash:
189 _, _ = io.WriteString(w, `const src = "`+server.URL+`/`+hash+`/master.m3u8"`)
190 case r.URL.Path == "/"+hash+"/master.m3u8":
191 _, _ = io.WriteString(w, `#EXTM3U
192#EXT-X-STREAM-INF:BANDWIDTH=1,NAME="720p"
193`+server.URL+`/`+hash+`/720p/index.m3u8
194#EXT-X-STREAM-INF:BANDWIDTH=2,NAME="1080p"
195`+server.URL+`/`+hash+`/1080p/index.m3u8`)
196 default:
197 http.NotFound(w, r)
198 }
199 }))
200 defer server.Close()
201
202 withAninekoTestClient(t, server.Client())
203
204 stream, err := resolveBibiemb(server.URL + "/" + hash)
205 if err != nil {
206 t.Fatalf("resolveBibiemb: %v", err)
207 }
208 if !strings.HasSuffix(stream.URL, "/1080p/index.m3u8") {
209 t.Fatalf("expected 1080p variant, got %q", stream.URL)
210 }
211}
212
213func TestStripPNGWrapper(t *testing.T) {
214 png := []byte{
215 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
216 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
217 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
218 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
219 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41,
220 0x54, 0x78, 0xda, 0x63, 0x64, 0xf8, 0xcf, 0x50,
221 0x0f, 0x00, 0x03, 0x86, 0x01, 0x80, 0x5a, 0x34,
222 0x7d, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
223 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
224 }
225 payload := []byte{0x47, 0x01, 0x02, 0x03}
226 data := append(append([]byte{}, png...), payload...)
227 if got := stripPNGWrapper(data); string(got) != string(payload) {
228 t.Fatalf("unexpected stripped payload %v", got)
229 }
230}
231
232func TestVibeProxyRewritesAndStripsSegments(t *testing.T) {
233 const (
234 id = "abc123"
235 variant = "1720.m3u8"
236 )
237
238 png := []byte{
239 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
240 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
241 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
242 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
243 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41,
244 0x54, 0x78, 0xda, 0x63, 0x64, 0xf8, 0xcf, 0x50,
245 0x0f, 0x00, 0x03, 0x86, 0x01, 0x80, 0x5a, 0x34,
246 0x7d, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
247 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, 0x47, 0x11,
248 }
249
250 remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
251 switch r.URL.Path {
252 case "/public/stream/" + id + "/master.m3u8":
253 _, _ = io.WriteString(w, "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1,NAME=\"720p\"\n"+variant+"\n")
254 case "/public/stream/" + id + "/" + variant:
255 _, _ = io.WriteString(w, "#EXTM3U\n#EXTINF:10.0,\n/public/segment.bin\n")
256 case "/public/segment.bin":
257 _, _ = w.Write(png)
258 default:
259 http.NotFound(w, r)
260 }
261 }))
262 defer remote.Close()
263
264 withAninekoTestClient(t, remote.Client())
265 resetVibeProxyForTest()
266
267 masterURL := remote.URL + "/public/stream/" + id + "/master.m3u8"
268 proxyURL, err := registerVibeStream(masterURL, remote.URL+"/"+id)
269 if err != nil {
270 t.Fatalf("registerVibeStream: %v", err)
271 }
272
273 resp, err := http.Get(proxyURL)
274 if err != nil {
275 t.Fatalf("get master: %v", err)
276 }
277 body, _ := io.ReadAll(resp.Body)
278 resp.Body.Close()
279 if !strings.Contains(string(body), "/1720.m3u8") {
280 t.Fatalf("master not rewritten: %s", body)
281 }
282
283 variantURL := ""
284 for _, line := range strings.Split(strings.ReplaceAll(string(body), "\r\n", "\n"), "\n") {
285 line = strings.TrimSpace(line)
286 if line != "" && !strings.HasPrefix(line, "#") {
287 variantURL = line
288 break
289 }
290 }
291 resp, err = http.Get(variantURL)
292 if err != nil {
293 t.Fatalf("get variant: %v", err)
294 }
295 body, _ = io.ReadAll(resp.Body)
296 resp.Body.Close()
297 segURL := ""
298 for _, line := range strings.Split(strings.TrimSpace(string(body)), "\n") {
299 line = strings.TrimSpace(line)
300 if line != "" && !strings.HasPrefix(line, "#") {
301 segURL = line
302 }
303 }
304
305 resp, err = http.Get(segURL)
306 if err != nil {
307 t.Fatalf("get segment: %v", err)
308 }
309 segBody, _ := io.ReadAll(resp.Body)
310 resp.Body.Close()
311 if len(segBody) != 2 || segBody[0] != 0x47 {
312 t.Fatalf("expected stripped mpeg-ts payload, got %v", segBody)
313 }
314}
internal/providers/anineko/register.go added +13
@@ -0,0 +1,13 @@
1package anineko
2
3import "github.com/wraient/curd/internal/providers"
4
5func init() {
6 providers.Register(providers.Meta{
7 Name: "anineko",
8 Aliases: []string{"ani-neko", "ani neko"},
9 Referrer: "https://anineko.to/",
10 }, func() providers.Provider {
11 return &Provider{}
12 })
13}
internal/providers/anineko/scrape.go added +107
@@ -0,0 +1,107 @@
1package anineko
2
3import (
4 "net/url"
5 "regexp"
6 "strings"
7)
8
9var (
10 dataVideoRE = regexp.MustCompile(`data-video="([^"]+)"`)
11 subtitleRE = regexp.MustCompile(`[?&](?:sub|caption_1|c1_file)=([^&"]+)`)
12)
13
14func extractLangEmbedURLs(html string) map[string][]string {
15 groups := map[string][]string{
16 "hsub": {},
17 "sub": {},
18 "dub": {},
19 }
20 markers := regexp.MustCompile(`data-id="(hsub|sub|dub)"`).FindAllStringSubmatchIndex(html, -1)
21 for i, marker := range markers {
22 if len(marker) < 4 {
23 continue
24 }
25 lang := html[marker[2]:marker[3]]
26 start := marker[1]
27 end := len(html)
28 if i+1 < len(markers) {
29 end = markers[i+1][0]
30 }
31 block := html[start:end]
32 seen := map[string]struct{}{}
33 for _, videoMatch := range dataVideoRE.FindAllStringSubmatch(block, -1) {
34 if len(videoMatch) < 2 {
35 continue
36 }
37 embedURL := strings.TrimSpace(videoMatch[1])
38 if embedURL == "" {
39 continue
40 }
41 if _, ok := seen[embedURL]; ok {
42 continue
43 }
44 seen[embedURL] = struct{}{}
45 groups[lang] = append(groups[lang], embedURL)
46 }
47 }
48 return groups
49}
50
51func partitionByHost(embedURLs []string) (bibiemb, vibeplayer, other []string) {
52 for _, embedURL := range embedURLs {
53 host := strings.ToLower(hostFromURL(embedURL))
54 switch {
55 case strings.Contains(host, "bibiemb."):
56 bibiemb = append(bibiemb, embedURL)
57 case strings.Contains(host, "vibeplayer."):
58 vibeplayer = append(vibeplayer, embedURL)
59 default:
60 other = append(other, embedURL)
61 }
62 }
63 return bibiemb, vibeplayer, other
64}
65
66func subtitleFromEmbedURL(embedURL string) string {
67 parsed, err := url.Parse(embedURL)
68 if err != nil {
69 return ""
70 }
71 for key, values := range parsed.Query() {
72 switch strings.ToLower(key) {
73 case "sub", "caption_1", "c1_file":
74 if len(values) > 0 {
75 if decoded, err := url.QueryUnescape(values[0]); err == nil {
76 return decoded
77 }
78 return values[0]
79 }
80 }
81 }
82 match := subtitleRE.FindStringSubmatch(embedURL)
83 if len(match) < 2 {
84 return ""
85 }
86 if decoded, err := url.QueryUnescape(match[1]); err == nil {
87 return decoded
88 }
89 return match[1]
90}
91
92func hostFromURL(rawURL string) string {
93 parsed, err := url.Parse(rawURL)
94 if err != nil {
95 return ""
96 }
97 return parsed.Host
98}
99
100func containsString(items []string, target string) bool {
101 for _, item := range items {
102 if item == target {
103 return true
104 }
105 }
106 return false
107}
internal/providers/anineko/search.go added +74
@@ -0,0 +1,74 @@
1package anineko
2
3import (
4 "encoding/json"
5 "fmt"
6 "net/url"
7 "regexp"
8 "strings"
9
10 "github.com/wraient/curd/internal/providers"
11)
12
13type searchResponse struct {
14 Success bool `json:"success"`
15 Results []struct {
16 Title string `json:"title"`
17 URL string `json:"url"`
18 Image string `json:"image"`
19 Meta string `json:"meta"`
20 } `json:"results"`
21}
22
23var slugFromPathRE = regexp.MustCompile(`/watch/([^/?#]+)`)
24
25func searchAnime(query, mode string) ([]providers.SelectionOption, error) {
26 query = strings.TrimSpace(query)
27 if query == "" {
28 return nil, fmt.Errorf("empty search query")
29 }
30
31 rawURL := fmt.Sprintf("%s/ajax/search?q=%s", baseURL, url.QueryEscape(query))
32 body, err := fetchString(rawURL, baseURL+"/")
33 if err != nil {
34 return nil, err
35 }
36
37 var payload searchResponse
38 if err := json.Unmarshal([]byte(body), &payload); err != nil {
39 return nil, fmt.Errorf("parse anineko search response: %w", err)
40 }
41 if !payload.Success {
42 return nil, fmt.Errorf("anineko search failed")
43 }
44
45 options := make([]providers.SelectionOption, 0, len(payload.Results))
46 for _, result := range payload.Results {
47 slug := slugFromWatchURL(result.URL)
48 if slug == "" {
49 continue
50 }
51 label := strings.TrimSpace(result.Title)
52 if meta := strings.TrimSpace(result.Meta); meta != "" {
53 label = label + " — " + meta
54 }
55 options = append(options, providers.SelectionOption{
56 Key: slug,
57 Label: label,
58 Title: strings.TrimSpace(result.Title),
59 Thumbnail: absoluteURL(result.Image),
60 })
61 }
62 if len(options) == 0 {
63 return nil, fmt.Errorf("no results for %q", query)
64 }
65 return options, nil
66}
67
68func slugFromWatchURL(watchPath string) string {
69 match := slugFromPathRE.FindStringSubmatch(watchPath)
70 if len(match) < 2 {
71 return ""
72 }
73 return strings.TrimSpace(match[1])
74}
internal/providers/anineko/streams.go added +66
@@ -0,0 +1,66 @@
1package anineko
2
3import (
4 "fmt"
5 "strings"
6
7 "github.com/wraient/curd/internal/providers"
8)
9
10func getEpisodeStreamsForMode(slug string, config providers.PlaybackConfig, epNo int) ([]string, map[string]providers.StreamPlaybackHint, error) {
11 slug = strings.TrimSpace(slug)
12 if slug == "" {
13 return nil, nil, fmt.Errorf("empty show id")
14 }
15 if epNo <= 0 {
16 return nil, nil, fmt.Errorf("invalid episode number %d", epNo)
17 }
18
19 mode := providers.NormalizeTranslationType(config.SubOrDub)
20 html, err := fetchString(watchURL(slug, epNo), baseURL+"/")
21 if err != nil {
22 return nil, nil, err
23 }
24
25 groups := extractLangEmbedURLs(html)
26 embedURLs, err := embedURLsForMode(groups, mode, config.SubStyle)
27 if err != nil {
28 return nil, nil, err
29 }
30 if len(embedURLs) == 0 {
31 return nil, nil, fmt.Errorf("no %s streams found for episode %d", mode, epNo)
32 }
33
34 bibiembURLs, vibeplayerURLs, _ := partitionByHost(embedURLs)
35
36 for _, embedURL := range bibiembURLs {
37 stream, err := resolveBibiemb(embedURL)
38 if err != nil {
39 continue
40 }
41 return singleStreamResult(stream)
42 }
43
44 for _, embedURL := range vibeplayerURLs {
45 stream, err := resolveVibeplayer(embedURL)
46 if err != nil {
47 continue
48 }
49 return singleStreamResult(stream)
50 }
51
52 return nil, nil, fmt.Errorf("no playable streams resolved for episode %d", epNo)
53}
54
55func singleStreamResult(stream resolvedStream) ([]string, map[string]providers.StreamPlaybackHint, error) {
56 if strings.TrimSpace(stream.URL) == "" {
57 return nil, nil, fmt.Errorf("empty stream url")
58 }
59 hints := map[string]providers.StreamPlaybackHint{
60 stream.URL: {
61 Referrer: stream.Referrer,
62 Subtitle: stream.Subtitle,
63 },
64 }
65 return []string{stream.URL}, hints, nil
66}
internal/providers/anineko/substyle.go added +138
@@ -0,0 +1,138 @@
1package anineko
2
3import (
4 "fmt"
5 "strings"
6 "sync"
7
8 "github.com/wraient/curd/internal/curdhost"
9)
10
11var (
12 subStyleChoiceMu sync.Mutex
13 subStyleChosen string
14)
15
16func normalizeSubStyle(style string) string {
17 switch strings.ToLower(strings.TrimSpace(style)) {
18 case "soft":
19 return "soft"
20 case "hard":
21 return "hard"
22 default:
23 return "ask"
24 }
25}
26
27func resolveSubStylePreference(fallback string) string {
28 if curdhost.CurrentSubStyle != nil {
29 if live := normalizeSubStyle(curdhost.CurrentSubStyle()); live != "ask" {
30 return live
31 }
32 }
33
34 subStyleChoiceMu.Lock()
35 defer subStyleChoiceMu.Unlock()
36 if subStyleChosen != "" {
37 return subStyleChosen
38 }
39 return normalizeSubStyle(fallback)
40}
41
42func rememberSubStyleChoice(style string) {
43 style = normalizeSubStyle(style)
44 if style != "soft" && style != "hard" {
45 return
46 }
47
48 subStyleChoiceMu.Lock()
49 subStyleChosen = style
50 subStyleChoiceMu.Unlock()
51
52 if curdhost.PersistSubStylePreference != nil {
53 _ = curdhost.PersistSubStylePreference(style)
54 }
55}
56
57func chooseSubStyle(groups map[string][]string, preference string) (string, error) {
58 preference = resolveSubStylePreference(preference)
59 hasSoft := len(groups["sub"]) > 0
60 hasHard := len(groups["hsub"]) > 0
61
62 switch preference {
63 case "soft":
64 if hasSoft {
65 return "soft", nil
66 }
67 if hasHard {
68 return "hard", nil
69 }
70 case "hard":
71 if hasHard {
72 return "hard", nil
73 }
74 if hasSoft {
75 return "soft", nil
76 }
77 case "ask":
78 if hasSoft && hasHard {
79 if curdhost.PromptSelect == nil {
80 rememberSubStyleChoice("soft")
81 return "soft", nil
82 }
83 if curdhost.Out != nil {
84 curdhost.Out("Both soft-sub and hard-sub streams are available.")
85 }
86 selected, err := curdhost.PromptSelect([]curdhost.PromptOption{
87 {Key: "soft", Label: "Soft sub (external subtitles)"},
88 {Key: "hard", Label: "Hard sub (burned-in subtitles)"},
89 })
90 if err != nil {
91 return "", err
92 }
93 chosen := "soft"
94 if selected.Key == "hard" {
95 chosen = "hard"
96 }
97 rememberSubStyleChoice(chosen)
98 return chosen, nil
99 }
100 if hasSoft {
101 return "soft", nil
102 }
103 if hasHard {
104 return "hard", nil
105 }
106 }
107
108 return "", fmt.Errorf("no sub streams found")
109}
110
111func embedURLsForSubStyle(groups map[string][]string, style string) []string {
112 switch style {
113 case "soft":
114 return append([]string{}, groups["sub"]...)
115 case "hard":
116 return append([]string{}, groups["hsub"]...)
117 default:
118 return nil
119 }
120}
121
122func embedURLsForMode(groups map[string][]string, mode, subStyle string) ([]string, error) {
123 if strings.EqualFold(mode, "dub") {
124 return groups["dub"], nil
125 }
126
127 chosen, err := chooseSubStyle(groups, subStyle)
128 if err != nil {
129 return nil, err
130 }
131 return embedURLsForSubStyle(groups, chosen), nil
132}
133
134func resetSubStyleForTest() {
135 subStyleChoiceMu.Lock()
136 subStyleChosen = ""
137 subStyleChoiceMu.Unlock()
138}
internal/providers/anineko/vibeplayer.go added +37
@@ -0,0 +1,37 @@
1package anineko
2
3import (
4 "fmt"
5 "regexp"
6 "strings"
7)
8
9var vibeplayerMasterRE = regexp.MustCompile(`const src = "(https://vibeplayer\.site/public/stream/[^"]+/master\.m3u8)"`)
10
11func resolveVibeplayer(embedURL string) (resolvedStream, error) {
12 embedURL = strings.TrimSpace(embedURL)
13 if embedURL == "" {
14 return resolvedStream{}, fmt.Errorf("empty vibeplayer embed url")
15 }
16
17 html, err := fetchString(embedURL, baseURL+"/")
18 if err != nil {
19 return resolvedStream{}, err
20 }
21
22 match := vibeplayerMasterRE.FindStringSubmatch(html)
23 if len(match) < 2 {
24 return resolvedStream{}, fmt.Errorf("vibeplayer master m3u8 not found")
25 }
26
27 proxyURL, err := registerVibeStream(match[1], embedURL)
28 if err != nil {
29 return resolvedStream{}, err
30 }
31
32 return resolvedStream{
33 URL: proxyURL,
34 Referrer: embedURL,
35 Subtitle: subtitleFromEmbedURL(embedURL),
36 }, nil
37}
internal/providers/anineko/vibeproxy.go added +242
@@ -0,0 +1,242 @@
1package anineko
2
3import (
4 "bytes"
5 "crypto/rand"
6 "encoding/hex"
7 "fmt"
8 "io"
9 "net"
10 "net/http"
11 "strconv"
12 "strings"
13 "sync"
14)
15
16var pngIENDMarker = []byte{0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}
17
18var (
19 vibeProxyMu sync.Mutex
20 vibeProxyServer *vibeProxy
21)
22
23type vibeSession struct {
24 masterURL string
25 referer string
26 variants map[string][]vibeSegment
27}
28
29type vibeSegment struct {
30 duration float64
31 url string
32}
33
34type vibeProxy struct {
35 baseURL string
36 server *http.Server
37 sessions map[string]*vibeSession
38}
39
40func registerVibeStream(masterURL, referer string) (string, error) {
41 proxy, err := getVibeProxy()
42 if err != nil {
43 return "", err
44 }
45 return proxy.register(masterURL, referer)
46}
47
48func getVibeProxy() (*vibeProxy, error) {
49 vibeProxyMu.Lock()
50 defer vibeProxyMu.Unlock()
51
52 if vibeProxyServer != nil {
53 return vibeProxyServer, nil
54 }
55
56 proxy := &vibeProxy{sessions: map[string]*vibeSession{}}
57 mux := http.NewServeMux()
58 mux.HandleFunc("/stream/", proxy.handle)
59 server := &http.Server{Handler: mux}
60
61 listener, err := net.Listen("tcp", "127.0.0.1:0")
62 if err != nil {
63 return nil, fmt.Errorf("start vibe proxy listener: %w", err)
64 }
65 proxy.server = server
66 proxy.baseURL = "http://" + listener.Addr().String()
67
68 go func() {
69 _ = server.Serve(listener)
70 }()
71
72 vibeProxyServer = proxy
73 return proxy, nil
74}
75
76func (p *vibeProxy) register(masterURL, referer string) (string, error) {
77 id, err := randomSessionID()
78 if err != nil {
79 return "", err
80 }
81 vibeProxyMu.Lock()
82 p.sessions[id] = &vibeSession{
83 masterURL: masterURL,
84 referer: referer,
85 variants: map[string][]vibeSegment{},
86 }
87 vibeProxyMu.Unlock()
88 return p.baseURL + "/stream/" + id + "/master.m3u8", nil
89}
90
91func (p *vibeProxy) handle(w http.ResponseWriter, r *http.Request) {
92 path := strings.TrimPrefix(r.URL.Path, "/stream/")
93 parts := strings.Split(path, "/")
94 if len(parts) < 2 {
95 http.NotFound(w, r)
96 return
97 }
98 sessionID := parts[0]
99
100 vibeProxyMu.Lock()
101 session, ok := p.sessions[sessionID]
102 vibeProxyMu.Unlock()
103 if !ok {
104 http.NotFound(w, r)
105 return
106 }
107
108 switch {
109 case len(parts) == 2 && parts[1] == "master.m3u8":
110 p.serveMaster(w, sessionID, session, parts[1])
111 case len(parts) == 2 && strings.HasSuffix(parts[1], ".m3u8"):
112 p.serveVariant(w, sessionID, session, parts[1])
113 case len(parts) == 4 && parts[2] == "seg":
114 p.serveSegment(w, r, session, parts[1], parts[3])
115 default:
116 http.NotFound(w, r)
117 }
118}
119
120func (p *vibeProxy) serveMaster(w http.ResponseWriter, sessionID string, session *vibeSession, _ string) {
121 body, err := fetchString(session.masterURL, session.referer)
122 if err != nil {
123 http.Error(w, err.Error(), http.StatusBadGateway)
124 return
125 }
126 rewritten := rewritePlaylistLines(body, func(line string) string {
127 line = strings.TrimSpace(line)
128 if line == "" || strings.HasPrefix(line, "#") {
129 return line
130 }
131 return p.baseURL + "/stream/" + sessionID + "/" + line
132 })
133 writePlaylist(w, rewritten)
134}
135
136func (p *vibeProxy) serveVariant(w http.ResponseWriter, sessionID string, session *vibeSession, variantName string) {
137 variantURL := resolvePlaylistURL(session.masterURL, variantName)
138 body, err := fetchString(variantURL, session.referer)
139 if err != nil {
140 http.Error(w, err.Error(), http.StatusBadGateway)
141 return
142 }
143
144 segments := make([]vibeSegment, 0)
145 var currentDuration float64
146 rewritten := rewritePlaylistLines(body, func(line string) string {
147 line = strings.TrimSpace(line)
148 if strings.HasPrefix(line, "#EXTINF:") {
149 currentDuration = parseExtInfDuration(line)
150 return line
151 }
152 if line == "" || strings.HasPrefix(line, "#") {
153 return line
154 }
155 segmentURL := resolvePlaylistURL(variantURL, line)
156 index := len(segments)
157 segments = append(segments, vibeSegment{duration: currentDuration, url: segmentURL})
158 return fmt.Sprintf("%s/stream/%s/%s/seg/%d", p.baseURL, sessionID, variantName, index)
159 })
160
161 vibeProxyMu.Lock()
162 session.variants[variantName] = segments
163 vibeProxyMu.Unlock()
164
165 writePlaylist(w, rewritten)
166}
167
168func (p *vibeProxy) serveSegment(w http.ResponseWriter, r *http.Request, session *vibeSession, variantName, indexText string) {
169 index, err := strconv.Atoi(indexText)
170 if err != nil || index < 0 {
171 http.NotFound(w, r)
172 return
173 }
174
175 vibeProxyMu.Lock()
176 segments := session.variants[variantName]
177 vibeProxyMu.Unlock()
178 if index >= len(segments) {
179 http.NotFound(w, r)
180 return
181 }
182
183 data, err := fetchBytes(segments[index].url, session.referer)
184 if err != nil {
185 http.Error(w, err.Error(), http.StatusBadGateway)
186 return
187 }
188 body := stripPNGWrapper(data)
189 w.Header().Set("Content-Type", "video/mp2t")
190 w.Header().Set("Content-Length", strconv.Itoa(len(body)))
191 _, _ = w.Write(body)
192}
193
194func rewritePlaylistLines(playlist string, mapLine func(string) string) string {
195 lines := strings.Split(strings.ReplaceAll(playlist, "\r\n", "\n"), "\n")
196 for i, line := range lines {
197 lines[i] = mapLine(line)
198 }
199 return strings.Join(lines, "\n")
200}
201
202func parseExtInfDuration(line string) float64 {
203 line = strings.TrimPrefix(strings.TrimSpace(line), "#EXTINF:")
204 if idx := strings.Index(line, ","); idx >= 0 {
205 line = line[:idx]
206 }
207 value, err := strconv.ParseFloat(strings.TrimSpace(line), 64)
208 if err != nil {
209 return 0
210 }
211 return value
212}
213
214func stripPNGWrapper(data []byte) []byte {
215 idx := bytes.Index(data, pngIENDMarker)
216 if idx < 0 {
217 return data
218 }
219 return data[idx+len(pngIENDMarker):]
220}
221
222func writePlaylist(w http.ResponseWriter, body string) {
223 w.Header().Set("Content-Type", "application/vnd.apple.mpegurl")
224 _, _ = io.WriteString(w, body)
225}
226
227func randomSessionID() (string, error) {
228 buf := make([]byte, 8)
229 if _, err := rand.Read(buf); err != nil {
230 return "", err
231 }
232 return hex.EncodeToString(buf), nil
233}
234
235func resetVibeProxyForTest() {
236 vibeProxyMu.Lock()
237 defer vibeProxyMu.Unlock()
238 if vibeProxyServer != nil && vibeProxyServer.server != nil {
239 _ = vibeProxyServer.server.Close()
240 }
241 vibeProxyServer = nil
242}
internal/providers/lang.go added +17
@@ -0,0 +1,17 @@
1package providers
2
3import "strings"
4
5func NormalizeTranslationType(mode string) string {
6 if strings.EqualFold(strings.TrimSpace(mode), "dub") {
7 return "dub"
8 }
9 return "sub"
10}
11
12func AlternateTranslationType(mode string) string {
13 if NormalizeTranslationType(mode) == "dub" {
14 return "sub"
15 }
16 return "dub"
17}
internal/providers/registry.go added +170
@@ -0,0 +1,170 @@
1package providers
2
3import (
4 "fmt"
5 "sort"
6 "strings"
7 "sync"
8)
9
10// Meta describes a registered streaming provider.
11type Meta struct {
12 Name string
13 Aliases []string
14 Referrer string
15 DefaultDisabled bool
16 DisableReason string
17 // OptOutToken excludes a provider from automatic fallback prompts, e.g. "no-animepahe".
18 OptOutToken string
19 // FallbackPrompt is shown when the host offers this provider as a fallback.
20 FallbackPrompt string
21}
22
23type entry struct {
24 meta Meta
25 factory func() Provider
26}
27
28var (
29 registryMu sync.RWMutex
30 registry = map[string]entry{}
31 aliases = map[string]string{}
32)
33
34// Register adds a provider factory to the global registry.
35func Register(meta Meta, factory func() Provider) {
36 registryMu.Lock()
37 defer registryMu.Unlock()
38
39 meta.Name = strings.ToLower(strings.Trim(strings.TrimSpace(meta.Name), "\"'[]"))
40 if meta.Name == "" {
41 panic("providers.Register: Name is required")
42 }
43 if factory == nil {
44 panic("providers.Register: factory is required")
45 }
46
47 meta.Name = strings.ReplaceAll(strings.ReplaceAll(meta.Name, "-", ""), " ", "")
48 if meta.Name == "" {
49 panic("providers.Register: Name is required")
50 }
51
52 registry[meta.Name] = entry{meta: meta, factory: factory}
53 registerAlias(meta.Name, meta.Name)
54 for _, alias := range meta.Aliases {
55 registerAlias(alias, meta.Name)
56 }
57}
58
59func registerAlias(alias, canonical string) {
60 alias = strings.Trim(strings.TrimSpace(alias), "\"'[]")
61 if alias == "" {
62 return
63 }
64 aliases[strings.ToLower(strings.Join(strings.Fields(alias), " "))] = canonical
65 compact := strings.ToLower(alias)
66 compact = strings.ReplaceAll(compact, "-", "")
67 compact = strings.ReplaceAll(compact, "_", "")
68 compact = strings.ReplaceAll(compact, " ", "")
69 if compact != "" {
70 aliases[compact] = canonical
71 }
72}
73
74// NormalizeName maps user/config input to a canonical provider name.
75func NormalizeName(name string) string {
76 registryMu.RLock()
77 defer registryMu.RUnlock()
78 return normalizeName(name)
79}
80
81func normalizeName(name string) string {
82 name = strings.Trim(strings.TrimSpace(name), "\"'[]")
83 if name == "" {
84 return ""
85 }
86 key := strings.ToLower(strings.Join(strings.Fields(name), " "))
87 if canonical, ok := aliases[key]; ok {
88 return canonical
89 }
90 key = strings.ReplaceAll(key, "-", "")
91 key = strings.ReplaceAll(key, "_", "")
92 key = strings.ReplaceAll(key, " ", "")
93 if canonical, ok := aliases[key]; ok {
94 return canonical
95 }
96 return ""
97}
98
99// MetaFor returns registration metadata for a provider name.
100func MetaFor(name string) (Meta, bool) {
101 registryMu.RLock()
102 defer registryMu.RUnlock()
103
104 name = normalizeName(name)
105 if name == "" {
106 return Meta{}, false
107 }
108 entry, ok := registry[name]
109 if !ok {
110 return Meta{}, false
111 }
112 return entry.meta, true
113}
114
115// RegisteredNames returns sorted canonical provider names.
116func RegisteredNames() []string {
117 registryMu.RLock()
118 defer registryMu.RUnlock()
119
120 names := make([]string, 0, len(registry))
121 for name := range registry {
122 names = append(names, name)
123 }
124 sort.Strings(names)
125 return names
126}
127
128// New creates a provider instance by canonical name.
129func New(name string) (Provider, error) {
130 registryMu.RLock()
131 defer registryMu.RUnlock()
132
133 name = normalizeName(name)
134 if name == "" {
135 return nil, fmt.Errorf("unknown provider %q", name)
136 }
137 entry, ok := registry[name]
138 if !ok {
139 return nil, fmt.Errorf("unknown provider %q", name)
140 }
141 return entry.factory(), nil
142}
143
144// Referrer returns the stream referrer for a provider, if configured.
145func Referrer(name string) string {
146 meta, ok := MetaFor(name)
147 if !ok {
148 return ""
149 }
150 return meta.Referrer
151}
152
153// SetFactoryForTest overrides a provider factory for the duration of a test.
154func SetFactoryForTest(name string, factory func() Provider) (restore func()) {
155 registryMu.Lock()
156 defer registryMu.Unlock()
157
158 name = normalizeName(name)
159 previous, ok := registry[name]
160 if !ok {
161 panic(fmt.Sprintf("providers.SetFactoryForTest: unknown provider %q", name))
162 }
163
164 registry[name] = entry{meta: previous.meta, factory: factory}
165 return func() {
166 registryMu.Lock()
167 registry[name] = previous
168 registryMu.Unlock()
169 }
170}
internal/providers/types.go added +46
@@ -0,0 +1,46 @@
1package providers
2
3// SelectionOption is a provider search or menu result item.
4type SelectionOption struct {
5 Key string
6 Label string
7 Title string
8 Thumbnail string
9 ExtraData any
10}
11
12// PlaybackConfig carries playback preferences passed into providers.
13type PlaybackConfig struct {
14 SubOrDub string
15 // SubStyle controls anineko subtitle stream tabs: ask, soft, or hard.
16 SubStyle string
17}
18
19// StreamPlaybackHint carries MPV playback metadata for a resolved stream URL.
20type StreamPlaybackHint struct {
21 Referrer string
22 Subtitle string
23}
24
25// Provider resolves catalog search, episode lists, and stream URLs.
26type Provider interface {
27 Name() string
28 SearchAnime(query, mode string) ([]SelectionOption, error)
29 EpisodesList(showID, mode string) ([]string, error)
30 GetEpisodeURL(config PlaybackConfig, id string, epNo int) ([]string, error)
31}
32
33// ModeResolver resolves episode URLs for an explicit sub/dub mode.
34type ModeResolver interface {
35 GetEpisodeURLForMode(config PlaybackConfig, id string, epNo int, mode string) ([]string, error)
36}
37
38// HintResolver resolves episode URLs with MPV playback hints.
39type HintResolver interface {
40 GetEpisodeURLForModeWithHints(config PlaybackConfig, id string, epNo int, mode string) ([]string, map[string]StreamPlaybackHint, error)
41}
42
43// IDResolver refreshes or validates a provider-specific show ID.
44type IDResolver interface {
45 ResolveProviderID(providerID, query string) (string, error)
46}
internal/selection_labels.go added +199
@@ -0,0 +1,199 @@
1package internal
2
3import (
4 "fmt"
5 "regexp"
6 "strconv"
7 "strings"
8
9 "github.com/wraient/curd/internal/providers/animepahe"
10)
11
12var selectionEpisodeCountRE = regexp.MustCompile(`\((\d+)\s+episodes?\)`)
13
14func FormatAnimeSearchLabel(title string, episodes int) string {
15 title = strings.TrimSpace(title)
16 if title == "" {
17 return ""
18 }
19 if episodes > 0 {
20 return fmt.Sprintf("%s (%d episodes)", title, episodes)
21 }
22 return title
23}
24
25func TrackerEpisodeHint(config *CurdConfig, entry *Entry) string {
26 if entry == nil || entry.Media.Episodes <= 0 {
27 return ""
28 }
29 tracker := RemoteTrackingDisplayName(config)
30 title := mediaDisplayTitle(entry.Media, config)
31 if title == "" {
32 return fmt.Sprintf("Your %s entry has %d episodes — pick the matching title below.", tracker, entry.Media.Episodes)
33 }
34 return fmt.Sprintf("Your %s entry for %q has %d episodes — pick the matching title below.", tracker, title, entry.Media.Episodes)
35}
36
37func episodeCountFromSelectionOption(option SelectionOption) (int, bool) {
38 for _, source := range []string{option.Label, option.Title} {
39 if source == "" {
40 continue
41 }
42 if matches := selectionEpisodeCountRE.FindStringSubmatch(source); len(matches) > 1 {
43 if count, err := strconv.Atoi(matches[1]); err == nil && count > 0 {
44 return count, true
45 }
46 }
47 }
48
49 if option.ExtraData != nil {
50 if item, ok := option.ExtraData.(animepahe.SearchItem); ok && item.Episodes > 0 {
51 return item.Episodes, true
52 }
53 }
54
55 return 0, false
56}
57
58func selectionOptionBaseTitle(option SelectionOption) string {
59 if option.Title != "" {
60 return strings.TrimSpace(option.Title)
61 }
62
63 label := strings.TrimSpace(option.Label)
64 if label == "" {
65 return ""
66 }
67 if idx := strings.Index(label, " ("); idx > 0 {
68 return strings.TrimSpace(label[:idx])
69 }
70 if idx := strings.Index(label, " — "); idx > 0 {
71 return strings.TrimSpace(label[:idx])
72 }
73 if idx := strings.Index(label, " ["); idx > 0 {
74 return strings.TrimSpace(label[:idx])
75 }
76 return label
77}
78
79func ensureEpisodeCountInLabel(option SelectionOption) SelectionOption {
80 if selectionEpisodeCountRE.MatchString(option.Label) {
81 return option
82 }
83
84 count, ok := episodeCountFromSelectionOption(option)
85 if !ok || count <= 0 {
86 return option
87 }
88
89 baseTitle := selectionOptionBaseTitle(option)
90 if baseTitle == "" {
91 return option
92 }
93
94 providerSuffix := ""
95 if idx := strings.LastIndex(option.Label, " ["); idx > 0 && strings.HasSuffix(option.Label, "]") {
96 providerSuffix = option.Label[idx:]
97 }
98
99 option.Label = FormatAnimeSearchLabel(baseTitle, count) + providerSuffix
100 if option.Title == "" {
101 option.Title = baseTitle
102 }
103 return option
104}
105
106func ProviderSearchOptionsForDisplay(options []SelectionOption, entry *Entry) []SelectionOption {
107 if len(options) == 0 {
108 return options
109 }
110
111 targetEpisodes := 0
112 if entry != nil {
113 targetEpisodes = entry.Media.Episodes
114 }
115
116 display := make([]SelectionOption, len(options))
117 for i, option := range options {
118 display[i] = ensureEpisodeCountInLabel(option)
119 if targetEpisodes <= 0 {
120 continue
121 }
122 if count, ok := episodeCountFromSelectionOption(display[i]); ok && count == targetEpisodes {
123 display[i].Label = display[i].Label + " ✓"
124 }
125 }
126 return display
127}
128
129func ManualProviderSearchEnabled(config *CurdConfig) bool {
130 return config != nil && config.ManualProviderSearch
131}
132
133func displayMediaFormat(format string) string {
134 format = strings.TrimSpace(strings.ToUpper(format))
135 switch format {
136 case "TV":
137 return "TV"
138 case "TV_SHORT":
139 return "TV Short"
140 case "MOVIE":
141 return "Movie"
142 case "OVA":
143 return "OVA"
144 case "ONA":
145 return "ONA"
146 case "SPECIAL":
147 return "Special"
148 case "MUSIC":
149 return "Music"
150 default:
151 return strings.ReplaceAll(format, "_", " ")
152 }
153}
154
155func formatEpisodeCountHint(episodes int) string {
156 if episodes > 0 {
157 return fmt.Sprintf("%d episodes", episodes)
158 }
159 return "unknown episode count"
160}
161
162func ManualProviderSearchHint(config *CurdConfig, entry *Entry, query, subOrDub string) string {
163 title := strings.TrimSpace(query)
164 mediaType := ""
165 episodes := 0
166
167 if entry != nil {
168 if trackerTitle := mediaDisplayTitle(entry.Media, config); trackerTitle != "" {
169 title = trackerTitle
170 }
171 mediaType = displayMediaFormat(entry.Media.Format)
172 episodes = entry.Media.Episodes
173 }
174 if title == "" {
175 title = "unknown title"
176 }
177
178 mode := strings.ToLower(normalizeTranslationType(subOrDub))
179 parts := []string{fmt.Sprintf("Searching for %q", title)}
180 if mediaType != "" {
181 parts = append(parts, mediaType)
182 }
183 parts = append(parts, formatEpisodeCountHint(episodes))
184 if mode != "" {
185 parts = append(parts, mode)
186 }
187 return strings.Join(parts, " · ") + " — select the matching provider entry below."
188}
189
190func promptProviderSearchSelectionWithHint(config *CurdConfig, options []SelectionOption, entry *Entry, hint string) (SelectionOption, error) {
191 if strings.TrimSpace(hint) != "" {
192 CurdOut(hint)
193 }
194 return DynamicSelect(ProviderSearchOptionsForDisplay(options, entry))
195}
196
197func promptProviderSearchSelection(config *CurdConfig, options []SelectionOption, entry *Entry) (SelectionOption, error) {
198 return promptProviderSearchSelectionWithHint(config, options, entry, TrackerEpisodeHint(config, entry))
199}
internal/selection_labels_test.go added +75
@@ -0,0 +1,75 @@
1package internal
2
3import (
4 "strings"
5 "testing"
6
7 "github.com/wraient/curd/internal/providers/animepahe"
8)
9
10func TestFormatAnimeSearchLabel(t *testing.T) {
11 if got := FormatAnimeSearchLabel("Frieren", 28); got != "Frieren (28 episodes)" {
12 t.Fatalf("unexpected label: %q", got)
13 }
14 if got := FormatAnimeSearchLabel("Airing Show", 0); got != "Airing Show" {
15 t.Fatalf("unexpected label without episodes: %q", got)
16 }
17}
18
19func TestProviderSearchOptionsForDisplayMarksEpisodeMatch(t *testing.T) {
20 options := []SelectionOption{
21 {Key: "a", Label: "One Piece (1090 episodes) [allanime]", Title: "One Piece"},
22 {Key: "b", Label: "One Pace (300 episodes) [anineko]", Title: "One Pace"},
23 }
24 entry := &Entry{Media: Media{Episodes: 1090}}
25
26 display := ProviderSearchOptionsForDisplay(options, entry)
27 if display[0].Label != "One Piece (1090 episodes) [allanime] ✓" {
28 t.Fatalf("expected match marker on first option, got %q", display[0].Label)
29 }
30 if display[1].Label != "One Pace (300 episodes) [anineko]" {
31 t.Fatalf("expected unchanged second option, got %q", display[1].Label)
32 }
33}
34
35func TestManualProviderSearchHint(t *testing.T) {
36 entry := &Entry{
37 Media: Media{
38 Format: "TV",
39 Episodes: 24,
40 Title: AnimeTitle{
41 Romaji: "Frieren",
42 },
43 },
44 }
45 hint := ManualProviderSearchHint(&CurdConfig{SubOrDub: "sub"}, entry, "frieren", "sub")
46 if !strings.Contains(hint, `Searching for "Frieren"`) {
47 t.Fatalf("unexpected hint: %q", hint)
48 }
49 if !strings.Contains(hint, "TV") || !strings.Contains(hint, "24 episodes") || !strings.Contains(hint, "sub") {
50 t.Fatalf("expected type, episode count, and mode in hint: %q", hint)
51 }
52}
53
54func TestManualProviderSearchEnabled(t *testing.T) {
55 if ManualProviderSearchEnabled(&CurdConfig{ManualProviderSearch: true}) != true {
56 t.Fatal("expected manual provider search to be enabled")
57 }
58 if ManualProviderSearchEnabled(&CurdConfig{}) != false {
59 t.Fatal("expected manual provider search to be disabled by default")
60 }
61}
62
63func TestEnsureEpisodeCountInLabelUsesExtraData(t *testing.T) {
64 option := SelectionOption{
65 Key: "session",
66 Label: "Frieren [animepahe]",
67 Title: "Frieren",
68 ExtraData: animepahe.SearchItem{Title: "Frieren", Episodes: 28},
69 }
70
71 display := ensureEpisodeCountInLabel(option)
72 if display.Label != "Frieren (28 episodes) [animepahe]" {
73 t.Fatalf("unexpected label: %q", display.Label)
74 }
75}
internal/structs.go +10 −2
@@ -71,6 +71,12 @@ type NextEpisode struct {
7171 Mode string
7272}
7373
74// StreamPlaybackHint carries MPV playback metadata for a resolved stream URL.
75type StreamPlaybackHint struct {
76 Referrer string
77 Subtitle string
78}
79
7480type playingVideo struct {
7581 Url string
7682 Speed float64 `json:"speed"`
@@ -98,8 +104,9 @@ func GetGlobalUser() *User {
98104
99105// AniListAnime is the struct for the API response
100106type AniListAnime struct {
101 ID int `json:"id"`
102 Title struct {
107 ID int `json:"id"`
108 Episodes int `json:"episodes"`
109 Title struct {
103110 Romaji string `json:"romaji"`
104111 English string `json:"english"`
105112 Native string `json:"native"`
@@ -122,6 +129,7 @@ type ResponseData struct {
122129type Media struct {
123130 Duration int `json:"duration"`
124131 Episodes int `json:"episodes"`
132 Format string `json:"format"`
125133 ID int `json:"id"`
126134 MalID int `json:"mal_id"`
127135 Title AnimeTitle `json:"title"`
internal/tracking.go +1 −1
@@ -70,7 +70,7 @@ func UsesDualRemoteTracking(config *CurdConfig) bool {
7070
7171func trackingCategoryEnabled(config *CurdConfig, key string) bool {
7272 switch key {
73 case "CURRENT", "ALL", "UNTRACKED", "CONTINUE_LAST", "PROVIDER":
73 case "CURRENT", "ALL", "UNTRACKED", "CONTINUE_LAST", "REMAP_PROVIDER", "PROVIDER":
7474 return true
7575 case "UPDATE", "PLANNING", "COMPLETED", "PAUSED", "DROPPED", "REWATCHING":
7676 return UsesRemoteTracking(config)
internal/user_intent_regression_test.go +8 −1
@@ -141,6 +141,7 @@ func TestGetProviderTotalEpisodesReturnsLookupErrorsWhenNoEpisodesFound(t *testi
141141}
142142
143143func TestGetAllAnimeEpisodesListUsesValidGraphQLVariableSyntax(t *testing.T) {
144 withAllProvidersEnabledForTest(t)
144145 previousClient := sharedHTTPClient
145146 t.Cleanup(func() {
146147 sharedHTTPClient = previousClient
@@ -163,7 +164,13 @@ func TestGetAllAnimeEpisodesListUsesValidGraphQLVariableSyntax(t *testing.T) {
163164 return testHTTPResponse(req, http.StatusOK, `{"data":{"show":{"_id":"show-id","availableEpisodesDetail":{"sub":[1,2,12]}}}}`), nil
164165 })}
165166
166 episodes, err := getAllAnimeEpisodesList("show-id", "sub")
167 episodes, err := func() ([]string, error) {
168 provider, err := ProviderByName("allanime")
169 if err != nil {
170 return nil, err
171 }
172 return provider.EpisodesList("show-id", "sub")
173 }()
167174 if err != nil {
168175 t.Fatalf("expected allanime episode list lookup to succeed: %v", err)
169176 }