Commit 1bfbdda6b9

1bfbdda6b9ad40e9457cb346b797233a038b3210

parent: e857c86c0c

Unsigned

Wraient <wraient.911@gmail.com> · 2026-06-26 16:12 UTC

Add: Senshi provider and related tests

- Implemented the Senshi provider for anime catalog search and streaming.
- Added functionality for searching anime, retrieving episode lists, and fetching streaming URLs.
- Created comprehensive tests for the Senshi provider, including search results parsing and episode streaming.
- Introduced live edge-case tests for various anime queries across multiple providers.
- Added benchmarking tests to compare performance between Senshi and Anineko APIs.
- Implemented terminal interrupt handling to restore the terminal state on exit.
- Added version management for the application.

Layout: unified · split

Build/update-aur.sh added +189
@@ -0,0 +1,189 @@
1#!/usr/bin/env bash
2
3set -euo pipefail
4
5AUR_REPO="${AUR_REPO:-$HOME/Projects/aur/curd}"
6UPSTREAM_REPO="${UPSTREAM_REPO:-Wraient/curd}"
7ASSET_NAME="${ASSET_NAME:-curd-linux-x86_64}"
8REMOTE="${REMOTE:-origin}"
9DRY_RUN="false"
10
11usage() {
12 cat <<'EOF'
13Usage: Build/update-aur.sh [--dry-run]
14
15Environment overrides:
16 AUR_REPO AUR git clone path (default: ~/Projects/aur/curd)
17 UPSTREAM_REPO GitHub repo in owner/name format (default: Wraient/curd)
18 ASSET_NAME Release asset to checksum (default: curd-linux-x86_64)
19 REMOTE Git remote to push (default: origin)
20EOF
21}
22
23require_cmd() {
24 if ! command -v "$1" >/dev/null 2>&1; then
25 echo "Missing required command: $1" >&2
26 exit 1
27 fi
28}
29
30for arg in "$@"; do
31 case "$arg" in
32 --dry-run)
33 DRY_RUN="true"
34 ;;
35 -h|--help)
36 usage
37 exit 0
38 ;;
39 *)
40 echo "Unknown argument: $arg" >&2
41 usage
42 exit 1
43 ;;
44 esac
45done
46
47require_cmd curl
48require_cmd jq
49require_cmd git
50require_cmd sed
51require_cmd sha256sum
52
53if [[ ! -d "$AUR_REPO/.git" ]]; then
54 echo "AUR repo not found at $AUR_REPO" >&2
55 exit 1
56fi
57
58if [[ "$DRY_RUN" == "true" ]]; then
59 echo "Dry run: skipping AUR repo pull."
60else
61 echo "Syncing AUR repo with upstream..."
62 git -C "$AUR_REPO" pull --ff-only "$REMOTE"
63fi
64
65PKGBUILD_PATH="$AUR_REPO/PKGBUILD"
66if [[ ! -f "$PKGBUILD_PATH" ]]; then
67 echo "PKGBUILD not found at $PKGBUILD_PATH" >&2
68 exit 1
69fi
70
71release_api="https://api.github.com/repos/${UPSTREAM_REPO}/releases/latest"
72release_json="$(curl -fsSL "$release_api")"
73
74tag_name="$(printf '%s' "$release_json" | jq -r '.tag_name')"
75if [[ -z "$tag_name" || "$tag_name" == "null" ]]; then
76 echo "Could not determine latest release tag from $release_api" >&2
77 exit 1
78fi
79
80pkgver="${tag_name#v}"
81download_url="$(printf '%s' "$release_json" | jq -r --arg n "$ASSET_NAME" '.assets[] | select(.name == $n) | .browser_download_url' | head -n1)"
82if [[ -z "$download_url" || "$download_url" == "null" ]]; then
83 echo "Asset $ASSET_NAME not found in release $tag_name" >&2
84 exit 1
85fi
86
87digest="$(printf '%s' "$release_json" | jq -r --arg n "$ASSET_NAME" '.assets[] | select(.name == $n) | (.digest // empty)' | head -n1)"
88if [[ "$digest" == sha256:* ]]; then
89 sha256="${digest#sha256:}"
90else
91 tmp_file="$(mktemp)"
92 trap 'rm -f "$tmp_file"' EXIT
93 curl -fL "$download_url" -o "$tmp_file"
94 sha256="$(sha256sum "$tmp_file" | awk '{print $1}')"
95 rm -f "$tmp_file"
96 trap - EXIT
97fi
98
99source_line="source=(\"https://github.com/${UPSTREAM_REPO}/releases/download/v\${pkgver}/${ASSET_NAME}\")"
100sha_line="sha256sums=('${sha256}')"
101
102PKGBUILD_BACKUP="$(mktemp)"
103SRCINFO_PATH="$AUR_REPO/.SRCINFO"
104SRCINFO_BACKUP=""
105cp "$PKGBUILD_PATH" "$PKGBUILD_BACKUP"
106if [[ -f "$SRCINFO_PATH" ]]; then
107 SRCINFO_BACKUP="$(mktemp)"
108 cp "$SRCINFO_PATH" "$SRCINFO_BACKUP"
109fi
110
111restore_dry_run_files() {
112 if [[ "$DRY_RUN" == "true" ]]; then
113 cp "$PKGBUILD_BACKUP" "$PKGBUILD_PATH"
114 if [[ -n "$SRCINFO_BACKUP" ]]; then
115 cp "$SRCINFO_BACKUP" "$SRCINFO_PATH"
116 else
117 rm -f "$SRCINFO_PATH"
118 fi
119 fi
120 rm -f "$PKGBUILD_BACKUP"
121 if [[ -n "$SRCINFO_BACKUP" ]]; then
122 rm -f "$SRCINFO_BACKUP"
123 fi
124}
125trap restore_dry_run_files EXIT
126
127sed -i -E "s/^pkgver=.*/pkgver=${pkgver}/" "$PKGBUILD_PATH"
128
129if grep -q '^source=' "$PKGBUILD_PATH"; then
130 sed -i -E "s|^source=.*$|${source_line}|" "$PKGBUILD_PATH"
131else
132 if grep -q '^conflicts=' "$PKGBUILD_PATH"; then
133 sed -i "/^conflicts=.*/a ${source_line}" "$PKGBUILD_PATH"
134 else
135 printf '\n%s\n' "$source_line" >> "$PKGBUILD_PATH"
136 fi
137fi
138
139if grep -q '^sha256sums=' "$PKGBUILD_PATH"; then
140 sed -i -E "s|^sha256sums=.*$|${sha_line}|" "$PKGBUILD_PATH"
141else
142 if grep -q '^source=' "$PKGBUILD_PATH"; then
143 sed -i "/^source=.*/a ${sha_line}" "$PKGBUILD_PATH"
144 else
145 printf '%s\n' "$sha_line" >> "$PKGBUILD_PATH"
146 fi
147fi
148
149if command -v makepkg >/dev/null 2>&1; then
150 (cd "$AUR_REPO" && makepkg --printsrcinfo > .SRCINFO)
151else
152 echo "Warning: makepkg not found; skipping .SRCINFO refresh" >&2
153fi
154
155if cmp -s "$PKGBUILD_PATH" "$PKGBUILD_BACKUP" && [[ ! -f "$AUR_REPO/.SRCINFO" || -z "$(git -C "$AUR_REPO" status --porcelain -- .SRCINFO)" ]]; then
156 echo "No PKGBUILD/.SRCINFO changes detected. Already up to date."
157 exit 0
158fi
159
160echo "Updated to ${tag_name}"
161echo " pkgver: ${pkgver}"
162echo " asset: ${ASSET_NAME}"
163echo " sha256: ${sha256}"
164
165if [[ "$DRY_RUN" == "true" ]]; then
166 git -C "$AUR_REPO" --no-pager diff -- PKGBUILD .SRCINFO || true
167 exit 0
168fi
169
170trap - EXIT
171rm -f "$PKGBUILD_BACKUP"
172if [[ -n "$SRCINFO_BACKUP" ]]; then
173 rm -f "$SRCINFO_BACKUP"
174fi
175
176git -C "$AUR_REPO" add PKGBUILD
177if [[ -f "$AUR_REPO/.SRCINFO" ]]; then
178 git -C "$AUR_REPO" add .SRCINFO
179fi
180
181if git -C "$AUR_REPO" diff --cached --quiet; then
182 echo "No staged changes to commit."
183 exit 0
184fi
185
186git -C "$AUR_REPO" commit -m "Update to ${tag_name}"
187git -C "$AUR_REPO" push "$REMOTE"
188
189echo "Pushed AUR update for ${tag_name}"
README.md +4 −2
@@ -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, AniNeko, and Animepahe) with ordered fallback and up to 1080p support 27- Multiple Content Providers (Senshi, AniNeko, AllAnime, 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
@@ -395,7 +395,7 @@ If the browser reaches the localhost callback page but curd does not continue au
395| `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. |
396| `SkipFiller` | Boolean | `true`, `false` | Skips filler episodes when supported. | 396| `SkipFiller` | Boolean | `true`, `false` | Skips filler episodes when supported. |
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` | 397| `MenuOrder` | String | Comma-separated list | Controls which menu items appear and their order. Available options: `CURRENT`, `ALL`, `UNTRACKED`, `UPDATE`, `REMAP_PROVIDER`, `CONTINUE_LAST`, `PLANNING`, `COMPLETED`, `PAUSED`, `DROPPED`, `REWATCHING`, `TRACKER`, `PROVIDER`. Only listed items will be shown. Default: `CURRENT,ALL,UNTRACKED,UPDATE,REMAP_PROVIDER,CONTINUE_LAST,TRACKER,PROVIDER` |
398| `Provider` | List | `["anineko"]`, `["allanime"]`, `["animepahe"]`, `["anineko","allanime"]`, `["allanime","animepahe"]`, `["allanime","no-animepahe"]`, `stacked` | Sets the ordered content-provider fallback list. Curd tries providers from left to right for the requested stream. `stacked` / `all` uses every enabled provider. AllAnime and Animepahe are disabled by default; include them in `Provider` to enable. If the primary provider has no search results or stream and Animepahe is not configured, Curd may ask before enabling Animepahe. Default: `["anineko"]` | 398| `Provider` | List | `stacked`, `["anipub"]`, `["anineko"]`, `["allanime"]`, `["animepahe"]` | Sets the content-provider fallback list. `stacked` (default) uses the preferred order: senshi → anipub → anineko → allanime → animepahe. A single-provider list uses only that site. AllAnime and Animepahe are disabled by default unless included in `Provider`. Default: `stacked` |
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` | 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` |
400| `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. |
401| `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. |
@@ -420,6 +420,8 @@ If the browser reaches the localhost callback page but curd does not continue au
420- [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
421- [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
422- [AllAnime Content](https://allanime.to/) - Fetch anime url 422- [AllAnime Content](https://allanime.to/) - Fetch anime url
423- [Senshi Project](https://senshi.live/) - Default provider with direct HLS streams and MAL-based catalog matching
424- [AniPub](https://anipub.xyz/) - Fast JSON catalog APIs with MegaPlay HLS streams
423- [AniNeko Content](https://anineko.to/) - Alternative provider with soft/hard sub stream selection 425- [AniNeko Content](https://anineko.to/) - Alternative provider with soft/hard sub stream selection
424- [Animepahe Content](https://animepahe.pw/) - Alternative provider for 1080p streams 426- [Animepahe Content](https://animepahe.pw/) - Alternative provider for 1080p streams
425- [Jikan](https://jikan.moe/) - Get filler episode number 427- [Jikan](https://jikan.moe/) - Get filler episode number
cmd/curd/main.go +8
@@ -48,6 +48,13 @@ func main() {
48 fmt.Println("Error loading config:", err) 48 fmt.Println("Error loading config:", err)
49 return 49 return
50 } 50 }
51 internal.SetCurdVersion(resolvedVersion())
52 if updated, migrateErr := internal.MigrateOnVersionUpgrade(configFilePath, &userCurdConfig, resolvedVersion()); migrateErr != nil {
53 fmt.Println("Error applying storage migration:", migrateErr)
54 return
55 } else if updated {
56 fmt.Println("Updated provider settings to the current default fallback stack.")
57 }
51 internal.SetGlobalConfig(&userCurdConfig) 58 internal.SetGlobalConfig(&userCurdConfig)
52 59
53 logFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "debug.log") 60 logFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "debug.log")
@@ -177,6 +184,7 @@ func main() {
177 184
178 // Setup screen for interactive mode (only if not changing token) 185 // Setup screen for interactive mode (only if not changing token)
179 internal.ClearScreen() 186 internal.ClearScreen()
187 internal.InstallTerminalInterruptHandler()
180 defer internal.RestoreScreen() 188 defer internal.RestoreScreen()
181 189
182 // Set SubOrDub based on the flags 190 // Set SubOrDub based on the flags
docs/providers.md +3
@@ -327,6 +327,9 @@ Document the decision in a short ADR before building. The compile-time registry
327 327
328| Provider | Package | Notes | 328| Provider | Package | Notes |
329|----------|---------|-------| 329|----------|---------|-------|
330| Senshi | `internal/providers/senshi` | REST search/episodes, direct HLS from `/episode-embeds`, MAL id keys and `/posters/{mal_id}.webp` thumbnails |
331| AniPub | `internal/providers/anipub` | JSON search/info/details APIs, MegaPlay embed resolution via `/stream/getSources`, MAL id in `ExtraData` for tracker matching |
332| AniNeko | `internal/providers/anineko` | AJAX search, HTML scrape, bibiemb/vibeplayer embed resolution, `SubStyle` / `HintResolver` |
330| AllAnime | `internal/providers/allanime` | GraphQL search/episodes, parallel stream resolution, `HintResolver` | 333| AllAnime | `internal/providers/allanime` | GraphQL search/episodes, parallel stream resolution, `HintResolver` |
331| Animepahe | `internal/providers/animepahe` | DDoS-Guard + rod browser, `IDResolver`, `DefaultDisabled`, `OptOutToken` | 334| Animepahe | `internal/providers/animepahe` | DDoS-Guard + rod browser, `IDResolver`, `DefaultDisabled`, `OptOutToken` |
332 335
internal/config.go +1 −1
@@ -105,7 +105,7 @@ func defaultConfigMap() map[string]string {
105 "AlternateScreen": "true", 105 "AlternateScreen": "true",
106 "DiscordPresence": "true", 106 "DiscordPresence": "true",
107 "DiscordClientId": "1287457464148820089", 107 "DiscordClientId": "1287457464148820089",
108 "Provider": "[\"anineko\"]", 108 "Provider": "stacked",
109 "DisabledProviders": "[]", 109 "DisabledProviders": "[]",
110 "ManualProviderSearch": "false", 110 "ManualProviderSearch": "false",
111 "TrackingLocal": "true", 111 "TrackingLocal": "true",
internal/curd.go +10 −10
@@ -157,12 +157,12 @@ func ExitCurd(err error) {
157 fmt.Println("Press Enter to exit") 157 fmt.Println("Press Enter to exit")
158 var wait string 158 var wait string
159 fmt.Scanln(&wait) 159 fmt.Scanln(&wait)
160 os.Exit(1) 160 exitWithRestore(1)
161 } else { 161 } else {
162 os.Exit(1) 162 exitWithRestore(1)
163 } 163 }
164 } 164 }
165 os.Exit(0) 165 exitWithRestore(0)
166} 166}
167 167
168func CurdOut(data interface{}) { 168func CurdOut(data interface{}) {
@@ -983,9 +983,9 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
983 needsProviderSearch := false 983 needsProviderSearch := false
984 if animePointer == nil { 984 if animePointer == nil {
985 needsProviderSearch = true 985 needsProviderSearch = true
986 } else if animePointer.ProviderName != "" && !ProviderStackContains(userCurdConfig, animePointer.ProviderName) { 986 } else if animePointer.ProviderId == "" {
987 needsProviderSearch = true 987 needsProviderSearch = true
988 } else if animePointer.ProviderName == "" && !ProviderStackContains(userCurdConfig, "allanime") { 988 } else if animePointer.ProviderName != "" && !ProviderStackContains(userCurdConfig, animePointer.ProviderName) {
989 needsProviderSearch = true 989 needsProviderSearch = true
990 } 990 }
991 991
@@ -1296,17 +1296,17 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1296 if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil { 1296 if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil {
1297 Log(fmt.Sprintf("Failed to resolve provider id: %v", err)) 1297 Log(fmt.Sprintf("Failed to resolve provider id: %v", err))
1298 CurdOut("Failed to resolve anime provider id: " + err.Error()) 1298 CurdOut("Failed to resolve anime provider id: " + err.Error())
1299 os.Exit(1) 1299 exitWithRestore(1)
1300 } 1300 }
1301 1301
1302 // Validate inputs 1302 // Validate inputs
1303 if anime.ProviderId == "" { 1303 if anime.ProviderId == "" {
1304 CurdOut("Error: No anime ID found") 1304 CurdOut("Error: No anime ID found")
1305 os.Exit(1) 1305 exitWithRestore(1)
1306 } 1306 }
1307 if anime.Ep.Number <= 0 { 1307 if anime.Ep.Number <= 0 {
1308 CurdOut("Error: Invalid episode number") 1308 CurdOut("Error: Invalid episode number")
1309 os.Exit(1) 1309 exitWithRestore(1)
1310 } 1310 }
1311 1311
1312 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) { 1312 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
@@ -1477,7 +1477,7 @@ episodeLinksReady:
1477 1477
1478 if err != nil { 1478 if err != nil {
1479 Log("Failed to start mpv") 1479 Log("Failed to start mpv")
1480 os.Exit(1) 1480 exitWithRestore(1)
1481 } 1481 }
1482 1482
1483 return mpvSocketPath 1483 return mpvSocketPath
@@ -2148,6 +2148,6 @@ func ChangeProvider(userCurdConfig *CurdConfig) {
2148 SaveConfigToFile(configPath, configMap) 2148 SaveConfigToFile(configPath, configMap)
2149 } 2149 }
2150 2150
2151 CurdOut(fmt.Sprintf("\nProvider successfully changed to %s.\n", selected.Label)) 2151 CurdOut(fmt.Sprintf("\nProvider successfully changed to %s.\n", providerConfigDisplayLabel(userCurdConfig.Provider)))
2152 time.Sleep(1 * time.Second) 2152 time.Sleep(1 * time.Second)
2153} 2153}
internal/loadproviders/load.go +2
@@ -5,4 +5,6 @@ import (
5 _ "github.com/wraient/curd/internal/providers/allanime" 5 _ "github.com/wraient/curd/internal/providers/allanime"
6 _ "github.com/wraient/curd/internal/providers/animepahe" 6 _ "github.com/wraient/curd/internal/providers/animepahe"
7 _ "github.com/wraient/curd/internal/providers/anineko" 7 _ "github.com/wraient/curd/internal/providers/anineko"
8 _ "github.com/wraient/curd/internal/providers/anipub"
9 _ "github.com/wraient/curd/internal/providers/senshi"
8) 10)
internal/localTracking.go +1 −1
@@ -498,7 +498,7 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
498 mpvSocketPath, err := StartVideo(PrioritizeLink(link), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(anime), anime.Ep.Number), &anime) 498 mpvSocketPath, err := StartVideo(PrioritizeLink(link), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(anime), anime.Ep.Number), &anime)
499 if err != nil { 499 if err != nil {
500 Log("Failed to start mpv") 500 Log("Failed to start mpv")
501 os.Exit(1) 501 exitWithRestore(1)
502 } 502 }
503 503
504 anime.Ep.Player.SocketPath = mpvSocketPath 504 anime.Ep.Player.SocketPath = mpvSocketPath
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 != "anineko" { 222 if got := GetProvider().Name(); got != "senshi" {
223 t.Fatalf("expected anineko provider when allanime is disabled, got %q", got) 223 t.Fatalf("expected senshi 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 != "anineko" { 238 if got := GetProvider().Name(); got != "senshi" {
239 t.Fatalf("expected anineko fallback for disabled provider, got %q", got) 239 t.Fatalf("expected senshi fallback for disabled provider, got %q", got)
240 } 240 }
241} 241}
242 242
internal/provider.go +10 −2
@@ -58,7 +58,7 @@ func parseProviderConfigParts(rawProvider string) []string {
58func parseProviderConfig(rawProvider string) ([]string, bool) { 58func parseProviderConfig(rawProvider string) ([]string, bool) {
59 rawProvider = strings.TrimSpace(rawProvider) 59 rawProvider = strings.TrimSpace(rawProvider)
60 if rawProvider == "" { 60 if rawProvider == "" {
61 rawProvider = firstEnabledProviderName() 61 return defaultEnabledProviderStack(), false
62 } 62 }
63 63
64 normalizedRaw := strings.ToLower(rawProvider) 64 normalizedRaw := strings.ToLower(rawProvider)
@@ -108,7 +108,7 @@ func parseProviderConfig(rawProvider string) ([]string, bool) {
108} 108}
109 109
110func configuredProviderNames(config *CurdConfig) []string { 110func configuredProviderNames(config *CurdConfig) []string {
111 rawProvider := firstEnabledProviderName() 111 rawProvider := stackedProviderConfigValue
112 if config != nil && strings.TrimSpace(config.Provider) != "" { 112 if config != nil && strings.TrimSpace(config.Provider) != "" {
113 rawProvider = config.Provider 113 rawProvider = config.Provider
114 } 114 }
@@ -122,7 +122,15 @@ func ConfiguredProviderNames(config *CurdConfig) []string {
122} 122}
123 123
124func canonicalProviderConfigValue(rawProvider string) string { 124func canonicalProviderConfigValue(rawProvider string) string {
125 rawProvider = strings.TrimSpace(rawProvider)
126 if isStackedProviderConfig(rawProvider) {
127 return stackedProviderConfigValue
128 }
129
125 names, animepaheDeclined := parseProviderConfig(rawProvider) 130 names, animepaheDeclined := parseProviderConfig(rawProvider)
131 if !animepaheDeclined && providerListsEqual(names, defaultEnabledProviderStack()) {
132 return stackedProviderConfigValue
133 }
126 return formatProviderConfigValue(names, animepaheDeclined) 134 return formatProviderConfigValue(names, animepaheDeclined)
127} 135}
128 136
internal/provider_disabled.go +36 −16
@@ -100,32 +100,52 @@ func filterEnabledProviders(names []string) []string {
100 return enabled 100 return enabled
101} 101}
102 102
103var preferredProviderOrder = []string{"senshi", "anipub", "anineko", "allanime", "animepahe"}
104
103func defaultEnabledProviderStack() []string { 105func defaultEnabledProviderStack() []string {
104 names := providers.RegisteredNames() 106 registered := providers.RegisteredNames()
105 return filterEnabledProviders(names) 107 registeredSet := make(map[string]struct{}, len(registered))
108 for _, name := range registered {
109 registeredSet[name] = struct{}{}
110 }
111
112 ordered := make([]string, 0, len(registered))
113 for _, name := range preferredProviderOrder {
114 if _, ok := registeredSet[name]; ok {
115 ordered = append(ordered, name)
116 }
117 }
118 for _, name := range registered {
119 found := false
120 for _, preferred := range preferredProviderOrder {
121 if name == preferred {
122 found = true
123 break
124 }
125 }
126 if !found {
127 ordered = append(ordered, name)
128 }
129 }
130 return filterEnabledProviders(ordered)
106} 131}
107 132
108func providerSelectionOptions() []SelectionOption { 133func providerSelectionOptions() []SelectionOption {
109 enabled := defaultEnabledProviderStack() 134 enabled := defaultEnabledProviderStack()
110 options := make([]SelectionOption, 0, len(enabled)*len(enabled)) 135 options := make([]SelectionOption, 0, len(enabled)+1)
136
137 stackLabel := providerConfigDisplayLabel(stackedProviderConfigValue)
138 options = append(options, SelectionOption{
139 Key: stackedProviderConfigValue,
140 Label: stackLabel,
141 })
142
111 for _, name := range enabled { 143 for _, name := range enabled {
112 options = append(options, SelectionOption{ 144 options = append(options, SelectionOption{
113 Key: formatProviderConfigValue([]string{name}, false), 145 Key: formatProviderConfigValue([]string{name}, false),
114 Label: name, 146 Label: name,
115 }) 147 })
116 } 148 }
117 for _, primary := range enabled {
118 for _, secondary := range enabled {
119 if primary == secondary {
120 continue
121 }
122 names := []string{primary, secondary}
123 options = append(options, SelectionOption{
124 Key: formatProviderConfigValue(names, false),
125 Label: primary + ", then " + secondary,
126 })
127 }
128 }
129 return options 149 return options
130} 150}
131 151
@@ -134,7 +154,7 @@ func firstEnabledProviderName() string {
134 if len(enabled) > 0 { 154 if len(enabled) > 0 {
135 return enabled[0] 155 return enabled[0]
136 } 156 }
137 return "anineko" 157 return "senshi"
138} 158}
139 159
140func ensureEnabledProviderNames(names []string) []string { 160func ensureEnabledProviderNames(names []string) []string {
internal/provider_disabled_test.go +8 −5
@@ -9,6 +9,9 @@ func TestProviderEnabledDisablesAllanimeAndAnimepaheByDefault(t *testing.T) {
9 if ProviderEnabled("animepahe") != false { 9 if ProviderEnabled("animepahe") != false {
10 t.Fatal("expected animepahe to be disabled by default") 10 t.Fatal("expected animepahe to be disabled by default")
11 } 11 }
12 if ProviderEnabled("senshi") != true {
13 t.Fatal("expected senshi to stay enabled")
14 }
12 if ProviderEnabled("anineko") != true { 15 if ProviderEnabled("anineko") != true {
13 t.Fatal("expected anineko to stay enabled") 16 t.Fatal("expected anineko to stay enabled")
14 } 17 }
@@ -26,11 +29,11 @@ func TestConfiguredProviderNamesFiltersDisabledProviders(t *testing.T) {
26 cfg *CurdConfig 29 cfg *CurdConfig
27 want []string 30 want []string
28 }{ 31 }{
29 {name: "empty", cfg: &CurdConfig{}, want: []string{"anineko"}}, 32 {name: "empty", cfg: &CurdConfig{}, want: []string{"senshi", "anipub", "anineko"}},
30 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"anineko"}}, 33 {name: "json list", cfg: &CurdConfig{Provider: `["allanime","animepahe"]`}, want: []string{"senshi"}},
31 {name: "animepahe only", cfg: &CurdConfig{Provider: `["animepahe"]`}, want: []string{"anineko"}}, 34 {name: "animepahe only", cfg: &CurdConfig{Provider: `["animepahe"]`}, want: []string{"senshi"}},
32 {name: "allanime only", cfg: &CurdConfig{Provider: `["allanime"]`}, want: []string{"anineko"}}, 35 {name: "allanime only", cfg: &CurdConfig{Provider: `["allanime"]`}, want: []string{"senshi"}},
33 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"anineko"}}, 36 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"senshi", "anipub", "anineko"}},
34 } 37 }
35 38
36 for _, tc := range cases { 39 for _, tc := range cases {
internal/provider_mapping.go +102 −16
@@ -11,6 +11,7 @@ import (
11 "strings" 11 "strings"
12 12
13 "github.com/wraient/curd/internal/providers/animepahe" 13 "github.com/wraient/curd/internal/providers/animepahe"
14 "github.com/wraient/curd/internal/providers/anipub"
14) 15)
15 16
16type ProviderMappingOutcome int 17type ProviderMappingOutcome int
@@ -49,11 +50,14 @@ func (s *providerMappingSearchState) currentProviderLabel() string {
49} 50}
50 51
51func (s *providerMappingSearchState) nextProviderLabel() string { 52func (s *providerMappingSearchState) nextProviderLabel() string {
53 if len(s.allProviders) == 0 {
54 return ""
55 }
52 if !s.sequential { 56 if !s.sequential {
53 if len(s.allProviders) > 0 { 57 if len(s.allProviders) <= 1 {
54 return s.allProviders[0] 58 return ""
55 } 59 }
56 return "" 60 return s.allProviders[0]
57 } 61 }
58 next := s.providerIndex + 1 62 next := s.providerIndex + 1
59 if next < len(s.allProviders) { 63 if next < len(s.allProviders) {
@@ -63,10 +67,16 @@ func (s *providerMappingSearchState) nextProviderLabel() string {
63} 67}
64 68
65func (s *providerMappingSearchState) advanceToNextProvider() bool { 69func (s *providerMappingSearchState) advanceToNextProvider() bool {
70 if len(s.allProviders) == 0 {
71 return false
72 }
66 if !s.sequential { 73 if !s.sequential {
74 if len(s.allProviders) <= 1 {
75 return false
76 }
67 s.sequential = true 77 s.sequential = true
68 s.providerIndex = 0 78 s.providerIndex = 0
69 return len(s.allProviders) > 0 79 return true
70 } 80 }
71 s.providerIndex++ 81 s.providerIndex++
72 return s.providerIndex < len(s.allProviders) 82 return s.providerIndex < len(s.allProviders)
@@ -116,10 +126,32 @@ func autoMatchProviderListing(config *CurdConfig, anime *Anime, animeList []Sele
116 126
117 anilistRegex := regexp.MustCompile(`anilistcdn/media/anime/cover/(?:large|medium)/(?:bx)?(\d+)`) 127 anilistRegex := regexp.MustCompile(`anilistcdn/media/anime/cover/(?:large|medium)/(?:bx)?(\d+)`)
118 malRegex := regexp.MustCompile(`myanimelist\.net/images/anime/[^/]+/([^/]+\.jpg)`) 128 malRegex := regexp.MustCompile(`myanimelist\.net/images/anime/[^/]+/([^/]+\.jpg)`)
129 senshiPosterRE := regexp.MustCompile(`/posters/(\d+)(?:\.webp)?`)
130
131 if anime.MalId == 0 {
132 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
133 }
134 if anime.MalId != 0 {
135 malIDStr := strconv.Itoa(anime.MalId)
136 for i, option := range animeList {
137 if option.Key == malIDStr {
138 Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s', Thumbnail='%s'", i, option.Key, option.Label, option.Thumbnail))
139 anime.ProviderId = option.Key
140 Log(fmt.Sprintf("Found MAL ID provider key match! Setting ProviderId to: %s", anime.ProviderId))
141 return true
142 }
143 }
144 }
119 145
120 for i, option := range animeList { 146 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)) 147 Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s', Thumbnail='%s'", i, option.Key, option.Label, option.Thumbnail))
122 148
149 if malID := malIDFromProviderExtraData(option.ExtraData); malID != 0 && anime.MalId != 0 && malID == anime.MalId {
150 anime.ProviderId = option.Key
151 Log(fmt.Sprintf("Found provider MAL ID extra-data match! Setting ProviderId to: %s", anime.ProviderId))
152 return true
153 }
154
123 if strings.Contains(option.Thumbnail, "anilist.co") { 155 if strings.Contains(option.Thumbnail, "anilist.co") {
124 matches := anilistRegex.FindStringSubmatch(option.Thumbnail) 156 matches := anilistRegex.FindStringSubmatch(option.Thumbnail)
125 if len(matches) > 1 && matches[1] == anilistIDStr { 157 if len(matches) > 1 && matches[1] == anilistIDStr {
@@ -155,6 +187,13 @@ func autoMatchProviderListing(config *CurdConfig, anime *Anime, animeList []Sele
155 } 187 }
156 } 188 }
157 } 189 }
190 } else if strings.Contains(option.Thumbnail, "/posters/") {
191 matches := senshiPosterRE.FindStringSubmatch(option.Thumbnail)
192 if len(matches) > 1 && anime.MalId != 0 && matches[1] == strconv.Itoa(anime.MalId) {
193 anime.ProviderId = option.Key
194 Log(fmt.Sprintf("Found Senshi MAL poster match! Setting ProviderId to: %s", anime.ProviderId))
195 return true
196 }
158 } 197 }
159 } 198 }
160 199
@@ -373,14 +412,57 @@ func promptProviderMatchRecovery(config *CurdConfig, state *providerMappingSearc
373 return selected.Key, nil 412 return selected.Key, nil
374} 413}
375 414
376func applySelectedProviderMapping(config *CurdConfig, anime *Anime, selected SelectionOption) { 415func activeProviderName(config *CurdConfig, state *providerMappingSearchState) string {
416 if state != nil && state.sequential {
417 if name := state.currentProviderLabel(); name != "" {
418 return name
419 }
420 }
421 names := configuredProviderNames(config)
422 if len(names) > 0 {
423 return names[0]
424 }
425 return firstEnabledProviderName()
426}
427
428func providerNameFromSelectionLabel(label string) string {
429 label = strings.TrimSpace(label)
430 if idx := strings.LastIndex(label, " ["); idx > 0 && strings.HasSuffix(label, "]") {
431 name := strings.TrimSpace(label[idx+2 : len(label)-1])
432 if normalized := normalizeProviderName(name); normalized != "" {
433 return normalized
434 }
435 }
436 return ""
437}
438
439func providerNameFromSelection(config *CurdConfig, state *providerMappingSearchState, selected SelectionOption) string {
440 if providerName, _, ok := ParseProviderQualifiedID(selected.Key); ok {
441 return providerName
442 }
443 if name := providerNameFromSelectionLabel(selected.Label); name != "" {
444 return name
445 }
446 return activeProviderName(config, state)
447}
448
449func applyMatchedProviderMapping(config *CurdConfig, state *providerMappingSearchState, anime *Anime) {
450 if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
451 anime.ProviderName = providerName
452 anime.ProviderId = rawProviderID
453 return
454 }
455 anime.ProviderName = activeProviderName(config, state)
456}
457
458func applySelectedProviderMapping(config *CurdConfig, state *providerMappingSearchState, anime *Anime, selected SelectionOption) {
377 anime.ProviderId = selected.Key 459 anime.ProviderId = selected.Key
378 if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok { 460 if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
379 anime.ProviderName = providerName 461 anime.ProviderName = providerName
380 anime.ProviderId = rawProviderID 462 anime.ProviderId = rawProviderID
381 } else { 463 return
382 anime.ProviderName = configuredProviderNames(config)[0]
383 } 464 }
465 anime.ProviderName = providerNameFromSelection(config, state, selected)
384} 466}
385 467
386func promptCustomProviderSearchQuery(config *CurdConfig, currentQuery, hint string) (string, bool, bool, error) { 468func promptCustomProviderSearchQuery(config *CurdConfig, currentQuery, hint string) (string, bool, bool, error) {
@@ -441,12 +523,7 @@ func resolveAnimeProviderMapping(config *CurdConfig, anime *Anime, query string,
441 523
442 anime.ProviderId = "" 524 anime.ProviderId = ""
443 if !manualOnly && autoMatchProviderListing(config, anime, animeList, state.query, anilistEntry) { 525 if !manualOnly && autoMatchProviderListing(config, anime, animeList, state.query, anilistEntry) {
444 if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok { 526 applyMatchedProviderMapping(config, state, anime)
445 anime.ProviderName = providerName
446 anime.ProviderId = rawProviderID
447 } else {
448 anime.ProviderName = configuredProviderNames(config)[0]
449 }
450 return ProviderMappingOK, nil 527 return ProviderMappingOK, nil
451 } 528 }
452 529
@@ -463,7 +540,7 @@ func resolveAnimeProviderMapping(config *CurdConfig, anime *Anime, query string,
463 case "-2": 540 case "-2":
464 return ProviderMappingBack, nil 541 return ProviderMappingBack, nil
465 default: 542 default:
466 applySelectedProviderMapping(config, anime, selected) 543 applySelectedProviderMapping(config, state, anime, selected)
467 return ProviderMappingOK, nil 544 return ProviderMappingOK, nil
468 } 545 }
469 } 546 }
@@ -516,7 +593,7 @@ func resolveAnimeProviderMapping(config *CurdConfig, anime *Anime, query string,
516 case "-2": 593 case "-2":
517 return ProviderMappingBack, nil 594 return ProviderMappingBack, nil
518 default: 595 default:
519 applySelectedProviderMapping(config, anime, selected) 596 applySelectedProviderMapping(config, state, anime, selected)
520 return ProviderMappingOK, nil 597 return ProviderMappingOK, nil
521 } 598 }
522 case "custom", "next_provider": 599 case "custom", "next_provider":
@@ -831,7 +908,16 @@ func ResolveUntrackedProviderSearch(config *CurdConfig, initialQuery string) (pr
831 if name, rawID, ok := ParseProviderQualifiedID(selected.Key); ok { 908 if name, rawID, ok := ParseProviderQualifiedID(selected.Key); ok {
832 return rawID, name, false, nil 909 return rawID, name, false, nil
833 } 910 }
834 return selected.Key, configuredProviderNames(config)[0], false, nil 911 return selected.Key, providerNameFromSelection(config, state, selected), false, nil
835 } 912 }
836 } 913 }
837} 914}
915
916func malIDFromProviderExtraData(extra any) int {
917 switch item := extra.(type) {
918 case anipub.SearchItem:
919 return item.MalID
920 default:
921 return 0
922 }
923}
internal/provider_mapping_test.go added +109
@@ -0,0 +1,109 @@
1package internal
2
3import (
4 "testing"
5
6 _ "github.com/wraient/curd/internal/loadproviders"
7)
8
9func TestProviderMappingSearchStateNextProvider(t *testing.T) {
10 t.Run("single provider hides next option", func(t *testing.T) {
11 state := &providerMappingSearchState{allProviders: []string{"anineko"}}
12 if got := state.nextProviderLabel(); got != "" {
13 t.Fatalf("nextProviderLabel() = %q, want empty", got)
14 }
15 if state.advanceToNextProvider() {
16 t.Fatal("advanceToNextProvider() = true, want false")
17 }
18 })
19
20 t.Run("stacked search offers first provider", func(t *testing.T) {
21 state := &providerMappingSearchState{allProviders: []string{"senshi", "anineko", "anipub"}}
22 if got := state.nextProviderLabel(); got != "senshi" {
23 t.Fatalf("nextProviderLabel() = %q, want senshi", got)
24 }
25 })
26
27 t.Run("sequential advance walks stack", func(t *testing.T) {
28 state := &providerMappingSearchState{allProviders: []string{"senshi", "anineko", "anipub"}}
29 if !state.advanceToNextProvider() {
30 t.Fatal("expected first advance to succeed")
31 }
32 if !state.sequential || state.providerIndex != 0 {
33 t.Fatalf("expected sequential at index 0, got sequential=%v index=%d", state.sequential, state.providerIndex)
34 }
35 if got := state.nextProviderLabel(); got != "anineko" {
36 t.Fatalf("nextProviderLabel() = %q, want anineko", got)
37 }
38 if !state.advanceToNextProvider() || state.providerIndex != 1 {
39 t.Fatalf("expected index 1 after second advance, got %d", state.providerIndex)
40 }
41 if got := state.nextProviderLabel(); got != "anipub" {
42 t.Fatalf("nextProviderLabel() = %q, want anipub", got)
43 }
44 if !state.advanceToNextProvider() || state.providerIndex != 2 {
45 t.Fatalf("expected index 2 after third advance, got %d", state.providerIndex)
46 }
47 if got := state.nextProviderLabel(); got != "" {
48 t.Fatalf("nextProviderLabel() = %q, want empty at end", got)
49 }
50 if state.advanceToNextProvider() {
51 t.Fatal("expected final advance to fail")
52 }
53 })
54}
55
56func TestProviderNameFromSelectionUsesSequentialProvider(t *testing.T) {
57 withAllProvidersEnabledForTest(t)
58 config := &CurdConfig{Provider: `["senshi","anineko"]`}
59 state := &providerMappingSearchState{
60 allProviders: []string{"senshi", "anineko"},
61 sequential: true,
62 providerIndex: 1,
63 }
64
65 selected := SelectionOption{
66 Key: "frieren-beyond-journeys-end",
67 Label: "Frieren: Beyond Journey's End",
68 Title: "Frieren: Beyond Journey's End",
69 }
70 if got := providerNameFromSelection(config, state, selected); got != "anineko" {
71 t.Fatalf("providerNameFromSelection() = %q, want anineko", got)
72 }
73
74 var anime Anime
75 applySelectedProviderMapping(config, state, &anime, selected)
76 if anime.ProviderName != "anineko" || anime.ProviderId != "frieren-beyond-journeys-end" {
77 t.Fatalf("unexpected mapping %+v", anime)
78 }
79}
80
81func TestProviderNameFromSelectionUsesQualifiedKey(t *testing.T) {
82 withAllProvidersEnabledForTest(t)
83 config := &CurdConfig{Provider: `["senshi","anineko"]`}
84 state := &providerMappingSearchState{allProviders: []string{"senshi", "anineko"}}
85
86 selected := SelectionOption{
87 Key: "anineko::frieren-beyond-journeys-end",
88 Label: "Frieren: Beyond Journey's End [anineko]",
89 }
90 if got := providerNameFromSelection(config, state, selected); got != "anineko" {
91 t.Fatalf("providerNameFromSelection() = %q, want anineko", got)
92 }
93}
94
95func TestApplyMatchedProviderMappingUsesSequentialProvider(t *testing.T) {
96 withAllProvidersEnabledForTest(t)
97 config := &CurdConfig{Provider: `["senshi","anineko"]`}
98 state := &providerMappingSearchState{
99 allProviders: []string{"senshi", "anineko"},
100 sequential: true,
101 providerIndex: 1,
102 }
103
104 anime := Anime{ProviderId: "frieren-beyond-journeys-end"}
105 applyMatchedProviderMapping(config, state, &anime)
106 if anime.ProviderName != "anineko" || anime.ProviderId != "frieren-beyond-journeys-end" {
107 t.Fatalf("unexpected mapping %+v", anime)
108 }
109}
internal/provider_migrate.go added +170
@@ -0,0 +1,170 @@
1package internal
2
3import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "strings"
8)
9
10const stackedProviderConfigValue = "stacked"
11
12func isStackedProviderConfig(raw string) bool {
13 switch strings.ToLower(strings.TrimSpace(raw)) {
14 case "stacked", "stack", "auto", "all":
15 return true
16 default:
17 return false
18 }
19}
20
21func isFactoryDefaultProvider(raw string) bool {
22 raw = strings.TrimSpace(raw)
23 if raw == "" {
24 return true
25 }
26 if isStackedProviderConfig(raw) {
27 return true
28 }
29
30 names, declined := parseProviderConfig(raw)
31 if declined {
32 return false
33 }
34 switch len(names) {
35 case 0:
36 return true
37 case 1:
38 switch names[0] {
39 case "senshi", "allanime":
40 return true
41 }
42 }
43 return false
44}
45
46func providerListsEqual(a, b []string) bool {
47 if len(a) != len(b) {
48 return false
49 }
50 for i := range a {
51 if a[i] != b[i] {
52 return false
53 }
54 }
55 return true
56}
57
58func migrateProviderConfig(raw string) (string, bool) {
59 raw = strings.TrimSpace(raw)
60 if isFactoryDefaultProvider(raw) {
61 if raw == stackedProviderConfigValue {
62 return raw, false
63 }
64 return stackedProviderConfigValue, true
65 }
66
67 if isStackedProviderConfig(raw) {
68 if raw != stackedProviderConfigValue {
69 return stackedProviderConfigValue, true
70 }
71 return raw, false
72 }
73
74 names, declined := parseProviderConfig(raw)
75 if len(names) > 1 {
76 return stackedProviderConfigValue, true
77 }
78
79 canonical := canonicalProviderConfigValue(raw)
80 if canonical != raw {
81 return canonical, true
82 }
83 _ = declined
84 return raw, false
85}
86
87func readStoredCurdVersion(storagePath string) string {
88 path := storageVersionFilePath(storagePath)
89 raw, err := os.ReadFile(path)
90 if err != nil {
91 return ""
92 }
93 return strings.TrimSpace(string(raw))
94}
95
96func writeStoredCurdVersion(storagePath, version string) error {
97 storagePath = strings.TrimSpace(storagePath)
98 version = strings.TrimSpace(version)
99 if storagePath == "" || version == "" {
100 return nil
101 }
102 if err := os.MkdirAll(storagePath, 0755); err != nil {
103 return err
104 }
105 return os.WriteFile(storageVersionFilePath(storagePath), []byte(version+"\n"), 0644)
106}
107
108// MigrateOnVersionUpgrade updates stored state and config when curd is upgraded.
109// Returns whether the config file was updated.
110func MigrateOnVersionUpgrade(configPath string, config *CurdConfig, appVersion string) (bool, error) {
111 if config == nil {
112 return false, nil
113 }
114
115 appVersion = strings.TrimSpace(appVersion)
116 if appVersion == "" {
117 appVersion = CurdVersion()
118 }
119
120 storagePath := os.ExpandEnv(config.StoragePath)
121 if storagePath == "" {
122 storagePath = filepath.Join(os.ExpandEnv("$HOME"), ".local", "share", "curd")
123 }
124
125 storedVersion := readStoredCurdVersion(storagePath)
126 configUpdated := false
127
128 if storedVersion != appVersion {
129 if nextProvider, changed := migrateProviderConfig(config.Provider); changed {
130 config.Provider = nextProvider
131 configUpdated = true
132 }
133 }
134
135 if err := writeStoredCurdVersion(storagePath, appVersion); err != nil {
136 return configUpdated, fmt.Errorf("write curd version file: %w", err)
137 }
138
139 if !configUpdated || strings.TrimSpace(configPath) == "" {
140 return configUpdated, nil
141 }
142
143 configMap, err := LoadConfigFromFile(configPath)
144 if err != nil {
145 return configUpdated, err
146 }
147 configMap["Provider"] = config.Provider
148 if err := SaveConfigToFile(configPath, configMap); err != nil {
149 return configUpdated, err
150 }
151 return configUpdated, nil
152}
153
154func providerConfigDisplayLabel(raw string) string {
155 if isStackedProviderConfig(raw) {
156 names := defaultEnabledProviderStack()
157 if len(names) == 0 {
158 return "Default with fallback"
159 }
160 return fmt.Sprintf("Default with fallback (%s)", strings.Join(names, " → "))
161 }
162 names, _ := parseProviderConfig(raw)
163 if len(names) == 1 {
164 return names[0]
165 }
166 if len(names) > 1 {
167 return strings.Join(names, " → ")
168 }
169 return raw
170}
internal/provider_migrate_test.go added +129
@@ -0,0 +1,129 @@
1package internal
2
3import (
4 "os"
5 "path/filepath"
6 "strings"
7 "testing"
8
9 _ "github.com/wraient/curd/internal/loadproviders"
10)
11
12func TestProviderSelectionOptionsUsesDefaultAndSingleProviders(t *testing.T) {
13 withAllProvidersEnabledForTest(t)
14 options := providerSelectionOptions()
15 if len(options) == 0 {
16 t.Fatal("expected provider options")
17 }
18 if options[0].Key != "stacked" {
19 t.Fatalf("first option key = %q, want stacked", options[0].Key)
20 }
21 if !strings.Contains(options[0].Label, "Default with fallback") {
22 t.Fatalf("first option label = %q", options[0].Label)
23 }
24 for _, option := range options {
25 if strings.Contains(option.Label, ", then ") {
26 t.Fatalf("unexpected combo label %q", option.Label)
27 }
28 }
29}
30
31func TestMigrateProviderConfig(t *testing.T) {
32 cases := []struct {
33 name string
34 raw string
35 want string
36 changed bool
37 }{
38 {name: "legacy senshi default", raw: `["senshi"]`, want: "stacked", changed: true},
39 {name: "legacy allanime default", raw: `["allanime"]`, want: "stacked", changed: true},
40 {name: "stack alias", raw: "stack", want: "stacked", changed: true},
41 {name: "already stacked", raw: "stacked", want: "stacked", changed: false},
42 {name: "single anineko", raw: `["anineko"]`, want: `["anineko"]`, changed: false},
43 {name: "legacy pair", raw: `["senshi","anineko"]`, want: "stacked", changed: true},
44 }
45
46 for _, tc := range cases {
47 got, changed := migrateProviderConfig(tc.raw)
48 if changed != tc.changed || got != tc.want {
49 t.Fatalf("%s: got (%q, %v), want (%q, %v)", tc.name, got, changed, tc.want, tc.changed)
50 }
51 }
52}
53
54func TestCanonicalProviderConfigValuePrefersStackedToken(t *testing.T) {
55 withAllProvidersEnabledForTest(t)
56 if got := canonicalProviderConfigValue("stacked"); got != "stacked" {
57 t.Fatalf("got %q, want stacked", got)
58 }
59 if got := canonicalProviderConfigValue(""); got != "stacked" {
60 t.Fatalf("empty got %q, want stacked", got)
61 }
62}
63
64func TestMigrateOnVersionUpgradeWritesVersionAndUpdatesProvider(t *testing.T) {
65 withAllProvidersEnabledForTest(t)
66 tempDir := t.TempDir()
67 configPath := filepath.Join(tempDir, "curd.conf")
68 storagePath := filepath.Join(tempDir, "share")
69 if err := os.WriteFile(configPath, []byte("Provider=[\"senshi\"]\nStoragePath="+storagePath+"\n"), 0644); err != nil {
70 t.Fatalf("write config: %v", err)
71 }
72
73 config, err := LoadConfig(configPath)
74 if err != nil {
75 t.Fatalf("LoadConfig: %v", err)
76 }
77 if config.Provider != `["senshi"]` {
78 t.Fatalf("pre-migration provider = %q", config.Provider)
79 }
80
81 updated, err := MigrateOnVersionUpgrade(configPath, &config, "2.1.0")
82 if err != nil {
83 t.Fatalf("MigrateOnVersionUpgrade: %v", err)
84 }
85 if !updated {
86 t.Fatal("expected provider config update")
87 }
88 if config.Provider != "stacked" {
89 t.Fatalf("provider = %q, want stacked", config.Provider)
90 }
91
92 versionBytes, err := os.ReadFile(filepath.Join(storagePath, "curd_version"))
93 if err != nil {
94 t.Fatalf("read version file: %v", err)
95 }
96 if strings.TrimSpace(string(versionBytes)) != "2.1.0" {
97 t.Fatalf("version file = %q", string(versionBytes))
98 }
99
100 contents, err := os.ReadFile(configPath)
101 if err != nil {
102 t.Fatalf("read config: %v", err)
103 }
104 if !strings.Contains(string(contents), "Provider=stacked") {
105 t.Fatalf("config not persisted: %s", string(contents))
106 }
107
108 updated, err = MigrateOnVersionUpgrade(configPath, &config, "2.1.0")
109 if err != nil {
110 t.Fatalf("second migration: %v", err)
111 }
112 if updated {
113 t.Fatal("expected no update on same version")
114 }
115}
116
117func TestConfiguredProviderNamesUsesStackedByDefault(t *testing.T) {
118 withAllProvidersEnabledForTest(t)
119 got := ConfiguredProviderNames(&CurdConfig{})
120 want := []string{"senshi", "anipub", "anineko", "allanime", "animepahe"}
121 if len(got) != len(want) {
122 t.Fatalf("got %v, want %v", got, want)
123 }
124 for i := range want {
125 if got[i] != want[i] {
126 t.Fatalf("got %v, want %v", got, want)
127 }
128 }
129}
internal/provider_stack_test.go +3 −3
@@ -95,11 +95,11 @@ func TestConfiguredProviderNamesAcceptsOrderedLists(t *testing.T) {
95 cfg *CurdConfig 95 cfg *CurdConfig
96 want []string 96 want []string
97 }{ 97 }{
98 {name: "empty", cfg: &CurdConfig{}, want: []string{"allanime"}}, 98 {name: "empty", cfg: &CurdConfig{}, want: []string{"senshi", "anipub", "anineko", "allanime", "animepahe"}},
99 {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"}},
100 {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"}},
101 {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"}},
102 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"allanime", "animepahe", "anineko"}}, 102 {name: "legacy alias", cfg: &CurdConfig{Provider: "stacked"}, want: []string{"senshi", "anipub", "anineko", "allanime", "animepahe"}},
103 } 103 }
104 104
105 for _, tc := range cases { 105 for _, tc := range cases {
@@ -125,7 +125,7 @@ func TestCanonicalProviderConfigValueMigratesLegacyValuesWithoutAddingAnimepahe(
125 {name: "legacy animepahe", raw: "animepahe", want: `["animepahe"]`}, 125 {name: "legacy animepahe", raw: "animepahe", want: `["animepahe"]`},
126 {name: "ordered stack", raw: "animepahe,allanime", want: `["animepahe","allanime"]`}, 126 {name: "ordered stack", raw: "animepahe,allanime", want: `["animepahe","allanime"]`},
127 {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"]`},
128 {name: "empty default", raw: "", want: `["anineko"]`}, 128 {name: "empty default", raw: "", want: "stacked"},
129 } 129 }
130 130
131 for _, tc := range cases { 131 for _, tc := range cases {
internal/providers/anipub/client.go added +103
@@ -0,0 +1,103 @@
1package anipub
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "net/url"
9 "strings"
10
11 "github.com/wraient/curd/internal/curdhost"
12)
13
14const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
15
16var (
17 baseURL = "https://anipub.xyz"
18 megaplayBaseURL = "https://megaplay.buzz"
19)
20
21func newRequest(method, rawURL, referer string) (*http.Request, error) {
22 req, err := http.NewRequest(method, rawURL, nil)
23 if err != nil {
24 return nil, err
25 }
26 req.Header.Set("User-Agent", userAgent)
27 if referer != "" {
28 req.Header.Set("Referer", referer)
29 }
30 return req, nil
31}
32
33func fetchJSON(rawURL, referer string, dest any) error {
34 req, err := newRequest(http.MethodGet, rawURL, referer)
35 if err != nil {
36 return err
37 }
38 req.Header.Set("Accept", "application/json")
39
40 resp, err := curdhost.HTTPClient().Do(req)
41 if err != nil {
42 return err
43 }
44 defer resp.Body.Close()
45
46 raw, err := io.ReadAll(resp.Body)
47 if err != nil {
48 return err
49 }
50 if !curdhost.HTTPStatusOK(resp.StatusCode) {
51 return curdhost.HTTPStatusError("anipub request", resp.StatusCode, raw)
52 }
53 if dest == nil {
54 return nil
55 }
56 if err := json.Unmarshal(raw, dest); err != nil {
57 return fmt.Errorf("parse anipub response: %w", err)
58 }
59 return nil
60}
61
62func fetchString(rawURL, referer string) (string, error) {
63 req, err := newRequest(http.MethodGet, rawURL, referer)
64 if err != nil {
65 return "", err
66 }
67 resp, err := curdhost.HTTPClient().Do(req)
68 if err != nil {
69 return "", err
70 }
71 defer resp.Body.Close()
72
73 body, err := io.ReadAll(resp.Body)
74 if err != nil {
75 return "", err
76 }
77 if !curdhost.HTTPStatusOK(resp.StatusCode) {
78 return "", curdhost.HTTPStatusError("anipub request", resp.StatusCode, body)
79 }
80 return string(body), nil
81}
82
83func searchURL(query string) string {
84 return fmt.Sprintf("%s/api/search/%s", baseURL, url.PathEscape(strings.TrimSpace(query)))
85}
86
87func infoURL(showID string) string {
88 return fmt.Sprintf("%s/api/info/%s", baseURL, url.PathEscape(strings.TrimSpace(showID)))
89}
90
91func detailsURL(showID string) string {
92 return fmt.Sprintf("%s/v1/api/details/%s", baseURL, url.PathEscape(strings.TrimSpace(showID)))
93}
94
95func thumbnailFromInfo(info infoResponse, fallback string) string {
96 for _, candidate := range []string{info.Image, info.Cover, fallback} {
97 candidate = strings.TrimSpace(candidate)
98 if candidate != "" {
99 return candidate
100 }
101 }
102 return ""
103}
internal/providers/anipub/episodes.go added +62
@@ -0,0 +1,62 @@
1package anipub
2
3import (
4 "fmt"
5 "strconv"
6 "strings"
7)
8
9func episodesList(showID, mode string) ([]string, error) {
10 showID, err := parseShowID(showID)
11 if err != nil {
12 return nil, err
13 }
14 _ = mode
15
16 var details detailsResponse
17 if err := fetchJSON(detailsURL(showID), baseURL+"/", &details); err != nil {
18 return nil, err
19 }
20
21 count := len(details.Local.Ep) + 1
22 if count <= 0 {
23 return nil, fmt.Errorf("no episodes found for show %s", showID)
24 }
25
26 episodes := make([]string, 0, count)
27 for epNo := 1; epNo <= count; epNo++ {
28 episodes = append(episodes, strconv.Itoa(epNo))
29 }
30 return episodes, nil
31}
32
33func episodeVideoLink(details detailsResponse, epNo int) (string, error) {
34 if epNo <= 0 {
35 return "", fmt.Errorf("invalid episode number %d", epNo)
36 }
37 if epNo == 1 {
38 return normalizeEpisodeLink(details.Local.Link), nil
39 }
40 idx := epNo - 2
41 if idx < 0 || idx >= len(details.Local.Ep) {
42 return "", fmt.Errorf("episode %d not found", epNo)
43 }
44 return normalizeEpisodeLink(details.Local.Ep[idx].Link), nil
45}
46
47func normalizeEpisodeLink(raw string) string {
48 raw = strings.TrimSpace(raw)
49 raw = strings.TrimPrefix(raw, "src=")
50 return strings.TrimSpace(raw)
51}
52
53func parseShowID(showID string) (string, error) {
54 showID = strings.TrimSpace(showID)
55 if showID == "" {
56 return "", fmt.Errorf("empty show id")
57 }
58 if _, err := strconv.Atoi(showID); err != nil {
59 return "", fmt.Errorf("invalid anipub show id %q", showID)
60 }
61 return showID, nil
62}
internal/providers/anipub/megaplay.go added +96
@@ -0,0 +1,96 @@
1package anipub
2
3import (
4 "fmt"
5 "net/url"
6 "regexp"
7 "strconv"
8 "strings"
9
10 "github.com/wraient/curd/internal/providers"
11)
12
13var (
14 videoPathRE = regexp.MustCompile(`/video/(\d+)/(sub|dub)`)
15 dataIDRE = regexp.MustCompile(`data-id="(\d+)"`)
16)
17
18func resolveMegaplayStream(videoLink, mode string) (string, string, error) {
19 videoLink = strings.TrimSpace(videoLink)
20 if videoLink == "" {
21 return "", "", fmt.Errorf("empty video link")
22 }
23
24 embedID, linkMode, err := parseVideoLink(videoLink)
25 if err != nil {
26 return "", "", err
27 }
28 mode = providers.NormalizeTranslationType(mode)
29 if mode == "dub" {
30 linkMode = "dub"
31 } else {
32 linkMode = "sub"
33 }
34
35 streamPage := fmt.Sprintf("%s/stream/s-2/%s/%s", megaplayBaseURL, embedID, linkMode)
36 html, err := fetchString(streamPage, baseURL+"/")
37 if err != nil {
38 return "", "", err
39 }
40
41 dataID := dataIDRE.FindStringSubmatch(html)
42 if len(dataID) < 2 {
43 return "", "", fmt.Errorf("megaplay data-id not found")
44 }
45
46 sourcesURL := fmt.Sprintf("%s/stream/getSources?id=%s", megaplayBaseURL, dataID[1])
47 var payload megaplaySourcesResponse
48 if err := fetchJSON(sourcesURL, streamPage, &payload); err != nil {
49 return "", "", err
50 }
51
52 streamURL := strings.TrimSpace(payload.Sources.File)
53 if streamURL == "" {
54 return "", "", fmt.Errorf("megaplay stream url missing")
55 }
56 subtitle := pickSubtitleTrack(payload, mode)
57 return streamURL, subtitle, nil
58}
59
60func parseVideoLink(videoLink string) (embedID, mode string, err error) {
61 parsed, err := url.Parse(videoLink)
62 if err != nil {
63 return "", "", fmt.Errorf("parse video link: %w", err)
64 }
65 matches := videoPathRE.FindStringSubmatch(parsed.Path)
66 if len(matches) < 3 {
67 return "", "", fmt.Errorf("unsupported video link %q", videoLink)
68 }
69 embedID = matches[1]
70 mode = matches[2]
71 if _, err := strconv.Atoi(embedID); err != nil {
72 return "", "", fmt.Errorf("invalid embed id %q", embedID)
73 }
74 return embedID, mode, nil
75}
76
77func pickSubtitleTrack(payload megaplaySourcesResponse, mode string) string {
78 if mode == "dub" {
79 return ""
80 }
81 var fallback string
82 for _, track := range payload.Tracks {
83 file := strings.TrimSpace(track.File)
84 if file == "" || !strings.EqualFold(strings.TrimSpace(track.Kind), "captions") {
85 continue
86 }
87 label := strings.ToLower(strings.TrimSpace(track.Label))
88 if track.Default || strings.Contains(label, "english") {
89 return file
90 }
91 if fallback == "" {
92 fallback = file
93 }
94 }
95 return fallback
96}
internal/providers/anipub/provider.go added +34
@@ -0,0 +1,34 @@
1package anipub
2
3import "github.com/wraient/curd/internal/providers"
4
5// Provider implements anipub.xyz catalog search and MegaPlay stream resolution.
6type Provider struct{}
7
8func (p *Provider) Name() string {
9 return "anipub"
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/anipub/provider_test.go added +260
@@ -0,0 +1,260 @@
1package anipub
2
3import (
4 "encoding/json"
5 "io"
6 "net/http"
7 "net/http/httptest"
8 "strings"
9 "testing"
10
11 "github.com/wraient/curd/internal/curdhost"
12 "github.com/wraient/curd/internal/providers"
13)
14
15type roundTripFunc func(*http.Request) (*http.Response, error)
16
17func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
18 return f(req)
19}
20
21func withAnipubTestClient(t *testing.T, client *http.Client) {
22 t.Helper()
23 previous := curdhost.HTTPClient
24 t.Cleanup(func() {
25 curdhost.HTTPClient = previous
26 })
27 curdhost.HTTPClient = func() *http.Client { return client }
28}
29
30func jsonResponse(req *http.Request, statusCode int, payload any) *http.Response {
31 body, _ := json.Marshal(payload)
32 resp := &http.Response{
33 StatusCode: statusCode,
34 Header: make(http.Header),
35 Body: io.NopCloser(strings.NewReader(string(body))),
36 Request: req,
37 }
38 resp.Header.Set("Content-Type", "application/json")
39 return resp
40}
41
42func textResponse(req *http.Request, statusCode int, body string) *http.Response {
43 return &http.Response{
44 StatusCode: statusCode,
45 Header: make(http.Header),
46 Body: io.NopCloser(strings.NewReader(body)),
47 Request: req,
48 }
49}
50
51func TestDecodeSearchResultsSupportsSingleObjectAndNotFound(t *testing.T) {
52 t.Run("array", func(t *testing.T) {
53 results, err := decodeSearchResults([]byte(`[{"Name":"Frieren","Id":2454}]`))
54 if err != nil || len(results) != 1 || results[0].ID != 2454 {
55 t.Fatalf("array decode: %#v err=%v", results, err)
56 }
57 })
58 t.Run("single object", func(t *testing.T) {
59 results, err := decodeSearchResults([]byte(`{"Name":"Delicious in Dungeon","Id":2475,"finder":"delicious-in-dungeon"}`))
60 if err != nil || len(results) != 1 || results[0].ID != 2475 {
61 t.Fatalf("single decode: %#v err=%v", results, err)
62 }
63 })
64 t.Run("not found", func(t *testing.T) {
65 results, err := decodeSearchResults([]byte(`{"found":false}`))
66 if err != nil || len(results) != 0 {
67 t.Fatalf("not found decode: %#v err=%v", results, err)
68 }
69 })
70}
71
72func TestSearchAnimeParsesResults(t *testing.T) {
73 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
74 switch {
75 case r.URL.Path == "/api/search/frieren":
76 _ = json.NewEncoder(w).Encode([]searchResult{{
77 Name: "Frieren: Beyond Journey's End",
78 ID: 2454,
79 Image: "https://cdn.example/frieren.jpg",
80 Finder: "frieren-beyond-journeys-end",
81 }})
82 case r.URL.Path == "/api/info/2454":
83 _ = json.NewEncoder(w).Encode(infoResponse{
84 ID: 2454,
85 Name: "Frieren: Beyond Journey's End",
86 MALID: "52991",
87 EpCount: 28,
88 })
89 default:
90 http.NotFound(w, r)
91 }
92 }))
93 defer server.Close()
94
95 withAnipubTestClient(t, server.Client())
96 originalBase := baseURL
97 t.Cleanup(func() { baseURL = originalBase })
98 baseURL = server.URL
99
100 options, err := searchAnime("frieren", "sub")
101 if err != nil {
102 t.Fatalf("searchAnime: %v", err)
103 }
104 if len(options) != 1 {
105 t.Fatalf("expected 1 option, got %d", len(options))
106 }
107 if options[0].Key != "2454" {
108 t.Fatalf("unexpected key %q", options[0].Key)
109 }
110 item, ok := options[0].ExtraData.(SearchItem)
111 if !ok || item.MalID != 52991 || item.Episodes != 28 {
112 t.Fatalf("unexpected extra data %+v", options[0].ExtraData)
113 }
114}
115
116func TestEpisodesListCountsLocalEpisodes(t *testing.T) {
117 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
118 if r.URL.Path != "/v1/api/details/2454" {
119 http.NotFound(w, r)
120 return
121 }
122 _ = json.NewEncoder(w).Encode(detailsResponse{
123 Local: localDetails{
124 Link: "src=https://anipub.xyz/video/107257/sub",
125 Ep: []episodeLink{
126 {Link: "src=https://anipub.xyz/video/107259/sub"},
127 {Link: "src=https://anipub.xyz/video/107260/sub"},
128 },
129 },
130 })
131 }))
132 defer server.Close()
133
134 withAnipubTestClient(t, server.Client())
135 originalBase := baseURL
136 t.Cleanup(func() { baseURL = originalBase })
137 baseURL = server.URL
138
139 episodes, err := episodesList("2454", "sub")
140 if err != nil {
141 t.Fatalf("episodesList: %v", err)
142 }
143 if len(episodes) != 3 || episodes[0] != "1" || episodes[2] != "3" {
144 t.Fatalf("unexpected episodes %#v", episodes)
145 }
146}
147
148func TestGetEpisodeStreamsForModeResolvesMegaplay(t *testing.T) {
149 megaplay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
150 switch r.URL.Path {
151 case "/stream/s-2/107257/sub":
152 w.Header().Set("Content-Type", "text/html")
153 _, _ = w.Write([]byte(`<div id="player" data-id="13461" data-realid="107257"></div>`))
154 case "/stream/getSources":
155 _ = json.NewEncoder(w).Encode(megaplaySourcesResponse{
156 Sources: struct {
157 File string `json:"file"`
158 }{File: "https://cdn.example/master.m3u8"},
159 Tracks: []struct {
160 File string `json:"file"`
161 Label string `json:"label"`
162 Kind string `json:"kind"`
163 Default bool `json:"default"`
164 }{
165 {File: "https://cdn.example/eng.vtt", Label: "English", Kind: "captions", Default: true},
166 },
167 })
168 default:
169 http.NotFound(w, r)
170 }
171 }))
172 defer megaplay.Close()
173
174 anipubServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
175 if r.URL.Path != "/v1/api/details/2454" {
176 http.NotFound(w, r)
177 return
178 }
179 _ = json.NewEncoder(w).Encode(detailsResponse{
180 Local: localDetails{
181 Link: "src=https://anipub.xyz/video/107257/sub",
182 },
183 })
184 }))
185 defer anipubServer.Close()
186
187 client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
188 if strings.HasPrefix(req.URL.String(), megaplay.URL) {
189 return http.DefaultTransport.RoundTrip(req)
190 }
191 if strings.HasPrefix(req.URL.String(), anipubServer.URL) {
192 return http.DefaultTransport.RoundTrip(req)
193 }
194 return textResponse(req, http.StatusNotFound, ""), nil
195 })}
196 withAnipubTestClient(t, client)
197 originalBase := baseURL
198 originalMega := megaplayBaseURL
199 t.Cleanup(func() {
200 baseURL = originalBase
201 megaplayBaseURL = originalMega
202 })
203 baseURL = anipubServer.URL
204 megaplayBaseURL = megaplay.URL
205
206 links, hints, err := getEpisodeStreamsForMode("2454", providers.PlaybackConfig{SubOrDub: "sub"}, 1)
207 if err != nil {
208 t.Fatalf("getEpisodeStreamsForMode: %v", err)
209 }
210 if len(links) != 1 || links[0] != "https://cdn.example/master.m3u8" {
211 t.Fatalf("unexpected links %#v", links)
212 }
213 if hints[links[0]].Referrer != megaplay.URL+"/" {
214 t.Fatalf("unexpected referrer %q", hints[links[0]].Referrer)
215 }
216 if hints[links[0]].Subtitle != "https://cdn.example/eng.vtt" {
217 t.Fatalf("unexpected subtitle %q", hints[links[0]].Subtitle)
218 }
219}
220
221func TestResolveMegaplayStreamUsesDubMode(t *testing.T) {
222 megaplay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
223 switch r.URL.Path {
224 case "/stream/s-2/42/dub":
225 w.Header().Set("Content-Type", "text/html")
226 _, _ = w.Write([]byte(`<div data-id="99"></div>`))
227 case "/stream/getSources":
228 _ = json.NewEncoder(w).Encode(megaplaySourcesResponse{
229 Sources: struct {
230 File string `json:"file"`
231 }{File: "https://cdn.example/dub.m3u8"},
232 })
233 default:
234 http.NotFound(w, r)
235 }
236 }))
237 defer megaplay.Close()
238
239 client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
240 if strings.HasPrefix(req.URL.String(), megaplay.URL) {
241 return http.DefaultTransport.RoundTrip(req)
242 }
243 return textResponse(req, http.StatusNotFound, ""), nil
244 })}
245 withAnipubTestClient(t, client)
246 originalMega := megaplayBaseURL
247 t.Cleanup(func() { megaplayBaseURL = originalMega })
248 megaplayBaseURL = megaplay.URL
249
250 streamURL, subtitle, err := resolveMegaplayStream("https://anipub.xyz/video/42/sub", "dub")
251 if err != nil {
252 t.Fatalf("resolveMegaplayStream: %v", err)
253 }
254 if streamURL != "https://cdn.example/dub.m3u8" {
255 t.Fatalf("unexpected stream %q", streamURL)
256 }
257 if subtitle != "" {
258 t.Fatalf("expected no subtitle for dub, got %q", subtitle)
259 }
260}
internal/providers/anipub/register.go added +13
@@ -0,0 +1,13 @@
1package anipub
2
3import "github.com/wraient/curd/internal/providers"
4
5func init() {
6 providers.Register(providers.Meta{
7 Name: "anipub",
8 Aliases: []string{"anipub.xyz"},
9 Referrer: "https://megaplay.buzz/",
10 }, func() providers.Provider {
11 return &Provider{}
12 })
13}
internal/providers/anipub/search.go added +128
@@ -0,0 +1,128 @@
1package anipub
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "strconv"
8 "strings"
9 "sync"
10
11 "github.com/wraient/curd/internal/providers"
12)
13
14func searchAnime(query, mode string) ([]providers.SelectionOption, error) {
15 query = strings.TrimSpace(query)
16 if query == "" {
17 return nil, fmt.Errorf("empty search query")
18 }
19 _ = mode
20
21 results, err := fetchSearchResults(query)
22 if err != nil {
23 return nil, err
24 }
25 if len(results) == 0 {
26 return nil, fmt.Errorf("no results for %q", query)
27 }
28
29 infos := fetchSearchInfos(results)
30 options := make([]providers.SelectionOption, 0, len(results))
31 for i, item := range results {
32 if item.ID <= 0 {
33 continue
34 }
35 info := infos[i]
36 label := formatSearchLabel(item, info)
37 extra := toSearchItem(item, info)
38 options = append(options, providers.SelectionOption{
39 Key: strconv.Itoa(item.ID),
40 Label: label,
41 Title: strings.TrimSpace(item.Name),
42 Thumbnail: thumbnailFromInfo(info, item.Image),
43 ExtraData: extra,
44 })
45 }
46 if len(options) == 0 {
47 return nil, fmt.Errorf("no results for %q", query)
48 }
49 return options, nil
50}
51
52func fetchSearchResults(query string) ([]searchResult, error) {
53 raw, err := fetchString(searchURL(query), baseURL+"/")
54 if err != nil {
55 return nil, err
56 }
57 return decodeSearchResults([]byte(raw))
58}
59
60func decodeSearchResults(raw []byte) ([]searchResult, error) {
61 raw = bytes.TrimSpace(raw)
62 if len(raw) == 0 {
63 return nil, fmt.Errorf("empty search response")
64 }
65
66 var notFound struct {
67 Found bool `json:"found"`
68 }
69 if err := json.Unmarshal(raw, &notFound); err == nil && strings.Contains(string(raw), `"found"`) && !notFound.Found {
70 return nil, nil
71 }
72
73 var results []searchResult
74 if err := json.Unmarshal(raw, &results); err == nil {
75 return results, nil
76 }
77
78 var single searchResult
79 if err := json.Unmarshal(raw, &single); err == nil && single.ID > 0 {
80 return []searchResult{single}, nil
81 }
82
83 return nil, fmt.Errorf("parse anipub search response")
84}
85
86func fetchSearchInfos(results []searchResult) []infoResponse {
87 infos := make([]infoResponse, len(results))
88 var wg sync.WaitGroup
89 wg.Add(len(results))
90 for i, item := range results {
91 i, item := i, item
92 go func() {
93 defer wg.Done()
94 if item.ID <= 0 {
95 return
96 }
97 var info infoResponse
98 if err := fetchJSON(infoURL(strconv.Itoa(item.ID)), baseURL+"/", &info); err == nil {
99 infos[i] = info
100 }
101 }()
102 }
103 wg.Wait()
104 return infos
105}
106
107func formatSearchLabel(item searchResult, info infoResponse) string {
108 parts := []string{strings.TrimSpace(item.Name)}
109 if info.EpCount > 0 {
110 parts = append(parts, fmt.Sprintf("%d eps", info.EpCount))
111 }
112 return strings.Join(parts, " · ")
113}
114
115func toSearchItem(item searchResult, info infoResponse) SearchItem {
116 malID, _ := strconv.Atoi(strings.TrimSpace(info.MALID))
117 episodes := info.EpCount
118 if episodes <= 0 && info.ID > 0 {
119 episodes = info.EpCount
120 }
121 return SearchItem{
122 ID: item.ID,
123 MalID: malID,
124 Name: strings.TrimSpace(item.Name),
125 Finder: strings.TrimSpace(item.Finder),
126 Episodes: episodes,
127 }
128}
internal/providers/anipub/streams.go added +41
@@ -0,0 +1,41 @@
1package anipub
2
3import (
4 "fmt"
5
6 "github.com/wraient/curd/internal/providers"
7)
8
9func getEpisodeStreamsForMode(showID string, config providers.PlaybackConfig, epNo int) ([]string, map[string]providers.StreamPlaybackHint, error) {
10 showID, err := parseShowID(showID)
11 if err != nil {
12 return nil, nil, err
13 }
14 if epNo <= 0 {
15 return nil, nil, fmt.Errorf("invalid episode number %d", epNo)
16 }
17
18 var details detailsResponse
19 if err := fetchJSON(detailsURL(showID), baseURL+"/", &details); err != nil {
20 return nil, nil, err
21 }
22
23 videoLink, err := episodeVideoLink(details, epNo)
24 if err != nil {
25 return nil, nil, err
26 }
27
28 mode := providers.NormalizeTranslationType(config.SubOrDub)
29 streamURL, subtitle, err := resolveMegaplayStream(videoLink, mode)
30 if err != nil {
31 return nil, nil, err
32 }
33
34 hints := map[string]providers.StreamPlaybackHint{
35 streamURL: {
36 Referrer: megaplayBaseURL + "/",
37 Subtitle: subtitle,
38 },
39 }
40 return []string{streamURL}, hints, nil
41}
internal/providers/anipub/types.go added +51
@@ -0,0 +1,51 @@
1package anipub
2
3// SearchItem is stored in SelectionOption.ExtraData for mapping hints.
4type SearchItem struct {
5 ID int
6 MalID int
7 Name string
8 Finder string
9 Episodes int
10}
11
12type searchResult struct {
13 Name string `json:"Name"`
14 ID int `json:"Id"`
15 Image string `json:"Image"`
16 Finder string `json:"finder"`
17}
18
19type infoResponse struct {
20 ID int `json:"_id"`
21 Name string `json:"Name"`
22 MALID string `json:"MALID"`
23 EpCount int `json:"epCount"`
24 Image string `json:"ImagePath"`
25 Cover string `json:"Cover"`
26}
27
28type detailsResponse struct {
29 Local localDetails `json:"local"`
30}
31
32type localDetails struct {
33 Link string `json:"link"`
34 Ep []episodeLink `json:"ep"`
35}
36
37type episodeLink struct {
38 Link string `json:"link"`
39}
40
41type megaplaySourcesResponse struct {
42 Sources struct {
43 File string `json:"file"`
44 } `json:"sources"`
45 Tracks []struct {
46 File string `json:"file"`
47 Label string `json:"label"`
48 Kind string `json:"kind"`
49 Default bool `json:"default"`
50 } `json:"tracks"`
51}
internal/providers/anipub_long_live_test.go added +81
@@ -0,0 +1,81 @@
1package providers_test
2
3import (
4 "net/http"
5 "os"
6 "strconv"
7 "testing"
8 "time"
9
10 "github.com/wraient/curd/internal/curdhost"
11)
12
13// Run AniPub edge cases in isolation with generous pacing to avoid rate limits:
14//
15// CURD_LIVE_ANIPUB=1 go test ./internal/providers -run TestLiveAnipubLong -v -timeout 60m
16//
17// Optional: CURD_LIVE_ANIPUB_DELAY_MS=2500 (default 2000)
18func initLiveAnipub(tb testing.TB) {
19 tb.Helper()
20 if os.Getenv("CURD_LIVE_ANIPUB") == "" {
21 tb.Skip("set CURD_LIVE_ANIPUB=1 to run isolated long AniPub live tests")
22 }
23 if curdhost.HTTPClient == nil {
24 curdhost.HTTPClient = func() *http.Client { return http.DefaultClient }
25 }
26}
27
28func anipubLiveDelay() time.Duration {
29 ms := 2000
30 if raw := os.Getenv("CURD_LIVE_ANIPUB_DELAY_MS"); raw != "" {
31 if parsed, err := strconv.Atoi(raw); err == nil && parsed > 0 {
32 ms = parsed
33 }
34 }
35 return time.Duration(ms) * time.Millisecond
36}
37
38func TestLiveAnipubLong(t *testing.T) {
39 initLiveAnipub(t)
40
41 delay := anipubLiveDelay()
42 t.Logf("anipub long run: %d cases, %v delay between requests", len(edgeAnimeCases), delay)
43
44 var anipub edgeProvider
45 for _, p := range edgeProviders() {
46 if p.name == "anipub" {
47 anipub = p
48 break
49 }
50 }
51 if anipub.name == "" {
52 t.Fatal("anipub provider not found")
53 }
54
55 type counts struct{ search, match, episodes, stream, total int }
56 var c counts
57
58 for i, tc := range edgeAnimeCases {
59 res := runEdgeCase(anipub, tc)
60 c.total++
61 if res.searchOK {
62 c.search++
63 }
64 if res.matchOK {
65 c.match++
66 }
67 if res.episodesOK {
68 c.episodes++
69 }
70 if res.streamOK {
71 c.stream++
72 }
73 t.Logf("[%d/%d] %s", i+1, len(edgeAnimeCases), edgeStatusLine(res))
74 if i < len(edgeAnimeCases)-1 {
75 time.Sleep(delay)
76 }
77 }
78
79 t.Logf("anipub long: search %d/%d match %d/%d episodes %d/%d stream %d/%d",
80 c.search, c.total, c.match, c.total, c.episodes, c.total, c.stream, c.total)
81}
internal/providers/benchmark_test.go added +213
@@ -0,0 +1,213 @@
1package providers_test
2
3import (
4 "net/http"
5 "os"
6 "sort"
7 "testing"
8 "time"
9
10 "github.com/wraient/curd/internal/curdhost"
11 _ "github.com/wraient/curd/internal/loadproviders"
12 "github.com/wraient/curd/internal/providers"
13 "github.com/wraient/curd/internal/providers/anipub"
14 "github.com/wraient/curd/internal/providers/anineko"
15 "github.com/wraient/curd/internal/providers/senshi"
16)
17
18const liveBenchQuery = "frieren"
19
20var liveBenchCases = []struct {
21 name string
22 provider string
23 showID string
24 epNo int
25 mode string
26 searchFn func(string, string) ([]providers.SelectionOption, error)
27 episodes func(string, string) ([]string, error)
28 streams func(string, providers.PlaybackConfig, int) ([]string, map[string]providers.StreamPlaybackHint, error)
29}{
30 {
31 name: "senshi",
32 provider: "senshi",
33 showID: "52991",
34 epNo: 1,
35 mode: "sub",
36 searchFn: func(query, mode string) ([]providers.SelectionOption, error) {
37 return senshiSearch(query, mode)
38 },
39 episodes: senshiEpisodes,
40 streams: senshiStreams,
41 },
42 {
43 name: "anipub",
44 provider: "anipub",
45 showID: "2454",
46 epNo: 1,
47 mode: "sub",
48 searchFn: anipubSearch,
49 episodes: anipubEpisodes,
50 streams: anipubStreams,
51 },
52 {
53 name: "anineko",
54 provider: "anineko",
55 showID: "",
56 epNo: 1,
57 mode: "sub",
58 searchFn: aninekoSearch,
59 episodes: nil,
60 streams: nil,
61 },
62}
63
64func senshiSearch(query, mode string) ([]providers.SelectionOption, error) {
65 p := &senshi.Provider{}
66 return p.SearchAnime(query, mode)
67}
68
69func senshiEpisodes(showID, mode string) ([]string, error) {
70 p := &senshi.Provider{}
71 return p.EpisodesList(showID, mode)
72}
73
74func senshiStreams(showID string, config providers.PlaybackConfig, epNo int) ([]string, map[string]providers.StreamPlaybackHint, error) {
75 p := &senshi.Provider{}
76 return p.GetEpisodeURLForModeWithHints(config, showID, epNo, config.SubOrDub)
77}
78
79func anipubSearch(query, mode string) ([]providers.SelectionOption, error) {
80 p := &anipub.Provider{}
81 return p.SearchAnime(query, mode)
82}
83
84func anipubEpisodes(showID, mode string) ([]string, error) {
85 p := &anipub.Provider{}
86 return p.EpisodesList(showID, mode)
87}
88
89func anipubStreams(showID string, config providers.PlaybackConfig, epNo int) ([]string, map[string]providers.StreamPlaybackHint, error) {
90 p := &anipub.Provider{}
91 return p.GetEpisodeURLForModeWithHints(config, showID, epNo, config.SubOrDub)
92}
93
94func aninekoSearch(query, mode string) ([]providers.SelectionOption, error) {
95 p := &anineko.Provider{}
96 return p.SearchAnime(query, mode)
97}
98
99func initLiveBench(tb testing.TB) {
100 tb.Helper()
101 if os.Getenv("CURD_LIVE_BENCH") == "" {
102 tb.Skip("set CURD_LIVE_BENCH=1 to run live benchmarks")
103 }
104 if curdhost.HTTPClient == nil {
105 curdhost.HTTPClient = func() *http.Client { return http.DefaultClient }
106 }
107}
108
109func BenchmarkProviderSearch(b *testing.B) {
110 initLiveBench(b)
111 for _, tc := range liveBenchCases {
112 if tc.searchFn == nil {
113 continue
114 }
115 b.Run(tc.name, func(b *testing.B) {
116 b.ResetTimer()
117 for i := 0; i < b.N; i++ {
118 if _, err := tc.searchFn(liveBenchQuery, tc.mode); err != nil {
119 b.Fatal(err)
120 }
121 }
122 })
123 }
124}
125
126func BenchmarkProviderEpisodeStream(b *testing.B) {
127 initLiveBench(b)
128 for _, tc := range liveBenchCases {
129 if tc.episodes == nil || tc.streams == nil {
130 continue
131 }
132 b.Run(tc.name, func(b *testing.B) {
133 b.ResetTimer()
134 for i := 0; i < b.N; i++ {
135 if _, err := tc.episodes(tc.showID, tc.mode); err != nil {
136 b.Fatal(err)
137 }
138 if _, _, err := tc.streams(tc.showID, providers.PlaybackConfig{SubOrDub: tc.mode}, tc.epNo); err != nil {
139 b.Fatal(err)
140 }
141 }
142 })
143 }
144}
145
146func TestLiveProviderFlowLatency(t *testing.T) {
147 initLiveBench(t)
148
149 type result struct {
150 name string
151 search time.Duration
152 flow time.Duration
153 }
154
155 results := make([]result, 0, len(liveBenchCases))
156 for _, tc := range liveBenchCases {
157 if tc.searchFn == nil || tc.episodes == nil || tc.streams == nil {
158 continue
159 }
160
161 searchStart := time.Now()
162 options, err := tc.searchFn(liveBenchQuery, tc.mode)
163 if err != nil {
164 t.Fatalf("%s search: %v", tc.name, err)
165 }
166 searchLatency := time.Since(searchStart)
167
168 showID := tc.showID
169 if showID == "" {
170 for _, option := range options {
171 if option.Key != "" {
172 showID = option.Key
173 break
174 }
175 }
176 }
177 if showID == "" {
178 t.Fatalf("%s: no show id for flow benchmark", tc.name)
179 }
180
181 flowStart := time.Now()
182 if _, err := tc.episodes(showID, tc.mode); err != nil {
183 t.Fatalf("%s episodes: %v", tc.name, err)
184 }
185 links, _, err := tc.streams(showID, providers.PlaybackConfig{SubOrDub: tc.mode}, tc.epNo)
186 if err != nil {
187 t.Fatalf("%s streams: %v", tc.name, err)
188 }
189 if len(links) == 0 {
190 t.Fatalf("%s: no stream links", tc.name)
191 }
192 flowLatency := time.Since(flowStart)
193
194 results = append(results, result{name: tc.name, search: searchLatency, flow: searchLatency + flowLatency})
195 t.Logf("%s search=%s full_flow=%s", tc.name, searchLatency, searchLatency+flowLatency)
196 }
197
198 if len(results) < 2 {
199 t.Skip("not enough providers with full flow support")
200 }
201
202 sort.Slice(results, func(i, j int) bool {
203 return results[i].flow < results[j].flow
204 })
205 fastest := results[0].name
206 t.Logf("fastest full flow: %s (%s)", fastest, results[0].flow)
207
208 for _, item := range results[1:] {
209 if item.flow > results[0].flow*3 {
210 t.Logf("warning: %s full flow is much slower than %s (%s vs %s)", item.name, fastest, item.flow, results[0].flow)
211 }
212 }
213}
internal/providers/movie_probe_live_test.go added +146
@@ -0,0 +1,146 @@
1package providers_test
2
3import (
4 "fmt"
5 "net/http"
6 "os"
7 "testing"
8 "time"
9
10 "github.com/wraient/curd/internal/curdhost"
11 _ "github.com/wraient/curd/internal/loadproviders"
12 "github.com/wraient/curd/internal/providers"
13)
14
15// Run with:
16//
17// CURD_LIVE_MOVIES=1 go test ./internal/providers -run TestLiveProviderMovies -v -timeout 30m
18func initLiveMovies(tb testing.TB) {
19 tb.Helper()
20 if os.Getenv("CURD_LIVE_MOVIES") == "" {
21 tb.Skip("set CURD_LIVE_MOVIES=1 to run live movie provider tests")
22 }
23 if curdhost.HTTPClient == nil {
24 curdhost.HTTPClient = func() *http.Client { return http.DefaultClient }
25 }
26}
27
28type movieCase struct {
29 name string
30 query string
31 wantInTitle string
32}
33
34var movieCases = []movieCase{
35 {name: "your_name", query: "your name", wantInTitle: "your name"},
36 {name: "your_name_romaji", query: "kimi no na wa", wantInTitle: "your name"},
37 {name: "suzume", query: "suzume", wantInTitle: "suzume"},
38 {name: "spirited_away", query: "spirited away", wantInTitle: "spirited"},
39 {name: "silent_voice", query: "a silent voice", wantInTitle: "silent"},
40 {name: "weathering", query: "weathering with you", wantInTitle: "weather"},
41 {name: "mugen_train", query: "demon slayer mugen train", wantInTitle: "mugen"},
42 {name: "jjk_0", query: "jujutsu kaisen 0", wantInTitle: "jujutsu kaisen 0"},
43 {name: "film_red", query: "one piece film red", wantInTitle: "red"},
44 {name: "howl", query: "howl's moving castle", wantInTitle: "howl"},
45 {name: "grave_fireflies", query: "grave of the fireflies", wantInTitle: "grave"},
46 {name: "akira", query: "akira", wantInTitle: "akira"},
47 {name: "perfect_blue", query: "perfect blue", wantInTitle: "perfect"},
48 {name: "promare", query: "promare", wantInTitle: "promare"},
49 {name: "look_back", query: "look back", wantInTitle: "look back"},
50 {name: "reze_arc", query: "chainsaw man reze arc", wantInTitle: "chainsaw"},
51 {name: "paprika", query: "paprika", wantInTitle: "paprika"},
52 {name: "girl_who_leapt", query: "girl who leapt through time", wantInTitle: "leapt"},
53}
54
55type movieResult struct {
56 provider, caseName, query string
57 searchOK, matchOK, epListOK, streamOK bool
58 epCount int
59 pickedTitle, pickedKey string
60 searchErr, episodesErr, streamErr string
61}
62
63func runMovieCase(p edgeProvider, tc movieCase) movieResult {
64 res := movieResult{provider: p.name, caseName: tc.name, query: tc.query}
65 opts, err := p.search(tc.query, "sub")
66 if err != nil {
67 res.searchErr = err.Error()
68 return res
69 }
70 if len(opts) == 0 {
71 res.searchErr = "no results"
72 return res
73 }
74 res.searchOK = true
75 picked, matched := pickEdgeResult(opts, tc.wantInTitle)
76 res.matchOK = matched
77 res.pickedTitle = picked.Title
78 if res.pickedTitle == "" {
79 res.pickedTitle = picked.Label
80 }
81 res.pickedKey = picked.Key
82 if picked.Key == "" {
83 return res
84 }
85 eps, err := p.episodes(picked.Key, "sub")
86 if err != nil {
87 res.episodesErr = err.Error()
88 } else if len(eps) == 0 {
89 res.episodesErr = "no episodes"
90 } else {
91 res.epListOK = true
92 res.epCount = len(eps)
93 }
94 links, _, err := p.streams(picked.Key, providers.PlaybackConfig{SubOrDub: "sub"}, 1)
95 if err != nil {
96 res.streamErr = err.Error()
97 } else if len(links) == 0 {
98 res.streamErr = "no stream url"
99 } else {
100 res.streamOK = true
101 }
102 return res
103}
104
105func TestLiveProviderMovies(t *testing.T) {
106 initLiveMovies(t)
107
108 type counts struct{ search, match, epList, stream, total int }
109 byProvider := map[string]counts{}
110
111 for _, p := range edgeProviders() {
112 for _, tc := range movieCases {
113 res := runMovieCase(p, tc)
114 c := byProvider[res.provider]
115 c.total++
116 if res.searchOK {
117 c.search++
118 }
119 if res.matchOK {
120 c.match++
121 }
122 if res.epListOK {
123 c.epList++
124 }
125 if res.streamOK {
126 c.stream++
127 }
128 byProvider[res.provider] = c
129
130 epNote := "no-list"
131 if res.epListOK {
132 epNote = fmt.Sprintf("%deps", res.epCount)
133 }
134 t.Logf("[%s] %-20s %-30s search=%s match=%s eps=%s stream=%s picked=%q",
135 res.provider, res.caseName, res.query,
136 boolMark(res.searchOK), boolMark(res.matchOK), epNote, boolMark(res.streamOK),
137 truncate(res.pickedTitle, 40))
138 time.Sleep(200 * time.Millisecond)
139 }
140 }
141
142 for name, c := range byProvider {
143 t.Logf("%s movies: search %d/%d match %d/%d episode_list %d/%d stream %d/%d",
144 name, c.search, c.total, c.match, c.total, c.epList, c.total, c.stream, c.total)
145 }
146}
internal/providers/provider_edge_live_test.go added +393
@@ -0,0 +1,393 @@
1package providers_test
2
3import (
4 "fmt"
5 "net/http"
6 "os"
7 "sort"
8 "strings"
9 "testing"
10 "time"
11
12 "github.com/wraient/curd/internal/curdhost"
13 _ "github.com/wraient/curd/internal/loadproviders"
14 "github.com/wraient/curd/internal/providers"
15 "github.com/wraient/curd/internal/providers/anineko"
16 "github.com/wraient/curd/internal/providers/anipub"
17 "github.com/wraient/curd/internal/providers/senshi"
18)
19
20// Run with:
21//
22// CURD_LIVE_EDGE=1 go test ./internal/providers -run TestLiveProviderEdgeCases -v -timeout 45m
23func initLiveEdge(tb testing.TB) {
24 tb.Helper()
25 if os.Getenv("CURD_LIVE_EDGE") == "" {
26 tb.Skip("set CURD_LIVE_EDGE=1 to run live provider edge-case tests")
27 }
28 if curdhost.HTTPClient == nil {
29 curdhost.HTTPClient = func() *http.Client { return http.DefaultClient }
30 }
31}
32
33type edgeAnimeCase struct {
34 name string
35 query string
36 wantInTitle string
37}
38
39var edgeAnimeCases = []edgeAnimeCase{
40 // punctuation & symbols (how users actually type)
41 {name: "colon_apostrophe", query: "frieren beyond journey's end", wantInTitle: "frieren"},
42 {name: "colon_short", query: "re:zero", wantInTitle: "re:zero"},
43 {name: "colon_spaced", query: "re zero", wantInTitle: "re:zero"},
44 {name: "semicolon", query: "steins;gate", wantInTitle: "stein"},
45 {name: "slash", query: "fate/stay night", wantInTitle: "fate"},
46 {name: "bang", query: "k-on!", wantInTitle: "k-on"},
47 {name: "double_bang", query: "love live superstar", wantInTitle: "love live"},
48
49 // apostrophe variants
50 {name: "apostrophe_full", query: "JoJo's Bizarre Adventure", wantInTitle: "jojo"},
51 {name: "apostrophe_stripped", query: "jojos bizarre adventure", wantInTitle: "jojo"},
52
53 // romaji vs english
54 {name: "romaji_snk", query: "shingeki no kyojin", wantInTitle: "attack on titan"},
55 {name: "english_aot", query: "attack on titan", wantInTitle: "attack on titan"},
56 {name: "romaji_mha", query: "boku no hero academia", wantInTitle: "hero academia"},
57 {name: "english_mha", query: "my hero academia", wantInTitle: "hero academia"},
58 {name: "romaji_frieren", query: "sousou no frieren", wantInTitle: "frieren"},
59
60 // short / numeric queries
61 {name: "numeric_86", query: "86", wantInTitle: "86"},
62 {name: "two_digit", query: "91 days", wantInTitle: "91 days"},
63 {name: "three_letters", query: "mha", wantInTitle: "hero"},
64
65 // x-in-title
66 {name: "x_hxh", query: "hunter x hunter", wantInTitle: "hunter"},
67 {name: "x_spy", query: "spy x family", wantInTitle: "spy"},
68
69 // long titles (truncated user search)
70 {name: "long_magirevo", query: "magical revolution reincarnated princess", wantInTitle: "magical revolution"},
71 {name: "long_slime", query: "that time i got reincarnated as a slime", wantInTitle: "slime"},
72 {name: "long_apothecary", query: "apothecary diaries", wantInTitle: "apothecary"},
73
74 // ambiguous / crowded results
75 {name: "ambiguous_monogatari", query: "monogatari", wantInTitle: "monogatari"},
76 {name: "ambiguous_fate", query: "fate", wantInTitle: "fate"},
77 {name: "ambiguous_gundam", query: "gundam", wantInTitle: "gundam"},
78
79 // season / cour noise
80 {name: "season_noise", query: "frieren season 2", wantInTitle: "frieren"},
81 {name: "cour_alias", query: "mushoku tensei jobless reincarnation", wantInTitle: "mushoku"},
82
83 // spinoffs & similar titles
84 {name: "spinoff_mini", query: "frieren marumaru mahou", wantInTitle: "frieren"},
85 {name: "long_runner", query: "one piece", wantInTitle: "one piece"},
86
87 // abbreviations & nicknames
88 {name: "abbr_sao", query: "sao", wantInTitle: "sword art"},
89 {name: "abbr_danmachi", query: "danmachi", wantInTitle: "danmachi"},
90 {name: "abbr_csm", query: "chainsaw man", wantInTitle: "chainsaw"},
91
92 // movies & one-shots
93 {name: "movie_your_name", query: "your name", wantInTitle: "your name"},
94 {name: "movie_suzume", query: "suzume", wantInTitle: "suzume"},
95
96 // recent popular
97 {name: "oshi_no_ko", query: "oshi no ko", wantInTitle: "oshi"},
98 {name: "bocchi", query: "bocchi the rock", wantInTitle: "bocchi"},
99 {name: "dungeon_meshi", query: "dungeon meshi", wantInTitle: "dungeon"},
100 {name: "delicious_in_dungeon", query: "delicious in dungeon", wantInTitle: "dungeon"},
101
102 // edge punctuation stripped
103 {name: "bleach_tybw", query: "bleach thousand year blood war", wantInTitle: "bleach"},
104 {name: "evangelion", query: "neon genesis evangelion", wantInTitle: "evangelion"},
105
106 // mild typo / spacing
107 {name: "demon_slayer", query: "demon slayer", wantInTitle: "demon"},
108 {name: "kimetsu", query: "kimetsu no yaiba", wantInTitle: "demon"},
109
110 // unicode-ish (user without diacritics)
111 {name: "witch_hat", query: "witch hat atelier", wantInTitle: "witch"},
112
113 // single word common
114 {name: "single_naruto", query: "naruto", wantInTitle: "naruto"},
115 {name: "single_bleach", query: "bleach", wantInTitle: "bleach"},
116}
117
118type edgeProvider struct {
119 name string
120 search func(string, string) ([]providers.SelectionOption, error)
121 episodes func(string, string) ([]string, error)
122 streams func(string, providers.PlaybackConfig, int) ([]string, map[string]providers.StreamPlaybackHint, error)
123}
124
125func edgeProviders() []edgeProvider {
126 return []edgeProvider{
127 {
128 name: "senshi",
129 search: func(q, mode string) ([]providers.SelectionOption, error) {
130 return (&senshi.Provider{}).SearchAnime(q, mode)
131 },
132 episodes: func(id, mode string) ([]string, error) {
133 return (&senshi.Provider{}).EpisodesList(id, mode)
134 },
135 streams: func(id string, cfg providers.PlaybackConfig, ep int) ([]string, map[string]providers.StreamPlaybackHint, error) {
136 return (&senshi.Provider{}).GetEpisodeURLForModeWithHints(cfg, id, ep, cfg.SubOrDub)
137 },
138 },
139 {
140 name: "anipub",
141 search: func(q, mode string) ([]providers.SelectionOption, error) {
142 return (&anipub.Provider{}).SearchAnime(q, mode)
143 },
144 episodes: func(id, mode string) ([]string, error) {
145 return (&anipub.Provider{}).EpisodesList(id, mode)
146 },
147 streams: func(id string, cfg providers.PlaybackConfig, ep int) ([]string, map[string]providers.StreamPlaybackHint, error) {
148 return (&anipub.Provider{}).GetEpisodeURLForModeWithHints(cfg, id, ep, cfg.SubOrDub)
149 },
150 },
151 {
152 name: "anineko",
153 search: func(q, mode string) ([]providers.SelectionOption, error) {
154 return (&anineko.Provider{}).SearchAnime(q, mode)
155 },
156 episodes: func(id, mode string) ([]string, error) {
157 return (&anineko.Provider{}).EpisodesList(id, mode)
158 },
159 streams: func(id string, cfg providers.PlaybackConfig, ep int) ([]string, map[string]providers.StreamPlaybackHint, error) {
160 return (&anineko.Provider{}).GetEpisodeURLForModeWithHints(cfg, id, ep, cfg.SubOrDub)
161 },
162 },
163 }
164}
165
166type edgeResult struct {
167 provider string
168 caseName string
169 query string
170 searchOK bool
171 matchOK bool
172 episodesOK bool
173 streamOK bool
174 searchErr string
175 episodesErr string
176 streamErr string
177 pickedTitle string
178 pickedKey string
179 epCount int
180 searchMs int64
181 flowMs int64
182}
183
184func pickEdgeResult(options []providers.SelectionOption, want string) (providers.SelectionOption, bool) {
185 want = strings.ToLower(strings.TrimSpace(want))
186 if want == "" && len(options) > 0 {
187 return options[0], true
188 }
189 for _, option := range options {
190 for _, candidate := range []string{option.Title, option.Label} {
191 if strings.Contains(strings.ToLower(candidate), want) {
192 return option, true
193 }
194 }
195 }
196 if len(options) > 0 {
197 return options[0], false
198 }
199 return providers.SelectionOption{}, false
200}
201
202func runEdgeCase(provider edgeProvider, tc edgeAnimeCase) edgeResult {
203 res := edgeResult{
204 provider: provider.name,
205 caseName: tc.name,
206 query: tc.query,
207 }
208
209 searchStart := time.Now()
210 options, err := provider.search(tc.query, "sub")
211 res.searchMs = time.Since(searchStart).Milliseconds()
212 if err != nil {
213 res.searchErr = err.Error()
214 return res
215 }
216 if len(options) == 0 {
217 res.searchErr = "no results"
218 return res
219 }
220 res.searchOK = true
221
222 picked, matched := pickEdgeResult(options, tc.wantInTitle)
223 res.pickedTitle = picked.Title
224 if res.pickedTitle == "" {
225 res.pickedTitle = picked.Label
226 }
227 res.pickedKey = picked.Key
228 res.matchOK = matched
229
230 if provider.episodes == nil || provider.streams == nil || picked.Key == "" {
231 return res
232 }
233
234 flowStart := time.Now()
235 eps, err := provider.episodes(picked.Key, "sub")
236 if err != nil {
237 res.episodesErr = err.Error()
238 res.flowMs = time.Since(flowStart).Milliseconds()
239 return res
240 }
241 if len(eps) == 0 {
242 res.episodesErr = "no episodes"
243 res.flowMs = time.Since(flowStart).Milliseconds()
244 return res
245 }
246 res.episodesOK = true
247 res.epCount = len(eps)
248
249 links, _, err := provider.streams(picked.Key, providers.PlaybackConfig{SubOrDub: "sub"}, 1)
250 res.flowMs = time.Since(flowStart).Milliseconds()
251 if err != nil {
252 res.streamErr = err.Error()
253 return res
254 }
255 if len(links) == 0 {
256 res.streamErr = "no stream url"
257 return res
258 }
259 res.streamOK = true
260 return res
261}
262
263func TestLiveProviderEdgeCases(t *testing.T) {
264 initLiveEdge(t)
265
266 providersList := edgeProviders()
267 results := make([]edgeResult, 0, len(edgeAnimeCases)*len(providersList))
268
269 for _, provider := range providersList {
270 for _, tc := range edgeAnimeCases {
271 res := runEdgeCase(provider, tc)
272 results = append(results, res)
273 t.Logf("%s", edgeStatusLine(res))
274 time.Sleep(150 * time.Millisecond)
275 }
276 }
277
278 sort.Slice(results, func(i, j int) bool {
279 if results[i].provider != results[j].provider {
280 return results[i].provider < results[j].provider
281 }
282 return results[i].caseName < results[j].caseName
283 })
284
285 t.Log(edgeSummary(results))
286
287 type counts struct{ search, match, episodes, stream, total int }
288 byProvider := map[string]counts{}
289 for _, res := range results {
290 c := byProvider[res.provider]
291 c.total++
292 if res.searchOK {
293 c.search++
294 }
295 if res.matchOK {
296 c.match++
297 }
298 if res.episodesOK {
299 c.episodes++
300 }
301 if res.streamOK {
302 c.stream++
303 }
304 byProvider[res.provider] = c
305 }
306
307 for name, c := range byProvider {
308 t.Logf("%s: search %d/%d match %d/%d episodes %d/%d stream %d/%d",
309 name, c.search, c.total, c.match, c.total, c.episodes, c.total, c.stream, c.total)
310 }
311
312 failures := make([]string, 0)
313 for _, res := range results {
314 if !res.searchOK {
315 failures = append(failures, fmt.Sprintf("%s/%s search failed: %s", res.provider, res.caseName, res.searchErr))
316 continue
317 }
318 if !res.matchOK {
319 failures = append(failures, fmt.Sprintf("%s/%s weak match: picked %q for query %q", res.provider, res.caseName, res.pickedTitle, res.query))
320 }
321 if res.searchOK && !res.streamOK {
322 failures = append(failures, fmt.Sprintf("%s/%s stream failed: episodes_err=%s stream_err=%s", res.provider, res.caseName, res.episodesErr, res.streamErr))
323 }
324 }
325
326 critical := []string{"english_aot", "single_naruto", "demon_slayer", "dungeon_meshi", "romaji_frieren"}
327 for _, provider := range []string{"senshi", "anineko"} {
328 for _, caseName := range critical {
329 for _, res := range results {
330 if res.provider == provider && res.caseName == caseName {
331 if !res.streamOK {
332 t.Errorf("critical case %s/%s must stream: search=%v episodes=%v stream_err=%s", provider, caseName, res.searchOK, res.episodesOK, res.streamErr)
333 }
334 break
335 }
336 }
337 }
338 }
339
340 if len(failures) > 0 {
341 t.Logf("%d edge-case issues logged (see above)", len(failures))
342 }
343}
344
345func edgeStatusLine(res edgeResult) string {
346 match := "ok"
347 if res.searchOK && !res.matchOK {
348 match = "weak"
349 }
350 if !res.searchOK {
351 match = "fail"
352 }
353 stream := "-"
354 if res.streamOK {
355 stream = "ok"
356 } else if res.searchOK {
357 stream = "fail"
358 }
359 return fmt.Sprintf("[%s] %-22s %-28s search=%s match=%s eps=%v stream=%s (%dms+%dms) picked=%q",
360 res.provider, res.caseName, res.query,
361 boolMark(res.searchOK), match, res.episodesOK, stream,
362 res.searchMs, res.flowMs, truncate(res.pickedTitle, 48))
363}
364
365func edgeSummary(results []edgeResult) string {
366 var b strings.Builder
367 b.WriteString("\n=== provider edge-case summary ===\n")
368 current := ""
369 for _, res := range results {
370 if res.provider != current {
371 current = res.provider
372 b.WriteString("\n-- " + current + " --\n")
373 }
374 b.WriteString(edgeStatusLine(res))
375 b.WriteByte('\n')
376 }
377 return b.String()
378}
379
380func boolMark(ok bool) string {
381 if ok {
382 return "ok"
383 }
384 return "FAIL"
385}
386
387func truncate(s string, max int) string {
388 s = strings.TrimSpace(s)
389 if len(s) <= max {
390 return s
391 }
392 return s[:max-3] + "..."
393}
internal/providers/senshi/benchmark_test.go added +85
@@ -0,0 +1,85 @@
1package senshi
2
3import (
4 "net/http"
5 "os"
6 "testing"
7 "time"
8
9 "github.com/wraient/curd/internal/curdhost"
10 "github.com/wraient/curd/internal/providers"
11)
12
13// Benchmark live senshi vs anineko APIs. Run with:
14//
15// CURD_LIVE_BENCH=1 go test ./internal/providers/senshi -run '^$' -bench Benchmark -benchtime=3x
16func BenchmarkSenshiSearch(b *testing.B) {
17 if os.Getenv("CURD_LIVE_BENCH") == "" {
18 b.Skip("set CURD_LIVE_BENCH=1 to run live benchmarks")
19 }
20 if curdhost.HTTPClient == nil {
21 curdhost.HTTPClient = func() *http.Client { return http.DefaultClient }
22 }
23 b.ResetTimer()
24 for i := 0; i < b.N; i++ {
25 if _, err := searchAnime("frieren", "sub"); err != nil {
26 b.Fatal(err)
27 }
28 }
29}
30
31func BenchmarkSenshiEpisodeStream(b *testing.B) {
32 if os.Getenv("CURD_LIVE_BENCH") == "" {
33 b.Skip("set CURD_LIVE_BENCH=1 to run live benchmarks")
34 }
35 if curdhost.HTTPClient == nil {
36 curdhost.HTTPClient = func() *http.Client { return http.DefaultClient }
37 }
38 const malID = "52991"
39 b.ResetTimer()
40 for i := 0; i < b.N; i++ {
41 if _, err := episodesList(malID, "sub"); err != nil {
42 b.Fatal(err)
43 }
44 if _, _, err := getEpisodeStreamsForMode(malID, providers.PlaybackConfig{SubOrDub: "sub"}, 1); err != nil {
45 b.Fatal(err)
46 }
47 }
48}
49
50func TestLiveBenchmarkSenshiFasterThanAninekoSearch(t *testing.T) {
51 if os.Getenv("CURD_LIVE_BENCH") == "" {
52 t.Skip("set CURD_LIVE_BENCH=1 to run live benchmarks")
53 }
54 if curdhost.HTTPClient == nil {
55 curdhost.HTTPClient = func() *http.Client { return http.DefaultClient }
56 }
57
58 senshiStart := time.Now()
59 if _, err := searchAnime("frieren", "sub"); err != nil {
60 t.Fatalf("senshi search: %v", err)
61 }
62 senshiSearch := time.Since(senshiStart)
63
64 aninekoStart := time.Now()
65 req, err := http.NewRequest(http.MethodGet, "https://anineko.to/ajax/search?q=frieren", nil)
66 if err != nil {
67 t.Fatal(err)
68 }
69 req.Header.Set("User-Agent", userAgent)
70 req.Header.Set("Referer", "https://anineko.to/")
71 resp, err := curdhost.HTTPClient().Do(req)
72 if err != nil {
73 t.Fatal(err)
74 }
75 resp.Body.Close()
76 if !curdhost.HTTPStatusOK(resp.StatusCode) {
77 t.Fatalf("anineko search status %d", resp.StatusCode)
78 }
79 aninekoSearch := time.Since(aninekoStart)
80
81 t.Logf("search latency senshi=%s anineko=%s", senshiSearch, aninekoSearch)
82 if senshiSearch > aninekoSearch*2 {
83 t.Fatalf("expected senshi search to be competitive, senshi=%s anineko=%s", senshiSearch, aninekoSearch)
84 }
85}
internal/providers/senshi/client.go added +89
@@ -0,0 +1,89 @@
1package senshi
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "strings"
10
11 "github.com/wraient/curd/internal/curdhost"
12)
13
14const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
15
16var baseURL = "https://senshi.live"
17
18func newRequest(method, rawURL string) (*http.Request, error) {
19 req, err := http.NewRequest(method, rawURL, nil)
20 if err != nil {
21 return nil, err
22 }
23 req.Header.Set("User-Agent", userAgent)
24 req.Header.Set("Referer", baseURL+"/")
25 return req, nil
26}
27
28func fetchJSON(method, rawURL string, payload any, dest any) error {
29 var body io.Reader
30 if payload != nil {
31 encoded, err := json.Marshal(payload)
32 if err != nil {
33 return err
34 }
35 body = bytes.NewReader(encoded)
36 }
37
38 req, err := http.NewRequest(method, rawURL, body)
39 if err != nil {
40 return err
41 }
42 req.Header.Set("User-Agent", userAgent)
43 req.Header.Set("Referer", baseURL+"/")
44 if payload != nil {
45 req.Header.Set("Content-Type", "application/json")
46 }
47
48 resp, err := curdhost.HTTPClient().Do(req)
49 if err != nil {
50 return err
51 }
52 defer resp.Body.Close()
53
54 raw, err := io.ReadAll(resp.Body)
55 if err != nil {
56 return err
57 }
58 if !curdhost.HTTPStatusOK(resp.StatusCode) {
59 return curdhost.HTTPStatusError("senshi request", resp.StatusCode, raw)
60 }
61 if dest == nil {
62 return nil
63 }
64 if err := json.Unmarshal(raw, dest); err != nil {
65 return fmt.Errorf("parse senshi response: %w", err)
66 }
67 return 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 path = "/" + path
80 }
81 return baseURL + path
82}
83
84func posterURL(malID int) string {
85 if malID <= 0 {
86 return ""
87 }
88 return fmt.Sprintf("%s/posters/%d.webp", baseURL, malID)
89}
internal/providers/senshi/episodes.go added +60
@@ -0,0 +1,60 @@
1package senshi
2
3import (
4 "fmt"
5 "net/http"
6 "sort"
7 "strconv"
8 "strings"
9)
10
11func episodesList(showID, mode string) ([]string, error) {
12 malID, err := parseMalID(showID)
13 if err != nil {
14 return nil, err
15 }
16 _ = mode
17
18 var episodes []episodeItem
19 if err := fetchJSON(http.MethodGet, fmt.Sprintf("%s/episodes/%d", baseURL, malID), nil, &episodes); err != nil {
20 return nil, err
21 }
22 if len(episodes) == 0 {
23 return nil, fmt.Errorf("no episodes found for mal id %d", malID)
24 }
25
26 seen := map[int]struct{}{}
27 for _, ep := range episodes {
28 epNo := ep.EpID
29 if epNo <= 0 {
30 epNo = ep.ID
31 }
32 if epNo > 0 {
33 seen[epNo] = struct{}{}
34 }
35 }
36
37 nums := make([]int, 0, len(seen))
38 for epNo := range seen {
39 nums = append(nums, epNo)
40 }
41 sort.Ints(nums)
42
43 result := make([]string, 0, len(nums))
44 for _, epNo := range nums {
45 result = append(result, strconv.Itoa(epNo))
46 }
47 return result, nil
48}
49
50func parseMalID(showID string) (int, error) {
51 showID = strings.TrimSpace(showID)
52 if showID == "" {
53 return 0, fmt.Errorf("empty show id")
54 }
55 malID, err := strconv.Atoi(showID)
56 if err != nil || malID <= 0 {
57 return 0, fmt.Errorf("invalid senshi mal id %q", showID)
58 }
59 return malID, nil
60}
internal/providers/senshi/provider.go added +34
@@ -0,0 +1,34 @@
1package senshi
2
3import "github.com/wraient/curd/internal/providers"
4
5// Provider implements senshi.live catalog search and direct HLS stream resolution.
6type Provider struct{}
7
8func (p *Provider) Name() string {
9 return "senshi"
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/senshi/provider_test.go added +142
@@ -0,0 +1,142 @@
1package senshi
2
3import (
4 "encoding/json"
5 "io"
6 "net/http"
7 "net/http/httptest"
8 "strings"
9 "testing"
10
11 "github.com/wraient/curd/internal/curdhost"
12 "github.com/wraient/curd/internal/providers"
13)
14
15type roundTripFunc func(*http.Request) (*http.Response, error)
16
17func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
18 return f(req)
19}
20
21func withSenshiTestClient(t *testing.T, client *http.Client) {
22 t.Helper()
23 previous := curdhost.HTTPClient
24 t.Cleanup(func() {
25 curdhost.HTTPClient = previous
26 })
27 curdhost.HTTPClient = func() *http.Client { return client }
28}
29
30func jsonResponse(req *http.Request, statusCode int, payload any) *http.Response {
31 body, _ := json.Marshal(payload)
32 resp := &http.Response{
33 StatusCode: statusCode,
34 Header: make(http.Header),
35 Body: io.NopCloser(strings.NewReader(string(body))),
36 Request: req,
37 }
38 resp.Header.Set("Content-Type", "application/json")
39 return resp
40}
41
42func TestSearchAnimeParsesResults(t *testing.T) {
43 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
44 if r.URL.Path != "/anime/filter" || r.Method != http.MethodPost {
45 http.NotFound(w, r)
46 return
47 }
48 _ = json.NewEncoder(w).Encode(filterResponse{
49 Data: []animeItem{{
50 ID: 52991,
51 PublicID: "4medy",
52 Title: "Sousou no Frieren",
53 TitleEnglish: "Frieren: Beyond Journey's End",
54 Type: "TV",
55 AniEpisodes: "28",
56 AniYear: 2023,
57 }},
58 Total: 1,
59 })
60 }))
61 defer server.Close()
62
63 withSenshiTestClient(t, server.Client())
64 originalBase := baseURL
65 t.Cleanup(func() { baseURL = originalBase })
66 baseURL = server.URL
67
68 options, err := searchAnime("frieren", "sub")
69 if err != nil {
70 t.Fatalf("searchAnime: %v", err)
71 }
72 if len(options) != 1 {
73 t.Fatalf("expected 1 option, got %d", len(options))
74 }
75 if options[0].Key != "52991" {
76 t.Fatalf("unexpected key %q", options[0].Key)
77 }
78 if !strings.Contains(options[0].Thumbnail, "/posters/52991.webp") {
79 t.Fatalf("unexpected thumbnail %q", options[0].Thumbnail)
80 }
81 item, ok := options[0].ExtraData.(SearchItem)
82 if !ok || item.Episodes != 28 {
83 t.Fatalf("unexpected extra data %+v", options[0].ExtraData)
84 }
85}
86
87func TestEpisodesListParsesEpisodeIDs(t *testing.T) {
88 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
89 if r.URL.Path != "/episodes/52991" {
90 http.NotFound(w, r)
91 return
92 }
93 _ = json.NewEncoder(w).Encode([]episodeItem{
94 {ID: 1, EpID: 1, MalID: 52991},
95 {ID: 3, EpID: 3, MalID: 52991},
96 })
97 }))
98 defer server.Close()
99
100 withSenshiTestClient(t, server.Client())
101 originalBase := baseURL
102 t.Cleanup(func() { baseURL = originalBase })
103 baseURL = server.URL
104
105 episodes, err := episodesList("52991", "sub")
106 if err != nil {
107 t.Fatalf("episodesList: %v", err)
108 }
109 if len(episodes) != 2 || episodes[0] != "1" || episodes[1] != "3" {
110 t.Fatalf("unexpected episodes %#v", episodes)
111 }
112}
113
114func TestGetEpisodeStreamsForModeSelectsHardSub(t *testing.T) {
115 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
116 if r.URL.Path != "/episode-embeds/52991/1" {
117 http.NotFound(w, r)
118 return
119 }
120 _ = json.NewEncoder(w).Encode([]embedItem{
121 {URL: "https://cdn.example/sub.m3u8", Status: "HardSub"},
122 {URL: "https://cdn.example/dub.m3u8", Status: "Dub"},
123 })
124 }))
125 defer server.Close()
126
127 withSenshiTestClient(t, server.Client())
128 originalBase := baseURL
129 t.Cleanup(func() { baseURL = originalBase })
130 baseURL = server.URL
131
132 links, hints, err := getEpisodeStreamsForMode("52991", providers.PlaybackConfig{SubOrDub: "sub"}, 1)
133 if err != nil {
134 t.Fatalf("getEpisodeStreamsForMode: %v", err)
135 }
136 if len(links) != 1 || links[0] != "https://cdn.example/sub.m3u8" {
137 t.Fatalf("unexpected links %#v", links)
138 }
139 if hints[links[0]].Referrer != baseURL+"/" {
140 t.Fatalf("unexpected referrer %q", hints[links[0]].Referrer)
141 }
142}
internal/providers/senshi/register.go added +13
@@ -0,0 +1,13 @@
1package senshi
2
3import "github.com/wraient/curd/internal/providers"
4
5func init() {
6 providers.Register(providers.Meta{
7 Name: "senshi",
8 Aliases: []string{"senshi.live", "senshi project"},
9 Referrer: "https://senshi.live/",
10 }, func() providers.Provider {
11 return &Provider{}
12 })
13}
internal/providers/senshi/search.go added +99
@@ -0,0 +1,99 @@
1package senshi
2
3import (
4 "fmt"
5 "net/http"
6 "strconv"
7 "strings"
8
9 "github.com/wraient/curd/internal/providers"
10)
11
12func searchAnime(query, mode string) ([]providers.SelectionOption, error) {
13 query = strings.TrimSpace(query)
14 if query == "" {
15 return nil, fmt.Errorf("empty search query")
16 }
17 _ = mode
18
19 var payload filterResponse
20 err := fetchJSON(http.MethodPost, baseURL+"/anime/filter", map[string]any{
21 "searchTerm": query,
22 "page": 1,
23 "limit": 25,
24 }, &payload)
25 if err != nil {
26 return nil, err
27 }
28 if len(payload.Data) == 0 {
29 return nil, fmt.Errorf("no results for %q", query)
30 }
31
32 options := make([]providers.SelectionOption, 0, len(payload.Data))
33 for _, item := range payload.Data {
34 malID := item.ID
35 if malID <= 0 {
36 continue
37 }
38 title := strings.TrimSpace(item.TitleEnglish)
39 if title == "" {
40 title = strings.TrimSpace(item.Title)
41 }
42 label := formatSearchLabel(item)
43 options = append(options, providers.SelectionOption{
44 Key: strconv.Itoa(malID),
45 Label: label,
46 Title: title,
47 Thumbnail: posterURL(malID),
48 ExtraData: toSearchItem(item),
49 })
50 }
51 if len(options) == 0 {
52 return nil, fmt.Errorf("no results for %q", query)
53 }
54 return options, nil
55}
56
57func formatSearchLabel(item animeItem) string {
58 title := strings.TrimSpace(item.TitleEnglish)
59 if title == "" {
60 title = strings.TrimSpace(item.Title)
61 }
62 parts := []string{title}
63 if item.Type != "" {
64 parts = append(parts, item.Type)
65 }
66 if item.AniYear > 0 {
67 parts = append(parts, strconv.Itoa(item.AniYear))
68 }
69 if episodes, ok := parseEpisodeCount(item.AniEpisodes); ok {
70 parts = append(parts, fmt.Sprintf("%d eps", episodes))
71 }
72 return strings.Join(parts, " · ")
73}
74
75func toSearchItem(item animeItem) SearchItem {
76 episodes, _ := parseEpisodeCount(item.AniEpisodes)
77 return SearchItem{
78 MalID: item.ID,
79 PublicID: item.PublicID,
80 Title: item.Title,
81 Type: item.Type,
82 Episodes: episodes,
83 Year: item.AniYear,
84 Score: item.Score,
85 Status: item.AniStatus,
86 }
87}
88
89func parseEpisodeCount(raw string) (int, bool) {
90 raw = strings.TrimSpace(raw)
91 if raw == "" || raw == "?" {
92 return 0, false
93 }
94 count, err := strconv.Atoi(raw)
95 if err != nil || count <= 0 {
96 return 0, false
97 }
98 return count, true
99}
internal/providers/senshi/streams.go added +52
@@ -0,0 +1,52 @@
1package senshi
2
3import (
4 "fmt"
5 "net/http"
6 "strings"
7
8 "github.com/wraient/curd/internal/providers"
9)
10
11func getEpisodeStreamsForMode(malIDStr string, config providers.PlaybackConfig, epNo int) ([]string, map[string]providers.StreamPlaybackHint, error) {
12 malID, err := parseMalID(malIDStr)
13 if err != nil {
14 return nil, nil, err
15 }
16 if epNo <= 0 {
17 return nil, nil, fmt.Errorf("invalid episode number %d", epNo)
18 }
19
20 mode := providers.NormalizeTranslationType(config.SubOrDub)
21 wantStatus := "HardSub"
22 if mode == "dub" {
23 wantStatus = "Dub"
24 }
25
26 var embeds []embedItem
27 url := fmt.Sprintf("%s/episode-embeds/%d/%d", baseURL, malID, epNo)
28 if err := fetchJSON(http.MethodGet, url, nil, &embeds); err != nil {
29 return nil, nil, err
30 }
31 if len(embeds) == 0 {
32 return nil, nil, fmt.Errorf("no streams found for episode %d", epNo)
33 }
34
35 for _, item := range embeds {
36 if !strings.EqualFold(strings.TrimSpace(item.Status), wantStatus) {
37 continue
38 }
39 streamURL := strings.TrimSpace(item.URL)
40 if streamURL == "" {
41 continue
42 }
43 hints := map[string]providers.StreamPlaybackHint{
44 streamURL: {
45 Referrer: baseURL + "/",
46 },
47 }
48 return []string{streamURL}, hints, nil
49 }
50
51 return nil, nil, fmt.Errorf("no %s streams found for episode %d", mode, epNo)
52}
internal/providers/senshi/types.go added +47
@@ -0,0 +1,47 @@
1package senshi
2
3// SearchItem is stored in SelectionOption.ExtraData for mapping hints.
4type SearchItem struct {
5 MalID int
6 PublicID string
7 Title string
8 Type string
9 Episodes int
10 Year int
11 Score float64
12 Status string
13}
14
15type filterResponse struct {
16 Data []animeItem `json:"data"`
17 Total int `json:"total"`
18}
19
20type animeItem struct {
21 ID int `json:"id"`
22 PublicID string `json:"public_id"`
23 AnimePicture string `json:"anime_picture"`
24 Title string `json:"title"`
25 TitleEnglish string `json:"title_english"`
26 Type string `json:"type"`
27 AniEpisodes string `json:"ani_episodes"`
28 AniStatus string `json:"ani_status"`
29 AniYear int `json:"ani_year"`
30 Score float64 `json:"score"`
31}
32
33type episodeItem struct {
34 ID int `json:"id"`
35 EpID int `json:"ep_id"`
36 MalID int `json:"mal_id"`
37 EpTitle string `json:"ep_title"`
38 EpFiller bool `json:"ep_filler"`
39 EpRecap bool `json:"ep_recap"`
40}
41
42type embedItem struct {
43 URL string `json:"url"`
44 Server2 *string `json:"server2"`
45 ServerFM *string `json:"serverFM"`
46 Status string `json:"status"`
47}
internal/selection_labels.go +8
@@ -7,6 +7,8 @@ import (
7 "strings" 7 "strings"
8 8
9 "github.com/wraient/curd/internal/providers/animepahe" 9 "github.com/wraient/curd/internal/providers/animepahe"
10 "github.com/wraient/curd/internal/providers/anipub"
11 "github.com/wraient/curd/internal/providers/senshi"
10) 12)
11 13
12var selectionEpisodeCountRE = regexp.MustCompile(`\((\d+)\s+episodes?\)`) 14var selectionEpisodeCountRE = regexp.MustCompile(`\((\d+)\s+episodes?\)`)
@@ -50,6 +52,12 @@ func episodeCountFromSelectionOption(option SelectionOption) (int, bool) {
50 if item, ok := option.ExtraData.(animepahe.SearchItem); ok && item.Episodes > 0 { 52 if item, ok := option.ExtraData.(animepahe.SearchItem); ok && item.Episodes > 0 {
51 return item.Episodes, true 53 return item.Episodes, true
52 } 54 }
55 if item, ok := option.ExtraData.(senshi.SearchItem); ok && item.Episodes > 0 {
56 return item.Episodes, true
57 }
58 if item, ok := option.ExtraData.(anipub.SearchItem); ok && item.Episodes > 0 {
59 return item.Episodes, true
60 }
53 } 61 }
54 62
55 return 0, false 63 return 0, false
internal/selection_menu.go +5 −3
@@ -716,12 +716,14 @@ func dynamicSelectInternal(options []SelectionOption, refreshConfig *SelectionRe
716 716
717 finalModel, err := p.Run() 717 finalModel, err := p.Run()
718 close(stopRefresh) 718 close(stopRefresh)
719 if err != nil {
720 return SelectionOption{}, err
721 }
722 719
720 // Bubbletea may leave the terminal in raw mode; always reset cursor state.
723 fmt.Print("\033[?25h") 721 fmt.Print("\033[?25h")
724 fmt.Print("\033[?7h") 722 fmt.Print("\033[?7h")
723 if err != nil {
724 RestoreScreen()
725 return SelectionOption{}, err
726 }
725 727
726 finalSelectionModel, ok := finalModel.(*Model) 728 finalSelectionModel, ok := finalModel.(*Model)
727 if !ok { 729 if !ok {
internal/terminal_screen.go added +33
@@ -0,0 +1,33 @@
1package internal
2
3import (
4 "os"
5 "os/signal"
6 "sync"
7 "syscall"
8)
9
10var (
11 interruptHandlerOnce sync.Once
12 interruptExitOnce sync.Once
13)
14
15// InstallTerminalInterruptHandler restores the terminal before exiting on Ctrl+C or SIGTERM.
16func InstallTerminalInterruptHandler() {
17 interruptHandlerOnce.Do(func() {
18 interrupts := make(chan os.Signal, 1)
19 signal.Notify(interrupts, os.Interrupt, syscall.SIGTERM)
20 go func() {
21 for range interrupts {
22 exitWithRestore(130)
23 }
24 }()
25 })
26}
27
28func exitWithRestore(code int) {
29 interruptExitOnce.Do(func() {
30 RestoreScreen()
31 os.Exit(code)
32 })
33}
internal/terminal_screen_test.go added +27
@@ -0,0 +1,27 @@
1package internal
2
3import "testing"
4
5func TestRestoreScreenOnlyWhenAlternateScreenActive(t *testing.T) {
6 previous := alternateScreenActive
7 t.Cleanup(func() {
8 alternateScreenActive = previous
9 })
10
11 alternateScreenActive = false
12 RestoreScreen()
13 if alternateScreenActive {
14 t.Fatal("restore should stay inactive when screen was not cleared")
15 }
16
17 alternateScreenActive = true
18 RestoreScreen()
19 if alternateScreenActive {
20 t.Fatal("restore should deactivate alternate screen")
21 }
22}
23
24func TestInstallTerminalInterruptHandlerIsIdempotent(t *testing.T) {
25 InstallTerminalInterruptHandler()
26 InstallTerminalInterruptHandler()
27}
internal/version.go added +28
@@ -0,0 +1,28 @@
1package internal
2
3import (
4 "path/filepath"
5 "strings"
6)
7
8var curdVersion = "dev"
9
10// SetCurdVersion records the running application version for storage migrations.
11func SetCurdVersion(version string) {
12 version = strings.TrimSpace(version)
13 if version != "" {
14 curdVersion = version
15 }
16}
17
18// CurdVersion returns the running application version.
19func CurdVersion() string {
20 if curdVersion == "" {
21 return "dev"
22 }
23 return curdVersion
24}
25
26func storageVersionFilePath(storagePath string) string {
27 return filepath.Join(strings.TrimSpace(storagePath), "curd_version")
28}