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 @@
1[Setup] 1[Setup]
2AppName=Curd Installer 2AppName=Curd Installer
3AppVersion=1.5.1 3AppVersion=1.5.3
4DefaultDirName={userappdata}\Curd 4DefaultDirName={userappdata}\Curd
5PrivilegesRequired=lowest 5PrivilegesRequired=lowest
6AllowNoIcons=yes 6AllowNoIcons=yes
README.md +8 −3
@@ -24,7 +24,7 @@ https://github.com/user-attachments/assets/cbf799bc-9fdd-4402-ab61-b4e31f1e264d
24 24
25 25
26## Features 26## 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
28- Built-in headless browser to bypass Cloudflare/DDoS-Guard protections 28- Built-in headless browser to bypass Cloudflare/DDoS-Guard protections
29- Stream anime online 29- Stream anime online
30- Track anime locally, on AniList, or on MyAnimeList 30- Track anime locally, on AniList, or on MyAnimeList
@@ -299,6 +299,8 @@ curd [options]
299| `-change-token` | Change your authentication token | - | 299| `-change-token` | Change your authentication token | - |
300| `-dub` | Watch the dubbed version of the anime | - | 300| `-dub` | Watch the dubbed version of the anime | - |
301| `-sub` | Watch the subbed version of the anime | - | 301| `-sub` | Watch the subbed version of the anime | - |
302| `-softsub` | Prefer soft subtitles when available (AniNeko) | - |
303| `-hardsub` | Prefer hard subtitles when available (AniNeko) | - |
302| `-new` | Add a new anime to your list | - | 304| `-new` | Add a new anime to your list | - |
303| `-e` | Edit the configuration file | - | 305| `-e` | Edit the configuration file | - |
304| `-skip-op` | Automatically skip the opening section of each episode | `true` | 306| `-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
381| `PercentageToMarkComplete`| Integer | `0` to `100` | Sets the percentage of an episode watched to consider it as completed. | 383| `PercentageToMarkComplete`| Integer | `0` to `100` | Sets the percentage of an episode watched to consider it as completed. |
382| `StoragePath` | String | Any valid path (Environment variables accepted) | Specifies the directory where Curd stores its data. | 384| `StoragePath` | String | Any valid path (Environment variables accepted) | Specifies the directory where Curd stores its data. |
383| `SubOrDub` | Enum | `sub`, `dub` | Sets the preferred format for anime audio. | 385| `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` |
384| `NextEpisodePrompt` | Boolean | `true`, `false` | Prompts the user before automatically playing the next episode. | 387| `NextEpisodePrompt` | Boolean | `true`, `false` | Prompts the user before automatically playing the next episode. |
385| `SubsLanguage` | String | `english` (redundant rn) | Sets the preferred subtitle language. | 388| `SubsLanguage` | String | `english` (redundant rn) | Sets the preferred subtitle language. |
386| `ScoreOnCompletion` | Boolean | `true`, `false` | Automatically prompts the user to rate the anime upon completion. | 389| `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
391| `Player` | String | any mpv-compatible binary (e.g. `mpv`, `iina`) | Player binary used for playback. If not found, Curd falls back to `mpv`. | 394| `Player` | String | any mpv-compatible binary (e.g. `mpv`, `iina`) | Player binary used for playback. If not found, Curd falls back to `mpv`. |
392| `SaveMpvSpeed` | Boolean | `true`, `false` | Retains the playback speed set in MPV for next episode. | 395| `SaveMpvSpeed` | Boolean | `true`, `false` | Retains the playback speed set in MPV for next episode. |
393| `SkipFiller` | Boolean | `true`, `false` | Skips filler episodes when supported. | 396| `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` | 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` |
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"]` | 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` |
396| `TrackingLocal` | Boolean | `true` | Legacy compatibility flag. Local playback history is always enabled. | 400| `TrackingLocal` | Boolean | `true` | Legacy compatibility flag. Local playback history is always enabled. |
397| `TrackingRemote` | Enum | `none`, `anilist`, `myanimelist`, `anilist+myanimelist` | Selects which remote tracker curd syncs with. | 401| `TrackingRemote` | Enum | `none`, `anilist`, `myanimelist`, `anilist+myanimelist` | Selects which remote tracker curd syncs with. |
398| `TrackingConfigured` | Boolean | `true`, `false` | Internal flag used to remember that the startup tracking prompt has already been completed. | 402| `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
416- [MyAnimeList API](https://myanimelist.net/apiconfig/references/api/v2) - MyAnimeList OAuth and tracking sync 420- [MyAnimeList API](https://myanimelist.net/apiconfig/references/api/v2) - MyAnimeList OAuth and tracking sync
417- [AniSkip API](https://api.aniskip.com/api-docs) - Get anime intro and outro timings 421- [AniSkip API](https://api.aniskip.com/api-docs) - Get anime intro and outro timings
418- [AllAnime Content](https://allanime.to/) - Fetch anime url 422- [AllAnime Content](https://allanime.to/) - Fetch anime url
423- [AniNeko Content](https://anineko.to/) - Alternative provider with soft/hard sub stream selection
419- [Animepahe Content](https://animepahe.pw/) - Alternative provider for 1080p streams 424- [Animepahe Content](https://animepahe.pw/) - Alternative provider for 1080p streams
420- [Jikan](https://jikan.moe/) - Get filler episode number 425- [Jikan](https://jikan.moe/) - Get filler episode number
421 426
cmd/curd/main.go +7
@@ -82,6 +82,8 @@ func main() {
82 editConfig := flag.Bool("e", false, "Edit config") 82 editConfig := flag.Bool("e", false, "Edit config")
83 subFlag := flag.Bool("sub", false, "Watch sub version") 83 subFlag := flag.Bool("sub", false, "Watch sub version")
84 dubFlag := flag.Bool("dub", false, "Watch dub version") 84 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)")
85 versionFlag := flag.Bool("v", false, "Print version information") 87 versionFlag := flag.Bool("v", false, "Print version information")
86 88
87 // Custom help/usage function 89 // Custom help/usage function
@@ -183,6 +185,11 @@ func main() {
183 } else if *dubFlag { 185 } else if *dubFlag {
184 userCurdConfig.SubOrDub = "dub" 186 userCurdConfig.SubOrDub = "dub"
185 } 187 }
188 if *softSubFlag {
189 userCurdConfig.SubStyle = "soft"
190 } else if *hardSubFlag {
191 userCurdConfig.SubStyle = "hard"
192 }
186 193
187 // Get the token from the token file for the configured remote tracker. 194 // Get the token from the token file for the configured remote tracker.
188 if internal.UsesRemoteTracking(&userCurdConfig) { 195 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 {
141} 141}
142 142
143func doAniListSearchRequest(url string, requestBody []byte, token string) ([]byte, error) { 143func 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) {
144 client := sharedHTTPClient 166 client := sharedHTTPClient
145 if client == nil { 167 if client == nil {
146 client = &http.Client{Timeout: 15 * time.Second} 168 client = &http.Client{Timeout: 15 * time.Second}
@@ -197,6 +219,7 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
197 Page(page: 1, perPage: 50) { 219 Page(page: 1, perPage: 50) {
198 media(search: $search, type: ANIME) { 220 media(search: $search, type: ANIME) {
199 id 221 id
222 episodes
200 title { 223 title {
201 romaji 224 romaji
202 english 225 english
@@ -233,10 +256,11 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
233 animeDict := make(map[string]RofiSelectPreview) 256 animeDict := make(map[string]RofiSelectPreview)
234 257
235 type scoredAnime struct { 258 type scoredAnime struct {
236 id string 259 id string
237 title string 260 title string
238 cover string 261 cover string
239 score int 262 episodes int
263 score int
240 } 264 }
241 var scored []scoredAnime 265 var scored []scoredAnime
242 for _, anime := range animeList { 266 for _, anime := range animeList {
@@ -247,7 +271,7 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
247 } 271 }
248 cover := anime.CoverImage.Large 272 cover := anime.CoverImage.Large
249 score := levenshtein(title, query) 273 score := levenshtein(title, query)
250 scored = append(scored, scoredAnime{idStr, title, cover, score}) 274 scored = append(scored, scoredAnime{idStr, title, cover, anime.Episodes, score})
251 } 275 }
252 sort.Slice(scored, func(i, j int) bool { 276 sort.Slice(scored, func(i, j int) bool {
253 return scored[i].score < scored[j].score 277 return scored[i].score < scored[j].score
@@ -257,7 +281,7 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
257 break 281 break
258 } 282 }
259 animeDict[s.id] = RofiSelectPreview{ 283 animeDict[s.id] = RofiSelectPreview{
260 Title: s.title, 284 Title: FormatAnimeSearchLabel(s.title, s.episodes),
261 CoverImage: s.cover, 285 CoverImage: s.cover,
262 } 286 }
263 } 287 }
@@ -273,6 +297,7 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
273 Page(page: 1, perPage: 50) { 297 Page(page: 1, perPage: 50) {
274 media(search: $search, type: ANIME) { 298 media(search: $search, type: ANIME) {
275 id 299 id
300 episodes
276 title { 301 title {
277 romaji 302 romaji
278 english 303 english
@@ -306,9 +331,10 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
306 var results []SelectionOption 331 var results []SelectionOption
307 332
308 type scoredAnime struct { 333 type scoredAnime struct {
309 id string 334 id string
310 title string 335 title string
311 score int 336 episodes int
337 score int
312 } 338 }
313 var scored []scoredAnime 339 var scored []scoredAnime
314 for _, anime := range animeList { 340 for _, anime := range animeList {
@@ -318,7 +344,7 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
318 title = anime.Title.Romaji 344 title = anime.Title.Romaji
319 } 345 }
320 score := levenshtein(title, query) 346 score := levenshtein(title, query)
321 scored = append(scored, scoredAnime{idStr, title, score}) 347 scored = append(scored, scoredAnime{idStr, title, anime.Episodes, score})
322 } 348 }
323 sort.Slice(scored, func(i, j int) bool { 349 sort.Slice(scored, func(i, j int) bool {
324 return scored[i].score < scored[j].score 350 return scored[i].score < scored[j].score
@@ -329,7 +355,8 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
329 } 355 }
330 results = append(results, SelectionOption{ 356 results = append(results, SelectionOption{
331 Key: s.id, 357 Key: s.id,
332 Label: s.title, 358 Label: FormatAnimeSearchLabel(s.title, s.episodes),
359 Title: s.title,
333 }) 360 })
334 } 361 }
335 return results, nil 362 return results, nil
@@ -497,6 +524,7 @@ func GetUserData(token string, userID int) (map[string]interface{}, error) {
497 idMal 524 idMal
498 episodes 525 episodes
499 duration 526 duration
527 format
500 title { 528 title {
501 romaji 529 romaji
502 english 530 english
@@ -554,6 +582,7 @@ func GetUserDataPreview(token string, userID int) (map[string]interface{}, error
554 idMal 582 idMal
555 episodes 583 episodes
556 duration 584 duration
585 format
557 coverImage { 586 coverImage {
558 large 587 large
559 } 588 }
@@ -872,6 +901,39 @@ func makePostRequest(url, query string, variables map[string]interface{}, header
872 return nil, fmt.Errorf("failed to marshal request body: %w", err) 901 return nil, fmt.Errorf("failed to marshal request body: %w", err)
873 } 902 }
874 903
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) {
875 client := sharedHTTPClient 937 client := sharedHTTPClient
876 if client == nil { 938 if client == nil {
877 client = &http.Client{Timeout: 15 * time.Second} 939 client = &http.Client{Timeout: 15 * time.Second}
@@ -1016,6 +1078,7 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
1016 Media: Media{ 1078 Media: Media{
1017 Duration: toInt(media["duration"]), 1079 Duration: toInt(media["duration"]),
1018 Episodes: toInt(media["episodes"]), 1080 Episodes: toInt(media["episodes"]),
1081 Format: safeString(media["format"]),
1019 ID: toInt(media["id"]), 1082 ID: toInt(media["id"]),
1020 MalID: toInt(media["idMal"]), 1083 MalID: toInt(media["idMal"]),
1021 Title: AnimeTitle{ 1084 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) {
69 } 69 }
70} 70}
71 71
72func BenchmarkSortAllanimeSourcesByPriority(b *testing.B) {
73 sources := make([]allanimeSource, 0, 1000)
74 for i := 0; i < 1000; i++ {
75 sources = append(sources, allanimeSource{
76 SourceUrl: fmt.Sprintf("https://example.com/%d.mp4", i),
77 SourceName: "Yt-mp4",
78 Priority: float64((i * 37) % 100),
79 })
80 }
81
82 b.ReportAllocs()
83 b.ResetTimer()
84 for i := 0; i < b.N; i++ {
85 _ = sortAllanimeSourcesByPriority(sources)
86 }
87}
88
89func BenchmarkLevenshteinAnimeTitles(b *testing.B) { 72func BenchmarkLevenshteinAnimeTitles(b *testing.B) {
90 for i := 0; i < b.N; i++ { 73 for i := 0; i < b.N; i++ {
91 _ = levenshtein("Sousou no Frieren Beyond Journey's End", "Frieren Beyond Journey's End") 74 _ = levenshtein("Sousou no Frieren Beyond Journey's End", "Frieren Beyond Journey's End")
internal/config.go +34 −8
@@ -42,6 +42,7 @@ type CurdConfig struct {
42 MpvArgs []string `config:"MpvArgs"` 42 MpvArgs []string `config:"MpvArgs"`
43 SubsLanguage string `config:"SubsLanguage"` 43 SubsLanguage string `config:"SubsLanguage"`
44 SubOrDub string `config:"SubOrDub"` 44 SubOrDub string `config:"SubOrDub"`
45 SubStyle string `config:"SubStyle"`
45 StoragePath string `config:"StoragePath"` 46 StoragePath string `config:"StoragePath"`
46 AnimeNameLanguage string `config:"AnimeNameLanguage"` 47 AnimeNameLanguage string `config:"AnimeNameLanguage"`
47 MenuOrder string `config:"MenuOrder"` 48 MenuOrder string `config:"MenuOrder"`
@@ -61,6 +62,8 @@ type CurdConfig struct {
61 DiscordPresence bool `config:"DiscordPresence"` 62 DiscordPresence bool `config:"DiscordPresence"`
62 DiscordClientId string `config:"DiscordClientId"` 63 DiscordClientId string `config:"DiscordClientId"`
63 Provider string `config:"Provider"` 64 Provider string `config:"Provider"`
65 DisabledProviders string `config:"DisabledProviders"`
66 ManualProviderSearch bool `config:"ManualProviderSearch"`
64 TrackingLocal bool `config:"TrackingLocal"` 67 TrackingLocal bool `config:"TrackingLocal"`
65 TrackingRemote string `config:"TrackingRemote"` 68 TrackingRemote string `config:"TrackingRemote"`
66 TrackingConfigured bool `config:"TrackingConfigured"` 69 TrackingConfigured bool `config:"TrackingConfigured"`
@@ -85,8 +88,9 @@ func defaultConfigMap() map[string]string {
85 "StoragePath": "$HOME/.local/share/curd", 88 "StoragePath": "$HOME/.local/share/curd",
86 "AnimeNameLanguage": "english", 89 "AnimeNameLanguage": "english",
87 "SubsLanguage": "english", 90 "SubsLanguage": "english",
88 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,TRACKER,PROVIDER", 91 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,REMAP_PROVIDER,CONTINUE_LAST,TRACKER,PROVIDER",
89 "SubOrDub": "sub", 92 "SubOrDub": "sub",
93 "SubStyle": "ask",
90 "PercentageToMarkComplete": "85", 94 "PercentageToMarkComplete": "85",
91 "NextEpisodePrompt": "false", 95 "NextEpisodePrompt": "false",
92 "SkipOp": "true", 96 "SkipOp": "true",
@@ -101,7 +105,9 @@ func defaultConfigMap() map[string]string {
101 "AlternateScreen": "true", 105 "AlternateScreen": "true",
102 "DiscordPresence": "true", 106 "DiscordPresence": "true",
103 "DiscordClientId": "1287457464148820089", 107 "DiscordClientId": "1287457464148820089",
104 "Provider": "[\"allanime\"]", 108 "Provider": "[\"anineko\"]",
109 "DisabledProviders": "[]",
110 "ManualProviderSearch": "false",
105 "TrackingLocal": "true", 111 "TrackingLocal": "true",
106 "TrackingRemote": "anilist", 112 "TrackingRemote": "anilist",
107 "TrackingConfigured": "false", 113 "TrackingConfigured": "false",
@@ -164,6 +170,25 @@ func parseStringArray(value string) []string {
164 170
165var GlobalConfigPath string 171var GlobalConfigPath string
166 172
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
167// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct 192// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct
168func LoadConfig(configPath string) (CurdConfig, error) { 193func LoadConfig(configPath string) (CurdConfig, error) {
169 configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME 194 configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME
@@ -687,13 +712,14 @@ func normalizeTrackingConfig(config *CurdConfig) {
687 712
688func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption { 713func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption {
689 // Define the default categories and all available labels 714 // 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"}
691 availableLabels := map[string]string{ 716 availableLabels := map[string]string{
692 "CURRENT": "Currently Watching", 717 "CURRENT": "Currently Watching",
693 "ALL": "Show All", 718 "ALL": "Show All",
694 "UNTRACKED": "Untracked Watching", 719 "UNTRACKED": "Untracked Watching",
695 "UPDATE": "Update (Episode, Status, Score)", 720 "UPDATE": "Update (Episode, Status, Score)",
696 "CONTINUE_LAST": "Continue Last Session", 721 "REMAP_PROVIDER": "Remap Provider",
722 "CONTINUE_LAST": "Continue Last Session",
697 "PLANNING": "Plan to Watch", 723 "PLANNING": "Plan to Watch",
698 "COMPLETED": "Completed", 724 "COMPLETED": "Completed",
699 "PAUSED": "Paused", 725 "PAUSED": "Paused",
internal/curd.go +79 −342
@@ -735,6 +735,11 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
735 // If WatchUntracked returns, user pressed back OR watched is done- continue to category selection 735 // If WatchUntracked returns, user pressed back OR watched is done- continue to category selection
736 ClearScreen() 736 ClearScreen()
737 continue categorySelectionLoop 737 continue categorySelectionLoop
738 } else if categorySelection.Key == "REMAP_PROVIDER" {
739 ClearScreen()
740 RemapProviderAnime(userCurdConfig, user, databaseAnimes)
741 ClearScreen()
742 continue categorySelectionLoop
738 } else if categorySelection.Key == "CONTINUE_LAST" { 743 } else if categorySelection.Key == "CONTINUE_LAST" {
739 anime.Ep.ContinueLast = true 744 anime.Ep.ContinueLast = true
740 } 745 }
@@ -915,7 +920,6 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
915 anime.StartedAt = selectedAnilistAnime.StartedAt 920 anime.StartedAt = selectedAnilistAnime.StartedAt
916 anime.CompletedAt = selectedAnilistAnime.CompletedAt 921 anime.CompletedAt = selectedAnilistAnime.CompletedAt
917 anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress) 922 anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
918 var animeList []SelectionOption
919 userQuery = anime.Title.Romaji 923 userQuery = anime.Title.Romaji
920 924
921 if selectedAnilistAnime.Status == "COMPLETED" { 925 if selectedAnilistAnime.Status == "COMPLETED" {
@@ -988,293 +992,21 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
988 // if anime not found in database or provider changed, find it in animeList 992 // if anime not found in database or provider changed, find it in animeList
989 if needsProviderSearch { 993 if needsProviderSearch {
990 Log("Anime not found in database for current provider, searching in animeList...") 994 Log("Anime not found in database for current provider, searching in animeList...")
991 // Get Anime list (All anime) 995 mappingOutcome, mappingErr := ResolveAnimeProviderMapping(userCurdConfig, anime, string(userQuery), selectedAnilistAnime)
992 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub)) 996 if mappingErr != nil {
993 997 Log(fmt.Sprintf("Provider mapping failed: %v", mappingErr))
994 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub) 998 ExitCurd(mappingErr)
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 }
1084 } 999 }
1085 1000 switch mappingOutcome {
1086 // 1b. Title/thumbnail scoring (AllAnime englishName vs AniList romaji query, etc.) 1001 case ProviderMappingBack:
1087 if !found { 1002 CurdOut("Going back to main menu...")
1088 if bestMatch, ok := confidentProviderSearchMatch(animeList, anime, userQuery); ok { 1003 RestoreScreen()
1089 anime.ProviderId = bestMatch.Key 1004 if anime.Ep.ContinueLast {
1090 Log(fmt.Sprintf("Found confident provider title match! Setting ProviderId to: %s (%s)", anime.ProviderId, bestMatch.Label)) 1005 anime.Ep.ContinueLast = false
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
1269 } 1006 }
1270 1007 continue
1271 anime.ProviderId = selectedAllanimeAnime.Key 1008 case ProviderMappingQuit:
1272 } 1009 ExitCurd(nil)
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]
1278 } 1010 }
1279 } 1011 }
1280 1012
@@ -1560,27 +1292,6 @@ func handleUnreleasedAnime(userCurdConfig *CurdConfig, user *User, anime *Anime,
1560 anime.Ep.ContinueLast = false 1292 anime.Ep.ContinueLast = false
1561} 1293}
1562 1294
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
1584func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string { 1295func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1585 if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil { 1296 if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil {
1586 Log(fmt.Sprintf("Failed to resolve provider id: %v", err)) 1297 Log(fmt.Sprintf("Failed to resolve provider id: %v", err))
@@ -1628,34 +1339,59 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1628 linkErr = err 1339 linkErr = err
1629 Log(fmt.Sprintf("ResolveEpisodeURL still failed after provider reselect: %v", linkErr)) 1340 Log(fmt.Sprintf("ResolveEpisodeURL still failed after provider reselect: %v", linkErr))
1630 } 1341 }
1631 // If unable to get episode link automatically get manually 1342 for {
1632 episodeProviderName, episodeProviderID := AnimeProviderID(anime) 1343 switch promptEpisodeLinkFailureRecovery(userCurdConfig) {
1633 episodeList, listErr := EpisodesList(QualifyProviderID(episodeProviderName, episodeProviderID), userCurdConfig.SubOrDub) 1344 case "remap":
1634 if listErr != nil { 1345 if RemapAnimeProviderOnEpisodeFailure(userCurdConfig, anime, nil) {
1635 CurdOut("No episode list found: " + listErr.Error()) 1346 episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1636 Log(fmt.Sprintf("EpisodesList failed: %v", listErr)) 1347 link = episodeResult.Links
1637 RestoreScreen() 1348 if err == nil && len(link) > 0 {
1638 os.Exit(1) 1349 anime.Ep.Links = link
1639 } 1350 applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1640 if len(episodeList) == 0 { 1351 goto episodeLinksReady
1641 CurdOut("No episodes were returned by the current provider for this anime.") 1352 }
1642 Log(fmt.Sprintf("EpisodesList returned no episodes for provider %s and id %s after ResolveEpisodeURL error: %v", episodeProviderName, episodeProviderID, linkErr)) 1353 if err != nil {
1643 RestoreScreen() 1354 linkErr = err
1644 os.Exit(1) 1355 Log(fmt.Sprintf("ResolveEpisodeURL failed after provider remap: %v", linkErr))
1645 } 1356 }
1646 episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1])) 1357 }
1647 if err != nil { 1358 case "episode":
1648 Log("Invalid episode input: " + err.Error()) 1359 episodeProviderName, episodeProviderID := AnimeProviderID(anime)
1649 CurdOut("Invalid episode number") 1360 episodeList, listErr := EpisodesList(QualifyProviderID(episodeProviderName, episodeProviderID), userCurdConfig.SubOrDub)
1650 RestoreScreen() 1361 if listErr != nil {
1651 os.Exit(1) 1362 CurdOut("No episode list found: " + listErr.Error())
1652 } 1363 Log(fmt.Sprintf("EpisodesList failed: %v", listErr))
1653 anime.Ep.Number = episodeNumber 1364 continue
1654 episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number) 1365 }
1655 link = episodeResult.Links 1366 if len(episodeList) == 0 {
1656 if err != nil { 1367 CurdOut("No episodes were returned by the current provider for this anime.")
1657 CurdOut("Failed to get episode link") 1368 Log(fmt.Sprintf("EpisodesList returned no episodes for provider %s and id %s after ResolveEpisodeURL error: %v", episodeProviderName, episodeProviderID, linkErr))
1658 os.Exit(1) 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 }
1659 } 1395 }
1660 } else { 1396 } else {
1661 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link on first try. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link))) 1397 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 {
1667episodeLinksReady: 1403episodeLinksReady:
1668 if len(anime.Ep.Links) == 0 { 1404 if len(anime.Ep.Links) == 0 {
1669 CurdOut("No episode links found") 1405 CurdOut("No episode links found")
1670 os.Exit(1) 1406 RestoreScreen()
1407 return ""
1671 } else { 1408 } else {
1672 Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links))) 1409 Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links)))
1673 } 1410 }
@@ -1763,10 +1500,6 @@ func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
1763 if err != nil { 1500 if err != nil {
1764 return err 1501 return err
1765 } 1502 }
1766 animepaheProvider, ok := provider.(*AnimepaheProvider)
1767 if !ok {
1768 return nil
1769 }
1770 1503
1771 query := GetAnimeName(*anime) 1504 query := GetAnimeName(*anime)
1772 if query == "" { 1505 if query == "" {
@@ -1776,7 +1509,7 @@ func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
1776 query = anime.Title.English 1509 query = anime.Title.English
1777 } 1510 }
1778 1511
1779 resolved, err := animepaheProvider.ResolveProviderID(providerID, query) 1512 resolved, err := resolveProviderID(provider, providerID, query)
1780 if err != nil { 1513 if err != nil {
1781 return err 1514 return err
1782 } 1515 }
@@ -1821,7 +1554,11 @@ func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason erro
1821 } 1554 }
1822 1555
1823 CurdOut("The saved Animepahe mapping is stale. Please select the anime again.") 1556 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)
1825 if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" { 1562 if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" {
1826 if err != nil { 1563 if err != nil {
1827 Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err)) 1564 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) {
10 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" { 10 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" {
11 t.Skip("set CURD_LIVE_ALLANIME_TEST=1") 11 t.Skip("set CURD_LIVE_ALLANIME_TEST=1")
12 } 12 }
13 withAllProvidersEnabledForTest(t)
13 14
14 showID := "NPpCgzb2MbnpiyxZ3" 15 showID := "NPpCgzb2MbnpiyxZ3"
15 links, err := getAllanimeEpisodeURLForMode(showID, "dub", 1) 16 provider, err := ProviderByName("allanime")
17 if err != nil {
18 t.Fatalf("allanime provider: %v", err)
19 }
20 resolver, ok := provider.(ProviderModeResolver)
21 if !ok {
22 t.Fatal("expected allanime provider to implement ProviderModeResolver")
23 }
24 links, err := resolver.GetEpisodeURLForMode(CurdConfig{SubOrDub: "dub"}, showID, 1, "dub")
16 if err == nil { 25 if err == nil {
17 for _, link := range links { 26 for _, link := range links {
18 if strings.Contains(link, "fast4speed.rsvp") { 27 if strings.Contains(link, "fast4speed.rsvp") {
@@ -27,9 +36,18 @@ func TestAllanimeMarchLionSubEp1Live(t *testing.T) {
27 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" { 36 if os.Getenv("CURD_LIVE_ALLANIME_TEST") != "1" {
28 t.Skip("set CURD_LIVE_ALLANIME_TEST=1") 37 t.Skip("set CURD_LIVE_ALLANIME_TEST=1")
29 } 38 }
39 withAllProvidersEnabledForTest(t)
30 40
31 showID := "NPpCgzb2MbnpiyxZ3" 41 showID := "NPpCgzb2MbnpiyxZ3"
32 links, err := getAllanimeEpisodeURLForMode(showID, "sub", 1) 42 provider, err := ProviderByName("allanime")
43 if err != nil {
44 t.Fatalf("allanime provider: %v", err)
45 }
46 resolver, ok := provider.(ProviderModeResolver)
47 if !ok {
48 t.Fatal("expected allanime provider to implement ProviderModeResolver")
49 }
50 links, err := resolver.GetEpisodeURLForMode(CurdConfig{SubOrDub: "sub"}, showID, 1, "sub")
33 if err != nil { 51 if err != nil {
34 t.Fatalf("sub episode link lookup failed: %v", err) 52 t.Fatalf("sub episode link lookup failed: %v", err)
35 } 53 }
internal/links.go +20
@@ -42,3 +42,23 @@ func linkSelectionScore(link string) int {
42 score += wixmpQualityScore(link) 42 score += wixmpQualityScore(link)
43 return score 43 return score
44} 44}
45
46func wixmpQualityScore(link string) int {
47 for _, quality := range []string{"1080p", "720p", "480p", "360p", "240p"} {
48 if strings.Contains(link, quality) {
49 switch quality {
50 case "1080p":
51 return 1080
52 case "720p":
53 return 720
54 case "480p":
55 return 480
56 case "360p":
57 return 360
58 case "240p":
59 return 240
60 }
61 }
62 }
63 return 0
64}
internal/loadproviders/load.go added +8
@@ -0,0 +1,8 @@
1// Package loadproviders registers built-in streaming providers via init side effects.
2package loadproviders
3
4import (
5 _ "github.com/wraient/curd/internal/providers/allanime"
6 _ "github.com/wraient/curd/internal/providers/animepahe"
7 _ "github.com/wraient/curd/internal/providers/anineko"
8)
internal/localTracking.go +105 −61
@@ -8,6 +8,8 @@ import (
8 "strconv" 8 "strconv"
9 "strings" 9 "strings"
10 "time" 10 "time"
11
12 "github.com/wraient/curd/internal/providers/animepahe"
11) 13)
12 14
13// Function to add an anime entry 15// Function to add an anime entry
@@ -54,7 +56,7 @@ func normalizeLocalProviderID(providerName, providerID, animeName string) string
54 return "" 56 return ""
55 } 57 }
56 58
57 stableID := stableAnimepaheProviderID(providerID) 59 stableID := animepahe.StableProviderID(providerID)
58 if stableID != "" { 60 if stableID != "" {
59 return stableID 61 return stableID
60 } 62 }
@@ -343,9 +345,82 @@ func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime
343 return bestMatch 345 return bestMatch
344} 346}
345 347
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
346func WatchUntracked(userCurdConfig *CurdConfig) { 422func WatchUntracked(userCurdConfig *CurdConfig) {
347 var query string 423 var query string
348 var animeList []SelectionOption
349 var err error 424 var err error
350 var anime Anime 425 var anime Anime
351 426
@@ -358,70 +433,22 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
358 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) 433 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
359 } 434 }
360 435
361 // Search for the anime 436 providerID, providerName, back, searchErr := ResolveUntrackedProviderSearch(userCurdConfig, query)
362 animeList, err = SearchAnime(query, userCurdConfig.SubOrDub) 437 if searchErr != nil {
363 if err != nil { 438 Log(fmt.Sprintf("Failed to search anime: %v", searchErr))
364 Log(fmt.Sprintf("Failed to search anime: %v", err))
365 ExitCurd(fmt.Errorf("Failed to search anime")) 439 ExitCurd(fmt.Errorf("Failed to search anime"))
366 } 440 }
367 441 if back {
368 if len(animeList) == 0 { 442 return
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 }
393 } 443 }
394 444 if providerID == "" {
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" {
403 ExitCurd(nil) 445 ExitCurd(nil)
404 } 446 }
405 447
406 // Back goes to home menu 448 anime.ProviderId = providerID
407 if selectedAnime.Key == "-2" { 449 anime.ProviderName = providerName
408 return // Return to caller (home menu) 450 anime.Title.English = query
409 } 451 anime.Title.Romaji = query
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 }
425 break 452 break
426 } 453 }
427 454
@@ -439,7 +466,24 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
439 resolvedLink, err := ResolveEpisodeURLForPlayback(*userCurdConfig, &anime, anime.Ep.Number) 466 resolvedLink, err := ResolveEpisodeURLForPlayback(*userCurdConfig, &anime, anime.Ep.Number)
440 if err != nil { 467 if err != nil {
441 Log(fmt.Sprintf("Failed to get episode link: %v", err)) 468 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
443 } 487 }
444 link := resolvedLink.Links 488 link := resolvedLink.Links
445 applyStreamPlaybackHints(&anime, link, resolvedLink.LinkHints) 489 applyStreamPlaybackHints(&anime, link, resolvedLink.LinkHints)
internal/logic_regression_test.go +4 −4
@@ -219,8 +219,8 @@ func TestGetProviderNormalizesConfiguredProviderName(t *testing.T) {
219 CurrentProvider = nil 219 CurrentProvider = nil
220 SetGlobalConfig(&CurdConfig{Provider: " AllAnime "}) 220 SetGlobalConfig(&CurdConfig{Provider: " AllAnime "})
221 221
222 if got := GetProvider().Name(); got != "allanime" { 222 if got := GetProvider().Name(); got != "anineko" {
223 t.Fatalf("expected allanime provider, got %q", got) 223 t.Fatalf("expected anineko provider when allanime is disabled, got %q", got)
224 } 224 }
225} 225}
226 226
@@ -235,8 +235,8 @@ func TestGetProviderFallsBackWhenConfiguredProviderDisabled(t *testing.T) {
235 CurrentProvider = nil 235 CurrentProvider = nil
236 SetGlobalConfig(&CurdConfig{Provider: " AnimePahe "}) 236 SetGlobalConfig(&CurdConfig{Provider: " AnimePahe "})
237 237
238 if got := GetProvider().Name(); got != "allanime" { 238 if got := GetProvider().Name(); got != "anineko" {
239 t.Fatalf("expected allanime fallback for disabled provider, got %q", got) 239 t.Fatalf("expected anineko fallback for disabled provider, got %q", got)
240 } 240 }
241} 241}
242 242
internal/myanimelist.go +24 −15
@@ -454,6 +454,10 @@ func renewMyAnimeListAccessToken(config *CurdConfig, tokenPath string, token *OA
454 Log(fmt.Sprintf("Failed to refresh MyAnimeList token after %s: %v", reason, refreshErr)) 454 Log(fmt.Sprintf("Failed to refresh MyAnimeList token after %s: %v", reason, refreshErr))
455 } 455 }
456 456
457 CurdOut("MyAnimeList sign-in required. Opening browser...")
458 Log(fmt.Sprintf("Starting MyAnimeList browser authentication after %s", reason))
459 clearStoredTokenFile(tokenPath)
460
457 accessToken, authErr := authenticateMyAnimeList(config, tokenPath) 461 accessToken, authErr := authenticateMyAnimeList(config, tokenPath)
458 if authErr != nil { 462 if authErr != nil {
459 return "", authErr 463 return "", authErr
@@ -547,24 +551,26 @@ func myAnimeListRequest(config *CurdConfig, method, requestURL string, form url.
547 return readErr 551 return readErr
548 } 552 }
549 553
550 if resp.StatusCode == http.StatusUnauthorized && attempt == 0 { 554 if resp.StatusCode == http.StatusUnauthorized || isInvalidTokenResponse(resp.StatusCode, body) {
551 tokenPath := myAnimeListTokenPath(config) 555 if attempt == 0 {
552 storedToken, tokenErr := loadToken(tokenPath) 556 tokenPath := myAnimeListTokenPath(config)
553 if tokenErr != nil { 557 storedToken, tokenErr := loadToken(tokenPath)
554 Log(fmt.Sprintf("Failed to load MyAnimeList token after unauthorized response, starting login: %v", tokenErr)) 558 if tokenErr != nil {
555 accessToken, authErr := renewMyAnimeListAccessToken(config, tokenPath, nil, "unauthorized API response") 559 Log(fmt.Sprintf("Failed to load MyAnimeList token after unauthorized response, starting login: %v", tokenErr))
556 if authErr != nil { 560 accessToken, authErr := renewMyAnimeListAccessToken(config, tokenPath, nil, "unauthorized API response")
557 return authErr 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
558 } 570 }
559 token = accessToken 571 token = accessToken
560 continue 572 continue
561 } 573 }
562 accessToken, renewErr := renewMyAnimeListAccessToken(config, tokenPath, storedToken, "unauthorized API response")
563 if renewErr != nil {
564 return renewErr
565 }
566 token = accessToken
567 continue
568 } 574 }
569 575
570 if resp.StatusCode < 200 || resp.StatusCode >= 300 { 576 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
@@ -724,6 +730,7 @@ func lookupAniListMediaByMalID(malID int) (Media, string, error) {
724 episodes 730 episodes
725 duration 731 duration
726 status 732 status
733 format
727 title { 734 title {
728 romaji 735 romaji
729 english 736 english
@@ -760,6 +767,7 @@ func lookupAniListMediaByMalID(malID int) (Media, string, error) {
760 Episodes: 0, 767 Episodes: 0,
761 Duration: 0, 768 Duration: 0,
762 Status: safeAniListString(mediaData["status"]), 769 Status: safeAniListString(mediaData["status"]),
770 Format: safeAniListString(mediaData["format"]),
763 Title: AnimeTitle{ 771 Title: AnimeTitle{
764 Romaji: safeAniListTitle(mediaData, "romaji"), 772 Romaji: safeAniListTitle(mediaData, "romaji"),
765 English: safeAniListTitle(mediaData, "english"), 773 English: safeAniListTitle(mediaData, "english"),
@@ -833,7 +841,7 @@ func lookupAniListMediaByMalIDs(malIDs []int) (map[int]aniListMediaLookupResult,
833 var query strings.Builder 841 var query strings.Builder
834 query.WriteString("query {") 842 query.WriteString("query {")
835 for idx, malID := range malIDs { 843 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)
837 } 845 }
838 query.WriteString(" }") 846 query.WriteString(" }")
839 847
@@ -876,6 +884,7 @@ func lookupAniListMediaByMalIDs(malIDs []int) (map[int]aniListMediaLookupResult,
876 Episodes: 0, 884 Episodes: 0,
877 Duration: 0, 885 Duration: 0,
878 Status: safeAniListString(rawMedia["status"]), 886 Status: safeAniListString(rawMedia["status"]),
887 Format: safeAniListString(rawMedia["format"]),
879 Title: AnimeTitle{ 888 Title: AnimeTitle{
880 Romaji: safeAniListTitle(rawMedia, "romaji"), 889 Romaji: safeAniListTitle(rawMedia, "romaji"),
881 English: safeAniListTitle(rawMedia, "english"), 890 English: safeAniListTitle(rawMedia, "english"),
internal/player.go +4 −2
@@ -12,6 +12,8 @@ import (
12 "strings" 12 "strings"
13 "sync" 13 "sync"
14 "time" 14 "time"
15
16 "github.com/wraient/curd/internal/providers"
15) 17)
16 18
17var logFile = "debug.log" 19var logFile = "debug.log"
@@ -23,8 +25,8 @@ func streamReferrerForLink(link, provider string) string {
23 if strings.Contains(strings.ToLower(link), "tools.fast4speed.rsvp") { 25 if strings.Contains(strings.ToLower(link), "tools.fast4speed.rsvp") {
24 return "https://allanime.to" 26 return "https://allanime.to"
25 } 27 }
26 if provider == "animepahe" { 28 if referrer := providers.Referrer(provider); referrer != "" {
27 return "https://kwik.cx/" 29 return referrer
28 } 30 }
29 return defaultStreamReferrer 31 return defaultStreamReferrer
30} 32}
internal/provider.go +49 −30
@@ -4,6 +4,9 @@ import (
4 "fmt" 4 "fmt"
5 "strconv" 5 "strconv"
6 "strings" 6 "strings"
7
8 "github.com/wraient/curd/internal/providers"
9 "github.com/wraient/curd/internal/providers/animepahe"
7) 10)
8 11
9// Provider interface defines methods for an anime provider. 12// Provider interface defines methods for an anime provider.
@@ -27,26 +30,12 @@ type ProviderEpisodeResult struct {
27} 30}
28 31
29const providerIDSeparator = "::" 32const providerIDSeparator = "::"
30const animepaheOptOutProvider = "no-animepahe"
31 33
32// Global variable to keep the current provider 34// Global variable to keep the current provider
33var CurrentProvider Provider 35var CurrentProvider Provider
34 36
35var providerFactories = map[string]func() Provider{
36 "allanime": func() Provider { return &AllanimeProvider{} },
37 "animepahe": func() Provider { return &AnimepaheProvider{} },
38}
39
40func normalizeProviderName(providerName string) string { 37func normalizeProviderName(providerName string) string {
41 providerName = strings.Trim(strings.TrimSpace(providerName), "\"'[]") 38 return providers.NormalizeName(providerName)
42 switch strings.ToLower(strings.TrimSpace(providerName)) {
43 case "allanime", "all-anime", "all anime":
44 return "allanime"
45 case "animepahe", "pahe":
46 return "animepahe"
47 default:
48 return ""
49 }
50} 39}
51 40
52func normalizeProviderConfigToken(token string) string { 41func normalizeProviderConfigToken(token string) string {
@@ -69,7 +58,7 @@ func parseProviderConfigParts(rawProvider string) []string {
69func parseProviderConfig(rawProvider string) ([]string, bool) { 58func parseProviderConfig(rawProvider string) ([]string, bool) {
70 rawProvider = strings.TrimSpace(rawProvider) 59 rawProvider = strings.TrimSpace(rawProvider)
71 if rawProvider == "" { 60 if rawProvider == "" {
72 rawProvider = "allanime" 61 rawProvider = firstEnabledProviderName()
73 } 62 }
74 63
75 normalizedRaw := strings.ToLower(rawProvider) 64 normalizedRaw := strings.ToLower(rawProvider)
@@ -83,7 +72,7 @@ func parseProviderConfig(rawProvider string) ([]string, bool) {
83 animepaheDeclined := false 72 animepaheDeclined := false
84 73
85 for _, part := range parts { 74 for _, part := range parts {
86 if normalizeProviderConfigToken(part) == animepaheOptOutProvider { 75 if isProviderOptOutToken(part) {
87 animepaheDeclined = true 76 animepaheDeclined = true
88 continue 77 continue
89 } 78 }
@@ -112,14 +101,14 @@ func parseProviderConfig(rawProvider string) ([]string, bool) {
112 } 101 }
113 102
114 if len(providers) == 0 { 103 if len(providers) == 0 {
115 providers = []string{"allanime"} 104 providers = []string{firstEnabledProviderName()}
116 } 105 }
117 106
118 return providers, animepaheDeclined 107 return providers, animepaheDeclined
119} 108}
120 109
121func configuredProviderNames(config *CurdConfig) []string { 110func configuredProviderNames(config *CurdConfig) []string {
122 rawProvider := "allanime" 111 rawProvider := firstEnabledProviderName()
123 if config != nil && strings.TrimSpace(config.Provider) != "" { 112 if config != nil && strings.TrimSpace(config.Provider) != "" {
124 rawProvider = config.Provider 113 rawProvider = config.Provider
125 } 114 }
@@ -143,11 +132,38 @@ func formatProviderConfigValue(names []string, animepaheDeclined bool) string {
143 quotedNames = append(quotedNames, fmt.Sprintf("%q", name)) 132 quotedNames = append(quotedNames, fmt.Sprintf("%q", name))
144 } 133 }
145 if animepaheDeclined { 134 if animepaheDeclined {
146 quotedNames = append(quotedNames, fmt.Sprintf("%q", animepaheOptOutProvider)) 135 if token := providerOptOutTokenForName("animepahe"); token != "" {
136 quotedNames = append(quotedNames, fmt.Sprintf("%q", token))
137 }
147 } 138 }
148 return "[" + strings.Join(quotedNames, ",") + "]" 139 return "[" + strings.Join(quotedNames, ",") + "]"
149} 140}
150 141
142func isProviderOptOutToken(token string) bool {
143 token = normalizeProviderConfigToken(token)
144 if token == "" {
145 return false
146 }
147 for _, name := range providers.RegisteredNames() {
148 meta, ok := providers.MetaFor(name)
149 if !ok || meta.OptOutToken == "" {
150 continue
151 }
152 if token == normalizeProviderConfigToken(meta.OptOutToken) {
153 return true
154 }
155 }
156 return false
157}
158
159func providerOptOutTokenForName(providerName string) string {
160 meta, ok := providers.MetaFor(providerName)
161 if !ok {
162 return ""
163 }
164 return meta.OptOutToken
165}
166
151func animepaheDeclinedInConfig(config *CurdConfig) bool { 167func animepaheDeclinedInConfig(config *CurdConfig) bool {
152 if config == nil { 168 if config == nil {
153 return false 169 return false
@@ -174,11 +190,11 @@ func ProviderByName(providerName string) (Provider, error) {
174 if reason := providerDisabledReason(providerName); reason != "" { 190 if reason := providerDisabledReason(providerName); reason != "" {
175 return nil, fmt.Errorf("provider %q is disabled: %s", providerName, reason) 191 return nil, fmt.Errorf("provider %q is disabled: %s", providerName, reason)
176 } 192 }
177 factory, ok := providerFactories[providerName] 193 provider, err := providers.New(providerName)
178 if !ok { 194 if err != nil {
179 return nil, fmt.Errorf("unknown provider %q", providerName) 195 return nil, err
180 } 196 }
181 return factory(), nil 197 return wrapProvider(provider), nil
182} 198}
183 199
184func GetProvider() Provider { 200func GetProvider() Provider {
@@ -190,8 +206,11 @@ func GetProvider() Provider {
190 primaryProviderName := providerNames[0] 206 primaryProviderName := providerNames[0]
191 provider, err := ProviderByName(primaryProviderName) 207 provider, err := ProviderByName(primaryProviderName)
192 if err != nil { 208 if err != nil {
193 CurrentProvider = &AllanimeProvider{} 209 if fallback, fallbackErr := ProviderByName(firstEnabledProviderName()); fallbackErr == nil {
194 return CurrentProvider 210 CurrentProvider = fallback
211 return CurrentProvider
212 }
213 return provider
195 } 214 }
196 CurrentProvider = provider 215 CurrentProvider = provider
197 return CurrentProvider 216 return CurrentProvider
@@ -280,7 +299,7 @@ func providerNamesForAnime(config *CurdConfig, anime *Anime) []string {
280 } 299 }
281 } 300 }
282 if len(result) == 0 { 301 if len(result) == 0 {
283 return []string{"allanime"} 302 return []string{firstEnabledProviderName()}
284 } 303 }
285 return result 304 return result
286} 305}
@@ -425,7 +444,7 @@ func appendProviderName(providerNames []string, providerName string) []string {
425 } 444 }
426 } 445 }
427 if len(result) == 0 { 446 if len(result) == 0 {
428 return []string{"allanime"} 447 return []string{firstEnabledProviderName()}
429 } 448 }
430 return result 449 return result
431} 450}
@@ -635,7 +654,7 @@ func episodeModeResult(config CurdConfig, anime *Anime, epNo int, mode string) (
635func episodeModeResultWithProviders(config CurdConfig, anime *Anime, epNo int, mode string, providerNames []string) (ProviderEpisodeResult, error) { 654func episodeModeResultWithProviders(config CurdConfig, anime *Anime, epNo int, mode string, providerNames []string) (ProviderEpisodeResult, error) {
636 mode = normalizeTranslationType(mode) 655 mode = normalizeTranslationType(mode)
637 if len(providerNames) == 0 { 656 if len(providerNames) == 0 {
638 providerNames = []string{"allanime"} 657 providerNames = []string{firstEnabledProviderName()}
639 } 658 }
640 659
641 var errors []string 660 var errors []string
@@ -832,7 +851,7 @@ func scoreProviderSearchOption(option SelectionOption, anime *Anime, query strin
832 if anime.TotalEpisodes > 0 && strings.Contains(option.Label, fmt.Sprintf("(%d episodes)", anime.TotalEpisodes)) { 851 if anime.TotalEpisodes > 0 && strings.Contains(option.Label, fmt.Sprintf("(%d episodes)", anime.TotalEpisodes)) {
833 score += 20 852 score += 20
834 } 853 }
835 if item, ok := option.ExtraData.(AnimepaheSearchItem); ok && anime.TotalEpisodes > 0 && item.Episodes == anime.TotalEpisodes { 854 if item, ok := option.ExtraData.(animepahe.SearchItem); ok && anime.TotalEpisodes > 0 && item.Episodes == anime.TotalEpisodes {
836 score += 20 855 score += 20
837 } 856 }
838 return score 857 return score
internal/provider_allanime.go deleted −28
@@ -1,28 +0,0 @@
1package internal
2
3type AllanimeProvider struct{}
4
5func (p *AllanimeProvider) Name() string {
6 return "allanime"
7}
8
9func (p *AllanimeProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
10 return searchAllAnime(query, mode)
11}
12
13func (p *AllanimeProvider) EpisodesList(showID, mode string) ([]string, error) {
14 return getAllAnimeEpisodesList(showID, mode)
15}
16
17func (p *AllanimeProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
18 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub)
19}
20
21func (p *AllanimeProvider) GetEpisodeURLForMode(config CurdConfig, id string, epNo int, mode string) ([]string, error) {
22 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, mode)
23 return links, err
24}
25
26func (p *AllanimeProvider) GetEpisodeURLForModeWithHints(config CurdConfig, id string, epNo int, mode string) ([]string, map[string]StreamPlaybackHint, error) {
27 return getAllanimeEpisodeStreamsForMode(id, mode, epNo)
28}
internal/provider_bridge.go added +181
@@ -0,0 +1,181 @@
1package internal
2
3import (
4 "net/http"
5
6 _ "github.com/wraient/curd/internal/loadproviders"
7
8 "github.com/wraient/curd/internal/curdhost"
9 "github.com/wraient/curd/internal/providers"
10)
11
12func init() {
13 curdhost.HTTPClient = func() *http.Client { return sharedHTTPClient }
14 curdhost.Log = func(msg string) { _ = Log(msg) }
15 curdhost.Out = func(msg string) { CurdOut(msg) }
16 curdhost.PromptSelect = func(options []curdhost.PromptOption) (curdhost.PromptOption, error) {
17 mapped := make([]SelectionOption, 0, len(options))
18 for _, option := range options {
19 mapped = append(mapped, SelectionOption{
20 Key: option.Key,
21 Label: option.Label,
22 })
23 }
24 selected, err := promptSelect(mapped)
25 if err != nil {
26 return curdhost.PromptOption{}, err
27 }
28 return curdhost.PromptOption{Key: selected.Key, Label: selected.Label}, nil
29 }
30 curdhost.PersistSubStylePreference = persistSubStylePreference
31 curdhost.CurrentSubStyle = func() string {
32 if cfg := GetGlobalConfig(); cfg != nil {
33 return cfg.SubStyle
34 }
35 return ""
36 }
37 curdhost.StoragePath = GetStoragePath
38 curdhost.AnimeNameLanguage = func() string {
39 if cfg := GetGlobalConfig(); cfg != nil {
40 return cfg.AnimeNameLanguage
41 }
42 return "english"
43 }
44 curdhost.SetCookiesForAnimepahe = SetCookiesForAnimepahe
45}
46
47func normalizeTranslationType(mode string) string {
48 return providers.NormalizeTranslationType(mode)
49}
50
51func alternateTranslationType(mode string) string {
52 return providers.AlternateTranslationType(mode)
53}
54
55func toInternalSelectionOptions(options []providers.SelectionOption) []SelectionOption {
56 if len(options) == 0 {
57 return nil
58 }
59 result := make([]SelectionOption, 0, len(options))
60 for _, option := range options {
61 result = append(result, SelectionOption{
62 Key: option.Key,
63 Label: option.Label,
64 Title: option.Title,
65 Thumbnail: option.Thumbnail,
66 ExtraData: option.ExtraData,
67 })
68 }
69 return result
70}
71
72func toProviderSelectionOptions(options []SelectionOption) []providers.SelectionOption {
73 if len(options) == 0 {
74 return nil
75 }
76 result := make([]providers.SelectionOption, 0, len(options))
77 for _, option := range options {
78 result = append(result, providers.SelectionOption{
79 Key: option.Key,
80 Label: option.Label,
81 Title: option.Title,
82 Thumbnail: option.Thumbnail,
83 ExtraData: option.ExtraData,
84 })
85 }
86 return result
87}
88
89func toPlaybackConfig(config CurdConfig) providers.PlaybackConfig {
90 return providers.PlaybackConfig{
91 SubOrDub: config.SubOrDub,
92 SubStyle: config.SubStyle,
93 }
94}
95
96func fromStreamHints(hints map[string]providers.StreamPlaybackHint) map[string]StreamPlaybackHint {
97 if len(hints) == 0 {
98 return nil
99 }
100 result := make(map[string]StreamPlaybackHint, len(hints))
101 for key, hint := range hints {
102 result[key] = StreamPlaybackHint{
103 Referrer: hint.Referrer,
104 Subtitle: hint.Subtitle,
105 }
106 }
107 return result
108}
109
110type providerAdapter struct {
111 inner providers.Provider
112}
113
114func (a *providerAdapter) Name() string {
115 return a.inner.Name()
116}
117
118func (a *providerAdapter) SearchAnime(query, mode string) ([]SelectionOption, error) {
119 options, err := a.inner.SearchAnime(query, mode)
120 return toInternalSelectionOptions(options), err
121}
122
123func (a *providerAdapter) EpisodesList(showID, mode string) ([]string, error) {
124 return a.inner.EpisodesList(showID, mode)
125}
126
127func (a *providerAdapter) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
128 return a.inner.GetEpisodeURL(toPlaybackConfig(config), id, epNo)
129}
130
131func (a *providerAdapter) GetEpisodeURLForMode(config CurdConfig, id string, epNo int, mode string) ([]string, error) {
132 if resolver, ok := a.inner.(providers.ModeResolver); ok {
133 return resolver.GetEpisodeURLForMode(toPlaybackConfig(config), id, epNo, mode)
134 }
135 return a.inner.GetEpisodeURL(toPlaybackConfig(config), id, epNo)
136}
137
138func (a *providerAdapter) GetEpisodeURLForModeWithHints(config CurdConfig, id string, epNo int, mode string) ([]string, map[string]StreamPlaybackHint, error) {
139 if resolver, ok := a.inner.(providers.HintResolver); ok {
140 links, hints, err := resolver.GetEpisodeURLForModeWithHints(toPlaybackConfig(config), id, epNo, mode)
141 return links, fromStreamHints(hints), err
142 }
143 links, err := a.GetEpisodeURLForMode(config, id, epNo, mode)
144 return links, nil, err
145}
146
147func resolveProviderID(provider Provider, providerID, query string) (string, error) {
148 inner := unwrapProvider(provider)
149 if inner == nil {
150 return providerID, nil
151 }
152 if resolver, ok := inner.(providers.IDResolver); ok {
153 return resolver.ResolveProviderID(providerID, query)
154 }
155 return providerID, nil
156}
157
158func wrapProvider(provider providers.Provider) Provider {
159 return &providerAdapter{inner: provider}
160}
161
162func unwrapProvider(provider Provider) providers.Provider {
163 if adapter, ok := provider.(*providerAdapter); ok {
164 return adapter.inner
165 }
166 return nil
167}
168
169func applyStreamPlaybackHints(anime *Anime, links []string, hints map[string]StreamPlaybackHint) {
170 if anime == nil || len(links) == 0 {
171 return
172 }
173 selected := PrioritizeLink(links)
174 if hint, ok := hints[selected]; ok {
175 anime.Ep.StreamReferrer = hint.Referrer
176 anime.Ep.SubtitleURL = hint.Subtitle
177 return
178 }
179 anime.Ep.StreamReferrer = ""
180 anime.Ep.SubtitleURL = ""
181}
internal/provider_disabled.go +82 −13
@@ -2,14 +2,11 @@ package internal
2 2
3import ( 3import (
4 "sort" 4 "sort"
5 "strings"
5 "testing" 6 "testing"
6)
7 7
8// disabledProviders lists providers kept in source but excluded from runtime use. 8 "github.com/wraient/curd/internal/providers"
9// Remove a provider from this map to re-enable it without restoring deleted code. 9)
10var disabledProviders = map[string]string{
11 "animepahe": "Cloudflare/DDoS-Guard protection cannot be bypassed reliably",
12}
13 10
14var disabledProviderReasonForTest func(string) string 11var disabledProviderReasonForTest func(string) string
15 12
@@ -21,7 +18,56 @@ func providerDisabledReason(name string) string {
21 if disabledProviderReasonForTest != nil { 18 if disabledProviderReasonForTest != nil {
22 return disabledProviderReasonForTest(name) 19 return disabledProviderReasonForTest(name)
23 } 20 }
24 return disabledProviders[name] 21 if reason := configDisabledProviderReason(name); reason != "" {
22 return reason
23 }
24 meta, ok := providers.MetaFor(name)
25 if !ok {
26 return ""
27 }
28 if meta.DefaultDisabled {
29 return meta.DisableReason
30 }
31 return ""
32}
33
34func configDisabledProviderReason(name string) string {
35 config := GetGlobalConfig()
36 if config == nil {
37 return ""
38 }
39 for _, disabledName := range parseDisabledProviderNames(config.DisabledProviders) {
40 if disabledName == name {
41 if meta, ok := providers.MetaFor(name); ok && meta.DisableReason != "" {
42 return meta.DisableReason
43 }
44 return "disabled in config"
45 }
46 }
47 return ""
48}
49
50func parseDisabledProviderNames(raw string) []string {
51 parts := parseStringArray(raw)
52 if len(parts) == 0 {
53 parts = strings.FieldsFunc(raw, func(r rune) bool {
54 return r == ',' || r == '+' || r == '|' || r == ';'
55 })
56 }
57 names := make([]string, 0, len(parts))
58 seen := make(map[string]struct{})
59 for _, part := range parts {
60 name := normalizeProviderName(part)
61 if name == "" {
62 continue
63 }
64 if _, exists := seen[name]; exists {
65 continue
66 }
67 seen[name] = struct{}{}
68 names = append(names, name)
69 }
70 return names
25} 71}
26 72
27// ProviderEnabled reports whether a provider may be used at runtime. 73// ProviderEnabled reports whether a provider may be used at runtime.
@@ -55,11 +101,7 @@ func filterEnabledProviders(names []string) []string {
55} 101}
56 102
57func defaultEnabledProviderStack() []string { 103func defaultEnabledProviderStack() []string {
58 names := make([]string, 0, len(providerFactories)) 104 names := providers.RegisteredNames()
59 for name := range providerFactories {
60 names = append(names, name)
61 }
62 sort.Strings(names)
63 return filterEnabledProviders(names) 105 return filterEnabledProviders(names)
64} 106}
65 107
@@ -87,12 +129,32 @@ func providerSelectionOptions() []SelectionOption {
87 return options 129 return options
88} 130}
89 131
132func firstEnabledProviderName() string {
133 enabled := defaultEnabledProviderStack()
134 if len(enabled) > 0 {
135 return enabled[0]
136 }
137 return "anineko"
138}
139
90func ensureEnabledProviderNames(names []string) []string { 140func ensureEnabledProviderNames(names []string) []string {
91 enabled := filterEnabledProviders(names) 141 enabled := filterEnabledProviders(names)
92 if len(enabled) > 0 { 142 if len(enabled) > 0 {
93 return enabled 143 return enabled
94 } 144 }
95 return []string{"allanime"} 145 fallback := filterEnabledProviders([]string{firstEnabledProviderName()})
146 if len(fallback) > 0 {
147 return fallback
148 }
149 if registered := providers.RegisteredNames(); len(registered) > 0 {
150 for _, name := range registered {
151 if ProviderEnabled(name) {
152 return []string{name}
153 }
154 }
155 return []string{registered[0]}
156 }
157 return []string{firstEnabledProviderName()}
96} 158}
97 159
98func withAllProvidersEnabledForTest(t *testing.T) { 160func withAllProvidersEnabledForTest(t *testing.T) {
@@ -103,3 +165,10 @@ func withAllProvidersEnabledForTest(t *testing.T) {
103 disabledProviderReasonForTest = previous 165 disabledProviderReasonForTest = previous
104 }) 166 })
105} 167}
168
169// RegisteredProviderNames returns sorted registered provider names.
170func RegisteredProviderNames() []string {
171 names := providers.RegisteredNames()
172 sort.Strings(names)
173 return names
174}
internal/provider_disabled_test.go +27 −16
@@ -2,12 +2,18 @@ package internal
2 2
3import "testing" 3import "testing"
4 4
5func TestProviderEnabledDisablesAnimepaheByDefault(t *testing.T) { 5func TestProviderEnabledDisablesAllanimeAndAnimepaheByDefault(t *testing.T) {
6 if ProviderEnabled("allanime") != true { 6 if ProviderEnabled("allanime") != false {
7 t.Fatal("expected allanime to stay enabled") 7 t.Fatal("expected allanime to be disabled by default")
8 } 8 }
9 if ProviderEnabled("animepahe") != false { 9 if ProviderEnabled("animepahe") != false {
10 t.Fatal("expected animepahe to be disabled") 10 t.Fatal("expected animepahe to be disabled by default")
11 }
12 if ProviderEnabled("anineko") != true {
13 t.Fatal("expected anineko to stay enabled")
14 }
15 if reason := ProviderDisabledReason("allanime"); reason == "" {
16 t.Fatal("expected allanime disable reason")
11 } 17 }
12 if reason := ProviderDisabledReason("animepahe"); reason == "" { 18 if reason := ProviderDisabledReason("animepahe"); reason == "" {
13 t.Fatal("expected animepahe disable reason") 19 t.Fatal("expected animepahe disable reason")
@@ -20,10 +26,11 @@ func TestConfiguredProviderNamesFiltersDisabledProviders(t *testing.T) {
20 cfg *CurdConfig 26 cfg *CurdConfig
21 want []string 27 want []string
22 }{ 28 }{
23 {name: "empty", cfg: &CurdConfig{}, want: []string{"allanime"}}, 29 {name: "empty", cfg: &CurdConfig{}, want: []string{"anineko"}},
24 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"allanime"}}, 30 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"anineko"}},
25 {name: "animepahe only", cfg: &CurdConfig{Provider: `["animepahe"]`}, want: []string{"allanime"}}, 31 {name: "animepahe only", cfg: &CurdConfig{Provider: `["animepahe"]`}, want: []string{"anineko"}},
26 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"allanime"}}, 32 {name: "allanime only", cfg: &CurdConfig{Provider: `["allanime"]`}, want: []string{"anineko"}},
33 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"anineko"}},
27 } 34 }
28 35
29 for _, tc := range cases { 36 for _, tc := range cases {
@@ -50,19 +57,23 @@ func TestConfiguredProviderNamesHonorsEnabledProvidersWhenOverridden(t *testing.
50} 57}
51 58
52func TestProviderByNameRejectsDisabledProvider(t *testing.T) { 59func TestProviderByNameRejectsDisabledProvider(t *testing.T) {
53 if _, err := ProviderByName("animepahe"); err == nil { 60 for _, name := range []string{"animepahe", "allanime"} {
54 t.Fatal("expected disabled provider error") 61 if _, err := ProviderByName(name); err == nil {
62 t.Fatalf("expected disabled provider error for %s", name)
63 }
55 } 64 }
56} 65}
57 66
58func TestProviderByNameAllowsDisabledProviderWhenOverridden(t *testing.T) { 67func TestProviderByNameAllowsDisabledProviderWhenOverridden(t *testing.T) {
59 withAllProvidersEnabledForTest(t) 68 withAllProvidersEnabledForTest(t)
60 69
61 provider, err := ProviderByName("animepahe") 70 for _, name := range []string{"animepahe", "allanime"} {
62 if err != nil { 71 provider, err := ProviderByName(name)
63 t.Fatalf("expected animepahe provider: %v", err) 72 if err != nil {
64 } 73 t.Fatalf("expected %s provider: %v", name, err)
65 if provider.Name() != "animepahe" { 74 }
66 t.Fatalf("got provider %q", provider.Name()) 75 if provider.Name() != name {
76 t.Fatalf("got provider %q", provider.Name())
77 }
67 } 78 }
68} 79}
internal/provider_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 (
6 "path/filepath" 6 "path/filepath"
7 "strings" 7 "strings"
8 "testing" 8 "testing"
9
10 "github.com/wraient/curd/internal/providers"
9) 11)
10 12
11type stackStubProvider struct { 13type stackStubProvider struct {
@@ -47,21 +49,44 @@ func (s *stackStubProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
47 return nil, nil 49 return nil, nil
48} 50}
49 51
50func withProviderFactories(t *testing.T, providers ...*stackStubProvider) { 52func withProviderFactories(t *testing.T, stubs ...*stackStubProvider) {
51 t.Helper() 53 t.Helper()
52 withAllProvidersEnabledForTest(t) 54 withAllProvidersEnabledForTest(t)
53 previousAllanime := providerFactories["allanime"] 55 restores := make([]func(), 0, len(stubs))
54 previousAnimepahe := providerFactories["animepahe"] 56 for _, stub := range stubs {
55 for _, provider := range providers { 57 stub := stub
56 provider := provider 58 restores = append(restores, providers.SetFactoryForTest(stub.name, func() providers.Provider {
57 providerFactories[provider.name] = func() Provider { return provider } 59 return &stackStubProviderBridge{stub}
60 }))
58 } 61 }
59 t.Cleanup(func() { 62 t.Cleanup(func() {
60 providerFactories["allanime"] = previousAllanime 63 for i := len(restores) - 1; i >= 0; i-- {
61 providerFactories["animepahe"] = previousAnimepahe 64 restores[i]()
65 }
62 }) 66 })
63} 67}
64 68
69type stackStubProviderBridge struct {
70 *stackStubProvider
71}
72
73func (s *stackStubProviderBridge) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
74 options, err := s.stackStubProvider.SearchAnime(query, mode)
75 return toProviderSelectionOptions(options), err
76}
77
78func (s *stackStubProviderBridge) EpisodesList(showID, mode string) ([]string, error) {
79 return s.stackStubProvider.EpisodesList(showID, mode)
80}
81
82func (s *stackStubProviderBridge) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
83 return s.stackStubProvider.GetEpisodeURL(CurdConfig{SubOrDub: config.SubOrDub}, id, epNo)
84}
85
86func (s *stackStubProviderBridge) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
87 return s.stackStubProvider.GetEpisodeURLForMode(CurdConfig{SubOrDub: config.SubOrDub}, id, epNo, mode)
88}
89
65func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) { 90func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) {
66 withAllProvidersEnabledForTest(t) 91 withAllProvidersEnabledForTest(t)
67 92
@@ -74,7 +99,7 @@ func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) {
74 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"allanime", "animepahe"}}, 99 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"allanime", "animepahe"}},
75 {name: "comma list", cfg: &CurdConfig{Provider: "animepahe,allanime"}, want: []string{"animepahe", "allanime"}}, 100 {name: "comma list", cfg: &CurdConfig{Provider: "animepahe,allanime"}, want: []string{"animepahe", "allanime"}},
76 {name: "plus list", cfg: &CurdConfig{Provider: "allanime+animepahe"}, want: []string{"allanime", "animepahe"}}, 101 {name: "plus list", cfg: &CurdConfig{Provider: "allanime+animepahe"}, want: []string{"allanime", "animepahe"}},
77 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"allanime", "animepahe"}}, 102 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"allanime", "animepahe", "anineko"}},
78 } 103 }
79 104
80 for _, tc := range cases { 105 for _, tc := range cases {
@@ -100,7 +125,7 @@ func TestCanonicalProviderConfigValueMigratesLegacyValuesWithoutAddingAnimepahe(
100 {name: "legacy animepahe", raw: "animepahe", want: `["animepahe"]`}, 125 {name: "legacy animepahe", raw: "animepahe", want: `["animepahe"]`},
101 {name: "ordered stack", raw: "animepahe,allanime", want: `["animepahe","allanime"]`}, 126 {name: "ordered stack", raw: "animepahe,allanime", want: `["animepahe","allanime"]`},
102 {name: "animepahe opt out", raw: "allanime,no-animepahe", want: `["allanime","no-animepahe"]`}, 127 {name: "animepahe opt out", raw: "allanime,no-animepahe", want: `["allanime","no-animepahe"]`},
103 {name: "empty default", raw: "", want: `["allanime"]`}, 128 {name: "empty default", raw: "", want: `["anineko"]`},
104 } 129 }
105 130
106 for _, tc := range cases { 131 for _, tc := range cases {
internal/episode_list.go → internal/providers/allanime/episodes.go renamed +11 −8
@@ -1,4 +1,4 @@
1package internal 1package allanime
2 2
3import ( 3import (
4 "bytes" 4 "bytes"
@@ -8,6 +8,9 @@ import (
8 "net/http" 8 "net/http"
9 "sort" 9 "sort"
10 "strconv" 10 "strconv"
11
12 "github.com/wraient/curd/internal/curdhost"
13 "github.com/wraient/curd/internal/providers"
11) 14)
12 15
13type episodesResponse struct { 16type episodesResponse struct {
@@ -33,7 +36,7 @@ type episodesResponse struct {
33 36
34// episodesList performs the API call and fetches the episodes list 37// episodesList performs the API call and fetches the episodes list
35func getAllAnimeEpisodesList(showID, mode string) ([]string, error) { 38func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
36 preferredMode := normalizeTranslationType(mode) 39 preferredMode := providers.NormalizeTranslationType(mode)
37 40
38 episodesListGql := `query ($showId: String!) { show( _id: $showId ) { _id availableEpisodesDetail }}` 41 episodesListGql := `query ($showId: String!) { show( _id: $showId ) { _id availableEpisodesDetail }}`
39 42
@@ -56,27 +59,27 @@ func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
56 req.Header.Set("Referer", "https://allanime.to") 59 req.Header.Set("Referer", "https://allanime.to")
57 req.Header.Set("Origin", "https://allanime.to") 60 req.Header.Set("Origin", "https://allanime.to")
58 61
59 resp, err := sharedHTTPClient.Do(req) 62 resp, err := curdhost.HTTPClient().Do(req)
60 if err != nil { 63 if err != nil {
61 Log(fmt.Sprint("Error making HTTP request:", err)) 64 curdhost.Log(fmt.Sprint("Error making HTTP request:", err))
62 return nil, err 65 return nil, err
63 } 66 }
64 defer resp.Body.Close() 67 defer resp.Body.Close()
65 68
66 body, err := io.ReadAll(resp.Body) 69 body, err := io.ReadAll(resp.Body)
67 if err != nil { 70 if err != nil {
68 Log(fmt.Sprint("Error reading response body:", err)) 71 curdhost.Log(fmt.Sprint("Error reading response body:", err))
69 return nil, err 72 return nil, err
70 } 73 }
71 if !httpStatusOK(resp.StatusCode) { 74 if !curdhost.HTTPStatusOK(resp.StatusCode) {
72 return nil, httpStatusError("allanime episode list", resp.StatusCode, body) 75 return nil, curdhost.HTTPStatusError("allanime episode list", resp.StatusCode, body)
73 } 76 }
74 77
75 // Parse the JSON response 78 // Parse the JSON response
76 var response episodesResponse 79 var response episodesResponse
77 err = json.Unmarshal(body, &response) 80 err = json.Unmarshal(body, &response)
78 if err != nil { 81 if err != nil {
79 Log(fmt.Sprint("Error parsing JSON:", err)) 82 curdhost.Log(fmt.Sprint("Error parsing JSON:", err))
80 return nil, err 83 return nil, err
81 } 84 }
82 85
internal/providers/allanime/provider.go added +33
@@ -0,0 +1,33 @@
1package allanime
2
3import (
4 "github.com/wraient/curd/internal/providers"
5)
6
7// Provider implements AllAnime catalog search and stream resolution.
8type Provider struct{}
9
10func (p *Provider) Name() string {
11 return "allanime"
12}
13
14func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
15 return searchAllAnime(query, mode)
16}
17
18func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
19 return getAllAnimeEpisodesList(showID, mode)
20}
21
22func (p *Provider) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
23 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub)
24}
25
26func (p *Provider) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
27 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, mode)
28 return links, err
29}
30
31func (p *Provider) GetEpisodeURLForModeWithHints(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, map[string]providers.StreamPlaybackHint, error) {
32 return getAllanimeEpisodeStreamsForMode(id, mode, epNo)
33}
internal/providers/allanime/register.go added +15
@@ -0,0 +1,15 @@
1package allanime
2
3import "github.com/wraient/curd/internal/providers"
4
5func init() {
6 providers.Register(providers.Meta{
7 Name: "allanime",
8 Aliases: []string{"all-anime", "all anime"},
9 Referrer: "https://allanime.day/",
10 DefaultDisabled: true,
11 DisableReason: "disabled by default; set Provider to include allanime to enable",
12 }, func() providers.Provider {
13 return &Provider{}
14 })
15}
internal/anime_list.go → internal/providers/allanime/search.go renamed +23 −38
@@ -1,4 +1,4 @@
1package internal 1package allanime
2 2
3import ( 3import (
4 "bytes" 4 "bytes"
@@ -6,8 +6,9 @@ import (
6 "fmt" 6 "fmt"
7 "io" 7 "io"
8 "net/http" 8 "net/http"
9 "path/filepath" 9
10 "strings" 10 "github.com/wraient/curd/internal/curdhost"
11 "github.com/wraient/curd/internal/providers"
11) 12)
12 13
13type anime struct { 14type anime struct {
@@ -26,20 +27,6 @@ type response struct {
26 } `json:"data"` 27 } `json:"data"`
27} 28}
28 29
29func normalizeTranslationType(mode string) string {
30 if strings.EqualFold(strings.TrimSpace(mode), "dub") {
31 return "dub"
32 }
33 return "sub"
34}
35
36func alternateTranslationType(mode string) string {
37 if normalizeTranslationType(mode) == "dub" {
38 return "sub"
39 }
40 return "dub"
41}
42
43// func main() { 30// func main() {
44// // Get environment variables 31// // Get environment variables
45// mode := "sub" 32// mode := "sub"
@@ -55,14 +42,12 @@ func alternateTranslationType(mode string) string {
55// fmt.Println(animeList) 42// fmt.Println(animeList)
56// } 43// }
57 44
58func searchAllAnime(query, mode string) ([]SelectionOption, error) { 45func searchAllAnime(query, mode string) ([]providers.SelectionOption, error) {
59 preferredMode := normalizeTranslationType(mode) 46 preferredMode := providers.NormalizeTranslationType(mode)
60 return searchAnimeByMode(query, preferredMode, preferredMode) 47 return searchAnimeByMode(query, preferredMode, preferredMode)
61} 48}
62 49
63func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, error) { 50func searchAnimeByMode(query, mode, preferredMode string) ([]providers.SelectionOption, error) {
64 userCurdConfig := GetGlobalConfig()
65 logFile = filepath.Join(GetStoragePath(), "debug.log")
66 const ( 51 const (
67 agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0" 52 agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
68 allanimeRef = "https://allanime.to" 53 allanimeRef = "https://allanime.to"
@@ -70,10 +55,10 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
70 allanimeAPI = "https://api." + allanimeBase + "/api" 55 allanimeAPI = "https://api." + allanimeBase + "/api"
71 ) 56 )
72 57
73 mode = normalizeTranslationType(mode) 58 mode = providers.NormalizeTranslationType(mode)
74 preferredMode = normalizeTranslationType(preferredMode) 59 preferredMode = providers.NormalizeTranslationType(preferredMode)
75 60
76 animeList := make([]SelectionOption, 0) 61 animeList := make([]providers.SelectionOption, 0)
77 62
78 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) { 63 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) {
79 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) { 64 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) {
@@ -107,14 +92,14 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
107 "variables": variables, 92 "variables": variables,
108 }) 93 })
109 if err != nil { 94 if err != nil {
110 Log(fmt.Sprintf("Error encoding request body to JSON: %v", err)) 95 curdhost.Log(fmt.Sprintf("Error encoding request body to JSON: %v", err))
111 return animeList, err 96 return animeList, err
112 } 97 }
113 98
114 // Make the HTTP POST request 99 // Make the HTTP POST request
115 req, err := http.NewRequest("POST", allanimeAPI, bytes.NewBuffer(requestBody)) 100 req, err := http.NewRequest("POST", allanimeAPI, bytes.NewBuffer(requestBody))
116 if err != nil { 101 if err != nil {
117 Log(fmt.Sprintf("Error creating HTTP request: %v", err)) 102 curdhost.Log(fmt.Sprintf("Error creating HTTP request: %v", err))
118 return animeList, err 103 return animeList, err
119 } 104 }
120 req.Header.Set("Content-Type", "application/json") 105 req.Header.Set("Content-Type", "application/json")
@@ -122,9 +107,9 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
122 req.Header.Set("Referer", allanimeRef) 107 req.Header.Set("Referer", allanimeRef)
123 req.Header.Set("Origin", allanimeRef) 108 req.Header.Set("Origin", allanimeRef)
124 109
125 resp, err := sharedHTTPClient.Do(req) 110 resp, err := curdhost.HTTPClient().Do(req)
126 if err != nil { 111 if err != nil {
127 Log(fmt.Sprintf("Error making HTTP request: %v", err)) 112 curdhost.Log(fmt.Sprintf("Error making HTTP request: %v", err))
128 return animeList, err 113 return animeList, err
129 } 114 }
130 defer resp.Body.Close() 115 defer resp.Body.Close()
@@ -132,16 +117,16 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
132 // Read the response body 117 // Read the response body
133 body, err := io.ReadAll(resp.Body) 118 body, err := io.ReadAll(resp.Body)
134 if err != nil { 119 if err != nil {
135 Log(fmt.Sprintf("Error reading response body: %v", err)) 120 curdhost.Log(fmt.Sprintf("Error reading response body: %v", err))
136 return animeList, err 121 return animeList, err
137 } 122 }
138 123
139 // Debug: Log the response status and first part of the body 124 // Debug: Log the response status and first part of the body
140 Log(fmt.Sprintf("Response Status: %s", resp.Status)) 125 curdhost.Log(fmt.Sprintf("Response Status: %s", resp.Status))
141 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)]))) 126 curdhost.Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
142 if !httpStatusOK(resp.StatusCode) { 127 if !curdhost.HTTPStatusOK(resp.StatusCode) {
143 err := httpStatusError("allanime search", resp.StatusCode, body) 128 err := curdhost.HTTPStatusError("allanime search", resp.StatusCode, body)
144 Log(err) 129 curdhost.Log(err.Error())
145 return animeList, err 130 return animeList, err
146 } 131 }
147 132
@@ -149,7 +134,7 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
149 var response response 134 var response response
150 err = json.Unmarshal(body, &response) 135 err = json.Unmarshal(body, &response)
151 if err != nil { 136 if err != nil {
152 Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body))) 137 curdhost.Log(fmt.Sprintf("Error parsing JSON for query '%s': %v\nBody: %s", query, err, string(body)))
153 return animeList, err 138 return animeList, err
154 } 139 }
155 140
@@ -167,7 +152,7 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
167 152
168 // Use English name if available and configured, otherwise use default name 153 // Use English name if available and configured, otherwise use default name
169 displayName := anime.Name 154 displayName := anime.Name
170 if anime.EnglishName != "" && userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" { 155 if anime.EnglishName != "" && curdhost.AnimeNameLanguage != nil && curdhost.AnimeNameLanguage() == "english" {
171 displayName = anime.EnglishName 156 displayName = anime.EnglishName
172 } 157 }
173 158
@@ -176,7 +161,7 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
176 label = fmt.Sprintf("%s [%s]", label, mode) 161 label = fmt.Sprintf("%s [%s]", label, mode)
177 } 162 }
178 163
179 animeList = append(animeList, SelectionOption{ 164 animeList = append(animeList, providers.SelectionOption{
180 Title: displayName, 165 Title: displayName,
181 Key: anime.ID, 166 Key: anime.ID,
182 Label: label, 167 Label: label,
internal/episode_url_anicli.go → internal/providers/allanime/streams.go renamed +18 −35
@@ -1,4 +1,4 @@
1package internal 1package allanime
2 2
3import ( 3import (
4 "encoding/json" 4 "encoding/json"
@@ -12,16 +12,13 @@ import (
12 "strings" 12 "strings"
13 "sync" 13 "sync"
14 "time" 14 "time"
15
16 "github.com/wraient/curd/internal/curdhost"
17 "github.com/wraient/curd/internal/providers"
15) 18)
16 19
17const allanimeUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0" 20const allanimeUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0"
18 21
19// StreamPlaybackHint carries MPV playback metadata extracted from AllAnime clock.json.
20type StreamPlaybackHint struct {
21 Referrer string
22 Subtitle string
23}
24
25type allanimeResolvedStream struct { 22type allanimeResolvedStream struct {
26 URL string 23 URL string
27 Referrer string 24 Referrer string
@@ -36,7 +33,7 @@ var (
36 allanimeStreamBandwidthPattern = regexp.MustCompile(`BANDWIDTH=(\d+)`) 33 allanimeStreamBandwidthPattern = regexp.MustCompile(`BANDWIDTH=(\d+)`)
37) 34)
38 35
39func getAllanimeEpisodeStreamsForMode(id, mode string, epNo int) ([]string, map[string]StreamPlaybackHint, error) { 36func getAllanimeEpisodeStreamsForMode(id, mode string, epNo int) ([]string, map[string]providers.StreamPlaybackHint, error) {
40 sourceUrls, err := fetchEpisodeSourcesForMode(id, mode, epNo) 37 sourceUrls, err := fetchEpisodeSourcesForMode(id, mode, epNo)
41 if err != nil { 38 if err != nil {
42 return nil, nil, err 39 return nil, nil, err
@@ -44,7 +41,7 @@ func getAllanimeEpisodeStreamsForMode(id, mode string, epNo int) ([]string, map[
44 return getLinksFromEncodedSourceUrls(sourceUrls) 41 return getLinksFromEncodedSourceUrls(sourceUrls)
45} 42}
46 43
47func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[string]StreamPlaybackHint, error) { 44func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[string]providers.StreamPlaybackHint, error) {
48 type providerJob struct { 45 type providerJob struct {
49 index int 46 index int
50 name string 47 name string
@@ -84,7 +81,7 @@ func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[s
84 go func(idx int, providerName, encodedURL string) { 81 go func(idx int, providerName, encodedURL string) {
85 defer wg.Done() 82 defer wg.Done()
86 decodedProviderID := decodeProviderID(encodedURL[2:]) 83 decodedProviderID := decodeProviderID(encodedURL[2:])
87 Log(fmt.Sprintf("Fetching Allanime provider %s via %s", providerName, decodedProviderID)) 84 curdhost.Log(fmt.Sprintf("Fetching Allanime provider %s via %s", providerName, decodedProviderID))
88 streams, err := resolveAllanimeClockProvider(providerName, decodedProviderID) 85 streams, err := resolveAllanimeClockProvider(providerName, decodedProviderID)
89 results <- streamResult{index: idx, streams: streams, err: err} 86 results <- streamResult{index: idx, streams: streams, err: err}
90 }(job.index, job.name, job.url) 87 }(job.index, job.name, job.url)
@@ -108,14 +105,14 @@ func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[s
108 } 105 }
109 completedCount++ 106 completedCount++
110 if res.err != nil { 107 if res.err != nil {
111 Log(fmt.Sprintf("Allanime provider %s failed: %v", jobs[res.index].name, res.err)) 108 curdhost.Log(fmt.Sprintf("Allanime provider %s failed: %v", jobs[res.index].name, res.err))
112 collectedErrors = append(collectedErrors, fmt.Errorf("%s: %w", jobs[res.index].name, res.err)) 109 collectedErrors = append(collectedErrors, fmt.Errorf("%s: %w", jobs[res.index].name, res.err))
113 continue 110 continue
114 } 111 }
115 if len(res.streams) > 0 { 112 if len(res.streams) > 0 {
116 orderedStreams[res.index] = res.streams 113 orderedStreams[res.index] = res.streams
117 successCount++ 114 successCount++
118 Log(fmt.Sprintf("Allanime provider %s returned %d stream(s)", jobs[res.index].name, len(res.streams))) 115 curdhost.Log(fmt.Sprintf("Allanime provider %s returned %d stream(s)", jobs[res.index].name, len(res.streams)))
119 } 116 }
120 case <-timeout: 117 case <-timeout:
121 if successCount > 0 { 118 if successCount > 0 {
@@ -131,7 +128,7 @@ func getLinksFromEncodedSourceUrls(sourceUrls []allanimeSource) ([]string, map[s
131 return buildAllanimeLinkResult(orderedStreams) 128 return buildAllanimeLinkResult(orderedStreams)
132} 129}
133 130
134func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]string, map[string]StreamPlaybackHint, error) { 131func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]string, map[string]providers.StreamPlaybackHint, error) {
135 allStreams := make([]allanimeResolvedStream, 0) 132 allStreams := make([]allanimeResolvedStream, 0)
136 for _, streams := range orderedStreams { 133 for _, streams := range orderedStreams {
137 allStreams = append(allStreams, streams...) 134 allStreams = append(allStreams, streams...)
@@ -141,7 +138,7 @@ func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]strin
141 }) 138 })
142 139
143 links := make([]string, 0, len(allStreams)) 140 links := make([]string, 0, len(allStreams))
144 hints := make(map[string]StreamPlaybackHint) 141 hints := make(map[string]providers.StreamPlaybackHint)
145 seen := make(map[string]struct{}) 142 seen := make(map[string]struct{})
146 for _, stream := range allStreams { 143 for _, stream := range allStreams {
147 if stream.URL == "" || isUnreliableAllanimeDirectURL(stream.URL) { 144 if stream.URL == "" || isUnreliableAllanimeDirectURL(stream.URL) {
@@ -156,7 +153,7 @@ func buildAllanimeLinkResult(orderedStreams [][]allanimeResolvedStream) ([]strin
156 if referrer == "" { 153 if referrer == "" {
157 referrer = allanimeGraphQLReferer 154 referrer = allanimeGraphQLReferer
158 } 155 }
159 hints[stream.URL] = StreamPlaybackHint{ 156 hints[stream.URL] = providers.StreamPlaybackHint{
160 Referrer: referrer, 157 Referrer: referrer,
161 Subtitle: stream.SubtitleURL, 158 Subtitle: stream.SubtitleURL,
162 } 159 }
@@ -242,7 +239,7 @@ func fetchAllanimeClockResponse(providerPath string) ([]byte, map[string]interfa
242 req.Header.Set("Referer", allanimeGraphQLReferer) 239 req.Header.Set("Referer", allanimeGraphQLReferer)
243 req.Header.Set("User-Agent", allanimeUserAgent) 240 req.Header.Set("User-Agent", allanimeUserAgent)
244 241
245 resp, err := sharedHTTPClient.Do(req) 242 resp, err := curdhost.HTTPClient().Do(req)
246 if err != nil { 243 if err != nil {
247 return nil, nil, err 244 return nil, nil, err
248 } 245 }
@@ -252,8 +249,8 @@ func fetchAllanimeClockResponse(providerPath string) ([]byte, map[string]interfa
252 if err != nil { 249 if err != nil {
253 return nil, nil, err 250 return nil, nil, err
254 } 251 }
255 if !httpStatusOK(resp.StatusCode) { 252 if !curdhost.HTTPStatusOK(resp.StatusCode) {
256 return nil, nil, httpStatusError("allanime source extractor", resp.StatusCode, body) 253 return nil, nil, curdhost.HTTPStatusError("allanime source extractor", resp.StatusCode, body)
257 } 254 }
258 255
259 var videoData map[string]interface{} 256 var videoData map[string]interface{}
@@ -303,7 +300,7 @@ func fetchAllanimeM3U8VariantStreams(masterURL, referrer, subtitleURL string) ([
303 req.Header.Set("Referer", referrer) 300 req.Header.Set("Referer", referrer)
304 req.Header.Set("User-Agent", allanimeUserAgent) 301 req.Header.Set("User-Agent", allanimeUserAgent)
305 302
306 resp, err := sharedHTTPClient.Do(req) 303 resp, err := curdhost.HTTPClient().Do(req)
307 if err != nil { 304 if err != nil {
308 return nil, err 305 return nil, err
309 } 306 }
@@ -312,8 +309,8 @@ func fetchAllanimeM3U8VariantStreams(masterURL, referrer, subtitleURL string) ([
312 if err != nil { 309 if err != nil {
313 return nil, err 310 return nil, err
314 } 311 }
315 if !httpStatusOK(resp.StatusCode) { 312 if !curdhost.HTTPStatusOK(resp.StatusCode) {
316 return nil, httpStatusError("allanime m3u8 master playlist", resp.StatusCode, body) 313 return nil, curdhost.HTTPStatusError("allanime m3u8 master playlist", resp.StatusCode, body)
317 } 314 }
318 315
319 playlist := string(body) 316 playlist := string(body)
@@ -449,17 +446,3 @@ func streamsFromPlainURLs(urls []string, referrer, subtitleURL string, qualitySc
449 } 446 }
450 return streams 447 return streams
451} 448}
452
453func applyStreamPlaybackHints(anime *Anime, links []string, hints map[string]StreamPlaybackHint) {
454 if anime == nil || len(links) == 0 {
455 return
456 }
457 selected := PrioritizeLink(links)
458 if hint, ok := hints[selected]; ok {
459 anime.Ep.StreamReferrer = hint.Referrer
460 anime.Ep.SubtitleURL = hint.Subtitle
461 return
462 }
463 anime.Ep.StreamReferrer = ""
464 anime.Ep.SubtitleURL = ""
465}
internal/episode_url.go → internal/providers/allanime/streams_legacy.go renamed +31 −28
@@ -1,4 +1,4 @@
1package internal 1package allanime
2 2
3import ( 3import (
4 "bytes" 4 "bytes"
@@ -17,6 +17,9 @@ import (
17 "sort" 17 "sort"
18 "strconv" 18 "strconv"
19 "strings" 19 "strings"
20
21 "github.com/wraient/curd/internal/curdhost"
22 "github.com/wraient/curd/internal/providers"
20) 23)
21 24
22type allanimeSource struct { 25type allanimeSource struct {
@@ -231,13 +234,13 @@ func decodeBase64URLRaw(input string) ([]byte, error) {
231func extractFilemoonLinks(videoData map[string]interface{}) []string { 234func extractFilemoonLinks(videoData map[string]interface{}) []string {
232 raw, err := json.Marshal(videoData) 235 raw, err := json.Marshal(videoData)
233 if err != nil { 236 if err != nil {
234 Log(fmt.Sprintf("Error marshaling filemoon payload: %v", err)) 237 curdhost.Log(fmt.Sprintf("Error marshaling filemoon payload: %v", err))
235 return nil 238 return nil
236 } 239 }
237 240
238 var payload filemoonResponse 241 var payload filemoonResponse
239 if err := json.Unmarshal(raw, &payload); err != nil { 242 if err := json.Unmarshal(raw, &payload); err != nil {
240 Log(fmt.Sprintf("Error parsing filemoon payload: %v", err)) 243 curdhost.Log(fmt.Sprintf("Error parsing filemoon payload: %v", err))
241 return nil 244 return nil
242 } 245 }
243 246
@@ -247,30 +250,30 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
247 250
248 keyPart1, err := decodeBase64URLRaw(payload.KeyParts[0]) 251 keyPart1, err := decodeBase64URLRaw(payload.KeyParts[0])
249 if err != nil { 252 if err != nil {
250 Log(fmt.Sprintf("Error decoding filemoon key part 1: %v", err)) 253 curdhost.Log(fmt.Sprintf("Error decoding filemoon key part 1: %v", err))
251 return nil 254 return nil
252 } 255 }
253 256
254 keyPart2, err := decodeBase64URLRaw(payload.KeyParts[1]) 257 keyPart2, err := decodeBase64URLRaw(payload.KeyParts[1])
255 if err != nil { 258 if err != nil {
256 Log(fmt.Sprintf("Error decoding filemoon key part 2: %v", err)) 259 curdhost.Log(fmt.Sprintf("Error decoding filemoon key part 2: %v", err))
257 return nil 260 return nil
258 } 261 }
259 262
260 iv, err := decodeBase64URLRaw(payload.IV) 263 iv, err := decodeBase64URLRaw(payload.IV)
261 if err != nil { 264 if err != nil {
262 Log(fmt.Sprintf("Error decoding filemoon IV: %v", err)) 265 curdhost.Log(fmt.Sprintf("Error decoding filemoon IV: %v", err))
263 return nil 266 return nil
264 } 267 }
265 268
266 ciphertext, err := decodeBase64URLRaw(payload.Payload) 269 ciphertext, err := decodeBase64URLRaw(payload.Payload)
267 if err != nil { 270 if err != nil {
268 Log(fmt.Sprintf("Error decoding filemoon ciphertext: %v", err)) 271 curdhost.Log(fmt.Sprintf("Error decoding filemoon ciphertext: %v", err))
269 return nil 272 return nil
270 } 273 }
271 274
272 if len(ciphertext) <= 16 { 275 if len(ciphertext) <= 16 {
273 Log("Filemoon ciphertext is too short") 276 curdhost.Log("Filemoon ciphertext is too short")
274 return nil 277 return nil
275 } 278 }
276 279
@@ -280,25 +283,25 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
280 keyHex := hex.EncodeToString(append(keyPart1, keyPart2...)) 283 keyHex := hex.EncodeToString(append(keyPart1, keyPart2...))
281 key, err := hex.DecodeString(keyHex) 284 key, err := hex.DecodeString(keyHex)
282 if err != nil { 285 if err != nil {
283 Log(fmt.Sprintf("Error decoding filemoon key hex: %v", err)) 286 curdhost.Log(fmt.Sprintf("Error decoding filemoon key hex: %v", err))
284 return nil 287 return nil
285 } 288 }
286 289
287 ctrIVHex := hex.EncodeToString(iv) + "00000002" 290 ctrIVHex := hex.EncodeToString(iv) + "00000002"
288 ctrIV, err := hex.DecodeString(ctrIVHex) 291 ctrIV, err := hex.DecodeString(ctrIVHex)
289 if err != nil { 292 if err != nil {
290 Log(fmt.Sprintf("Error decoding filemoon CTR IV: %v", err)) 293 curdhost.Log(fmt.Sprintf("Error decoding filemoon CTR IV: %v", err))
291 return nil 294 return nil
292 } 295 }
293 296
294 if len(ctrIV) != aes.BlockSize { 297 if len(ctrIV) != aes.BlockSize {
295 Log(fmt.Sprintf("Invalid filemoon CTR IV size: %d", len(ctrIV))) 298 curdhost.Log(fmt.Sprintf("Invalid filemoon CTR IV size: %d", len(ctrIV)))
296 return nil 299 return nil
297 } 300 }
298 301
299 block, err := aes.NewCipher(key) 302 block, err := aes.NewCipher(key)
300 if err != nil { 303 if err != nil {
301 Log(fmt.Sprintf("Error creating filemoon cipher: %v", err)) 304 curdhost.Log(fmt.Sprintf("Error creating filemoon cipher: %v", err))
302 return nil 305 return nil
303 } 306 }
304 307
@@ -359,7 +362,7 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
359 } 362 }
360 363
361 if len(links) > 0 { 364 if len(links) > 0 {
362 Log("Filemoon links fetched") 365 curdhost.Log("Filemoon links fetched")
363 } 366 }
364 367
365 return links 368 return links
@@ -376,17 +379,17 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
376// Returns: 379// Returns:
377// - []string: a list of links for specified episode. 380// - []string: a list of links for specified episode.
378// - error: an error if the episode is not found or if there is an issue during the search. 381// - error: an error if the episode is not found or if there is an issue during the search.
379func getAllanimeEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) { 382func getAllanimeEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
380 preferredMode := normalizeTranslationType(config.SubOrDub) 383 preferredMode := providers.NormalizeTranslationType(config.SubOrDub)
381 return getAllanimeEpisodeURLForMode(id, preferredMode, epNo) 384 return getAllanimeEpisodeURLForMode(id, preferredMode, epNo)
382} 385}
383 386
384func getAllanimeEpisodeURLForMode(id, mode string, epNo int) ([]string, error) { 387func getAllanimeEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
385 return getEpisodeURLForMode(id, normalizeTranslationType(mode), epNo) 388 return getEpisodeURLForMode(id, providers.NormalizeTranslationType(mode), epNo)
386} 389}
387 390
388func fetchAllanimeEpisodeSources(id, mode string, epNo int) ([]allanimeSource, error) { 391func fetchAllanimeEpisodeSources(id, mode string, epNo int) ([]allanimeSource, error) {
389 return fetchEpisodeSourcesForMode(id, normalizeTranslationType(mode), epNo) 392 return fetchEpisodeSourcesForMode(id, providers.NormalizeTranslationType(mode), epNo)
390} 393}
391 394
392func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, error) { 395func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, error) {
@@ -398,7 +401,7 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
398 401
399 variables := map[string]interface{}{ 402 variables := map[string]interface{}{
400 "showId": id, 403 "showId": id,
401 "translationType": normalizeTranslationType(mode), 404 "translationType": providers.NormalizeTranslationType(mode),
402 "episodeString": fmt.Sprintf("%d", epNo), 405 "episodeString": fmt.Sprintf("%d", epNo),
403 } 406 }
404 407
@@ -429,7 +432,7 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
429 req.Header.Set("Referer", allanimePersistedQueryReferer) 432 req.Header.Set("Referer", allanimePersistedQueryReferer)
430 req.Header.Set("Origin", allanimePersistedQueryReferer) 433 req.Header.Set("Origin", allanimePersistedQueryReferer)
431 434
432 resp, err := sharedHTTPClient.Do(req) 435 resp, err := curdhost.HTTPClient().Do(req)
433 if err != nil { 436 if err != nil {
434 return nil, fmt.Errorf("failed to send persisted query request: %w", err) 437 return nil, fmt.Errorf("failed to send persisted query request: %w", err)
435 } 438 }
@@ -438,13 +441,13 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
438 if err != nil { 441 if err != nil {
439 return nil, fmt.Errorf("failed to read persisted query response: %w", err) 442 return nil, fmt.Errorf("failed to read persisted query response: %w", err)
440 } 443 }
441 if !httpStatusOK(resp.StatusCode) { 444 if !curdhost.HTTPStatusOK(resp.StatusCode) {
442 return nil, httpStatusError("allanime episode persisted query", resp.StatusCode, body) 445 return nil, curdhost.HTTPStatusError("allanime episode persisted query", resp.StatusCode, body)
443 } 446 }
444 447
445 var response allanimeResponse 448 var response allanimeResponse
446 if err := json.Unmarshal(body, &response); err != nil { 449 if err := json.Unmarshal(body, &response); err != nil {
447 Log(fmt.Sprint("Error parsing persisted query JSON: ", err)) 450 curdhost.Log(fmt.Sprint("Error parsing persisted query JSON: ", err))
448 } 451 }
449 452
450 useFallback := response.Data.Tobeparsed == "" && len(response.Data.Episode.SourceUrls) == 0 453 useFallback := response.Data.Tobeparsed == "" && len(response.Data.Episode.SourceUrls) == 0
@@ -473,7 +476,7 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
473 req.Header.Set("Referer", allanimeGraphQLReferer) 476 req.Header.Set("Referer", allanimeGraphQLReferer)
474 req.Header.Set("Origin", allanimeGraphQLReferer) 477 req.Header.Set("Origin", allanimeGraphQLReferer)
475 478
476 resp, err := sharedHTTPClient.Do(req) 479 resp, err := curdhost.HTTPClient().Do(req)
477 if err != nil { 480 if err != nil {
478 return nil, fmt.Errorf("failed to send request: %w", err) 481 return nil, fmt.Errorf("failed to send request: %w", err)
479 } 482 }
@@ -483,24 +486,24 @@ func fetchEpisodeSourcesForMode(id, mode string, epNo int) ([]allanimeSource, er
483 if err != nil { 486 if err != nil {
484 return nil, fmt.Errorf("failed to read response body: %w", err) 487 return nil, fmt.Errorf("failed to read response body: %w", err)
485 } 488 }
486 if !httpStatusOK(resp.StatusCode) { 489 if !curdhost.HTTPStatusOK(resp.StatusCode) {
487 return nil, httpStatusError("allanime episode fallback query", resp.StatusCode, body) 490 return nil, curdhost.HTTPStatusError("allanime episode fallback query", resp.StatusCode, body)
488 } 491 }
489 492
490 if err := json.Unmarshal(body, &response); err != nil { 493 if err := json.Unmarshal(body, &response); err != nil {
491 Log(fmt.Sprint("Error parsing fallback JSON: ", err)) 494 curdhost.Log(fmt.Sprint("Error parsing fallback JSON: ", err))
492 return nil, err 495 return nil, err
493 } 496 }
494 } 497 }
495 498
496 if response.Data.Tobeparsed != "" { 499 if response.Data.Tobeparsed != "" {
497 Log("Found tobeparsed field, decoding source URLs") 500 curdhost.Log("Found tobeparsed field, decoding source URLs")
498 decodedSources, err := decodeTobeparsed(response.Data.Tobeparsed) 501 decodedSources, err := decodeTobeparsed(response.Data.Tobeparsed)
499 if err != nil { 502 if err != nil {
500 return nil, err 503 return nil, err
501 } 504 }
502 505
503 Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources))) 506 curdhost.Log(fmt.Sprintf("Decoded %d Allanime source URLs from tobeparsed payload", len(decodedSources)))
504 return decodedSources, nil 507 return decodedSources, nil
505 } 508 }
506 509
internal/episode_url_test.go → internal/providers/allanime/streams_test.go renamed +1 −1
@@ -1,4 +1,4 @@
1package internal 1package allanime
2 2
3import ( 3import (
4 "strings" 4 "strings"
internal/provider_animepahe.go → internal/providers/animepahe/provider.go renamed +69 −58
@@ -1,4 +1,4 @@
1package internal 1package animepahe
2 2
3import ( 3import (
4 "encoding/json" 4 "encoding/json"
@@ -16,13 +16,16 @@ import (
16 16
17 "github.com/go-rod/rod" 17 "github.com/go-rod/rod"
18 "github.com/go-rod/rod/lib/launcher" 18 "github.com/go-rod/rod/lib/launcher"
19
20 "github.com/wraient/curd/internal/curdhost"
21 "github.com/wraient/curd/internal/providers"
19) 22)
20 23
21var animepaheCookiesBypassed bool 24var animepaheCookiesBypassed bool
22var solveAnimepaheBrowserChallenge = solveAnimepaheBrowserChallengeWithRod 25var solveAnimepaheBrowserChallenge = solveAnimepaheBrowserChallengeWithRod
23 26
24func getCookieFilePath() string { 27func getCookieFilePath() string {
25 return filepath.Join(GetStoragePath(), "animepahe_cookies.json") 28 return filepath.Join(curdhost.StoragePath(), "animepahe_cookies.json")
26} 29}
27 30
28func saveCookies(cookies []*http.Cookie) { 31func saveCookies(cookies []*http.Cookie) {
@@ -57,6 +60,11 @@ func newAnimepaheAPIRequest(rawURL string) (*http.Request, error) {
57 return req, nil 60 return req, nil
58} 61}
59 62
63// NewPageRequest builds an HTTP request for animepahe HTML pages.
64func NewPageRequest(rawURL string) (*http.Request, error) {
65 return newAnimepahePageRequest(rawURL)
66}
67
60func newAnimepahePageRequest(rawURL string) (*http.Request, error) { 68func newAnimepahePageRequest(rawURL string) (*http.Request, error) {
61 req, err := http.NewRequest("GET", rawURL, nil) 69 req, err := http.NewRequest("GET", rawURL, nil)
62 if err != nil { 70 if err != nil {
@@ -74,7 +82,7 @@ func checkCookiesValid() bool {
74 return false 82 return false
75 } 83 }
76 84
77 resp, err := sharedHTTPClient.Do(req) 85 resp, err := curdhost.HTTPClient().Do(req)
78 if err != nil { 86 if err != nil {
79 return false 87 return false
80 } 88 }
@@ -112,7 +120,7 @@ func isAnimepaheChallengeBody(body []byte) bool {
112 strings.Contains(normalized, "checking your browser") 120 strings.Contains(normalized, "checking your browser")
113} 121}
114 122
115func (p *AnimepaheProvider) ensureBypass() (err error) { 123func (p *Provider) ensureBypass() (err error) {
116 defer func() { 124 defer func() {
117 if recovered := recover(); recovered != nil { 125 if recovered := recover(); recovered != nil {
118 err = fmt.Errorf("failed to solve Animepahe DDoS-Guard challenge: %v", recovered) 126 err = fmt.Errorf("failed to solve Animepahe DDoS-Guard challenge: %v", recovered)
@@ -126,36 +134,36 @@ func (p *AnimepaheProvider) ensureBypass() (err error) {
126 cookies := loadCookies() 134 cookies := loadCookies()
127 if len(cookies) > 0 { 135 if len(cookies) > 0 {
128 u, _ := url.Parse("https://animepahe.pw") 136 u, _ := url.Parse("https://animepahe.pw")
129 SetCookiesForAnimepahe(u, cookies) 137 curdhost.SetCookiesForAnimepahe(u, cookies)
130 138
131 if checkCookiesValid() { 139 if checkCookiesValid() {
132 animepaheCookiesBypassed = true 140 animepaheCookiesBypassed = true
133 Log("Successfully restored Animepahe session from cache.") 141 curdhost.Log("Successfully restored Animepahe session from cache.")
134 return nil 142 return nil
135 } 143 }
136 Log("Cached Animepahe session expired. Requesting new session...") 144 curdhost.Log("Cached Animepahe session expired. Requesting new session...")
137 } 145 }
138 146
139 return p.refreshBypass() 147 return p.refreshBypass()
140} 148}
141 149
142func (p *AnimepaheProvider) refreshBypass() error { 150func (p *Provider) refreshBypass() error {
143 u, _ := url.Parse("https://animepahe.pw") 151 u, _ := url.Parse("https://animepahe.pw")
144 animepaheCookiesBypassed = false 152 animepaheCookiesBypassed = false
145 if err := os.Remove(getCookieFilePath()); err != nil && !os.IsNotExist(err) { 153 if err := os.Remove(getCookieFilePath()); err != nil && !os.IsNotExist(err) {
146 Log(fmt.Sprintf("Failed to remove cached Animepahe cookies: %v", err)) 154 curdhost.Log(fmt.Sprintf("Failed to remove cached Animepahe cookies: %v", err))
147 } 155 }
148 156
149 CurdOut("Animepahe needs a browser challenge before Curd can search or play. Starting a temporary headless browser...") 157 curdhost.Out("Animepahe needs a browser challenge before Curd can search or play. Starting a temporary headless browser...")
150 httpCookies, err := solveAnimepaheBrowserChallenge() 158 httpCookies, err := solveAnimepaheBrowserChallenge()
151 if err != nil { 159 if err != nil {
152 CurdOut("Animepahe browser challenge failed. Try again later or switch provider.") 160 curdhost.Out("Animepahe browser challenge failed. Try again later or switch provider.")
153 return fmt.Errorf("animepahe browser challenge failed: %w", err) 161 return fmt.Errorf("animepahe browser challenge failed: %w", err)
154 } 162 }
155 if len(httpCookies) == 0 { 163 if len(httpCookies) == 0 {
156 return fmt.Errorf("animepahe browser challenge returned no cookies") 164 return fmt.Errorf("animepahe browser challenge returned no cookies")
157 } 165 }
158 SetCookiesForAnimepahe(u, httpCookies) 166 curdhost.SetCookiesForAnimepahe(u, httpCookies)
159 167
160 if !checkCookiesValid() { 168 if !checkCookiesValid() {
161 return fmt.Errorf("bypassed cookies are still invalid") 169 return fmt.Errorf("bypassed cookies are still invalid")
@@ -163,7 +171,7 @@ func (p *AnimepaheProvider) refreshBypass() error {
163 171
164 saveCookies(httpCookies) 172 saveCookies(httpCookies)
165 animepaheCookiesBypassed = true 173 animepaheCookiesBypassed = true
166 CurdOut("Successfully bypassed DDoS-Guard.") 174 curdhost.Out("Successfully bypassed DDoS-Guard.")
167 return nil 175 return nil
168} 176}
169 177
@@ -201,13 +209,14 @@ func solveAnimepaheBrowserChallengeWithRod() (httpCookies []*http.Cookie, err er
201 return httpCookies, nil 209 return httpCookies, nil
202} 210}
203 211
204type AnimepaheProvider struct{} 212type Provider struct{}
205 213
206func (p *AnimepaheProvider) Name() string { 214func (p *Provider) Name() string {
207 return "animepahe" 215 return "animepahe"
208} 216}
209 217
210type AnimepaheSearchItem struct { 218// SearchItem is an animepahe API search result payload.
219type SearchItem struct {
211 ID int `json:"id"` 220 ID int `json:"id"`
212 Title string `json:"title"` 221 Title string `json:"title"`
213 Type string `json:"type"` 222 Type string `json:"type"`
@@ -220,19 +229,19 @@ type AnimepaheSearchItem struct {
220 Session string `json:"session"` 229 Session string `json:"session"`
221} 230}
222 231
223type animepaheAnimeRef struct { 232type AnimeRef struct {
224 ReleaseID string 233 ReleaseID string
225 Session string 234 Session string
226} 235}
227 236
228func (r animepaheAnimeRef) apiID() string { 237func (r AnimeRef) apiID() string {
229 if r.Session != "" { 238 if r.Session != "" {
230 return r.Session 239 return r.Session
231 } 240 }
232 return r.ReleaseID 241 return r.ReleaseID
233} 242}
234 243
235func formatAnimepaheProviderID(item AnimepaheSearchItem) string { 244func formatAnimepaheProviderID(item SearchItem) string {
236 if item.ID > 0 && item.Session != "" { 245 if item.ID > 0 && item.Session != "" {
237 return fmt.Sprintf("%d:%s", item.ID, item.Session) 246 return fmt.Sprintf("%d:%s", item.ID, item.Session)
238 } 247 }
@@ -245,36 +254,38 @@ func formatAnimepaheProviderID(item AnimepaheSearchItem) string {
245 return "" 254 return ""
246} 255}
247 256
248func parseAnimepaheProviderID(providerID string) animepaheAnimeRef { 257// ParseProviderID parses a stored animepahe show identifier.
258func ParseProviderID(providerID string) AnimeRef {
249 providerID = strings.TrimSpace(providerID) 259 providerID = strings.TrimSpace(providerID)
250 if providerID == "" { 260 if providerID == "" {
251 return animepaheAnimeRef{} 261 return AnimeRef{}
252 } 262 }
253 263
254 parts := strings.SplitN(providerID, ":", 2) 264 parts := strings.SplitN(providerID, ":", 2)
255 if len(parts) == 2 && parts[0] != "" && parts[1] != "" { 265 if len(parts) == 2 && parts[0] != "" && parts[1] != "" {
256 if _, err := strconv.Atoi(parts[0]); err == nil { 266 if _, err := strconv.Atoi(parts[0]); err == nil {
257 return animepaheAnimeRef{ReleaseID: parts[0], Session: parts[1]} 267 return AnimeRef{ReleaseID: parts[0], Session: parts[1]}
258 } 268 }
259 } 269 }
260 270
261 if _, err := strconv.Atoi(providerID); err == nil { 271 if _, err := strconv.Atoi(providerID); err == nil {
262 return animepaheAnimeRef{ReleaseID: providerID} 272 return AnimeRef{ReleaseID: providerID}
263 } 273 }
264 274
265 return animepaheAnimeRef{Session: providerID} 275 return AnimeRef{Session: providerID}
266} 276}
267 277
268func stableAnimepaheProviderID(providerID string) string { 278// StableProviderID returns the release id portion used for history matching.
269 animeRef := parseAnimepaheProviderID(providerID) 279func StableProviderID(providerID string) string {
280 animeRef := ParseProviderID(providerID)
270 if animeRef.ReleaseID != "" { 281 if animeRef.ReleaseID != "" {
271 return animeRef.ReleaseID 282 return animeRef.ReleaseID
272 } 283 }
273 return providerID 284 return providerID
274} 285}
275 286
276func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string, error) { 287func (p *Provider) ResolveProviderID(providerID, query string) (string, error) {
277 animeRef := parseAnimepaheProviderID(providerID) 288 animeRef := ParseProviderID(providerID)
278 query = strings.TrimSpace(query) 289 query = strings.TrimSpace(query)
279 if query == "" { 290 if query == "" {
280 if animeRef.Session != "" { 291 if animeRef.Session != "" {
@@ -286,14 +297,14 @@ func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string,
286 options, err := p.SearchAnime(query, "") 297 options, err := p.SearchAnime(query, "")
287 if err != nil { 298 if err != nil {
288 if animeRef.Session != "" { 299 if animeRef.Session != "" {
289 Log(fmt.Sprintf("Animepahe provider id refresh failed for %q, using existing session: %v", providerID, err)) 300 curdhost.Log(fmt.Sprintf("Animepahe provider id refresh failed for %q, using existing session: %v", providerID, err))
290 return providerID, nil 301 return providerID, nil
291 } 302 }
292 return "", err 303 return "", err
293 } 304 }
294 305
295 for _, option := range options { 306 for _, option := range options {
296 item, ok := option.ExtraData.(AnimepaheSearchItem) 307 item, ok := option.ExtraData.(SearchItem)
297 if !ok { 308 if !ok {
298 continue 309 continue
299 } 310 }
@@ -307,7 +318,7 @@ func (p *AnimepaheProvider) ResolveProviderID(providerID, query string) (string,
307 } 318 }
308 319
309 if animeRef.Session != "" { 320 if animeRef.Session != "" {
310 Log(fmt.Sprintf("Animepahe provider id %q was not found in search results for %q, using existing session", providerID, query)) 321 curdhost.Log(fmt.Sprintf("Animepahe provider id %q was not found in search results for %q, using existing session", providerID, query))
311 return providerID, nil 322 return providerID, nil
312 } 323 }
313 324
@@ -319,10 +330,10 @@ type animepaheSearchResponse struct {
319 PerPage int `json:"per_page"` 330 PerPage int `json:"per_page"`
320 CurrentPage int `json:"current_page"` 331 CurrentPage int `json:"current_page"`
321 LastPage int `json:"last_page"` 332 LastPage int `json:"last_page"`
322 Data []AnimepaheSearchItem `json:"data"` 333 Data []SearchItem `json:"data"`
323} 334}
324 335
325func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption, error) { 336func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
326 if err := p.ensureBypass(); err != nil { 337 if err := p.ensureBypass(); err != nil {
327 return nil, err 338 return nil, err
328 } 339 }
@@ -334,7 +345,7 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
334 return nil, err 345 return nil, err
335 } 346 }
336 347
337 resp, err := sharedHTTPClient.Do(req) 348 resp, err := curdhost.HTTPClient().Do(req)
338 if err != nil { 349 if err != nil {
339 return nil, err 350 return nil, err
340 } 351 }
@@ -344,8 +355,8 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
344 if err != nil { 355 if err != nil {
345 return nil, err 356 return nil, err
346 } 357 }
347 if !httpStatusOK(resp.StatusCode) { 358 if !curdhost.HTTPStatusOK(resp.StatusCode) {
348 return nil, httpStatusError("animepahe search", resp.StatusCode, body) 359 return nil, curdhost.HTTPStatusError("animepahe search", resp.StatusCode, body)
349 } 360 }
350 361
351 var searchResp animepaheSearchResponse 362 var searchResp animepaheSearchResponse
@@ -354,10 +365,10 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
354 return nil, err 365 return nil, err
355 } 366 }
356 367
357 var result []SelectionOption 368 var result []providers.SelectionOption
358 for _, item := range searchResp.Data { 369 for _, item := range searchResp.Data {
359 label := fmt.Sprintf("%s (%d episodes) [animepahe]", item.Title, item.Episodes) 370 label := fmt.Sprintf("%s (%d episodes) [animepahe]", item.Title, item.Episodes)
360 result = append(result, SelectionOption{ 371 result = append(result, providers.SelectionOption{
361 Title: item.Title, 372 Title: item.Title,
362 Label: label, 373 Label: label,
363 Key: formatAnimepaheProviderID(item), 374 Key: formatAnimepaheProviderID(item),
@@ -382,11 +393,11 @@ type animepaheEpisodesResponse struct {
382 } `json:"data"` 393 } `json:"data"`
383} 394}
384 395
385func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error) { 396func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
386 if err := p.ensureBypass(); err != nil { 397 if err := p.ensureBypass(); err != nil {
387 return nil, err 398 return nil, err
388 } 399 }
389 animeRef := parseAnimepaheProviderID(showID) 400 animeRef := ParseProviderID(showID)
390 apiID := animeRef.apiID() 401 apiID := animeRef.apiID()
391 if apiID == "" { 402 if apiID == "" {
392 return nil, fmt.Errorf("animepahe provider id %q is invalid; please reselect this anime", showID) 403 return nil, fmt.Errorf("animepahe provider id %q is invalid; please reselect this anime", showID)
@@ -403,7 +414,7 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
403 return nil, err 414 return nil, err
404 } 415 }
405 416
406 resp, err := sharedHTTPClient.Do(req) 417 resp, err := curdhost.HTTPClient().Do(req)
407 if err != nil { 418 if err != nil {
408 return nil, err 419 return nil, err
409 } 420 }
@@ -417,15 +428,15 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
417 if challengeRetried { 428 if challengeRetried {
418 return nil, fmt.Errorf("animepahe episode list is still blocked by DDoS-Guard after refreshing browser session") 429 return nil, fmt.Errorf("animepahe episode list is still blocked by DDoS-Guard after refreshing browser session")
419 } 430 }
420 Log("Animepahe episode list returned DDoS-Guard challenge. Refreshing browser session...") 431 curdhost.Log("Animepahe episode list returned DDoS-Guard challenge. Refreshing browser session...")
421 if err := p.refreshBypass(); err != nil { 432 if err := p.refreshBypass(); err != nil {
422 return nil, err 433 return nil, err
423 } 434 }
424 challengeRetried = true 435 challengeRetried = true
425 continue 436 continue
426 } 437 }
427 if !httpStatusOK(resp.StatusCode) { 438 if !curdhost.HTTPStatusOK(resp.StatusCode) {
428 return nil, httpStatusError("animepahe episode list", resp.StatusCode, body) 439 return nil, curdhost.HTTPStatusError("animepahe episode list", resp.StatusCode, body)
429 } 440 }
430 441
431 var epsResp animepaheEpisodesResponse 442 var epsResp animepaheEpisodesResponse
@@ -453,15 +464,15 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
453 return result, nil 464 return result, nil
454} 465}
455 466
456func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) { 467func (p *Provider) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
457 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub) 468 return p.GetEpisodeURLForMode(config, id, epNo, config.SubOrDub)
458} 469}
459 470
460func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, epNo int, mode string) ([]string, error) { 471func (p *Provider) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
461 if err := p.ensureBypass(); err != nil { 472 if err := p.ensureBypass(); err != nil {
462 return nil, err 473 return nil, err
463 } 474 }
464 animeRef := parseAnimepaheProviderID(id) 475 animeRef := ParseProviderID(id)
465 if animeRef.Session == "" { 476 if animeRef.Session == "" {
466 return nil, fmt.Errorf("animepahe provider id %q is missing session id; please reselect this anime", id) 477 return nil, fmt.Errorf("animepahe provider id %q is missing session id; please reselect this anime", id)
467 } 478 }
@@ -492,7 +503,7 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
492 return nil, err 503 return nil, err
493 } 504 }
494 505
495 resp, err := sharedHTTPClient.Do(req) 506 resp, err := curdhost.HTTPClient().Do(req)
496 if err != nil { 507 if err != nil {
497 return nil, err 508 return nil, err
498 } 509 }
@@ -502,8 +513,8 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
502 if err != nil { 513 if err != nil {
503 return nil, err 514 return nil, err
504 } 515 }
505 if !httpStatusOK(resp.StatusCode) { 516 if !curdhost.HTTPStatusOK(resp.StatusCode) {
506 return nil, httpStatusError("animepahe episode lookup", resp.StatusCode, body) 517 return nil, curdhost.HTTPStatusError("animepahe episode lookup", resp.StatusCode, body)
507 } 518 }
508 519
509 var epsResp animepaheEpisodesResponse 520 var epsResp animepaheEpisodesResponse
@@ -537,7 +548,7 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
537 return nil, err 548 return nil, err
538 } 549 }
539 550
540 resp, err := sharedHTTPClient.Do(req) 551 resp, err := curdhost.HTTPClient().Do(req)
541 if err != nil { 552 if err != nil {
542 return nil, err 553 return nil, err
543 } 554 }
@@ -547,8 +558,8 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
547 if err != nil { 558 if err != nil {
548 return nil, err 559 return nil, err
549 } 560 }
550 if !httpStatusOK(resp.StatusCode) { 561 if !curdhost.HTTPStatusOK(resp.StatusCode) {
551 return nil, httpStatusError("animepahe player page", resp.StatusCode, body) 562 return nil, curdhost.HTTPStatusError("animepahe player page", resp.StatusCode, body)
552 } 563 }
553 564
554 bodyStr := string(body) 565 bodyStr := string(body)
@@ -606,7 +617,7 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
606 sortFunc(dubLinks) 617 sortFunc(dubLinks)
607 618
608 var links []string 619 var links []string
609 requestedMode := normalizeTranslationType(mode) 620 requestedMode := providers.NormalizeTranslationType(mode)
610 if requestedMode == "dub" { 621 if requestedMode == "dub" {
611 for _, l := range dubLinks { 622 for _, l := range dubLinks {
612 links = append(links, l.url) 623 links = append(links, l.url)
@@ -635,13 +646,13 @@ func (p *AnimepaheProvider) GetEpisodeURLForMode(config CurdConfig, id string, e
635 return finalLinks, nil 646 return finalLinks, nil
636} 647}
637 648
638func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) { 649func (p *Provider) extractKwikM3u8(kwikUrl string) (string, error) {
639 req, err := newAnimepahePageRequest(kwikUrl) 650 req, err := newAnimepahePageRequest(kwikUrl)
640 if err != nil { 651 if err != nil {
641 return "", err 652 return "", err
642 } 653 }
643 654
644 resp, err := sharedHTTPClient.Do(req) 655 resp, err := curdhost.HTTPClient().Do(req)
645 if err != nil { 656 if err != nil {
646 return "", err 657 return "", err
647 } 658 }
@@ -651,8 +662,8 @@ func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) {
651 if err != nil { 662 if err != nil {
652 return "", err 663 return "", err
653 } 664 }
654 if !httpStatusOK(resp.StatusCode) { 665 if !curdhost.HTTPStatusOK(resp.StatusCode) {
655 return "", httpStatusError("kwik stream page", resp.StatusCode, body) 666 return "", curdhost.HTTPStatusError("kwik stream page", resp.StatusCode, body)
656 } 667 }
657 bodyStr := string(body) 668 bodyStr := string(body)
658 669
internal/provider_animepahe_test.go → internal/providers/animepahe/provider_test.go renamed +31 −13
@@ -1,16 +1,25 @@
1package internal 1package animepahe
2 2
3import ( 3import (
4 "io" 4 "io"
5 "net/http" 5 "net/http"
6 "net/http/cookiejar" 6 "net/http/cookiejar"
7 "net/url"
7 "os" 8 "os"
8 "strings" 9 "strings"
9 "testing" 10 "testing"
11
12 "github.com/wraient/curd/internal/curdhost"
10) 13)
11 14
12const animepaheChallengeHTML = `<!doctype html><html><head><title>DDoS-Guard</title></head><body>Checking your browser</body></html>` 15const animepaheChallengeHTML = `<!doctype html><html><head><title>DDoS-Guard</title></head><body>Checking your browser</body></html>`
13 16
17type roundTripFunc func(*http.Request) (*http.Response, error)
18
19func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
20 return f(req)
21}
22
14func animepaheTestResponse(req *http.Request, statusCode int, body string, headers map[string]string) *http.Response { 23func animepaheTestResponse(req *http.Request, statusCode int, body string, headers map[string]string) *http.Response {
15 resp := &http.Response{ 24 resp := &http.Response{
16 StatusCode: statusCode, 25 StatusCode: statusCode,
@@ -27,21 +36,30 @@ func animepaheTestResponse(req *http.Request, statusCode int, body string, heade
27func withAnimepaheTestHooks(t *testing.T, client *http.Client, solver func() ([]*http.Cookie, error)) { 36func withAnimepaheTestHooks(t *testing.T, client *http.Client, solver func() ([]*http.Cookie, error)) {
28 t.Helper() 37 t.Helper()
29 38
30 previousClient := sharedHTTPClient 39 previousClient := curdhost.HTTPClient
40 previousLog := curdhost.Log
41 previousOut := curdhost.Out
42 previousCookies := curdhost.SetCookiesForAnimepahe
31 previousSolver := solveAnimepaheBrowserChallenge 43 previousSolver := solveAnimepaheBrowserChallenge
32 previousBypassed := animepaheCookiesBypassed 44 previousBypassed := animepaheCookiesBypassed
33 previousConfig := GetGlobalConfig() 45 previousStoragePath := curdhost.StoragePath
34 46
35 t.Cleanup(func() { 47 t.Cleanup(func() {
36 sharedHTTPClient = previousClient 48 curdhost.HTTPClient = previousClient
49 curdhost.Log = previousLog
50 curdhost.Out = previousOut
51 curdhost.SetCookiesForAnimepahe = previousCookies
37 solveAnimepaheBrowserChallenge = previousSolver 52 solveAnimepaheBrowserChallenge = previousSolver
38 animepaheCookiesBypassed = previousBypassed 53 animepaheCookiesBypassed = previousBypassed
39 SetGlobalConfig(previousConfig) 54 curdhost.StoragePath = previousStoragePath
40 }) 55 })
41 56
42 sharedHTTPClient = client 57 curdhost.HTTPClient = func() *http.Client { return client }
58 curdhost.Log = func(string) {}
59 curdhost.Out = func(string) {}
60 curdhost.SetCookiesForAnimepahe = func(*url.URL, []*http.Cookie) {}
43 solveAnimepaheBrowserChallenge = solver 61 solveAnimepaheBrowserChallenge = solver
44 SetGlobalConfig(&CurdConfig{StoragePath: t.TempDir()}) 62 curdhost.StoragePath = func() string { return t.TempDir() }
45} 63}
46 64
47func TestAnimepaheEpisodesListRefreshesSessionWhenReleaseEndpointReturnsChallenge(t *testing.T) { 65func TestAnimepaheEpisodesListRefreshesSessionWhenReleaseEndpointReturnsChallenge(t *testing.T) {
@@ -82,7 +100,7 @@ func TestAnimepaheEpisodesListRefreshesSessionWhenReleaseEndpointReturnsChalleng
82 }) 100 })
83 animepaheCookiesBypassed = true 101 animepaheCookiesBypassed = true
84 102
85 episodes, err := (&AnimepaheProvider{}).EpisodesList("4:session-id", "sub") 103 episodes, err := (&Provider{}).EpisodesList("4:session-id", "sub")
86 if err != nil { 104 if err != nil {
87 t.Fatalf("expected episode list retry to succeed: %v", err) 105 t.Fatalf("expected episode list retry to succeed: %v", err)
88 } 106 }
@@ -129,7 +147,7 @@ func TestAnimepaheEpisodesListReportsPersistentChallengeAfterRefresh(t *testing.
129 }) 147 })
130 animepaheCookiesBypassed = true 148 animepaheCookiesBypassed = true
131 149
132 _, err = (&AnimepaheProvider{}).EpisodesList("4:session-id", "sub") 150 _, err = (&Provider{}).EpisodesList("4:session-id", "sub")
133 if err == nil { 151 if err == nil {
134 t.Fatalf("expected persistent DDoS-Guard challenge to fail") 152 t.Fatalf("expected persistent DDoS-Guard challenge to fail")
135 } 153 }
@@ -146,16 +164,16 @@ func TestAnimepaheEpisodesListLiveOnePiece(t *testing.T) {
146 t.Skip("set CURD_LIVE_ANIMEPAHE_TEST=1 to run live Animepahe episode-list verification") 164 t.Skip("set CURD_LIVE_ANIMEPAHE_TEST=1 to run live Animepahe episode-list verification")
147 } 165 }
148 166
149 previousConfig := GetGlobalConfig()
150 previousBypassed := animepaheCookiesBypassed 167 previousBypassed := animepaheCookiesBypassed
168 previousStoragePath := curdhost.StoragePath
151 t.Cleanup(func() { 169 t.Cleanup(func() {
152 SetGlobalConfig(previousConfig)
153 animepaheCookiesBypassed = previousBypassed 170 animepaheCookiesBypassed = previousBypassed
171 curdhost.StoragePath = previousStoragePath
154 }) 172 })
155 SetGlobalConfig(&CurdConfig{StoragePath: t.TempDir()}) 173 curdhost.StoragePath = func() string { return t.TempDir() }
156 animepaheCookiesBypassed = false 174 animepaheCookiesBypassed = false
157 175
158 episodes, err := (&AnimepaheProvider{}).EpisodesList("4:15a36fc8-73b9-8c2e-ee5f-fb1bcd4fcdc6", "sub") 176 episodes, err := (&Provider{}).EpisodesList("4:15a36fc8-73b9-8c2e-ee5f-fb1bcd4fcdc6", "sub")
159 if err != nil { 177 if err != nil {
160 t.Fatalf("live Animepahe One Piece episode list failed: %v", err) 178 t.Fatalf("live Animepahe One Piece episode list failed: %v", err)
161 } 179 }
internal/providers/animepahe/register.go added +17
@@ -0,0 +1,17 @@
1package animepahe
2
3import "github.com/wraient/curd/internal/providers"
4
5func init() {
6 providers.Register(providers.Meta{
7 Name: "animepahe",
8 Aliases: []string{"pahe"},
9 Referrer: "https://kwik.cx/",
10 DefaultDisabled: true,
11 DisableReason: "Cloudflare/DDoS-Guard protection cannot be bypassed reliably",
12 OptOutToken: "no-animepahe",
13 FallbackPrompt: "Animepahe may require downloading a Chromium browser for DDoS-Guard verification (~500 MB).",
14 }, func() providers.Provider {
15 return &Provider{}
16 })
17}
internal/providers/anineko/bibiemb.go added +110
@@ -0,0 +1,110 @@
1package anineko
2
3import (
4 "fmt"
5 "net/url"
6 "regexp"
7 "strings"
8)
9
10var (
11 bibiembMasterRE = regexp.MustCompile(`const src = "(https?://[^"]+/master\.m3u8)"`)
12 streamInfRE = regexp.MustCompile(`(?m)^#EXT-X-STREAM-INF:.*NAME="([^"]+)".*\r?\n([^\r\n#]+)`)
13)
14
15var bibiembQualityOrder = []string{"1080p", "720p", "480p", "360p"}
16
17type resolvedStream struct {
18 URL string
19 Referrer string
20 Subtitle string
21}
22
23func resolveBibiemb(embedURL string) (resolvedStream, error) {
24 embedURL = strings.TrimSpace(embedURL)
25 if embedURL == "" {
26 return resolvedStream{}, fmt.Errorf("empty bibiemb embed url")
27 }
28
29 html, err := fetchString(embedURL, baseURL+"/")
30 if err != nil {
31 return resolvedStream{}, err
32 }
33
34 match := bibiembMasterRE.FindStringSubmatch(html)
35 if len(match) < 2 {
36 return resolvedStream{}, fmt.Errorf("bibiemb master m3u8 not found")
37 }
38
39 masterURL := match[1]
40 variantURL, err := pickBibiembVariant(masterURL, embedURL)
41 if err != nil {
42 return resolvedStream{}, err
43 }
44
45 return resolvedStream{
46 URL: variantURL,
47 Referrer: embedURL,
48 Subtitle: subtitleFromEmbedURL(embedURL),
49 }, nil
50}
51
52func pickBibiembVariant(masterURL, referer string) (string, error) {
53 playlist, err := fetchString(masterURL, referer)
54 if err != nil {
55 return "", err
56 }
57
58 type variant struct {
59 name string
60 url string
61 }
62 variants := make([]variant, 0)
63 for _, match := range streamInfRE.FindAllStringSubmatch(playlist, -1) {
64 if len(match) < 3 {
65 continue
66 }
67 variants = append(variants, variant{
68 name: strings.TrimSpace(match[1]),
69 url: resolvePlaylistURL(masterURL, strings.TrimSpace(match[2])),
70 })
71 }
72 if len(variants) == 0 {
73 return "", fmt.Errorf("no bibiemb variants in master playlist")
74 }
75
76 byName := map[string]string{}
77 for _, item := range variants {
78 byName[strings.ToLower(item.name)] = item.url
79 }
80 for _, quality := range bibiembQualityOrder {
81 if streamURL, ok := byName[quality]; ok {
82 return streamURL, nil
83 }
84 }
85 return variants[0].url, nil
86}
87
88func resolvePlaylistURL(baseURL, entry string) string {
89 if strings.HasPrefix(entry, "http://") || strings.HasPrefix(entry, "https://") {
90 return entry
91 }
92 parsed, err := url.Parse(baseURL)
93 if err != nil {
94 return entry
95 }
96 if strings.HasPrefix(entry, "/") {
97 parsed.Path = entry
98 parsed.RawQuery = ""
99 parsed.Fragment = ""
100 return parsed.Scheme + "://" + parsed.Host + entry
101 }
102 if idx := strings.LastIndex(parsed.Path, "/"); idx >= 0 {
103 parsed.Path = parsed.Path[:idx+1] + entry
104 } else {
105 parsed.Path = "/" + entry
106 }
107 parsed.RawQuery = ""
108 parsed.Fragment = ""
109 return parsed.String()
110}
internal/providers/anineko/client.go added +92
@@ -0,0 +1,92 @@
1package anineko
2
3import (
4 "fmt"
5 "io"
6 "net/http"
7 "strings"
8
9 "github.com/wraient/curd/internal/curdhost"
10)
11
12const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
13
14var baseURL = "https://anineko.to"
15
16func newRequest(method, rawURL, referer string) (*http.Request, error) {
17 req, err := http.NewRequest(method, rawURL, nil)
18 if err != nil {
19 return nil, err
20 }
21 req.Header.Set("User-Agent", userAgent)
22 if referer != "" {
23 req.Header.Set("Referer", referer)
24 }
25 return req, nil
26}
27
28func fetchString(rawURL, referer string) (string, error) {
29 req, err := newRequest(http.MethodGet, rawURL, referer)
30 if err != nil {
31 return "", err
32 }
33 resp, err := curdhost.HTTPClient().Do(req)
34 if err != nil {
35 return "", err
36 }
37 defer resp.Body.Close()
38
39 body, err := io.ReadAll(resp.Body)
40 if err != nil {
41 return "", err
42 }
43 if !curdhost.HTTPStatusOK(resp.StatusCode) {
44 return "", curdhost.HTTPStatusError("anineko request", resp.StatusCode, body)
45 }
46 return string(body), nil
47}
48
49func fetchBytes(rawURL, referer string) ([]byte, error) {
50 req, err := newRequest(http.MethodGet, rawURL, referer)
51 if err != nil {
52 return nil, err
53 }
54 resp, err := curdhost.HTTPClient().Do(req)
55 if err != nil {
56 return nil, err
57 }
58 defer resp.Body.Close()
59
60 body, err := io.ReadAll(resp.Body)
61 if err != nil {
62 return nil, err
63 }
64 if !curdhost.HTTPStatusOK(resp.StatusCode) {
65 return nil, curdhost.HTTPStatusError("anineko request", resp.StatusCode, body)
66 }
67 return body, nil
68}
69
70func absoluteURL(path string) string {
71 path = strings.TrimSpace(path)
72 if path == "" {
73 return ""
74 }
75 if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
76 return path
77 }
78 if strings.HasPrefix(path, "//") {
79 return "https:" + path
80 }
81 if !strings.HasPrefix(path, "/") {
82 path = "/" + path
83 }
84 return baseURL + path
85}
86
87func watchURL(slug string, epNo int) string {
88 if epNo > 0 {
89 return fmt.Sprintf("%s/watch/%s/ep-%d", baseURL, slug, epNo)
90 }
91 return fmt.Sprintf("%s/watch/%s", baseURL, slug)
92}
internal/providers/anineko/episodes.go added +50
@@ -0,0 +1,50 @@
1package anineko
2
3import (
4 "fmt"
5 "regexp"
6 "sort"
7 "strconv"
8 "strings"
9)
10
11var episodePathRE = regexp.MustCompile(`/ep-(\d+)`)
12
13func episodesList(showID, mode string) ([]string, error) {
14 slug := strings.TrimSpace(showID)
15 if slug == "" {
16 return nil, fmt.Errorf("empty show id")
17 }
18
19 html, err := fetchString(watchURL(slug, 0), baseURL+"/")
20 if err != nil {
21 return nil, err
22 }
23
24 seen := map[int]struct{}{}
25 for _, match := range episodePathRE.FindAllStringSubmatch(html, -1) {
26 if len(match) < 2 {
27 continue
28 }
29 epNo, err := strconv.Atoi(match[1])
30 if err != nil || epNo <= 0 {
31 continue
32 }
33 seen[epNo] = struct{}{}
34 }
35 if len(seen) == 0 {
36 return nil, fmt.Errorf("no episodes found for %q", slug)
37 }
38
39 episodes := make([]int, 0, len(seen))
40 for epNo := range seen {
41 episodes = append(episodes, epNo)
42 }
43 sort.Ints(episodes)
44
45 result := make([]string, 0, len(episodes))
46 for _, epNo := range episodes {
47 result = append(result, strconv.Itoa(epNo))
48 }
49 return result, nil
50}
internal/providers/anineko/provider.go added +34
@@ -0,0 +1,34 @@
1package anineko
2
3import "github.com/wraient/curd/internal/providers"
4
5// Provider implements anineko.to catalog search and stream resolution.
6type Provider struct{}
7
8func (p *Provider) Name() string {
9 return "anineko"
10}
11
12func (p *Provider) SearchAnime(query, mode string) ([]providers.SelectionOption, error) {
13 return searchAnime(query, mode)
14}
15
16func (p *Provider) EpisodesList(showID, mode string) ([]string, error) {
17 return episodesList(showID, mode)
18}
19
20func (p *Provider) GetEpisodeURL(config providers.PlaybackConfig, id string, epNo int) ([]string, error) {
21 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, config.SubOrDub)
22 return links, err
23}
24
25func (p *Provider) GetEpisodeURLForMode(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, error) {
26 links, _, err := p.GetEpisodeURLForModeWithHints(config, id, epNo, mode)
27 return links, err
28}
29
30func (p *Provider) GetEpisodeURLForModeWithHints(config providers.PlaybackConfig, id string, epNo int, mode string) ([]string, map[string]providers.StreamPlaybackHint, error) {
31 playback := config
32 playback.SubOrDub = providers.NormalizeTranslationType(mode)
33 return getEpisodeStreamsForMode(id, playback, epNo)
34}
internal/providers/anineko/provider_test.go added +314
@@ -0,0 +1,314 @@
1package anineko
2
3import (
4 "io"
5 "net/http"
6 "net/http/httptest"
7 "strings"
8 "testing"
9
10 "github.com/wraient/curd/internal/curdhost"
11)
12
13type roundTripFunc func(*http.Request) (*http.Response, error)
14
15func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
16 return f(req)
17}
18
19func testResponse(req *http.Request, statusCode int, body string, headers map[string]string) *http.Response {
20 resp := &http.Response{
21 StatusCode: statusCode,
22 Header: make(http.Header),
23 Body: io.NopCloser(strings.NewReader(body)),
24 Request: req,
25 }
26 for key, value := range headers {
27 resp.Header.Set(key, value)
28 }
29 return resp
30}
31
32func withAninekoTestClient(t *testing.T, client *http.Client) {
33 t.Helper()
34 previous := curdhost.HTTPClient
35 t.Cleanup(func() {
36 curdhost.HTTPClient = previous
37 resetVibeProxyForTest()
38 resetSubStyleForTest()
39 })
40 curdhost.HTTPClient = func() *http.Client { return client }
41}
42
43func TestSearchAnimeParsesResults(t *testing.T) {
44 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
45 if r.URL.Path != "/ajax/search" {
46 http.NotFound(w, r)
47 return
48 }
49 _, _ = io.WriteString(w, `{"success":true,"results":[{"title":"One Piece","url":"/watch/one-piece","image":"/img/op.jpg","meta":"TV"}]}`)
50 }))
51 defer server.Close()
52
53 withAninekoTestClient(t, server.Client())
54
55 originalBase := baseURL
56 t.Cleanup(func() { baseURL = originalBase })
57 baseURL = server.URL
58
59 options, err := searchAnime("one piece", "sub")
60 if err != nil {
61 t.Fatalf("searchAnime: %v", err)
62 }
63 if len(options) != 1 {
64 t.Fatalf("expected 1 option, got %d", len(options))
65 }
66 if options[0].Key != "one-piece" {
67 t.Fatalf("unexpected key %q", options[0].Key)
68 }
69 if options[0].Thumbnail != server.URL+"/img/op.jpg" {
70 t.Fatalf("unexpected thumbnail %q", options[0].Thumbnail)
71 }
72}
73
74func TestEpisodesListParsesEpisodeLinks(t *testing.T) {
75 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
76 _, _ = io.WriteString(w, `<a href="/watch/frieren/ep-1">1</a><a href="/watch/frieren/ep-12">12</a>`)
77 }))
78 defer server.Close()
79
80 withAninekoTestClient(t, server.Client())
81 originalBase := baseURL
82 t.Cleanup(func() { baseURL = originalBase })
83 baseURL = server.URL
84
85 episodes, err := episodesList("frieren", "sub")
86 if err != nil {
87 t.Fatalf("episodesList: %v", err)
88 }
89 if strings.Join(episodes, ",") != "1,12" {
90 t.Fatalf("unexpected episodes %v", episodes)
91 }
92}
93
94func TestExtractLangEmbedURLs(t *testing.T) {
95 html := `
96<div class="server-items" data-id="sub">
97 <div data-video="https://bibiemb.xyz/aaa"></div>
98 <div data-video="https://vibeplayer.site/bbb?sub=https://cdn.example/sub.vtt"></div>
99</div>
100<div class="server-items" data-id="dub">
101 <div data-video="https://bibiemb.xyz/ccc"></div>
102</div>`
103
104 groups := extractLangEmbedURLs(html)
105 if len(groups["sub"]) != 2 {
106 t.Fatalf("expected 2 sub urls, got %d", len(groups["sub"]))
107 }
108 if len(groups["dub"]) != 1 {
109 t.Fatalf("expected 1 dub url, got %d", len(groups["dub"]))
110 }
111 subURLs := embedURLsForSubStyle(groups, "soft")
112 if len(subURLs) != 2 {
113 t.Fatalf("expected 2 soft sub urls, got %d", len(subURLs))
114 }
115 if subtitleFromEmbedURL(subURLs[1]) != "https://cdn.example/sub.vtt" {
116 t.Fatalf("unexpected subtitle %q", subtitleFromEmbedURL(subURLs[1]))
117 }
118}
119
120func TestChooseSubStyleRespectsPreference(t *testing.T) {
121 groups := map[string][]string{
122 "hsub": {"https://vibeplayer.site/hard"},
123 "sub": {"https://vibeplayer.site/soft?sub=https://cdn.example/sub.vtt"},
124 "dub": {"https://vibeplayer.site/dub"},
125 }
126
127 style, err := chooseSubStyle(groups, "soft")
128 if err != nil || style != "soft" {
129 t.Fatalf("chooseSubStyle soft: style=%q err=%v", style, err)
130 }
131
132 style, err = chooseSubStyle(groups, "hard")
133 if err != nil || style != "hard" {
134 t.Fatalf("chooseSubStyle hard: style=%q err=%v", style, err)
135 }
136}
137
138func TestChooseSubStylePromptSelectOnce(t *testing.T) {
139 groups := map[string][]string{
140 "hsub": {"https://vibeplayer.site/hard"},
141 "sub": {"https://vibeplayer.site/soft?sub=https://cdn.example/sub.vtt"},
142 }
143
144 prompts := 0
145 previousPrompt := curdhost.PromptSelect
146 previousOut := curdhost.Out
147 previousPersist := curdhost.PersistSubStylePreference
148 previousCurrent := curdhost.CurrentSubStyle
149 curdhost.PromptSelect = func(options []curdhost.PromptOption) (curdhost.PromptOption, error) {
150 prompts++
151 return curdhost.PromptOption{Key: "hard", Label: "Hard sub"}, nil
152 }
153 curdhost.Out = func(string) {}
154 saved := ""
155 curdhost.PersistSubStylePreference = func(style string) error {
156 saved = style
157 return nil
158 }
159 curdhost.CurrentSubStyle = func() string { return saved }
160 t.Cleanup(func() {
161 curdhost.PromptSelect = previousPrompt
162 curdhost.Out = previousOut
163 curdhost.PersistSubStylePreference = previousPersist
164 curdhost.CurrentSubStyle = previousCurrent
165 resetSubStyleForTest()
166 })
167
168 for i := 0; i < 2; i++ {
169 style, err := chooseSubStyle(groups, "ask")
170 if err != nil || style != "hard" {
171 t.Fatalf("iteration %d: style=%q err=%v", i, style, err)
172 }
173 }
174 if prompts != 1 {
175 t.Fatalf("expected 1 prompt, got %d", prompts)
176 }
177 if saved != "hard" {
178 t.Fatalf("expected saved preference hard, got %q", saved)
179 }
180}
181
182func TestResolveBibiembPicks1080pVariant(t *testing.T) {
183 const hash = "agdeadbeef"
184
185 var server *httptest.Server
186 server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
187 switch {
188 case r.URL.Path == "/"+hash:
189 _, _ = io.WriteString(w, `const src = "`+server.URL+`/`+hash+`/master.m3u8"`)
190 case r.URL.Path == "/"+hash+"/master.m3u8":
191 _, _ = io.WriteString(w, `#EXTM3U
192#EXT-X-STREAM-INF:BANDWIDTH=1,NAME="720p"
193`+server.URL+`/`+hash+`/720p/index.m3u8
194#EXT-X-STREAM-INF:BANDWIDTH=2,NAME="1080p"
195`+server.URL+`/`+hash+`/1080p/index.m3u8`)
196 default:
197 http.NotFound(w, r)
198 }
199 }))
200 defer server.Close()
201
202 withAninekoTestClient(t, server.Client())
203
204 stream, err := resolveBibiemb(server.URL + "/" + hash)
205 if err != nil {
206 t.Fatalf("resolveBibiemb: %v", err)
207 }
208 if !strings.HasSuffix(stream.URL, "/1080p/index.m3u8") {
209 t.Fatalf("expected 1080p variant, got %q", stream.URL)
210 }
211}
212
213func TestStripPNGWrapper(t *testing.T) {
214 png := []byte{
215 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
216 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
217 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
218 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
219 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41,
220 0x54, 0x78, 0xda, 0x63, 0x64, 0xf8, 0xcf, 0x50,
221 0x0f, 0x00, 0x03, 0x86, 0x01, 0x80, 0x5a, 0x34,
222 0x7d, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
223 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
224 }
225 payload := []byte{0x47, 0x01, 0x02, 0x03}
226 data := append(append([]byte{}, png...), payload...)
227 if got := stripPNGWrapper(data); string(got) != string(payload) {
228 t.Fatalf("unexpected stripped payload %v", got)
229 }
230}
231
232func TestVibeProxyRewritesAndStripsSegments(t *testing.T) {
233 const (
234 id = "abc123"
235 variant = "1720.m3u8"
236 )
237
238 png := []byte{
239 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
240 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
241 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
242 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
243 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41,
244 0x54, 0x78, 0xda, 0x63, 0x64, 0xf8, 0xcf, 0x50,
245 0x0f, 0x00, 0x03, 0x86, 0x01, 0x80, 0x5a, 0x34,
246 0x7d, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
247 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, 0x47, 0x11,
248 }
249
250 remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
251 switch r.URL.Path {
252 case "/public/stream/" + id + "/master.m3u8":
253 _, _ = io.WriteString(w, "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1,NAME=\"720p\"\n"+variant+"\n")
254 case "/public/stream/" + id + "/" + variant:
255 _, _ = io.WriteString(w, "#EXTM3U\n#EXTINF:10.0,\n/public/segment.bin\n")
256 case "/public/segment.bin":
257 _, _ = w.Write(png)
258 default:
259 http.NotFound(w, r)
260 }
261 }))
262 defer remote.Close()
263
264 withAninekoTestClient(t, remote.Client())
265 resetVibeProxyForTest()
266
267 masterURL := remote.URL + "/public/stream/" + id + "/master.m3u8"
268 proxyURL, err := registerVibeStream(masterURL, remote.URL+"/"+id)
269 if err != nil {
270 t.Fatalf("registerVibeStream: %v", err)
271 }
272
273 resp, err := http.Get(proxyURL)
274 if err != nil {
275 t.Fatalf("get master: %v", err)
276 }
277 body, _ := io.ReadAll(resp.Body)
278 resp.Body.Close()
279 if !strings.Contains(string(body), "/1720.m3u8") {
280 t.Fatalf("master not rewritten: %s", body)
281 }
282
283 variantURL := ""
284 for _, line := range strings.Split(strings.ReplaceAll(string(body), "\r\n", "\n"), "\n") {
285 line = strings.TrimSpace(line)
286 if line != "" && !strings.HasPrefix(line, "#") {
287 variantURL = line
288 break
289 }
290 }
291 resp, err = http.Get(variantURL)
292 if err != nil {
293 t.Fatalf("get variant: %v", err)
294 }
295 body, _ = io.ReadAll(resp.Body)
296 resp.Body.Close()
297 segURL := ""
298 for _, line := range strings.Split(strings.TrimSpace(string(body)), "\n") {
299 line = strings.TrimSpace(line)
300 if line != "" && !strings.HasPrefix(line, "#") {
301 segURL = line
302 }
303 }
304
305 resp, err = http.Get(segURL)
306 if err != nil {
307 t.Fatalf("get segment: %v", err)
308 }
309 segBody, _ := io.ReadAll(resp.Body)
310 resp.Body.Close()
311 if len(segBody) != 2 || segBody[0] != 0x47 {
312 t.Fatalf("expected stripped mpeg-ts payload, got %v", segBody)
313 }
314}
internal/providers/anineko/register.go added +13
@@ -0,0 +1,13 @@
1package anineko
2
3import "github.com/wraient/curd/internal/providers"
4
5func init() {
6 providers.Register(providers.Meta{
7 Name: "anineko",
8 Aliases: []string{"ani-neko", "ani neko"},
9 Referrer: "https://anineko.to/",
10 }, func() providers.Provider {
11 return &Provider{}
12 })
13}
internal/providers/anineko/scrape.go added +107
@@ -0,0 +1,107 @@
1package anineko
2
3import (
4 "net/url"
5 "regexp"
6 "strings"
7)
8
9var (
10 dataVideoRE = regexp.MustCompile(`data-video="([^"]+)"`)
11 subtitleRE = regexp.MustCompile(`[?&](?:sub|caption_1|c1_file)=([^&"]+)`)
12)
13
14func extractLangEmbedURLs(html string) map[string][]string {
15 groups := map[string][]string{
16 "hsub": {},
17 "sub": {},
18 "dub": {},
19 }
20 markers := regexp.MustCompile(`data-id="(hsub|sub|dub)"`).FindAllStringSubmatchIndex(html, -1)
21 for i, marker := range markers {
22 if len(marker) < 4 {
23 continue
24 }
25 lang := html[marker[2]:marker[3]]
26 start := marker[1]
27 end := len(html)
28 if i+1 < len(markers) {
29 end = markers[i+1][0]
30 }
31 block := html[start:end]
32 seen := map[string]struct{}{}
33 for _, videoMatch := range dataVideoRE.FindAllStringSubmatch(block, -1) {
34 if len(videoMatch) < 2 {
35 continue
36 }
37 embedURL := strings.TrimSpace(videoMatch[1])
38 if embedURL == "" {
39 continue
40 }
41 if _, ok := seen[embedURL]; ok {
42 continue
43 }
44 seen[embedURL] = struct{}{}
45 groups[lang] = append(groups[lang], embedURL)
46 }
47 }
48 return groups
49}
50
51func partitionByHost(embedURLs []string) (bibiemb, vibeplayer, other []string) {
52 for _, embedURL := range embedURLs {
53 host := strings.ToLower(hostFromURL(embedURL))
54 switch {
55 case strings.Contains(host, "bibiemb."):
56 bibiemb = append(bibiemb, embedURL)
57 case strings.Contains(host, "vibeplayer."):
58 vibeplayer = append(vibeplayer, embedURL)
59 default:
60 other = append(other, embedURL)
61 }
62 }
63 return bibiemb, vibeplayer, other
64}
65
66func subtitleFromEmbedURL(embedURL string) string {
67 parsed, err := url.Parse(embedURL)
68 if err != nil {
69 return ""
70 }
71 for key, values := range parsed.Query() {
72 switch strings.ToLower(key) {
73 case "sub", "caption_1", "c1_file":
74 if len(values) > 0 {
75 if decoded, err := url.QueryUnescape(values[0]); err == nil {
76 return decoded
77 }
78 return values[0]
79 }
80 }
81 }
82 match := subtitleRE.FindStringSubmatch(embedURL)
83 if len(match) < 2 {
84 return ""
85 }
86 if decoded, err := url.QueryUnescape(match[1]); err == nil {
87 return decoded
88 }
89 return match[1]
90}
91
92func hostFromURL(rawURL string) string {
93 parsed, err := url.Parse(rawURL)
94 if err != nil {
95 return ""
96 }
97 return parsed.Host
98}
99
100func containsString(items []string, target string) bool {
101 for _, item := range items {
102 if item == target {
103 return true
104 }
105 }
106 return false
107}
internal/providers/anineko/search.go added +74
@@ -0,0 +1,74 @@
1package anineko
2
3import (
4 "encoding/json"
5 "fmt"
6 "net/url"
7 "regexp"
8 "strings"
9
10 "github.com/wraient/curd/internal/providers"
11)
12
13type searchResponse struct {
14 Success bool `json:"success"`
15 Results []struct {
16 Title string `json:"title"`
17 URL string `json:"url"`
18 Image string `json:"image"`
19 Meta string `json:"meta"`
20 } `json:"results"`
21}
22
23var slugFromPathRE = regexp.MustCompile(`/watch/([^/?#]+)`)
24
25func searchAnime(query, mode string) ([]providers.SelectionOption, error) {
26 query = strings.TrimSpace(query)
27 if query == "" {
28 return nil, fmt.Errorf("empty search query")
29 }
30
31 rawURL := fmt.Sprintf("%s/ajax/search?q=%s", baseURL, url.QueryEscape(query))
32 body, err := fetchString(rawURL, baseURL+"/")
33 if err != nil {
34 return nil, err
35 }
36
37 var payload searchResponse
38 if err := json.Unmarshal([]byte(body), &payload); err != nil {
39 return nil, fmt.Errorf("parse anineko search response: %w", err)
40 }
41 if !payload.Success {
42 return nil, fmt.Errorf("anineko search failed")
43 }
44
45 options := make([]providers.SelectionOption, 0, len(payload.Results))
46 for _, result := range payload.Results {
47 slug := slugFromWatchURL(result.URL)
48 if slug == "" {
49 continue
50 }
51 label := strings.TrimSpace(result.Title)
52 if meta := strings.TrimSpace(result.Meta); meta != "" {
53 label = label + " — " + meta
54 }
55 options = append(options, providers.SelectionOption{
56 Key: slug,
57 Label: label,
58 Title: strings.TrimSpace(result.Title),
59 Thumbnail: absoluteURL(result.Image),
60 })
61 }
62 if len(options) == 0 {
63 return nil, fmt.Errorf("no results for %q", query)
64 }
65 return options, nil
66}
67
68func slugFromWatchURL(watchPath string) string {
69 match := slugFromPathRE.FindStringSubmatch(watchPath)
70 if len(match) < 2 {
71 return ""
72 }
73 return strings.TrimSpace(match[1])
74}
internal/providers/anineko/streams.go added +66
@@ -0,0 +1,66 @@
1package anineko
2
3import (
4 "fmt"
5 "strings"
6
7 "github.com/wraient/curd/internal/providers"
8)
9
10func getEpisodeStreamsForMode(slug string, config providers.PlaybackConfig, epNo int) ([]string, map[string]providers.StreamPlaybackHint, error) {
11 slug = strings.TrimSpace(slug)
12 if slug == "" {
13 return nil, nil, fmt.Errorf("empty show id")
14 }
15 if epNo <= 0 {
16 return nil, nil, fmt.Errorf("invalid episode number %d", epNo)
17 }
18
19 mode := providers.NormalizeTranslationType(config.SubOrDub)
20 html, err := fetchString(watchURL(slug, epNo), baseURL+"/")
21 if err != nil {
22 return nil, nil, err
23 }
24
25 groups := extractLangEmbedURLs(html)
26 embedURLs, err := embedURLsForMode(groups, mode, config.SubStyle)
27 if err != nil {
28 return nil, nil, err
29 }
30 if len(embedURLs) == 0 {
31 return nil, nil, fmt.Errorf("no %s streams found for episode %d", mode, epNo)
32 }
33
34 bibiembURLs, vibeplayerURLs, _ := partitionByHost(embedURLs)
35
36 for _, embedURL := range bibiembURLs {
37 stream, err := resolveBibiemb(embedURL)
38 if err != nil {
39 continue
40 }
41 return singleStreamResult(stream)
42 }
43
44 for _, embedURL := range vibeplayerURLs {
45 stream, err := resolveVibeplayer(embedURL)
46 if err != nil {
47 continue
48 }
49 return singleStreamResult(stream)
50 }
51
52 return nil, nil, fmt.Errorf("no playable streams resolved for episode %d", epNo)
53}
54
55func singleStreamResult(stream resolvedStream) ([]string, map[string]providers.StreamPlaybackHint, error) {
56 if strings.TrimSpace(stream.URL) == "" {
57 return nil, nil, fmt.Errorf("empty stream url")
58 }
59 hints := map[string]providers.StreamPlaybackHint{
60 stream.URL: {
61 Referrer: stream.Referrer,
62 Subtitle: stream.Subtitle,
63 },
64 }
65 return []string{stream.URL}, hints, nil
66}
internal/providers/anineko/substyle.go added +138
@@ -0,0 +1,138 @@
1package anineko
2
3import (
4 "fmt"
5 "strings"
6 "sync"
7
8 "github.com/wraient/curd/internal/curdhost"
9)
10
11var (
12 subStyleChoiceMu sync.Mutex
13 subStyleChosen string
14)
15
16func normalizeSubStyle(style string) string {
17 switch strings.ToLower(strings.TrimSpace(style)) {
18 case "soft":
19 return "soft"
20 case "hard":
21 return "hard"
22 default:
23 return "ask"
24 }
25}
26
27func resolveSubStylePreference(fallback string) string {
28 if curdhost.CurrentSubStyle != nil {
29 if live := normalizeSubStyle(curdhost.CurrentSubStyle()); live != "ask" {
30 return live
31 }
32 }
33
34 subStyleChoiceMu.Lock()
35 defer subStyleChoiceMu.Unlock()
36 if subStyleChosen != "" {
37 return subStyleChosen
38 }
39 return normalizeSubStyle(fallback)
40}
41
42func rememberSubStyleChoice(style string) {
43 style = normalizeSubStyle(style)
44 if style != "soft" && style != "hard" {
45 return
46 }
47
48 subStyleChoiceMu.Lock()
49 subStyleChosen = style
50 subStyleChoiceMu.Unlock()
51
52 if curdhost.PersistSubStylePreference != nil {
53 _ = curdhost.PersistSubStylePreference(style)
54 }
55}
56
57func chooseSubStyle(groups map[string][]string, preference string) (string, error) {
58 preference = resolveSubStylePreference(preference)
59 hasSoft := len(groups["sub"]) > 0
60 hasHard := len(groups["hsub"]) > 0
61
62 switch preference {
63 case "soft":
64 if hasSoft {
65 return "soft", nil
66 }
67 if hasHard {
68 return "hard", nil
69 }
70 case "hard":
71 if hasHard {
72 return "hard", nil
73 }
74 if hasSoft {
75 return "soft", nil
76 }
77 case "ask":
78 if hasSoft && hasHard {
79 if curdhost.PromptSelect == nil {
80 rememberSubStyleChoice("soft")
81 return "soft", nil
82 }
83 if curdhost.Out != nil {
84 curdhost.Out("Both soft-sub and hard-sub streams are available.")
85 }
86 selected, err := curdhost.PromptSelect([]curdhost.PromptOption{
87 {Key: "soft", Label: "Soft sub (external subtitles)"},
88 {Key: "hard", Label: "Hard sub (burned-in subtitles)"},
89 })
90 if err != nil {
91 return "", err
92 }
93 chosen := "soft"
94 if selected.Key == "hard" {
95 chosen = "hard"
96 }
97 rememberSubStyleChoice(chosen)
98 return chosen, nil
99 }
100 if hasSoft {
101 return "soft", nil
102 }
103 if hasHard {
104 return "hard", nil
105 }
106 }
107
108 return "", fmt.Errorf("no sub streams found")
109}
110
111func embedURLsForSubStyle(groups map[string][]string, style string) []string {
112 switch style {
113 case "soft":
114 return append([]string{}, groups["sub"]...)
115 case "hard":
116 return append([]string{}, groups["hsub"]...)
117 default:
118 return nil
119 }
120}
121
122func embedURLsForMode(groups map[string][]string, mode, subStyle string) ([]string, error) {
123 if strings.EqualFold(mode, "dub") {
124 return groups["dub"], nil
125 }
126
127 chosen, err := chooseSubStyle(groups, subStyle)
128 if err != nil {
129 return nil, err
130 }
131 return embedURLsForSubStyle(groups, chosen), nil
132}
133
134func resetSubStyleForTest() {
135 subStyleChoiceMu.Lock()
136 subStyleChosen = ""
137 subStyleChoiceMu.Unlock()
138}
internal/providers/anineko/vibeplayer.go added +37
@@ -0,0 +1,37 @@
1package anineko
2
3import (
4 "fmt"
5 "regexp"
6 "strings"
7)
8
9var vibeplayerMasterRE = regexp.MustCompile(`const src = "(https://vibeplayer\.site/public/stream/[^"]+/master\.m3u8)"`)
10
11func resolveVibeplayer(embedURL string) (resolvedStream, error) {
12 embedURL = strings.TrimSpace(embedURL)
13 if embedURL == "" {
14 return resolvedStream{}, fmt.Errorf("empty vibeplayer embed url")
15 }
16
17 html, err := fetchString(embedURL, baseURL+"/")
18 if err != nil {
19 return resolvedStream{}, err
20 }
21
22 match := vibeplayerMasterRE.FindStringSubmatch(html)
23 if len(match) < 2 {
24 return resolvedStream{}, fmt.Errorf("vibeplayer master m3u8 not found")
25 }
26
27 proxyURL, err := registerVibeStream(match[1], embedURL)
28 if err != nil {
29 return resolvedStream{}, err
30 }
31
32 return resolvedStream{
33 URL: proxyURL,
34 Referrer: embedURL,
35 Subtitle: subtitleFromEmbedURL(embedURL),
36 }, nil
37}
internal/providers/anineko/vibeproxy.go added +242
@@ -0,0 +1,242 @@
1package anineko
2
3import (
4 "bytes"
5 "crypto/rand"
6 "encoding/hex"
7 "fmt"
8 "io"
9 "net"
10 "net/http"
11 "strconv"
12 "strings"
13 "sync"
14)
15
16var pngIENDMarker = []byte{0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}
17
18var (
19 vibeProxyMu sync.Mutex
20 vibeProxyServer *vibeProxy
21)
22
23type vibeSession struct {
24 masterURL string
25 referer string
26 variants map[string][]vibeSegment
27}
28
29type vibeSegment struct {
30 duration float64
31 url string
32}
33
34type vibeProxy struct {
35 baseURL string
36 server *http.Server
37 sessions map[string]*vibeSession
38}
39
40func registerVibeStream(masterURL, referer string) (string, error) {
41 proxy, err := getVibeProxy()
42 if err != nil {
43 return "", err
44 }
45 return proxy.register(masterURL, referer)
46}
47
48func getVibeProxy() (*vibeProxy, error) {
49 vibeProxyMu.Lock()
50 defer vibeProxyMu.Unlock()
51
52 if vibeProxyServer != nil {
53 return vibeProxyServer, nil
54 }
55
56 proxy := &vibeProxy{sessions: map[string]*vibeSession{}}
57 mux := http.NewServeMux()
58 mux.HandleFunc("/stream/", proxy.handle)
59 server := &http.Server{Handler: mux}
60
61 listener, err := net.Listen("tcp", "127.0.0.1:0")
62 if err != nil {
63 return nil, fmt.Errorf("start vibe proxy listener: %w", err)
64 }
65 proxy.server = server
66 proxy.baseURL = "http://" + listener.Addr().String()
67
68 go func() {
69 _ = server.Serve(listener)
70 }()
71
72 vibeProxyServer = proxy
73 return proxy, nil
74}
75
76func (p *vibeProxy) register(masterURL, referer string) (string, error) {
77 id, err := randomSessionID()
78 if err != nil {
79 return "", err
80 }
81 vibeProxyMu.Lock()
82 p.sessions[id] = &vibeSession{
83 masterURL: masterURL,
84 referer: referer,
85 variants: map[string][]vibeSegment{},
86 }
87 vibeProxyMu.Unlock()
88 return p.baseURL + "/stream/" + id + "/master.m3u8", nil
89}
90
91func (p *vibeProxy) handle(w http.ResponseWriter, r *http.Request) {
92 path := strings.TrimPrefix(r.URL.Path, "/stream/")
93 parts := strings.Split(path, "/")
94 if len(parts) < 2 {
95 http.NotFound(w, r)
96 return
97 }
98 sessionID := parts[0]
99
100 vibeProxyMu.Lock()
101 session, ok := p.sessions[sessionID]
102 vibeProxyMu.Unlock()
103 if !ok {
104 http.NotFound(w, r)
105 return
106 }
107
108 switch {
109 case len(parts) == 2 && parts[1] == "master.m3u8":
110 p.serveMaster(w, sessionID, session, parts[1])
111 case len(parts) == 2 && strings.HasSuffix(parts[1], ".m3u8"):
112 p.serveVariant(w, sessionID, session, parts[1])
113 case len(parts) == 4 && parts[2] == "seg":
114 p.serveSegment(w, r, session, parts[1], parts[3])
115 default:
116 http.NotFound(w, r)
117 }
118}
119
120func (p *vibeProxy) serveMaster(w http.ResponseWriter, sessionID string, session *vibeSession, _ string) {
121 body, err := fetchString(session.masterURL, session.referer)
122 if err != nil {
123 http.Error(w, err.Error(), http.StatusBadGateway)
124 return
125 }
126 rewritten := rewritePlaylistLines(body, func(line string) string {
127 line = strings.TrimSpace(line)
128 if line == "" || strings.HasPrefix(line, "#") {
129 return line
130 }
131 return p.baseURL + "/stream/" + sessionID + "/" + line
132 })
133 writePlaylist(w, rewritten)
134}
135
136func (p *vibeProxy) serveVariant(w http.ResponseWriter, sessionID string, session *vibeSession, variantName string) {
137 variantURL := resolvePlaylistURL(session.masterURL, variantName)
138 body, err := fetchString(variantURL, session.referer)
139 if err != nil {
140 http.Error(w, err.Error(), http.StatusBadGateway)
141 return
142 }
143
144 segments := make([]vibeSegment, 0)
145 var currentDuration float64
146 rewritten := rewritePlaylistLines(body, func(line string) string {
147 line = strings.TrimSpace(line)
148 if strings.HasPrefix(line, "#EXTINF:") {
149 currentDuration = parseExtInfDuration(line)
150 return line
151 }
152 if line == "" || strings.HasPrefix(line, "#") {
153 return line
154 }
155 segmentURL := resolvePlaylistURL(variantURL, line)
156 index := len(segments)
157 segments = append(segments, vibeSegment{duration: currentDuration, url: segmentURL})
158 return fmt.Sprintf("%s/stream/%s/%s/seg/%d", p.baseURL, sessionID, variantName, index)
159 })
160
161 vibeProxyMu.Lock()
162 session.variants[variantName] = segments
163 vibeProxyMu.Unlock()
164
165 writePlaylist(w, rewritten)
166}
167
168func (p *vibeProxy) serveSegment(w http.ResponseWriter, r *http.Request, session *vibeSession, variantName, indexText string) {
169 index, err := strconv.Atoi(indexText)
170 if err != nil || index < 0 {
171 http.NotFound(w, r)
172 return
173 }
174
175 vibeProxyMu.Lock()
176 segments := session.variants[variantName]
177 vibeProxyMu.Unlock()
178 if index >= len(segments) {
179 http.NotFound(w, r)
180 return
181 }
182
183 data, err := fetchBytes(segments[index].url, session.referer)
184 if err != nil {
185 http.Error(w, err.Error(), http.StatusBadGateway)
186 return
187 }
188 body := stripPNGWrapper(data)
189 w.Header().Set("Content-Type", "video/mp2t")
190 w.Header().Set("Content-Length", strconv.Itoa(len(body)))
191 _, _ = w.Write(body)
192}
193
194func rewritePlaylistLines(playlist string, mapLine func(string) string) string {
195 lines := strings.Split(strings.ReplaceAll(playlist, "\r\n", "\n"), "\n")
196 for i, line := range lines {
197 lines[i] = mapLine(line)
198 }
199 return strings.Join(lines, "\n")
200}
201
202func parseExtInfDuration(line string) float64 {
203 line = strings.TrimPrefix(strings.TrimSpace(line), "#EXTINF:")
204 if idx := strings.Index(line, ","); idx >= 0 {
205 line = line[:idx]
206 }
207 value, err := strconv.ParseFloat(strings.TrimSpace(line), 64)
208 if err != nil {
209 return 0
210 }
211 return value
212}
213
214func stripPNGWrapper(data []byte) []byte {
215 idx := bytes.Index(data, pngIENDMarker)
216 if idx < 0 {
217 return data
218 }
219 return data[idx+len(pngIENDMarker):]
220}
221
222func writePlaylist(w http.ResponseWriter, body string) {
223 w.Header().Set("Content-Type", "application/vnd.apple.mpegurl")
224 _, _ = io.WriteString(w, body)
225}
226
227func randomSessionID() (string, error) {
228 buf := make([]byte, 8)
229 if _, err := rand.Read(buf); err != nil {
230 return "", err
231 }
232 return hex.EncodeToString(buf), nil
233}
234
235func resetVibeProxyForTest() {
236 vibeProxyMu.Lock()
237 defer vibeProxyMu.Unlock()
238 if vibeProxyServer != nil && vibeProxyServer.server != nil {
239 _ = vibeProxyServer.server.Close()
240 }
241 vibeProxyServer = nil
242}
internal/providers/lang.go added +17
@@ -0,0 +1,17 @@
1package providers
2
3import "strings"
4
5func NormalizeTranslationType(mode string) string {
6 if strings.EqualFold(strings.TrimSpace(mode), "dub") {
7 return "dub"
8 }
9 return "sub"
10}
11
12func AlternateTranslationType(mode string) string {
13 if NormalizeTranslationType(mode) == "dub" {
14 return "sub"
15 }
16 return "dub"
17}
internal/providers/registry.go added +170
@@ -0,0 +1,170 @@
1package providers
2
3import (
4 "fmt"
5 "sort"
6 "strings"
7 "sync"
8)
9
10// Meta describes a registered streaming provider.
11type Meta struct {
12 Name string
13 Aliases []string
14 Referrer string
15 DefaultDisabled bool
16 DisableReason string
17 // OptOutToken excludes a provider from automatic fallback prompts, e.g. "no-animepahe".
18 OptOutToken string
19 // FallbackPrompt is shown when the host offers this provider as a fallback.
20 FallbackPrompt string
21}
22
23type entry struct {
24 meta Meta
25 factory func() Provider
26}
27
28var (
29 registryMu sync.RWMutex
30 registry = map[string]entry{}
31 aliases = map[string]string{}
32)
33
34// Register adds a provider factory to the global registry.
35func Register(meta Meta, factory func() Provider) {
36 registryMu.Lock()
37 defer registryMu.Unlock()
38
39 meta.Name = strings.ToLower(strings.Trim(strings.TrimSpace(meta.Name), "\"'[]"))
40 if meta.Name == "" {
41 panic("providers.Register: Name is required")
42 }
43 if factory == nil {
44 panic("providers.Register: factory is required")
45 }
46
47 meta.Name = strings.ReplaceAll(strings.ReplaceAll(meta.Name, "-", ""), " ", "")
48 if meta.Name == "" {
49 panic("providers.Register: Name is required")
50 }
51
52 registry[meta.Name] = entry{meta: meta, factory: factory}
53 registerAlias(meta.Name, meta.Name)
54 for _, alias := range meta.Aliases {
55 registerAlias(alias, meta.Name)
56 }
57}
58
59func registerAlias(alias, canonical string) {
60 alias = strings.Trim(strings.TrimSpace(alias), "\"'[]")
61 if alias == "" {
62 return
63 }
64 aliases[strings.ToLower(strings.Join(strings.Fields(alias), " "))] = canonical
65 compact := strings.ToLower(alias)
66 compact = strings.ReplaceAll(compact, "-", "")
67 compact = strings.ReplaceAll(compact, "_", "")
68 compact = strings.ReplaceAll(compact, " ", "")
69 if compact != "" {
70 aliases[compact] = canonical
71 }
72}
73
74// NormalizeName maps user/config input to a canonical provider name.
75func NormalizeName(name string) string {
76 registryMu.RLock()
77 defer registryMu.RUnlock()
78 return normalizeName(name)
79}
80
81func normalizeName(name string) string {
82 name = strings.Trim(strings.TrimSpace(name), "\"'[]")
83 if name == "" {
84 return ""
85 }
86 key := strings.ToLower(strings.Join(strings.Fields(name), " "))
87 if canonical, ok := aliases[key]; ok {
88 return canonical
89 }
90 key = strings.ReplaceAll(key, "-", "")
91 key = strings.ReplaceAll(key, "_", "")
92 key = strings.ReplaceAll(key, " ", "")
93 if canonical, ok := aliases[key]; ok {
94 return canonical
95 }
96 return ""
97}
98
99// MetaFor returns registration metadata for a provider name.
100func MetaFor(name string) (Meta, bool) {
101 registryMu.RLock()
102 defer registryMu.RUnlock()
103
104 name = normalizeName(name)
105 if name == "" {
106 return Meta{}, false
107 }
108 entry, ok := registry[name]
109 if !ok {
110 return Meta{}, false
111 }
112 return entry.meta, true
113}
114
115// RegisteredNames returns sorted canonical provider names.
116func RegisteredNames() []string {
117 registryMu.RLock()
118 defer registryMu.RUnlock()
119
120 names := make([]string, 0, len(registry))
121 for name := range registry {
122 names = append(names, name)
123 }
124 sort.Strings(names)
125 return names
126}
127
128// New creates a provider instance by canonical name.
129func New(name string) (Provider, error) {
130 registryMu.RLock()
131 defer registryMu.RUnlock()
132
133 name = normalizeName(name)
134 if name == "" {
135 return nil, fmt.Errorf("unknown provider %q", name)
136 }
137 entry, ok := registry[name]
138 if !ok {
139 return nil, fmt.Errorf("unknown provider %q", name)
140 }
141 return entry.factory(), nil
142}
143
144// Referrer returns the stream referrer for a provider, if configured.
145func Referrer(name string) string {
146 meta, ok := MetaFor(name)
147 if !ok {
148 return ""
149 }
150 return meta.Referrer
151}
152
153// SetFactoryForTest overrides a provider factory for the duration of a test.
154func SetFactoryForTest(name string, factory func() Provider) (restore func()) {
155 registryMu.Lock()
156 defer registryMu.Unlock()
157
158 name = normalizeName(name)
159 previous, ok := registry[name]
160 if !ok {
161 panic(fmt.Sprintf("providers.SetFactoryForTest: unknown provider %q", name))
162 }
163
164 registry[name] = entry{meta: previous.meta, factory: factory}
165 return func() {
166 registryMu.Lock()
167 registry[name] = previous
168 registryMu.Unlock()
169 }
170}
internal/providers/types.go added +46
@@ -0,0 +1,46 @@
1package providers
2
3// SelectionOption is a provider search or menu result item.
4type SelectionOption struct {
5 Key string
6 Label string
7 Title string
8 Thumbnail string
9 ExtraData any
10}
11
12// PlaybackConfig carries playback preferences passed into providers.
13type PlaybackConfig struct {
14 SubOrDub string
15 // SubStyle controls anineko subtitle stream tabs: ask, soft, or hard.
16 SubStyle string
17}
18
19// StreamPlaybackHint carries MPV playback metadata for a resolved stream URL.
20type StreamPlaybackHint struct {
21 Referrer string
22 Subtitle string
23}
24
25// Provider resolves catalog search, episode lists, and stream URLs.
26type Provider interface {
27 Name() string
28 SearchAnime(query, mode string) ([]SelectionOption, error)
29 EpisodesList(showID, mode string) ([]string, error)
30 GetEpisodeURL(config PlaybackConfig, id string, epNo int) ([]string, error)
31}
32
33// ModeResolver resolves episode URLs for an explicit sub/dub mode.
34type ModeResolver interface {
35 GetEpisodeURLForMode(config PlaybackConfig, id string, epNo int, mode string) ([]string, error)
36}
37
38// HintResolver resolves episode URLs with MPV playback hints.
39type HintResolver interface {
40 GetEpisodeURLForModeWithHints(config PlaybackConfig, id string, epNo int, mode string) ([]string, map[string]StreamPlaybackHint, error)
41}
42
43// IDResolver refreshes or validates a provider-specific show ID.
44type IDResolver interface {
45 ResolveProviderID(providerID, query string) (string, error)
46}
internal/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 {
71 Mode string 71 Mode string
72} 72}
73 73
74// StreamPlaybackHint carries MPV playback metadata for a resolved stream URL.
75type StreamPlaybackHint struct {
76 Referrer string
77 Subtitle string
78}
79
74type playingVideo struct { 80type playingVideo struct {
75 Url string 81 Url string
76 Speed float64 `json:"speed"` 82 Speed float64 `json:"speed"`
@@ -98,8 +104,9 @@ func GetGlobalUser() *User {
98 104
99// AniListAnime is the struct for the API response 105// AniListAnime is the struct for the API response
100type AniListAnime struct { 106type AniListAnime struct {
101 ID int `json:"id"` 107 ID int `json:"id"`
102 Title struct { 108 Episodes int `json:"episodes"`
109 Title struct {
103 Romaji string `json:"romaji"` 110 Romaji string `json:"romaji"`
104 English string `json:"english"` 111 English string `json:"english"`
105 Native string `json:"native"` 112 Native string `json:"native"`
@@ -122,6 +129,7 @@ type ResponseData struct {
122type Media struct { 129type Media struct {
123 Duration int `json:"duration"` 130 Duration int `json:"duration"`
124 Episodes int `json:"episodes"` 131 Episodes int `json:"episodes"`
132 Format string `json:"format"`
125 ID int `json:"id"` 133 ID int `json:"id"`
126 MalID int `json:"mal_id"` 134 MalID int `json:"mal_id"`
127 Title AnimeTitle `json:"title"` 135 Title AnimeTitle `json:"title"`
internal/tracking.go +1 −1
@@ -70,7 +70,7 @@ func UsesDualRemoteTracking(config *CurdConfig) bool {
70 70
71func trackingCategoryEnabled(config *CurdConfig, key string) bool { 71func trackingCategoryEnabled(config *CurdConfig, key string) bool {
72 switch key { 72 switch key {
73 case "CURRENT", "ALL", "UNTRACKED", "CONTINUE_LAST", "PROVIDER": 73 case "CURRENT", "ALL", "UNTRACKED", "CONTINUE_LAST", "REMAP_PROVIDER", "PROVIDER":
74 return true 74 return true
75 case "UPDATE", "PLANNING", "COMPLETED", "PAUSED", "DROPPED", "REWATCHING": 75 case "UPDATE", "PLANNING", "COMPLETED", "PAUSED", "DROPPED", "REWATCHING":
76 return UsesRemoteTracking(config) 76 return UsesRemoteTracking(config)
internal/user_intent_regression_test.go +8 −1
@@ -141,6 +141,7 @@ func TestGetProviderTotalEpisodesReturnsLookupErrorsWhenNoEpisodesFound(t *testi
141} 141}
142 142
143func TestGetAllAnimeEpisodesListUsesValidGraphQLVariableSyntax(t *testing.T) { 143func TestGetAllAnimeEpisodesListUsesValidGraphQLVariableSyntax(t *testing.T) {
144 withAllProvidersEnabledForTest(t)
144 previousClient := sharedHTTPClient 145 previousClient := sharedHTTPClient
145 t.Cleanup(func() { 146 t.Cleanup(func() {
146 sharedHTTPClient = previousClient 147 sharedHTTPClient = previousClient
@@ -163,7 +164,13 @@ func TestGetAllAnimeEpisodesListUsesValidGraphQLVariableSyntax(t *testing.T) {
163 return testHTTPResponse(req, http.StatusOK, `{"data":{"show":{"_id":"show-id","availableEpisodesDetail":{"sub":[1,2,12]}}}}`), nil 164 return testHTTPResponse(req, http.StatusOK, `{"data":{"show":{"_id":"show-id","availableEpisodesDetail":{"sub":[1,2,12]}}}}`), nil
164 })} 165 })}
165 166
166 episodes, err := getAllAnimeEpisodesList("show-id", "sub") 167 episodes, err := func() ([]string, error) {
168 provider, err := ProviderByName("allanime")
169 if err != nil {
170 return nil, err
171 }
172 return provider.EpisodesList("show-id", "sub")
173 }()
167 if err != nil { 174 if err != nil {
168 t.Fatalf("expected allanime episode list lookup to succeed: %v", err) 175 t.Fatalf("expected allanime episode list lookup to succeed: %v", err)
169 } 176 }