Commit ab433f1f7b

ab433f1f7be268ab37fa3ed2e8c61b5eb4b2ca1a

parent: 60789e58c4

Unsigned

Wraient <wraient.911@gmail.com> · 2026-06-22 13:56 UTC

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

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

Layout: unified · split

Build/curd-windows-build.iss +1 −1
@@ -1,6 +1,6 @@
1[Setup] 1[Setup]
2AppName=Curd Installer 2AppName=Curd Installer
3AppVersion=1.5.1 3AppVersion=1.5.3
4DefaultDirName={userappdata}\Curd 4DefaultDirName={userappdata}\Curd
5PrivilegesRequired=lowest 5PrivilegesRequired=lowest
6AllowNoIcons=yes 6AllowNoIcons=yes
README.md +8 −3
@@ -24,7 +24,7 @@ https://github.com/user-attachments/assets/cbf799bc-9fdd-4402-ab61-b4e31f1e264d
24 24
25 25
26## Features 26## Features
27- Multiple Content Providers (AllAnime and Animepahe) with ordered fallback and up to 1080p support 27- Multiple Content Providers (AllAnime, AniNeko, and Animepahe) with ordered fallback and up to 1080p support
28- Built-in headless browser to bypass Cloudflare/DDoS-Guard protections 28- Built-in headless browser to bypass Cloudflare/DDoS-Guard protections
29- Stream anime online 29- Stream anime online
30- Track anime locally, on AniList, or on MyAnimeList 30- Track anime locally, on AniList, or on MyAnimeList
@@ -299,6 +299,8 @@ curd [options]
299| `-change-token` | Change your authentication token | - | 299| `-change-token` | Change your authentication token | - |
300| `-dub` | Watch the dubbed version of the anime | - | 300| `-dub` | Watch the dubbed version of the anime | - |
301| `-sub` | Watch the subbed version of the anime | - | 301| `-sub` | Watch the subbed version of the anime | - |
302| `-softsub` | Prefer soft subtitles when available (AniNeko) | - |
303| `-hardsub` | Prefer hard subtitles when available (AniNeko) | - |
302| `-new` | Add a new anime to your list | - | 304| `-new` | Add a new anime to your list | - |
303| `-e` | Edit the configuration file | - | 305| `-e` | Edit the configuration file | - |
304| `-skip-op` | Automatically skip the opening section of each episode | `true` | 306| `-skip-op` | Automatically skip the opening section of each episode | `true` |
@@ -381,6 +383,7 @@ If the browser reaches the localhost callback page but curd does not continue au
381| `PercentageToMarkComplete`| Integer | `0` to `100` | Sets the percentage of an episode watched to consider it as completed. | 383| `PercentageToMarkComplete`| Integer | `0` to `100` | Sets the percentage of an episode watched to consider it as completed. |
382| `StoragePath` | String | Any valid path (Environment variables accepted) | Specifies the directory where Curd stores its data. | 384| `StoragePath` | String | Any valid path (Environment variables accepted) | Specifies the directory where Curd stores its data. |
383| `SubOrDub` | Enum | `sub`, `dub` | Sets the preferred format for anime audio. | 385| `SubOrDub` | Enum | `sub`, `dub` | Sets the preferred format for anime audio. |
386| `SubStyle` | Enum | `ask`, `soft`, `hard` | For AniNeko sub streams: `ask` prompts once when both soft-sub and hard-sub servers exist, then saves your choice here; `soft` uses external `.vtt` subtitles via mpv; `hard` uses burned-in subs. Default: `ask` |
384| `NextEpisodePrompt` | Boolean | `true`, `false` | Prompts the user before automatically playing the next episode. | 387| `NextEpisodePrompt` | Boolean | `true`, `false` | Prompts the user before automatically playing the next episode. |
385| `SubsLanguage` | String | `english` (redundant rn) | Sets the preferred subtitle language. | 388| `SubsLanguage` | String | `english` (redundant rn) | Sets the preferred subtitle language. |
386| `ScoreOnCompletion` | Boolean | `true`, `false` | Automatically prompts the user to rate the anime upon completion. | 389| `ScoreOnCompletion` | Boolean | `true`, `false` | Automatically prompts the user to rate the anime upon completion. |
@@ -391,8 +394,9 @@ If the browser reaches the localhost callback page but curd does not continue au
391| `Player` | String | any mpv-compatible binary (e.g. `mpv`, `iina`) | Player binary used for playback. If not found, Curd falls back to `mpv`. | 394| `Player` | String | any mpv-compatible binary (e.g. `mpv`, `iina`) | Player binary used for playback. If not found, Curd falls back to `mpv`. |
392| `SaveMpvSpeed` | Boolean | `true`, `false` | Retains the playback speed set in MPV for next episode. | 395| `SaveMpvSpeed` | Boolean | `true`, `false` | Retains the playback speed set in MPV for next episode. |
393| `SkipFiller` | Boolean | `true`, `false` | Skips filler episodes when supported. | 396| `SkipFiller` | Boolean | `true`, `false` | Skips filler episodes when supported. |
394| `MenuOrder` | String | Comma-separated list | Controls which menu items appear and their order. Available options: `CURRENT`, `ALL`, `UNTRACKED`, `UPDATE`, `CONTINUE_LAST`, `PLANNING`, `COMPLETED`, `PAUSED`, `DROPPED`, `REWATCHING`, `TRACKER`, `PROVIDER`. Only listed items will be shown. Default: `CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,TRACKER,PROVIDER` | 397| `MenuOrder` | String | Comma-separated list | Controls which menu items appear and their order. Available options: `CURRENT`, `ALL`, `UNTRACKED`, `UPDATE`, `REMAP_PROVIDER`, `CONTINUE_LAST`, `PLANNING`, `COMPLETED`, `PAUSED`, `DROPPED`, `REWATCHING`, `TRACKER`, `PROVIDER`. Only listed items will be shown. Default: `CURRENT,ALL,UNTRACKED,UPDATE,REMAP_PROVIDER,CONTINUE_LAST,TRACKER,PROVIDER` |
395| `Provider` | List | `["allanime"]`, `["animepahe"]`, `["allanime","animepahe"]`, `["allanime","no-animepahe"]` | Sets the ordered content-provider fallback list. Curd tries providers from left to right for the requested stream. If AllAnime has no search results or the requested episode stream is unavailable and Animepahe is not configured, Curd asks before enabling Animepahe and warns that DDoS-Guard verification may require a ~500 MB chromium download. Declining stores `no-animepahe` so Curd does not ask again. Legacy single values like `allanime` are migrated to list form. Default: `["allanime"]` | 398| `Provider` | List | `["anineko"]`, `["allanime"]`, `["animepahe"]`, `["anineko","allanime"]`, `["allanime","animepahe"]`, `["allanime","no-animepahe"]`, `stacked` | Sets the ordered content-provider fallback list. Curd tries providers from left to right for the requested stream. `stacked` / `all` uses every enabled provider. AllAnime and Animepahe are disabled by default; include them in `Provider` to enable. If the primary provider has no search results or stream and Animepahe is not configured, Curd may ask before enabling Animepahe. Default: `["anineko"]` |
399| `ManualProviderSearch` | Boolean | `true`, `false` | Skip automatic provider matching and always show provider search results for manual selection. Displays a hint with the tracker title, format (TV/Movie/etc.), episode count, and sub/dub mode. Default: `false` |
396| `TrackingLocal` | Boolean | `true` | Legacy compatibility flag. Local playback history is always enabled. | 400| `TrackingLocal` | Boolean | `true` | Legacy compatibility flag. Local playback history is always enabled. |
397| `TrackingRemote` | Enum | `none`, `anilist`, `myanimelist`, `anilist+myanimelist` | Selects which remote tracker curd syncs with. | 401| `TrackingRemote` | Enum | `none`, `anilist`, `myanimelist`, `anilist+myanimelist` | Selects which remote tracker curd syncs with. |
398| `TrackingConfigured` | Boolean | `true`, `false` | Internal flag used to remember that the startup tracking prompt has already been completed. | 402| `TrackingConfigured` | Boolean | `true`, `false` | Internal flag used to remember that the startup tracking prompt has already been completed. |
@@ -416,6 +420,7 @@ If the browser reaches the localhost callback page but curd does not continue au
416- [MyAnimeList API](https://myanimelist.net/apiconfig/references/api/v2) - MyAnimeList OAuth and tracking sync 420- [MyAnimeList API](https://myanimelist.net/apiconfig/references/api/v2) - MyAnimeList OAuth and tracking sync
417- [AniSkip API](https://api.aniskip.com/api-docs) - Get anime intro and outro timings 421- [AniSkip API](https://api.aniskip.com/api-docs) - Get anime intro and outro timings
418- [AllAnime Content](https://allanime.to/) - Fetch anime url 422- [AllAnime Content](https://allanime.to/) - Fetch anime url
423- [AniNeko Content](https://anineko.to/) - Alternative provider with soft/hard sub stream selection
419- [Animepahe Content](https://animepahe.pw/) - Alternative provider for 1080p streams 424- [Animepahe Content](https://animepahe.pw/) - Alternative provider for 1080p streams
420- [Jikan](https://jikan.moe/) - Get filler episode number 425- [Jikan](https://jikan.moe/) - Get filler episode number
421 426
cmd/curd/main.go +7
@@ -82,6 +82,8 @@ func main() {
82 editConfig := flag.Bool("e", false, "Edit config") 82 editConfig := flag.Bool("e", false, "Edit config")
83 subFlag := flag.Bool("sub", false, "Watch sub version") 83 subFlag := flag.Bool("sub", false, "Watch sub version")
84 dubFlag := flag.Bool("dub", false, "Watch dub version") 84 dubFlag := flag.Bool("dub", false, "Watch dub version")
85 softSubFlag := flag.Bool("softsub", false, "Prefer soft subtitles when available (anineko)")
86 hardSubFlag := flag.Bool("hardsub", false, "Prefer hard subtitles when available (anineko)")
85 versionFlag := flag.Bool("v", false, "Print version information") 87 versionFlag := flag.Bool("v", false, "Print version information")
86 88
87 // Custom help/usage function 89 // Custom help/usage function
@@ -183,6 +185,11 @@ func main() {
183 } else if *dubFlag { 185 } else if *dubFlag {
184 userCurdConfig.SubOrDub = "dub" 186 userCurdConfig.SubOrDub = "dub"
185 } 187 }
188 if *softSubFlag {
189 userCurdConfig.SubStyle = "soft"
190 } else if *hardSubFlag {
191 userCurdConfig.SubStyle = "hard"
192 }
186 193
187 // Get the token from the token file for the configured remote tracker. 194 // Get the token from the token file for the configured remote tracker.
188 if internal.UsesRemoteTracking(&userCurdConfig) { 195 if internal.UsesRemoteTracking(&userCurdConfig) {
internal/anilist.go +74 −11
@@ -141,6 +141,28 @@ func min3(a, b, c int) int {
141} 141}
142 142
143func doAniListSearchRequest(url string, requestBody []byte, token string) ([]byte, error) { 143func doAniListSearchRequest(url string, requestBody []byte, token string) ([]byte, error) {
144 for authAttempt := 0; authAttempt < 2; authAttempt++ {
145 body, err := doAniListSearchRequestAttempt(url, requestBody, token)
146 if err == nil {
147 return body, nil
148 }
149 if authAttempt == 0 && isInvalidTokenError(err) {
150 newToken, renewed, renewErr := tryRenewAniListTokenForAPI(token, "invalid token")
151 if renewErr != nil {
152 return nil, renewErr
153 }
154 if renewed {
155 token = newToken
156 continue
157 }
158 }
159 return nil, err
160 }
161
162 return nil, fmt.Errorf("AniList search failed after token renewal")
163}
164
165func doAniListSearchRequestAttempt(url string, requestBody []byte, token string) ([]byte, error) {
144 client := sharedHTTPClient 166 client := sharedHTTPClient
145 if client == nil { 167 if client == nil {
146 client = &http.Client{Timeout: 15 * time.Second} 168 client = &http.Client{Timeout: 15 * time.Second}
@@ -197,6 +219,7 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
197 Page(page: 1, perPage: 50) { 219 Page(page: 1, perPage: 50) {
198 media(search: $search, type: ANIME) { 220 media(search: $search, type: ANIME) {
199 id 221 id
222 episodes
200 title { 223 title {
201 romaji 224 romaji
202 english 225 english
@@ -233,10 +256,11 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
233 animeDict := make(map[string]RofiSelectPreview) 256 animeDict := make(map[string]RofiSelectPreview)
234 257
235 type scoredAnime struct { 258 type scoredAnime struct {
236 id string 259 id string
237 title string 260 title string
238 cover string 261 cover string
239 score int 262 episodes int
263 score int
240 } 264 }
241 var scored []scoredAnime 265 var scored []scoredAnime
242 for _, anime := range animeList { 266 for _, anime := range animeList {
@@ -247,7 +271,7 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
247 } 271 }
248 cover := anime.CoverImage.Large 272 cover := anime.CoverImage.Large
249 score := levenshtein(title, query) 273 score := levenshtein(title, query)
250 scored = append(scored, scoredAnime{idStr, title, cover, score}) 274 scored = append(scored, scoredAnime{idStr, title, cover, anime.Episodes, score})
251 } 275 }
252 sort.Slice(scored, func(i, j int) bool { 276 sort.Slice(scored, func(i, j int) bool {
253 return scored[i].score < scored[j].score 277 return scored[i].score < scored[j].score
@@ -257,7 +281,7 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie
257 break 281 break
258 } 282 }
259 animeDict[s.id] = RofiSelectPreview{ 283 animeDict[s.id] = RofiSelectPreview{
260 Title: s.title, 284 Title: FormatAnimeSearchLabel(s.title, s.episodes),
261 CoverImage: s.cover, 285 CoverImage: s.cover,
262 } 286 }
263 } 287 }
@@ -273,6 +297,7 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
273 Page(page: 1, perPage: 50) { 297 Page(page: 1, perPage: 50) {
274 media(search: $search, type: ANIME) { 298 media(search: $search, type: ANIME) {
275 id 299 id
300 episodes
276 title { 301 title {
277 romaji 302 romaji
278 english 303 english
@@ -306,9 +331,10 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
306 var results []SelectionOption 331 var results []SelectionOption
307 332
308 type scoredAnime struct { 333 type scoredAnime struct {
309 id string 334 id string
310 title string 335 title string
311 score int 336 episodes int
337 score int
312 } 338 }
313 var scored []scoredAnime 339 var scored []scoredAnime
314 for _, anime := range animeList { 340 for _, anime := range animeList {
@@ -318,7 +344,7 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
318 title = anime.Title.Romaji 344 title = anime.Title.Romaji
319 } 345 }
320 score := levenshtein(title, query) 346 score := levenshtein(title, query)
321 scored = append(scored, scoredAnime{idStr, title, score}) 347 scored = append(scored, scoredAnime{idStr, title, anime.Episodes, score})
322 } 348 }
323 sort.Slice(scored, func(i, j int) bool { 349 sort.Slice(scored, func(i, j int) bool {
324 return scored[i].score < scored[j].score 350 return scored[i].score < scored[j].score
@@ -329,7 +355,8 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
329 } 355 }
330 results = append(results, SelectionOption{ 356 results = append(results, SelectionOption{
331 Key: s.id, 357 Key: s.id,
332 Label: s.title, 358 Label: FormatAnimeSearchLabel(s.title, s.episodes),
359 Title: s.title,
333 }) 360 })
334 } 361 }
335 return results, nil 362 return results, nil
@@ -497,6 +524,7 @@ func GetUserData(token string, userID int) (map[string]interface{}, error) {
497 idMal 524 idMal
498 episodes 525 episodes
499 duration 526 duration
527 format
500 title { 528 title {
501 romaji 529 romaji
502 english 530 english
@@ -554,6 +582,7 @@ func GetUserDataPreview(token string, userID int) (map[string]interface{}, error
554 idMal 582 idMal
555 episodes 583 episodes
556 duration 584 duration
585 format
557 coverImage { 586 coverImage {
558 large 587 large
559 } 588 }
@@ -872,6 +901,39 @@ func makePostRequest(url, query string, variables map[string]interface{}, header
872 return nil, fmt.Errorf("failed to marshal request body: %w", err) 901 return nil, fmt.Errorf("failed to marshal request body: %w", err)
873 } 902 }
874 903
904 token := ""
905 if headers != nil {
906 if authHeader := headers["Authorization"]; strings.HasPrefix(authHeader, "Bearer ") {
907 token = strings.TrimPrefix(authHeader, "Bearer ")
908 }
909 }
910
911 for authAttempt := 0; authAttempt < 2; authAttempt++ {
912 response, err := makePostRequestAttempt(url, requestBody, headers)
913 if err == nil {
914 return response, nil
915 }
916 if authAttempt == 0 && isInvalidTokenError(err) && token != "" {
917 newToken, renewed, renewErr := tryRenewAniListTokenForAPI(token, "invalid token")
918 if renewErr != nil {
919 return nil, renewErr
920 }
921 if renewed {
922 token = newToken
923 if headers == nil {
924 headers = map[string]string{}
925 }
926 headers["Authorization"] = "Bearer " + newToken
927 continue
928 }
929 }
930 return nil, err
931 }
932
933 return nil, fmt.Errorf("AniList request failed after token renewal")
934}
935
936func makePostRequestAttempt(url string, requestBody []byte, headers map[string]string) (map[string]interface{}, error) {
875 client := sharedHTTPClient 937 client := sharedHTTPClient
876 if client == nil { 938 if client == nil {
877 client = &http.Client{Timeout: 15 * time.Second} 939 client = &http.Client{Timeout: 15 * time.Second}
@@ -1016,6 +1078,7 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
1016 Media: Media{ 1078 Media: Media{
1017 Duration: toInt(media["duration"]), 1079 Duration: toInt(media["duration"]),
1018 Episodes: toInt(media["episodes"]), 1080 Episodes: toInt(media["episodes"]),
1081 Format: safeString(media["format"]),
1019 ID: toInt(media["id"]), 1082 ID: toInt(media["id"]),
1020 MalID: toInt(media["idMal"]), 1083 MalID: toInt(media["idMal"]),
1021 Title: AnimeTitle{ 1084 Title: AnimeTitle{
internal/auth_token.go added +83
@@ -0,0 +1,83 @@
1package internal
2
3import (
4 "fmt"
5 "net/http"
6 "os"
7 "path/filepath"
8 "strings"
9)
10
11func isInvalidTokenResponse(statusCode int, body []byte) bool {
12 lower := strings.ToLower(string(body))
13 if strings.Contains(lower, "invalid token") || strings.Contains(lower, "invalid_token") {
14 return true
15 }
16 return statusCode == http.StatusUnauthorized
17}
18
19func isInvalidTokenError(err error) bool {
20 if err == nil {
21 return false
22 }
23 lower := strings.ToLower(err.Error())
24 return strings.Contains(lower, "invalid token") || strings.Contains(lower, "invalid_token")
25}
26
27func anilistTokenPath(config *CurdConfig) string {
28 return filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")
29}
30
31func ReauthenticateAniList(config *CurdConfig, user *User, reason string) (string, error) {
32 if config == nil {
33 config = GetGlobalConfig()
34 }
35 if config == nil {
36 return "", fmt.Errorf("missing config for AniList reauthentication")
37 }
38
39 tokenPath := anilistTokenPath(config)
40 if reason != "" {
41 CurdOut(fmt.Sprintf("AniList sign-in required (%s). Opening browser...", reason))
42 Log(fmt.Sprintf("AniList token invalid (%s), starting browser authentication", reason))
43 } else {
44 CurdOut("AniList sign-in required. Opening browser...")
45 Log("AniList token invalid, starting browser authentication")
46 }
47
48 if err := os.Remove(tokenPath); err != nil && !os.IsNotExist(err) {
49 Log(fmt.Sprintf("Failed to clear stale AniList token file: %v", err))
50 }
51
52 accessToken, err := authenticateWithBrowser(tokenPath)
53 if err != nil {
54 return "", err
55 }
56
57 if user != nil {
58 user.Token = accessToken
59 } else if globalUser := GetGlobalUser(); globalUser != nil {
60 globalUser.Token = accessToken
61 }
62
63 return accessToken, nil
64}
65
66func tryRenewAniListTokenForAPI(currentToken string, reason string) (string, bool, error) {
67 config := GetGlobalConfig()
68 if config == nil {
69 return currentToken, false, nil
70 }
71
72 newToken, err := ReauthenticateAniList(config, GetGlobalUser(), reason)
73 if err != nil {
74 return currentToken, false, err
75 }
76 return newToken, true, nil
77}
78
79func clearStoredTokenFile(tokenPath string) {
80 if err := os.Remove(tokenPath); err != nil && !os.IsNotExist(err) {
81 Log(fmt.Sprintf("Failed to clear stale token file %s: %v", tokenPath, err))
82 }
83}
internal/config.go +34 −8
@@ -42,6 +42,7 @@ type CurdConfig struct {
42 MpvArgs []string `config:"MpvArgs"` 42 MpvArgs []string `config:"MpvArgs"`
43 SubsLanguage string `config:"SubsLanguage"` 43 SubsLanguage string `config:"SubsLanguage"`
44 SubOrDub string `config:"SubOrDub"` 44 SubOrDub string `config:"SubOrDub"`
45 SubStyle string `config:"SubStyle"`
45 StoragePath string `config:"StoragePath"` 46 StoragePath string `config:"StoragePath"`
46 AnimeNameLanguage string `config:"AnimeNameLanguage"` 47 AnimeNameLanguage string `config:"AnimeNameLanguage"`
47 MenuOrder string `config:"MenuOrder"` 48 MenuOrder string `config:"MenuOrder"`
@@ -61,6 +62,8 @@ type CurdConfig struct {
61 DiscordPresence bool `config:"DiscordPresence"` 62 DiscordPresence bool `config:"DiscordPresence"`
62 DiscordClientId string `config:"DiscordClientId"` 63 DiscordClientId string `config:"DiscordClientId"`
63 Provider string `config:"Provider"` 64 Provider string `config:"Provider"`
65 DisabledProviders string `config:"DisabledProviders"`
66 ManualProviderSearch bool `config:"ManualProviderSearch"`
64 TrackingLocal bool `config:"TrackingLocal"` 67 TrackingLocal bool `config:"TrackingLocal"`
65 TrackingRemote string `config:"TrackingRemote"` 68 TrackingRemote string `config:"TrackingRemote"`
66 TrackingConfigured bool `config:"TrackingConfigured"` 69 TrackingConfigured bool `config:"TrackingConfigured"`
@@ -85,8 +88,9 @@ func defaultConfigMap() map[string]string {
85 "StoragePath": "$HOME/.local/share/curd", 88 "StoragePath": "$HOME/.local/share/curd",
86 "AnimeNameLanguage": "english", 89 "AnimeNameLanguage": "english",
87 "SubsLanguage": "english", 90 "SubsLanguage": "english",
88 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,TRACKER,PROVIDER", 91 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,REMAP_PROVIDER,CONTINUE_LAST,TRACKER,PROVIDER",
89 "SubOrDub": "sub", 92 "SubOrDub": "sub",
93 "SubStyle": "ask",
90 "PercentageToMarkComplete": "85", 94 "PercentageToMarkComplete": "85",
91 "NextEpisodePrompt": "false", 95 "NextEpisodePrompt": "false",
92 "SkipOp": "true", 96 "SkipOp": "true",
@@ -101,7 +105,9 @@ func defaultConfigMap() map[string]string {
101 "AlternateScreen": "true", 105 "AlternateScreen": "true",
102 "DiscordPresence": "true", 106 "DiscordPresence": "true",
103 "DiscordClientId": "1287457464148820089", 107 "DiscordClientId": "1287457464148820089",
104 "Provider": "[\"allanime\"]", 108 "Provider": "[\"anineko\"]",
109 "DisabledProviders": "[]",
110 "ManualProviderSearch": "false",
105 "TrackingLocal": "true", 111 "TrackingLocal": "true",
106 "TrackingRemote": "anilist", 112 "TrackingRemote": "anilist",
107 "TrackingConfigured": "false", 113 "TrackingConfigured": "false",
@@ -164,6 +170,25 @@ func parseStringArray(value string) []string {
164 170
165var GlobalConfigPath string 171var GlobalConfigPath string
166 172
173func persistSubStylePreference(style string) error {
174 style = strings.ToLower(strings.TrimSpace(style))
175 if style != "soft" && style != "hard" {
176 return nil
177 }
178 if cfg := GetGlobalConfig(); cfg != nil {
179 cfg.SubStyle = style
180 }
181 if strings.TrimSpace(GlobalConfigPath) == "" {
182 return nil
183 }
184 configMap, err := LoadConfigFromFile(GlobalConfigPath)
185 if err != nil {
186 return err
187 }
188 configMap["SubStyle"] = style
189 return SaveConfigToFile(GlobalConfigPath, configMap)
190}
191
167// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct 192// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct
168func LoadConfig(configPath string) (CurdConfig, error) { 193func LoadConfig(configPath string) (CurdConfig, error) {
169 configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME 194 configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME
@@ -687,13 +712,14 @@ func normalizeTrackingConfig(config *CurdConfig) {
687 712
688func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption { 713func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption {
689 // Define the default categories and all available labels 714 // Define the default categories and all available labels
690 defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "CONTINUE_LAST", "TRACKER", "PROVIDER"} 715 defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "REMAP_PROVIDER", "CONTINUE_LAST", "TRACKER", "PROVIDER"}
691 availableLabels := map[string]string{ 716 availableLabels := map[string]string{
692 "CURRENT": "Currently Watching", 717 "CURRENT": "Currently Watching",
693 "ALL": "Show All", 718 "ALL": "Show All",
694 "UNTRACKED": "Untracked Watching", 719 "UNTRACKED": "Untracked Watching",
695 "UPDATE": "Update (Episode, Status, Score)", 720 "UPDATE": "Update (Episode, Status, Score)",
696 "CONTINUE_LAST": "Continue Last Session", 721 "REMAP_PROVIDER": "Remap Provider",
722 "CONTINUE_LAST": "Continue Last Session",
697 "PLANNING": "Plan to Watch", 723 "PLANNING": "Plan to Watch",
698 "COMPLETED": "Completed", 724 "COMPLETED": "Completed",
699 "PAUSED": "Paused", 725 "PAUSED": "Paused",
internal/curd.go +79 −342
@@ -735,6 +735,11 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
735 // If WatchUntracked returns, user pressed back OR watched is done- continue to category selection 735 // If WatchUntracked returns, user pressed back OR watched is done- continue to category selection
736 ClearScreen() 736 ClearScreen()
737 continue categorySelectionLoop 737 continue categorySelectionLoop
738 } else if categorySelection.Key == "REMAP_PROVIDER" {
739 ClearScreen()
740 RemapProviderAnime(userCurdConfig, user, databaseAnimes)
741 ClearScreen()
742 continue categorySelectionLoop
738 } else if categorySelection.Key == "CONTINUE_LAST" { 743 } else if categorySelection.Key == "CONTINUE_LAST" {
739 anime.Ep.ContinueLast = true 744 anime.Ep.ContinueLast = true
740 } 745 }
@@ -915,7 +920,6 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
915 anime.StartedAt = selectedAnilistAnime.StartedAt 920 anime.StartedAt = selectedAnilistAnime.StartedAt
916 anime.CompletedAt = selectedAnilistAnime.CompletedAt 921 anime.CompletedAt = selectedAnilistAnime.CompletedAt
917 anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress) 922 anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
918 var animeList []SelectionOption
919 userQuery = anime.Title.Romaji 923 userQuery = anime.Title.Romaji
920 924
921 if selectedAnilistAnime.Status == "COMPLETED" { 925 if selectedAnilistAnime.Status == "COMPLETED" {
@@ -988,293 +992,21 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
988 // if anime not found in database or provider changed, find it in animeList 992 // if anime not found in database or provider changed, find it in animeList
989 if needsProviderSearch { 993 if needsProviderSearch {
990 Log("Anime not found in database for current provider, searching in animeList...") 994 Log("Anime not found in database for current provider, searching in animeList...")
991 // Get Anime list (All anime) 995 mappingOutcome, mappingErr := ResolveAnimeProviderMapping(userCurdConfig, anime, string(userQuery), selectedAnilistAnime)
992 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub)) 996 if mappingErr != nil {
993 997 Log(fmt.Sprintf("Provider mapping failed: %v", mappingErr))
994 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub) 998 ExitCurd(mappingErr)
995 if err != nil {
996 Log(fmt.Sprintf("Failed to select anime: %v", err))
997 ExitCurd(fmt.Errorf("Failed to select anime"))
998 }
999 // Prompt user for manual query only when no results were found
1000 if len(animeList) == 0 {
1001 for {
1002 var manualQuery string
1003 manualQuery, err = promptText(userCurdConfig, fmt.Sprintf("No results found for '%s'. Press Enter to search with AniList name, or enter a custom name to search on configured providers.", userQuery), true)
1004 if err != nil {
1005 Log("Error getting user input: " + err.Error())
1006 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1007 }
1008
1009 // If empty, use original AniList name
1010 if manualQuery == "" {
1011 manualQuery = string(userQuery)
1012 }
1013
1014 animeList, err = SearchAnime(manualQuery, userCurdConfig.SubOrDub)
1015 if err != nil {
1016 Log(fmt.Sprintf("Failed to search anime with query '%s': %v", manualQuery, err))
1017 ExitCurd(fmt.Errorf("Failed to search anime"))
1018 }
1019
1020 if len(animeList) > 0 {
1021 break
1022 }
1023 }
1024 }
1025
1026 // Automatic mapping using Thumbnail clues
1027 // 1. Try AniList and MAL thumbnail matching
1028 found := false
1029 anilistIDStr := strconv.Itoa(anime.AnilistId)
1030 var jikanUrls []string
1031 fetchedJikan := false
1032
1033 // Helper regex
1034 // AniList regex extracts ID from strings like "bx155348-" or "/155348.jpg"
1035 anilistRegex := regexp.MustCompile(`anilistcdn/media/anime/cover/(?:large|medium)/(?:bx)?(\d+)`)
1036 // MyAnimeList regex extracts the filename like "120128.jpg"
1037 malRegex := regexp.MustCompile(`myanimelist\.net/images/anime/[^/]+/([^/]+\.jpg)`)
1038
1039 for i, option := range animeList {
1040 Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s', Thumbnail='%s'", i, option.Key, option.Label, option.Thumbnail))
1041
1042 if strings.Contains(option.Thumbnail, "anilist.co") {
1043 matches := anilistRegex.FindStringSubmatch(option.Thumbnail)
1044 if len(matches) > 1 && matches[1] == anilistIDStr {
1045 anime.ProviderId = option.Key
1046 Log(fmt.Sprintf("Found Anilist Thumbnail match! Setting ProviderId to: %s", anime.ProviderId))
1047 found = true
1048 break
1049 }
1050 } else if strings.Contains(option.Thumbnail, "myanimelist.net") {
1051 matches := malRegex.FindStringSubmatch(option.Thumbnail)
1052 if len(matches) > 1 {
1053 fileName := matches[1]
1054
1055 // Fetch Jikan pictures lazily (only once)
1056 if !fetchedJikan {
1057 if anime.MalId == 0 {
1058 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
1059 }
1060 if anime.MalId != 0 {
1061 urls, err := FetchJikanPictures(anime.MalId)
1062 if err != nil {
1063 Log(fmt.Sprintf("Failed to fetch Jikan pictures: %v", err))
1064 } else {
1065 jikanUrls = urls
1066 }
1067 }
1068 fetchedJikan = true
1069 }
1070
1071 for _, url := range jikanUrls {
1072 if strings.HasSuffix(url, "/"+fileName) || strings.Contains(url, fileName) {
1073 anime.ProviderId = option.Key
1074 Log(fmt.Sprintf("Found MyAnimeList Thumbnail match (%s)! Setting ProviderId to: %s", fileName, anime.ProviderId))
1075 found = true
1076 break
1077 }
1078 }
1079 }
1080 if found {
1081 break
1082 }
1083 }
1084 } 999 }
1085 1000 switch mappingOutcome {
1086 // 1b. Title/thumbnail scoring (AllAnime englishName vs AniList romaji query, etc.) 1001 case ProviderMappingBack:
1087 if !found { 1002 CurdOut("Going back to main menu...")
1088 if bestMatch, ok := confidentProviderSearchMatch(animeList, anime, userQuery); ok { 1003 RestoreScreen()
1089 anime.ProviderId = bestMatch.Key 1004 if anime.Ep.ContinueLast {
1090 Log(fmt.Sprintf("Found confident provider title match! Setting ProviderId to: %s (%s)", anime.ProviderId, bestMatch.Label)) 1005 anime.Ep.ContinueLast = false
1091 found = true
1092 }
1093 }
1094
1095 // 2. Jikan Metadata & Exact Anilist Meta Tag Matching (for animepahe)
1096 if !found && ProviderEnabled("animepahe") && ProviderStackContains(userCurdConfig, "animepahe") {
1097 Log("Attempting deep metadata matching and exact AniList meta tag check for Animepahe...")
1098
1099 targetAnilistID := strconv.Itoa(anime.AnilistId)
1100 var bestMatch *SelectionOption
1101 var highestScore int
1102
1103 if anime.MalId == 0 {
1104 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
1105 }
1106
1107 var malData *JikanAnimeData
1108 if anime.MalId != 0 {
1109 malData, _ = FetchJikanAnimeData(anime.MalId)
1110 }
1111
1112 for i := range animeList {
1113 opt := &animeList[i]
1114 optionProviderName, rawProviderID, ok := ParseProviderQualifiedID(opt.Key)
1115 if ok {
1116 if optionProviderName != "animepahe" {
1117 continue
1118 }
1119 } else {
1120 rawProviderID = opt.Key
1121 if configuredProviderNames(userCurdConfig)[0] != "animepahe" {
1122 continue
1123 }
1124 }
1125 score := 0
1126
1127 if malData != nil && opt.ExtraData != nil {
1128 if paheData, ok := opt.ExtraData.(AnimepaheSearchItem); ok {
1129 paheTitleLower := strings.ToLower(paheData.Title)
1130 malTitleLower := strings.ToLower(malData.Title)
1131 malTitleEngLower := strings.ToLower(malData.TitleEnglish)
1132 malTitleJapLower := strings.ToLower(malData.TitleJapanese)
1133
1134 if paheTitleLower == malTitleLower || (malTitleEngLower != "" && paheTitleLower == malTitleEngLower) || (malTitleJapLower != "" && paheTitleLower == malTitleJapLower) {
1135 score += 5
1136 } else if strings.Contains(paheTitleLower, malTitleLower) || strings.Contains(malTitleLower, paheTitleLower) ||
1137 (malTitleEngLower != "" && (strings.Contains(paheTitleLower, malTitleEngLower) || strings.Contains(malTitleEngLower, paheTitleLower))) {
1138 score += 2
1139 }
1140
1141 if paheData.Year > 0 && malData.Year > 0 && paheData.Year == malData.Year {
1142 score += 3
1143 }
1144 if paheData.Season != "" && malData.Season != "" && strings.EqualFold(paheData.Season, malData.Season) {
1145 score += 2
1146 }
1147 if paheData.Type != "" && malData.Type != "" && strings.EqualFold(paheData.Type, malData.Type) {
1148 score += 2
1149 }
1150 if paheData.Episodes > 0 && malData.Episodes > 0 && paheData.Episodes == malData.Episodes {
1151 score += 2
1152 } else if (paheData.Episodes == 0 && malData.Status == "Currently Airing") || (malData.Episodes == 0 && paheData.Status == "Currently Airing") {
1153 score += 2
1154 }
1155 if strings.EqualFold(paheData.Status, malData.Status) {
1156 score += 1
1157 }
1158 }
1159 } else {
1160 if strings.Contains(strings.ToLower(opt.Title), strings.ToLower(string(userQuery))) {
1161 score += 2
1162 }
1163 }
1164
1165 // If it has a decent score (or there are very few options), let's verify with the exact AniList meta tag
1166 if score >= 2 || len(animeList) <= 3 {
1167 animeRef := parseAnimepaheProviderID(rawProviderID)
1168 if animeRef.Session == "" {
1169 continue
1170 }
1171 animeUrl := fmt.Sprintf("https://animepahe.pw/anime/%s", animeRef.Session)
1172 Log(fmt.Sprintf("Fetching %s to check exact AniList meta tag...", animeUrl))
1173 req, err := newAnimepahePageRequest(animeUrl)
1174 if err != nil {
1175 Log(fmt.Sprintf("Failed to build animepahe detail request %s: %v", animeUrl, err))
1176 continue
1177 }
1178
1179 resp, err := sharedHTTPClient.Do(req)
1180 if err != nil {
1181 Log(fmt.Sprintf("Failed to fetch animepahe detail page %s: %v", animeUrl, err))
1182 continue
1183 }
1184 body, readErr := io.ReadAll(resp.Body)
1185 resp.Body.Close()
1186 if readErr != nil {
1187 Log(fmt.Sprintf("Failed to read animepahe detail page %s: %v", animeUrl, readErr))
1188 continue
1189 }
1190 if resp.StatusCode == http.StatusOK {
1191 bodyStr := string(body)
1192
1193 metaTag := fmt.Sprintf(`<meta name="anilist" content="%s">`, targetAnilistID)
1194 if strings.Contains(bodyStr, metaTag) {
1195 Log(fmt.Sprintf("FOUND EXACT ANILIST META TAG MATCH in %s!", opt.Title))
1196 bestMatch = opt
1197 highestScore = 100 // Guarantee selection
1198 break
1199 } else {
1200 malMetaTag := fmt.Sprintf(`<meta name="mal" content="%d">`, anime.MalId)
1201 if anime.MalId != 0 && strings.Contains(bodyStr, malMetaTag) {
1202 Log(fmt.Sprintf("FOUND EXACT MAL META TAG MATCH in %s!", opt.Title))
1203 bestMatch = opt
1204 highestScore = 100
1205 break
1206 }
1207 }
1208 }
1209 }
1210
1211 if score > highestScore {
1212 highestScore = score
1213 bestMatch = opt
1214 }
1215 }
1216
1217 if bestMatch != nil && highestScore == 100 {
1218 anime.ProviderId = bestMatch.Key
1219 Log(fmt.Sprintf("Found EXACT meta tag match! Score: %d. Setting ProviderId to: %s", highestScore, anime.ProviderId))
1220 found = true
1221 } else if bestMatch != nil {
1222 Log(fmt.Sprintf("Highest match score was %d (needed 100 for Animepahe exact meta tag match). Not selecting automatically to prevent false positives.", highestScore))
1223 if confirmProviderMatch(*bestMatch, "Animepahe metadata") {
1224 anime.ProviderId = bestMatch.Key
1225 Log(fmt.Sprintf("User confirmed Animepahe match. Setting ProviderId to: %s", anime.ProviderId))
1226 found = true
1227 }
1228 }
1229 }
1230
1231 // 3. Fallback to naive title/episode match
1232 if !found {
1233 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes)
1234 for _, option := range animeList {
1235 if fmt.Sprintf("%s (%d episodes)", option.Title, selectedAnilistAnime.Media.Episodes) == targetLabel {
1236 if confirmProviderMatch(option, "title and episode count") {
1237 anime.ProviderId = option.Key
1238 Log(fmt.Sprintf("User confirmed exact text match. Setting ProviderId to: %s", anime.ProviderId))
1239 found = true
1240 }
1241 break
1242 }
1243 }
1244 if !found {
1245 Log(fmt.Sprintf("No exact match found for label '%s'. Will require manual selection.", targetLabel))
1246 }
1247 }
1248
1249 // If unable to get Allanime id automatically get manually
1250 if anime.ProviderId == "" {
1251 CurdOut("We didn't find any matches. Please select manually.")
1252 selectedAllanimeAnime, err := DynamicSelect(animeList)
1253 if err != nil {
1254 ExitCurd(fmt.Errorf("No anime available"))
1255 }
1256
1257 if selectedAllanimeAnime.Key == "-1" {
1258 ExitCurd(nil)
1259 }
1260
1261 // Handle back button - go back to main menu
1262 if selectedAllanimeAnime.Key == "-2" {
1263 CurdOut("Going back to main menu...")
1264 RestoreScreen()
1265 if anime.Ep.ContinueLast {
1266 anime.Ep.ContinueLast = false
1267 }
1268 continue
1269 } 1006 }
1270 1007 continue
1271 anime.ProviderId = selectedAllanimeAnime.Key 1008 case ProviderMappingQuit:
1272 } 1009 ExitCurd(nil)
1273 if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
1274 anime.ProviderName = providerName
1275 anime.ProviderId = rawProviderID
1276 } else {
1277 anime.ProviderName = configuredProviderNames(userCurdConfig)[0]
1278 } 1010 }
1279 } 1011 }
1280 1012
@@ -1560,27 +1292,6 @@ func handleUnreleasedAnime(userCurdConfig *CurdConfig, user *User, anime *Anime,
1560 anime.Ep.ContinueLast = false 1292 anime.Ep.ContinueLast = false
1561} 1293}
1562 1294
1563func confirmProviderMatch(option SelectionOption, reason string) bool {
1564 label := option.Label
1565 if label == "" {
1566 label = option.Title
1567 }
1568 if label == "" {
1569 label = option.Key
1570 }
1571
1572 CurdOut(fmt.Sprintf("Provider match found by %s: %s", reason, label))
1573 selected, err := promptSelect([]SelectionOption{
1574 {Key: "use", Label: "Use this match"},
1575 {Key: "manual", Label: "Select manually"},
1576 })
1577 if err != nil {
1578 Log(fmt.Sprintf("Error confirming provider match: %v", err))
1579 return false
1580 }
1581 return selected.Key == "use"
1582}
1583
1584func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string { 1295func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1585 if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil { 1296 if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil {
1586 Log(fmt.Sprintf("Failed to resolve provider id: %v", err)) 1297 Log(fmt.Sprintf("Failed to resolve provider id: %v", err))
@@ -1628,34 +1339,59 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1628 linkErr = err 1339 linkErr = err
1629 Log(fmt.Sprintf("ResolveEpisodeURL still failed after provider reselect: %v", linkErr)) 1340 Log(fmt.Sprintf("ResolveEpisodeURL still failed after provider reselect: %v", linkErr))
1630 } 1341 }
1631 // If unable to get episode link automatically get manually 1342 for {
1632 episodeProviderName, episodeProviderID := AnimeProviderID(anime) 1343 switch promptEpisodeLinkFailureRecovery(userCurdConfig) {
1633 episodeList, listErr := EpisodesList(QualifyProviderID(episodeProviderName, episodeProviderID), userCurdConfig.SubOrDub) 1344 case "remap":
1634 if listErr != nil { 1345 if RemapAnimeProviderOnEpisodeFailure(userCurdConfig, anime, nil) {
1635 CurdOut("No episode list found: " + listErr.Error()) 1346 episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1636 Log(fmt.Sprintf("EpisodesList failed: %v", listErr)) 1347 link = episodeResult.Links
1637 RestoreScreen() 1348 if err == nil && len(link) > 0 {
1638 os.Exit(1) 1349 anime.Ep.Links = link
1639 } 1350 applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1640 if len(episodeList) == 0 { 1351 goto episodeLinksReady
1641 CurdOut("No episodes were returned by the current provider for this anime.") 1352 }
1642 Log(fmt.Sprintf("EpisodesList returned no episodes for provider %s and id %s after ResolveEpisodeURL error: %v", episodeProviderName, episodeProviderID, linkErr)) 1353 if err != nil {
1643 RestoreScreen() 1354 linkErr = err
1644 os.Exit(1) 1355 Log(fmt.Sprintf("ResolveEpisodeURL failed after provider remap: %v", linkErr))
1645 } 1356 }
1646 episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1])) 1357 }
1647 if err != nil { 1358 case "episode":
1648 Log("Invalid episode input: " + err.Error()) 1359 episodeProviderName, episodeProviderID := AnimeProviderID(anime)
1649 CurdOut("Invalid episode number") 1360 episodeList, listErr := EpisodesList(QualifyProviderID(episodeProviderName, episodeProviderID), userCurdConfig.SubOrDub)
1650 RestoreScreen() 1361 if listErr != nil {
1651 os.Exit(1) 1362 CurdOut("No episode list found: " + listErr.Error())
1652 } 1363 Log(fmt.Sprintf("EpisodesList failed: %v", listErr))
1653 anime.Ep.Number = episodeNumber 1364 continue
1654 episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number) 1365 }
1655 link = episodeResult.Links 1366 if len(episodeList) == 0 {
1656 if err != nil { 1367 CurdOut("No episodes were returned by the current provider for this anime.")
1657 CurdOut("Failed to get episode link") 1368 Log(fmt.Sprintf("EpisodesList returned no episodes for provider %s and id %s after ResolveEpisodeURL error: %v", episodeProviderName, episodeProviderID, linkErr))
1658 os.Exit(1) 1369 continue
1370 }
1371 episodeNumber, promptErr := promptPositiveEpisodeNumber(userCurdConfig, fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1372 if promptErr != nil {
1373 Log("Invalid episode input: " + promptErr.Error())
1374 CurdOut("Invalid episode number")
1375 continue
1376 }
1377 anime.Ep.Number = episodeNumber
1378 episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1379 link = episodeResult.Links
1380 if err == nil && len(link) > 0 {
1381 anime.Ep.Links = link
1382 applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1383 goto episodeLinksReady
1384 }
1385 if err != nil {
1386 linkErr = err
1387 Log(fmt.Sprintf("ResolveEpisodeURL failed for episode %d: %v", anime.Ep.Number, linkErr))
1388 } else {
1389 CurdOut("Failed to get episode link")
1390 }
1391 default:
1392 RestoreScreen()
1393 return ""
1394 }
1659 } 1395 }
1660 } else { 1396 } else {
1661 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link on first try. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link))) 1397 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link on first try. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link)))
@@ -1667,7 +1403,8 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1667episodeLinksReady: 1403episodeLinksReady:
1668 if len(anime.Ep.Links) == 0 { 1404 if len(anime.Ep.Links) == 0 {
1669 CurdOut("No episode links found") 1405 CurdOut("No episode links found")
1670 os.Exit(1) 1406 RestoreScreen()
1407 return ""
1671 } else { 1408 } else {
1672 Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links))) 1409 Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links)))
1673 } 1410 }
@@ -1763,10 +1500,6 @@ func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
1763 if err != nil { 1500 if err != nil {
1764 return err 1501 return err
1765 } 1502 }
1766 animepaheProvider, ok := provider.(*AnimepaheProvider)
1767 if !ok {
1768 return nil
1769 }
1770 1503
1771 query := GetAnimeName(*anime) 1504 query := GetAnimeName(*anime)
1772 if query == "" { 1505 if query == "" {
@@ -1776,7 +1509,7 @@ func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
1776 query = anime.Title.English 1509 query = anime.Title.English
1777 } 1510 }
1778 1511
1779 resolved, err := animepaheProvider.ResolveProviderID(providerID, query) 1512 resolved, err := resolveProviderID(provider, providerID, query)
1780 if err != nil { 1513 if err != nil {
1781 return err 1514 return err
1782 } 1515 }
@@ -1821,7 +1554,11 @@ func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason erro
1821 } 1554 }
1822 1555
1823 CurdOut("The saved Animepahe mapping is stale. Please select the anime again.") 1556 CurdOut("The saved Animepahe mapping is stale. Please select the anime again.")
1824 selected, err := promptSelect(options) 1557 var trackerEntry *Entry
1558 if anime.TotalEpisodes > 0 {
1559 trackerEntry = &Entry{Media: Media{Episodes: anime.TotalEpisodes}}
1560 }
1561 selected, err := promptProviderSearchSelection(userCurdConfig, options, trackerEntry)
1825 if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" { 1562 if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" {
1826 if err != nil { 1563 if err != nil {
1827 Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err)) 1564 Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err))
internal/localTracking.go +105 −61
@@ -8,6 +8,8 @@ import (
8 "strconv" 8 "strconv"
9 "strings" 9 "strings"
10 "time" 10 "time"
11
12 "github.com/wraient/curd/internal/providers/animepahe"
11) 13)
12 14
13// Function to add an anime entry 15// Function to add an anime entry
@@ -54,7 +56,7 @@ func normalizeLocalProviderID(providerName, providerID, animeName string) string
54 return "" 56 return ""
55 } 57 }
56 58
57 stableID := stableAnimepaheProviderID(providerID) 59 stableID := animepahe.StableProviderID(providerID)
58 if stableID != "" { 60 if stableID != "" {
59 return stableID 61 return stableID
60 } 62 }
@@ -343,9 +345,82 @@ func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime
343 return bestMatch 345 return bestMatch
344} 346}
345 347
348func LocalRemapAnimeProvider(databaseFile string, anilistID int, providerName, providerID, animeName string, watchingEpisode, playbackTime, animeDuration int) error {
349 providerID = normalizeLocalProviderID(providerName, providerID, animeName)
350 animeList := LocalGetAllAnime(databaseFile)
351
352 target := LocalFindAnime(animeList, anilistID, "")
353 if target == nil {
354 newAnime := Anime{
355 AnilistId: anilistID,
356 ProviderId: providerID,
357 ProviderName: providerName,
358 Ep: Episode{
359 Number: watchingEpisode,
360 Player: playingVideo{PlaybackTime: playbackTime},
361 Duration: animeDuration,
362 },
363 Title: AnimeTitle{
364 English: animeName,
365 Romaji: animeName,
366 },
367 }
368 animeList = append(animeList, newAnime)
369 } else {
370 oldProviderID := normalizeLocalProviderID(target.ProviderName, target.ProviderId, GetAnimeName(*target))
371 updated := false
372 for i := range animeList {
373 entry := &animeList[i]
374 if entry.AnilistId != anilistID {
375 continue
376 }
377 entryProviderID := normalizeLocalProviderID(entry.ProviderName, entry.ProviderId, GetAnimeName(*entry))
378 if entryProviderID != oldProviderID {
379 continue
380 }
381 entry.ProviderId = providerID
382 entry.ProviderName = providerName
383 entry.Ep.Number = watchingEpisode
384 entry.Ep.Player.PlaybackTime = playbackTime
385 entry.Ep.Duration = animeDuration
386 if animeName != "" {
387 entry.Title.English = animeName
388 entry.Title.Romaji = animeName
389 }
390 updated = true
391 }
392 if !updated {
393 return fmt.Errorf("failed to update local history for AniList ID %d", anilistID)
394 }
395 }
396
397 file, err := os.Create(databaseFile)
398 if err != nil {
399 return fmt.Errorf("create local history file: %w", err)
400 }
401 defer file.Close()
402
403 writer := csv.NewWriter(file)
404 for _, anime := range animeList {
405 record := []string{
406 strconv.Itoa(anime.AnilistId),
407 normalizeLocalProviderID(anime.ProviderName, anime.ProviderId, GetAnimeName(anime)),
408 strconv.Itoa(anime.Ep.Number),
409 strconv.Itoa(anime.Ep.Player.PlaybackTime),
410 strconv.Itoa(anime.Ep.Duration),
411 anime.ProviderName,
412 GetAnimeName(anime),
413 }
414 if err := writer.Write(record); err != nil {
415 return fmt.Errorf("write local history: %w", err)
416 }
417 }
418 writer.Flush()
419 return writer.Error()
420}
421
346func WatchUntracked(userCurdConfig *CurdConfig) { 422func WatchUntracked(userCurdConfig *CurdConfig) {
347 var query string 423 var query string
348 var animeList []SelectionOption
349 var err error 424 var err error
350 var anime Anime 425 var anime Anime
351 426
@@ -358,70 +433,22 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
358 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) 433 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
359 } 434 }
360 435
361 // Search for the anime 436 providerID, providerName, back, searchErr := ResolveUntrackedProviderSearch(userCurdConfig, query)
362 animeList, err = SearchAnime(query, userCurdConfig.SubOrDub) 437 if searchErr != nil {
363 if err != nil { 438 Log(fmt.Sprintf("Failed to search anime: %v", searchErr))
364 Log(fmt.Sprintf("Failed to search anime: %v", err))
365 ExitCurd(fmt.Errorf("Failed to search anime")) 439 ExitCurd(fmt.Errorf("Failed to search anime"))
366 } 440 }
367 441 if back {
368 if len(animeList) == 0 { 442 return
369 // Prompt user for manual query
370 for {
371 var manualQuery string
372 manualQuery, err = promptText(userCurdConfig, fmt.Sprintf("No results found for '%s'. Press Enter to search with the original name, or enter a custom name to search on AllAnime.", query), true)
373 if err != nil {
374 Log("Error getting user input: " + err.Error())
375 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
376 }
377
378 // If empty, use original query name
379 if manualQuery == "" {
380 manualQuery = query
381 }
382
383 animeList, err = SearchAnime(manualQuery, userCurdConfig.SubOrDub)
384 if err != nil {
385 Log(fmt.Sprintf("Failed to search anime with query '%s': %v", manualQuery, err))
386 ExitCurd(fmt.Errorf("Failed to search anime"))
387 }
388
389 if len(animeList) > 0 {
390 break
391 }
392 }
393 } 443 }
394 444 if providerID == "" {
395 // Select anime from search results
396 selectedAnime, err := DynamicSelect(animeList)
397 if err != nil {
398 Log(fmt.Sprintf("Failed to select anime: %v", err))
399 ExitCurd(fmt.Errorf("Failed to select anime"))
400 }
401
402 if selectedAnime.Key == "-1" {
403 ExitCurd(nil) 445 ExitCurd(nil)
404 } 446 }
405 447
406 // Back goes to home menu 448 anime.ProviderId = providerID
407 if selectedAnime.Key == "-2" { 449 anime.ProviderName = providerName
408 return // Return to caller (home menu) 450 anime.Title.English = query
409 } 451 anime.Title.Romaji = query
410
411 anime.ProviderId = selectedAnime.Key
412 if providerName, rawProviderID, ok := ParseProviderQualifiedID(selectedAnime.Key); ok {
413 anime.ProviderName = providerName
414 anime.ProviderId = rawProviderID
415 } else {
416 anime.ProviderName = configuredProviderNames(userCurdConfig)[0]
417 }
418 if selectedAnime.Title != "" {
419 anime.Title.English = selectedAnime.Title
420 anime.Title.Romaji = selectedAnime.Title
421 } else {
422 anime.Title.English = selectedAnime.Label
423 anime.Title.Romaji = selectedAnime.Label
424 }
425 break 452 break
426 } 453 }
427 454
@@ -439,7 +466,24 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
439 resolvedLink, err := ResolveEpisodeURLForPlayback(*userCurdConfig, &anime, anime.Ep.Number) 466 resolvedLink, err := ResolveEpisodeURLForPlayback(*userCurdConfig, &anime, anime.Ep.Number)
440 if err != nil { 467 if err != nil {
441 Log(fmt.Sprintf("Failed to get episode link: %v", err)) 468 Log(fmt.Sprintf("Failed to get episode link: %v", err))
442 ExitCurd(fmt.Errorf("Failed to get episode link")) 469 switch promptEpisodeLinkFailureRecovery(userCurdConfig) {
470 case "remap":
471 if RemapAnimeProviderOnEpisodeFailure(userCurdConfig, &anime, nil) {
472 continue
473 }
474 case "episode":
475 episodeNumber, promptErr := promptPositiveEpisodeNumber(userCurdConfig, "Enter the episode number")
476 if promptErr != nil {
477 Log(fmt.Sprintf("Invalid episode number: %v", promptErr))
478 CurdOut("Invalid episode number")
479 continue
480 }
481 anime.Ep.Number = episodeNumber
482 continue
483 default:
484 ExitCurd(nil)
485 }
486 continue
443 } 487 }
444 link := resolvedLink.Links 488 link := resolvedLink.Links
445 applyStreamPlaybackHints(&anime, link, resolvedLink.LinkHints) 489 applyStreamPlaybackHints(&anime, link, resolvedLink.LinkHints)
internal/myanimelist.go +24 −15
@@ -454,6 +454,10 @@ func renewMyAnimeListAccessToken(config *CurdConfig, tokenPath string, token *OA
454 Log(fmt.Sprintf("Failed to refresh MyAnimeList token after %s: %v", reason, refreshErr)) 454 Log(fmt.Sprintf("Failed to refresh MyAnimeList token after %s: %v", reason, refreshErr))
455 } 455 }
456 456
457 CurdOut("MyAnimeList sign-in required. Opening browser...")
458 Log(fmt.Sprintf("Starting MyAnimeList browser authentication after %s", reason))
459 clearStoredTokenFile(tokenPath)
460
457 accessToken, authErr := authenticateMyAnimeList(config, tokenPath) 461 accessToken, authErr := authenticateMyAnimeList(config, tokenPath)
458 if authErr != nil { 462 if authErr != nil {
459 return "", authErr 463 return "", authErr
@@ -547,24 +551,26 @@ func myAnimeListRequest(config *CurdConfig, method, requestURL string, form url.
547 return readErr 551 return readErr
548 } 552 }
549 553
550 if resp.StatusCode == http.StatusUnauthorized && attempt == 0 { 554 if resp.StatusCode == http.StatusUnauthorized || isInvalidTokenResponse(resp.StatusCode, body) {
551 tokenPath := myAnimeListTokenPath(config) 555 if attempt == 0 {
552 storedToken, tokenErr := loadToken(tokenPath) 556 tokenPath := myAnimeListTokenPath(config)
553 if tokenErr != nil { 557 storedToken, tokenErr := loadToken(tokenPath)
554 Log(fmt.Sprintf("Failed to load MyAnimeList token after unauthorized response, starting login: %v", tokenErr)) 558 if tokenErr != nil {
555 accessToken, authErr := renewMyAnimeListAccessToken(config, tokenPath, nil, "unauthorized API response") 559 Log(fmt.Sprintf("Failed to load MyAnimeList token after unauthorized response, starting login: %v", tokenErr))
556 if authErr != nil { 560 accessToken, authErr := renewMyAnimeListAccessToken(config, tokenPath, nil, "unauthorized API response")
557 return authErr 561 if authErr != nil {
562 return authErr
563 }
564 token = accessToken
565 continue
566 }
567 accessToken, renewErr := renewMyAnimeListAccessToken(config, tokenPath, storedToken, "unauthorized API response")
568 if renewErr != nil {
569 return renewErr
558 } 570 }
559 token = accessToken 571 token = accessToken
560 continue 572 continue
561 } 573 }
562 accessToken, renewErr := renewMyAnimeListAccessToken(config, tokenPath, storedToken, "unauthorized API response")
563 if renewErr != nil {
564 return renewErr
565 }
566 token = accessToken
567 continue
568 } 574 }
569 575
570 if resp.StatusCode < 200 || resp.StatusCode >= 300 { 576 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
@@ -724,6 +730,7 @@ func lookupAniListMediaByMalID(malID int) (Media, string, error) {
724 episodes 730 episodes
725 duration 731 duration
726 status 732 status
733 format
727 title { 734 title {
728 romaji 735 romaji
729 english 736 english
@@ -760,6 +767,7 @@ func lookupAniListMediaByMalID(malID int) (Media, string, error) {
760 Episodes: 0, 767 Episodes: 0,
761 Duration: 0, 768 Duration: 0,
762 Status: safeAniListString(mediaData["status"]), 769 Status: safeAniListString(mediaData["status"]),
770 Format: safeAniListString(mediaData["format"]),
763 Title: AnimeTitle{ 771 Title: AnimeTitle{
764 Romaji: safeAniListTitle(mediaData, "romaji"), 772 Romaji: safeAniListTitle(mediaData, "romaji"),
765 English: safeAniListTitle(mediaData, "english"), 773 English: safeAniListTitle(mediaData, "english"),
@@ -833,7 +841,7 @@ func lookupAniListMediaByMalIDs(malIDs []int) (map[int]aniListMediaLookupResult,
833 var query strings.Builder 841 var query strings.Builder
834 query.WriteString("query {") 842 query.WriteString("query {")
835 for idx, malID := range malIDs { 843 for idx, malID := range malIDs {
836 fmt.Fprintf(&query, " m%d: Media(idMal: %d, type: ANIME) { id idMal episodes duration status title { romaji english native } coverImage { large } }", idx, malID) 844 fmt.Fprintf(&query, " m%d: Media(idMal: %d, type: ANIME) { id idMal episodes duration status format title { romaji english native } coverImage { large } }", idx, malID)
837 } 845 }
838 query.WriteString(" }") 846 query.WriteString(" }")
839 847
@@ -876,6 +884,7 @@ func lookupAniListMediaByMalIDs(malIDs []int) (map[int]aniListMediaLookupResult,
876 Episodes: 0, 884 Episodes: 0,
877 Duration: 0, 885 Duration: 0,
878 Status: safeAniListString(rawMedia["status"]), 886 Status: safeAniListString(rawMedia["status"]),
887 Format: safeAniListString(rawMedia["format"]),
879 Title: AnimeTitle{ 888 Title: AnimeTitle{
880 Romaji: safeAniListTitle(rawMedia, "romaji"), 889 Romaji: safeAniListTitle(rawMedia, "romaji"),
881 English: safeAniListTitle(rawMedia, "english"), 890 English: safeAniListTitle(rawMedia, "english"),
internal/provider_mapping.go added +837
@@ -0,0 +1,837 @@
1package internal
2
3import (
4 "fmt"
5 "io"
6 "net/http"
7 "os"
8 "path/filepath"
9 "regexp"
10 "strconv"
11 "strings"
12
13 "github.com/wraient/curd/internal/providers/animepahe"
14)
15
16type ProviderMappingOutcome int
17
18const (
19 ProviderMappingOK ProviderMappingOutcome = iota
20 ProviderMappingBack
21 ProviderMappingQuit
22)
23
24type providerMappingSearchState struct {
25 query string
26 allProviders []string
27 sequential bool
28 providerIndex int
29}
30
31func (s *providerMappingSearchState) activeProviders() []string {
32 if !s.sequential {
33 return s.allProviders
34 }
35 if s.providerIndex >= len(s.allProviders) {
36 return nil
37 }
38 return []string{s.allProviders[s.providerIndex]}
39}
40
41func (s *providerMappingSearchState) currentProviderLabel() string {
42 if !s.sequential {
43 return "all configured providers"
44 }
45 if s.providerIndex >= len(s.allProviders) {
46 return ""
47 }
48 return s.allProviders[s.providerIndex]
49}
50
51func (s *providerMappingSearchState) nextProviderLabel() string {
52 if !s.sequential {
53 if len(s.allProviders) > 0 {
54 return s.allProviders[0]
55 }
56 return ""
57 }
58 next := s.providerIndex + 1
59 if next < len(s.allProviders) {
60 return s.allProviders[next]
61 }
62 return ""
63}
64
65func (s *providerMappingSearchState) advanceToNextProvider() bool {
66 if !s.sequential {
67 s.sequential = true
68 s.providerIndex = 0
69 return len(s.allProviders) > 0
70 }
71 s.providerIndex++
72 return s.providerIndex < len(s.allProviders)
73}
74
75func (s *providerMappingSearchState) resetToAllProviders() {
76 s.sequential = false
77 s.providerIndex = 0
78}
79
80func searchAnimeForMapping(config *CurdConfig, state *providerMappingSearchState, mode string) ([]SelectionOption, error) {
81 providers := state.activeProviders()
82 if len(providers) == 0 {
83 return nil, nil
84 }
85 if !state.sequential && len(providers) == len(state.allProviders) {
86 return SearchAnime(state.query, mode)
87 }
88 return searchAnimeWithProviders(providers, state.query, mode)
89}
90
91func confirmProviderMatch(option SelectionOption, reason string) bool {
92 label := option.Label
93 if label == "" {
94 label = option.Title
95 }
96 if label == "" {
97 label = option.Key
98 }
99
100 CurdOut(fmt.Sprintf("Provider match found by %s: %s", reason, label))
101 selected, err := promptSelect([]SelectionOption{
102 {Key: "use", Label: "Use this match"},
103 {Key: "manual", Label: "Select manually"},
104 })
105 if err != nil {
106 Log(fmt.Sprintf("Error confirming provider match: %v", err))
107 return false
108 }
109 return selected.Key == "use"
110}
111
112func autoMatchProviderListing(config *CurdConfig, anime *Anime, animeList []SelectionOption, userQuery string, anilistEntry *Entry) bool {
113 anilistIDStr := strconv.Itoa(anime.AnilistId)
114 var jikanUrls []string
115 fetchedJikan := false
116
117 anilistRegex := regexp.MustCompile(`anilistcdn/media/anime/cover/(?:large|medium)/(?:bx)?(\d+)`)
118 malRegex := regexp.MustCompile(`myanimelist\.net/images/anime/[^/]+/([^/]+\.jpg)`)
119
120 for i, option := range animeList {
121 Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s', Thumbnail='%s'", i, option.Key, option.Label, option.Thumbnail))
122
123 if strings.Contains(option.Thumbnail, "anilist.co") {
124 matches := anilistRegex.FindStringSubmatch(option.Thumbnail)
125 if len(matches) > 1 && matches[1] == anilistIDStr {
126 anime.ProviderId = option.Key
127 Log(fmt.Sprintf("Found Anilist Thumbnail match! Setting ProviderId to: %s", anime.ProviderId))
128 return true
129 }
130 } else if strings.Contains(option.Thumbnail, "myanimelist.net") {
131 matches := malRegex.FindStringSubmatch(option.Thumbnail)
132 if len(matches) > 1 {
133 fileName := matches[1]
134
135 if !fetchedJikan {
136 if anime.MalId == 0 {
137 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
138 }
139 if anime.MalId != 0 {
140 urls, err := FetchJikanPictures(anime.MalId)
141 if err != nil {
142 Log(fmt.Sprintf("Failed to fetch Jikan pictures: %v", err))
143 } else {
144 jikanUrls = urls
145 }
146 }
147 fetchedJikan = true
148 }
149
150 for _, url := range jikanUrls {
151 if strings.HasSuffix(url, "/"+fileName) || strings.Contains(url, fileName) {
152 anime.ProviderId = option.Key
153 Log(fmt.Sprintf("Found MyAnimeList Thumbnail match (%s)! Setting ProviderId to: %s", fileName, anime.ProviderId))
154 return true
155 }
156 }
157 }
158 }
159 }
160
161 if bestMatch, ok := confidentProviderSearchMatch(animeList, anime, userQuery); ok {
162 anime.ProviderId = bestMatch.Key
163 Log(fmt.Sprintf("Found confident provider title match! Setting ProviderId to: %s (%s)", anime.ProviderId, bestMatch.Label))
164 return true
165 }
166
167 if ProviderEnabled("animepahe") && ProviderStackContains(config, "animepahe") {
168 Log("Attempting deep metadata matching and exact AniList meta tag check for Animepahe...")
169
170 targetAnilistID := strconv.Itoa(anime.AnilistId)
171 var bestMatch *SelectionOption
172 var highestScore int
173
174 if anime.MalId == 0 {
175 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
176 }
177
178 var malData *JikanAnimeData
179 if anime.MalId != 0 {
180 malData, _ = FetchJikanAnimeData(anime.MalId)
181 }
182
183 for i := range animeList {
184 opt := &animeList[i]
185 optionProviderName, rawProviderID, ok := ParseProviderQualifiedID(opt.Key)
186 if ok {
187 if optionProviderName != "animepahe" {
188 continue
189 }
190 } else {
191 rawProviderID = opt.Key
192 if configuredProviderNames(config)[0] != "animepahe" {
193 continue
194 }
195 }
196 score := 0
197
198 if malData != nil && opt.ExtraData != nil {
199 if paheData, ok := opt.ExtraData.(animepahe.SearchItem); ok {
200 paheTitleLower := strings.ToLower(paheData.Title)
201 malTitleLower := strings.ToLower(malData.Title)
202 malTitleEngLower := strings.ToLower(malData.TitleEnglish)
203 malTitleJapLower := strings.ToLower(malData.TitleJapanese)
204
205 if paheTitleLower == malTitleLower || (malTitleEngLower != "" && paheTitleLower == malTitleEngLower) || (malTitleJapLower != "" && paheTitleLower == malTitleJapLower) {
206 score += 5
207 } else if strings.Contains(paheTitleLower, malTitleLower) || strings.Contains(malTitleLower, paheTitleLower) ||
208 (malTitleEngLower != "" && (strings.Contains(paheTitleLower, malTitleEngLower) || strings.Contains(malTitleEngLower, paheTitleLower))) {
209 score += 2
210 }
211
212 if paheData.Year > 0 && malData.Year > 0 && paheData.Year == malData.Year {
213 score += 3
214 }
215 if paheData.Season != "" && malData.Season != "" && strings.EqualFold(paheData.Season, malData.Season) {
216 score += 2
217 }
218 if paheData.Type != "" && malData.Type != "" && strings.EqualFold(paheData.Type, malData.Type) {
219 score += 2
220 }
221 if paheData.Episodes > 0 && malData.Episodes > 0 && paheData.Episodes == malData.Episodes {
222 score += 2
223 } else if (paheData.Episodes == 0 && malData.Status == "Currently Airing") || (malData.Episodes == 0 && paheData.Status == "Currently Airing") {
224 score += 2
225 }
226 if strings.EqualFold(paheData.Status, malData.Status) {
227 score += 1
228 }
229 }
230 } else if strings.Contains(strings.ToLower(opt.Title), strings.ToLower(string(userQuery))) {
231 score += 2
232 }
233
234 if score >= 2 || len(animeList) <= 3 {
235 animeRef := animepahe.ParseProviderID(rawProviderID)
236 if animeRef.Session == "" {
237 continue
238 }
239 animeUrl := fmt.Sprintf("https://animepahe.pw/anime/%s", animeRef.Session)
240 Log(fmt.Sprintf("Fetching %s to check exact AniList meta tag...", animeUrl))
241 req, err := animepahe.NewPageRequest(animeUrl)
242 if err != nil {
243 Log(fmt.Sprintf("Failed to build animepahe detail request %s: %v", animeUrl, err))
244 continue
245 }
246
247 resp, err := sharedHTTPClient.Do(req)
248 if err != nil {
249 Log(fmt.Sprintf("Failed to fetch animepahe detail page %s: %v", animeUrl, err))
250 continue
251 }
252 body, readErr := io.ReadAll(resp.Body)
253 resp.Body.Close()
254 if readErr != nil {
255 Log(fmt.Sprintf("Failed to read animepahe detail page %s: %v", animeUrl, readErr))
256 continue
257 }
258 if resp.StatusCode == http.StatusOK {
259 bodyStr := string(body)
260
261 metaTag := fmt.Sprintf(`<meta name="anilist" content="%s">`, targetAnilistID)
262 if strings.Contains(bodyStr, metaTag) {
263 Log(fmt.Sprintf("FOUND EXACT ANILIST META TAG MATCH in %s!", opt.Title))
264 bestMatch = opt
265 highestScore = 100
266 break
267 }
268
269 malMetaTag := fmt.Sprintf(`<meta name="mal" content="%d">`, anime.MalId)
270 if anime.MalId != 0 && strings.Contains(bodyStr, malMetaTag) {
271 Log(fmt.Sprintf("FOUND EXACT MAL META TAG MATCH in %s!", opt.Title))
272 bestMatch = opt
273 highestScore = 100
274 break
275 }
276 }
277 }
278
279 if score > highestScore {
280 highestScore = score
281 bestMatch = opt
282 }
283 }
284
285 if bestMatch != nil && highestScore == 100 {
286 anime.ProviderId = bestMatch.Key
287 Log(fmt.Sprintf("Found EXACT meta tag match! Score: %d. Setting ProviderId to: %s", highestScore, anime.ProviderId))
288 return true
289 }
290 if bestMatch != nil {
291 Log(fmt.Sprintf("Highest match score was %d (needed 100 for Animepahe exact meta tag match). Not selecting automatically to prevent false positives.", highestScore))
292 if confirmProviderMatch(*bestMatch, "Animepahe metadata") {
293 anime.ProviderId = bestMatch.Key
294 Log(fmt.Sprintf("User confirmed Animepahe match. Setting ProviderId to: %s", anime.ProviderId))
295 return true
296 }
297 }
298 }
299
300 if anilistEntry != nil {
301 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, anilistEntry.Media.Episodes)
302 for _, option := range animeList {
303 if fmt.Sprintf("%s (%d episodes)", option.Title, anilistEntry.Media.Episodes) == targetLabel {
304 if confirmProviderMatch(option, "title and episode count") {
305 anime.ProviderId = option.Key
306 Log(fmt.Sprintf("User confirmed exact text match. Setting ProviderId to: %s", anime.ProviderId))
307 return true
308 }
309 break
310 }
311 }
312 Log(fmt.Sprintf("No exact match found for label '%s'. Will require manual selection.", targetLabel))
313 }
314
315 return anime.ProviderId != ""
316}
317
318func promptProviderSearchRecovery(config *CurdConfig, state *providerMappingSearchState, reason string) (action string, err error) {
319 options := []SelectionOption{
320 {Key: "custom", Label: "Search with a different name"},
321 }
322 if next := state.nextProviderLabel(); next != "" {
323 options = append(options, SelectionOption{
324 Key: "next_provider",
325 Label: fmt.Sprintf("Try next provider (%s)", next),
326 })
327 }
328 options = append(options, SelectionOption{Key: "back", Label: "Back to menu"})
329
330 message := reason
331 if message == "" {
332 message = fmt.Sprintf("No results found for '%s' on %s.", state.query, state.currentProviderLabel())
333 }
334 CurdOut(message)
335
336 selected, err := promptSelect(options)
337 if err != nil {
338 return "", err
339 }
340 if selected.Key == "-1" {
341 return "quit", nil
342 }
343 if selected.Key == "-2" {
344 return "back", nil
345 }
346 return selected.Key, nil
347}
348
349func promptProviderMatchRecovery(config *CurdConfig, state *providerMappingSearchState) (action string, err error) {
350 options := []SelectionOption{
351 {Key: "pick", Label: "Pick from search results"},
352 {Key: "custom", Label: "Search with a different name"},
353 }
354 if next := state.nextProviderLabel(); next != "" {
355 options = append(options, SelectionOption{
356 Key: "next_provider",
357 Label: fmt.Sprintf("Try next provider (%s)", next),
358 })
359 }
360 options = append(options, SelectionOption{Key: "back", Label: "Back to menu"})
361
362 CurdOut("We didn't find an automatic provider match.")
363 selected, err := promptSelect(options)
364 if err != nil {
365 return "", err
366 }
367 if selected.Key == "-1" {
368 return "quit", nil
369 }
370 if selected.Key == "-2" {
371 return "back", nil
372 }
373 return selected.Key, nil
374}
375
376func applySelectedProviderMapping(config *CurdConfig, anime *Anime, selected SelectionOption) {
377 anime.ProviderId = selected.Key
378 if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
379 anime.ProviderName = providerName
380 anime.ProviderId = rawProviderID
381 } else {
382 anime.ProviderName = configuredProviderNames(config)[0]
383 }
384}
385
386func promptCustomProviderSearchQuery(config *CurdConfig, currentQuery, hint string) (string, bool, bool, error) {
387 manualQuery, err := promptText(config, hint, true)
388 if err != nil {
389 return "", false, false, err
390 }
391 if manualQuery == "" {
392 manualQuery = currentQuery
393 }
394 return manualQuery, false, false, nil
395}
396
397func ResolveAnimeProviderMapping(config *CurdConfig, anime *Anime, query string, anilistEntry *Entry) (ProviderMappingOutcome, error) {
398 return resolveAnimeProviderMapping(config, anime, query, anilistEntry, ManualProviderSearchEnabled(config))
399}
400
401func resolveAnimeProviderMapping(config *CurdConfig, anime *Anime, query string, anilistEntry *Entry, manualOnly bool) (ProviderMappingOutcome, error) {
402 state := &providerMappingSearchState{
403 query: query,
404 allProviders: configuredProviderNames(config),
405 }
406
407 for {
408 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s, scope: %s", state.query, config.SubOrDub, state.currentProviderLabel()))
409
410 animeList, err := searchAnimeForMapping(config, state, config.SubOrDub)
411 if err != nil {
412 Log(fmt.Sprintf("Provider search failed: %v", err))
413 action, actionErr := promptProviderSearchRecovery(config, state, fmt.Sprintf("Provider search failed for '%s': %v", state.query, err))
414 if actionErr != nil {
415 return ProviderMappingQuit, actionErr
416 }
417 outcome, cont, actionErr := handleProviderMappingAction(config, state, action, query)
418 if actionErr != nil {
419 return ProviderMappingQuit, actionErr
420 }
421 if !cont {
422 return outcome, nil
423 }
424 continue
425 }
426
427 if len(animeList) == 0 {
428 action, actionErr := promptProviderSearchRecovery(config, state, "")
429 if actionErr != nil {
430 return ProviderMappingQuit, actionErr
431 }
432 outcome, cont, actionErr := handleProviderMappingAction(config, state, action, query)
433 if actionErr != nil {
434 return ProviderMappingQuit, actionErr
435 }
436 if !cont {
437 return outcome, nil
438 }
439 continue
440 }
441
442 anime.ProviderId = ""
443 if !manualOnly && autoMatchProviderListing(config, anime, animeList, state.query, anilistEntry) {
444 if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
445 anime.ProviderName = providerName
446 anime.ProviderId = rawProviderID
447 } else {
448 anime.ProviderName = configuredProviderNames(config)[0]
449 }
450 return ProviderMappingOK, nil
451 }
452
453 if manualOnly {
454 for {
455 hint := ManualProviderSearchHint(config, anilistEntry, state.query, config.SubOrDub)
456 selected, selectErr := promptProviderSearchSelectionWithHint(config, animeList, anilistEntry, hint)
457 if selectErr != nil {
458 Log(fmt.Sprintf("Failed to select anime: %v", selectErr))
459 } else {
460 switch selected.Key {
461 case "-1":
462 // fall through to recovery menu
463 case "-2":
464 return ProviderMappingBack, nil
465 default:
466 applySelectedProviderMapping(config, anime, selected)
467 return ProviderMappingOK, nil
468 }
469 }
470
471 action, actionErr := promptProviderMatchRecovery(config, state)
472 if actionErr != nil {
473 return ProviderMappingQuit, actionErr
474 }
475 switch action {
476 case "pick":
477 continue
478 case "custom", "next_provider":
479 outcome, cont, handleErr := handleProviderMappingAction(config, state, action, query)
480 if handleErr != nil {
481 return ProviderMappingQuit, handleErr
482 }
483 if !cont {
484 return outcome, nil
485 }
486 break
487 case "back":
488 return ProviderMappingBack, nil
489 case "quit":
490 return ProviderMappingQuit, nil
491 default:
492 continue
493 }
494 break
495 }
496 continue
497 }
498
499 for {
500 action, actionErr := promptProviderMatchRecovery(config, state)
501 if actionErr != nil {
502 return ProviderMappingQuit, actionErr
503 }
504
505 switch action {
506 case "pick":
507 CurdOut("Select the correct anime from the search results.")
508 selected, selectErr := promptProviderSearchSelection(config, animeList, anilistEntry)
509 if selectErr != nil {
510 Log(fmt.Sprintf("Failed to select anime: %v", selectErr))
511 continue
512 }
513 switch selected.Key {
514 case "-1":
515 continue
516 case "-2":
517 return ProviderMappingBack, nil
518 default:
519 applySelectedProviderMapping(config, anime, selected)
520 return ProviderMappingOK, nil
521 }
522 case "custom", "next_provider":
523 outcome, cont, handleErr := handleProviderMappingAction(config, state, action, query)
524 if handleErr != nil {
525 return ProviderMappingQuit, handleErr
526 }
527 if !cont {
528 return outcome, nil
529 }
530 break
531 case "back":
532 return ProviderMappingBack, nil
533 case "quit":
534 return ProviderMappingQuit, nil
535 default:
536 continue
537 }
538 break
539 }
540 }
541}
542
543func RemapProviderAnime(userCurdConfig *CurdConfig, user *User, databaseAnimes *[]Anime) {
544 if userCurdConfig == nil || user == nil {
545 return
546 }
547
548 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
549 Log(fmt.Sprintf("Failed to refresh anime list before provider remap: %v", err))
550 }
551
552 if user.ListSync != nil {
553 user.AnimeList = user.ListSync.Current()
554 }
555
556 options := buildCategorySelectionOptions(user.AnimeList, "ALL")
557 if len(options) == 0 {
558 CurdOut("No anime found in your lists.")
559 return
560 }
561
562 var selected SelectionOption
563 var err error
564 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
565 preview := buildCategoryPreviewOptions(user.AnimeList, "ALL")
566 selected, err = DynamicSelectPreview(preview, false)
567 } else {
568 selected, err = DynamicSelect(options)
569 }
570 if err != nil {
571 Log(fmt.Sprintf("Failed to select anime for provider remap: %v", err))
572 return
573 }
574 if selected.Key == "-1" || selected.Key == "-2" {
575 return
576 }
577
578 anilistEntry, err := FindAnimeByAnilistID(user.AnimeList, selected.Key)
579 if err != nil {
580 Log(fmt.Sprintf("Failed to resolve selected anime: %v", err))
581 CurdOut("Could not find the selected anime in your lists.")
582 return
583 }
584
585 historyPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_history.txt")
586 if databaseAnimes != nil {
587 if existing := LocalFindAnime(*databaseAnimes, anilistEntry.Media.ID, ""); existing != nil {
588 CurdOut(fmt.Sprintf("Current provider mapping: %s (%s)", CurrentAnimeProviderName(existing), existing.ProviderId))
589 } else {
590 CurdOut("No saved provider mapping in local history yet.")
591 }
592 }
593
594 query := mediaDisplayTitle(anilistEntry.Media, userCurdConfig)
595 anime := Anime{
596 AnilistId: anilistEntry.Media.ID,
597 MalId: anilistEntry.Media.MalID,
598 Title: anilistEntry.Media.Title,
599 TotalEpisodes: anilistEntry.Media.Episodes,
600 CoverImage: anilistEntry.CoverImage,
601 }
602
603 outcome, mappingErr := resolveAnimeProviderMapping(userCurdConfig, &anime, query, anilistEntry, true)
604 if mappingErr != nil {
605 Log(fmt.Sprintf("Provider remap failed: %v", mappingErr))
606 CurdOut("Failed to update provider mapping.")
607 return
608 }
609 switch outcome {
610 case ProviderMappingBack, ProviderMappingQuit:
611 return
612 case ProviderMappingOK:
613 if err := persistRemappedProvider(historyPath, databaseAnimes, anilistEntry, &anime, query); err != nil {
614 Log(fmt.Sprintf("Failed to save remapped provider: %v", err))
615 CurdOut("Provider selected, but failed to save mapping to local history.")
616 return
617 }
618 CurdOut(fmt.Sprintf("Updated provider mapping to %s (%s).", anime.ProviderName, anime.ProviderId))
619 }
620}
621
622func persistRemappedProvider(historyPath string, databaseAnimes *[]Anime, anilistEntry *Entry, anime *Anime, animeName string) error {
623 if anime == nil || anilistEntry == nil {
624 return fmt.Errorf("missing anime data")
625 }
626
627 episode := 1
628 playbackTime := 0
629 duration := 0
630 if databaseAnimes != nil {
631 if existing := LocalFindAnime(*databaseAnimes, anime.AnilistId, ""); existing != nil {
632 episode = existing.Ep.Number
633 playbackTime = existing.Ep.Player.PlaybackTime
634 duration = existing.Ep.Duration
635 if savedName := GetAnimeName(*existing); savedName != "" {
636 animeName = savedName
637 }
638 }
639 }
640 if episode <= 0 {
641 episode = nextEpisodeFromProgress(anilistEntry.Progress)
642 if episode <= 0 {
643 episode = 1
644 }
645 }
646
647 if err := LocalRemapAnimeProvider(historyPath, anime.AnilistId, anime.ProviderName, anime.ProviderId, animeName, episode, playbackTime, duration); err != nil {
648 return err
649 }
650 if databaseAnimes != nil {
651 *databaseAnimes = LocalGetAllAnime(historyPath)
652 }
653 return nil
654}
655
656func handleProviderMappingAction(config *CurdConfig, state *providerMappingSearchState, action, defaultQuery string) (ProviderMappingOutcome, bool, error) {
657 switch action {
658 case "custom":
659 hint := fmt.Sprintf("Enter a search name for configured providers (current: '%s').", state.query)
660 newQuery, _, _, err := promptCustomProviderSearchQuery(config, state.query, hint)
661 if err != nil {
662 return ProviderMappingQuit, false, err
663 }
664 state.query = newQuery
665 state.resetToAllProviders()
666 return ProviderMappingOK, true, nil
667 case "next_provider":
668 if !state.advanceToNextProvider() {
669 CurdOut("No more providers left to try.")
670 action, err := promptProviderSearchRecovery(config, state, "No more providers left to try.")
671 if err != nil {
672 return ProviderMappingQuit, false, err
673 }
674 return handleProviderMappingAction(config, state, action, defaultQuery)
675 }
676 return ProviderMappingOK, true, nil
677 case "back":
678 return ProviderMappingBack, false, nil
679 case "quit":
680 return ProviderMappingQuit, false, nil
681 default:
682 return ProviderMappingOK, true, nil
683 }
684}
685
686func untrackedProviderSearchSelection(config *CurdConfig, query string, animeList []SelectionOption) (SelectionOption, error) {
687 if ManualProviderSearchEnabled(config) {
688 hint := ManualProviderSearchHint(config, nil, query, config.SubOrDub)
689 return promptProviderSearchSelectionWithHint(config, animeList, nil, hint)
690 }
691 return promptProviderSearchSelection(config, animeList, nil)
692}
693
694func RemapAnimeProviderOnEpisodeFailure(config *CurdConfig, anime *Anime, anilistEntry *Entry) bool {
695 query := GetAnimeName(*anime)
696 if query == "" {
697 query = anime.Title.Romaji
698 }
699 if query == "" {
700 query = anime.Title.English
701 }
702 if query == "" {
703 return false
704 }
705
706 CurdOut("Could not get an episode link with the current provider mapping.")
707 anime.ProviderId = ""
708 anime.ProviderName = ""
709 anime.Ep.NextEpisode = NextEpisode{}
710
711 outcome, err := ResolveAnimeProviderMapping(config, anime, query, anilistEntry)
712 if err != nil {
713 Log(fmt.Sprintf("Provider remap failed: %v", err))
714 return false
715 }
716 return outcome == ProviderMappingOK
717}
718
719func promptEpisodeLinkFailureRecovery(config *CurdConfig) string {
720 selected, err := promptSelect([]SelectionOption{
721 {Key: "remap", Label: "Search providers again"},
722 {Key: "episode", Label: "Try a different episode number"},
723 {Key: "quit", Label: "Cancel playback"},
724 })
725 if err != nil {
726 return "quit"
727 }
728 if selected.Key == "-1" || selected.Key == "-2" {
729 return "quit"
730 }
731 return selected.Key
732}
733
734func ResolveUntrackedProviderSearch(config *CurdConfig, initialQuery string) (providerID, providerName string, back bool, err error) {
735 state := &providerMappingSearchState{
736 query: initialQuery,
737 allProviders: configuredProviderNames(config),
738 }
739
740 for {
741 animeList, searchErr := searchAnimeForMapping(config, state, config.SubOrDub)
742 if searchErr != nil {
743 Log(fmt.Sprintf("Provider search failed: %v", searchErr))
744 action, actionErr := promptProviderSearchRecovery(config, state, fmt.Sprintf("Provider search failed for '%s': %v", state.query, searchErr))
745 if actionErr != nil {
746 return "", "", false, actionErr
747 }
748 if action == "back" {
749 return "", "", true, nil
750 }
751 if action == "quit" {
752 return "", "", false, nil
753 }
754 _, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
755 if handleErr != nil {
756 return "", "", false, handleErr
757 }
758 if !cont {
759 return "", "", false, nil
760 }
761 continue
762 }
763
764 if len(animeList) == 0 {
765 action, actionErr := promptProviderSearchRecovery(config, state, "")
766 if actionErr != nil {
767 return "", "", false, actionErr
768 }
769 if action == "back" {
770 return "", "", true, nil
771 }
772 if action == "quit" {
773 return "", "", false, nil
774 }
775 _, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
776 if handleErr != nil {
777 return "", "", false, handleErr
778 }
779 if !cont {
780 return "", "", false, nil
781 }
782 continue
783 }
784
785 selected, selectErr := untrackedProviderSearchSelection(config, state.query, animeList)
786 if selectErr != nil {
787 Log(fmt.Sprintf("Failed to select anime: %v", selectErr))
788 action, actionErr := promptProviderMatchRecovery(config, state)
789 if actionErr != nil {
790 return "", "", false, actionErr
791 }
792 if action == "back" {
793 return "", "", true, nil
794 }
795 if action == "quit" {
796 return "", "", false, nil
797 }
798 _, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
799 if handleErr != nil {
800 return "", "", false, handleErr
801 }
802 if !cont {
803 return "", "", false, nil
804 }
805 continue
806 }
807
808 switch selected.Key {
809 case "-1":
810 action, actionErr := promptProviderMatchRecovery(config, state)
811 if actionErr != nil {
812 return "", "", false, actionErr
813 }
814 if action == "back" {
815 return "", "", true, nil
816 }
817 if action == "quit" {
818 return "", "", false, nil
819 }
820 _, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
821 if handleErr != nil {
822 return "", "", false, handleErr
823 }
824 if !cont {
825 return "", "", false, nil
826 }
827 continue
828 case "-2":
829 return "", "", true, nil
830 default:
831 if name, rawID, ok := ParseProviderQualifiedID(selected.Key); ok {
832 return rawID, name, false, nil
833 }
834 return selected.Key, configuredProviderNames(config)[0], false, nil
835 }
836 }
837}
internal/selection_labels.go added +199
@@ -0,0 +1,199 @@
1package internal
2
3import (
4 "fmt"
5 "regexp"
6 "strconv"
7 "strings"
8
9 "github.com/wraient/curd/internal/providers/animepahe"
10)
11
12var selectionEpisodeCountRE = regexp.MustCompile(`\((\d+)\s+episodes?\)`)
13
14func FormatAnimeSearchLabel(title string, episodes int) string {
15 title = strings.TrimSpace(title)
16 if title == "" {
17 return ""
18 }
19 if episodes > 0 {
20 return fmt.Sprintf("%s (%d episodes)", title, episodes)
21 }
22 return title
23}
24
25func TrackerEpisodeHint(config *CurdConfig, entry *Entry) string {
26 if entry == nil || entry.Media.Episodes <= 0 {
27 return ""
28 }
29 tracker := RemoteTrackingDisplayName(config)
30 title := mediaDisplayTitle(entry.Media, config)
31 if title == "" {
32 return fmt.Sprintf("Your %s entry has %d episodes — pick the matching title below.", tracker, entry.Media.Episodes)
33 }
34 return fmt.Sprintf("Your %s entry for %q has %d episodes — pick the matching title below.", tracker, title, entry.Media.Episodes)
35}
36
37func episodeCountFromSelectionOption(option SelectionOption) (int, bool) {
38 for _, source := range []string{option.Label, option.Title} {
39 if source == "" {
40 continue
41 }
42 if matches := selectionEpisodeCountRE.FindStringSubmatch(source); len(matches) > 1 {
43 if count, err := strconv.Atoi(matches[1]); err == nil && count > 0 {
44 return count, true
45 }
46 }
47 }
48
49 if option.ExtraData != nil {
50 if item, ok := option.ExtraData.(animepahe.SearchItem); ok && item.Episodes > 0 {
51 return item.Episodes, true
52 }
53 }
54
55 return 0, false
56}
57
58func selectionOptionBaseTitle(option SelectionOption) string {
59 if option.Title != "" {
60 return strings.TrimSpace(option.Title)
61 }
62
63 label := strings.TrimSpace(option.Label)
64 if label == "" {
65 return ""
66 }
67 if idx := strings.Index(label, " ("); idx > 0 {
68 return strings.TrimSpace(label[:idx])
69 }
70 if idx := strings.Index(label, " — "); idx > 0 {
71 return strings.TrimSpace(label[:idx])
72 }
73 if idx := strings.Index(label, " ["); idx > 0 {
74 return strings.TrimSpace(label[:idx])
75 }
76 return label
77}
78
79func ensureEpisodeCountInLabel(option SelectionOption) SelectionOption {
80 if selectionEpisodeCountRE.MatchString(option.Label) {
81 return option
82 }
83
84 count, ok := episodeCountFromSelectionOption(option)
85 if !ok || count <= 0 {
86 return option
87 }
88
89 baseTitle := selectionOptionBaseTitle(option)
90 if baseTitle == "" {
91 return option
92 }
93
94 providerSuffix := ""
95 if idx := strings.LastIndex(option.Label, " ["); idx > 0 && strings.HasSuffix(option.Label, "]") {
96 providerSuffix = option.Label[idx:]
97 }
98
99 option.Label = FormatAnimeSearchLabel(baseTitle, count) + providerSuffix
100 if option.Title == "" {
101 option.Title = baseTitle
102 }
103 return option
104}
105
106func ProviderSearchOptionsForDisplay(options []SelectionOption, entry *Entry) []SelectionOption {
107 if len(options) == 0 {
108 return options
109 }
110
111 targetEpisodes := 0
112 if entry != nil {
113 targetEpisodes = entry.Media.Episodes
114 }
115
116 display := make([]SelectionOption, len(options))
117 for i, option := range options {
118 display[i] = ensureEpisodeCountInLabel(option)
119 if targetEpisodes <= 0 {
120 continue
121 }
122 if count, ok := episodeCountFromSelectionOption(display[i]); ok && count == targetEpisodes {
123 display[i].Label = display[i].Label + " ✓"
124 }
125 }
126 return display
127}
128
129func ManualProviderSearchEnabled(config *CurdConfig) bool {
130 return config != nil && config.ManualProviderSearch
131}
132
133func displayMediaFormat(format string) string {
134 format = strings.TrimSpace(strings.ToUpper(format))
135 switch format {
136 case "TV":
137 return "TV"
138 case "TV_SHORT":
139 return "TV Short"
140 case "MOVIE":
141 return "Movie"
142 case "OVA":
143 return "OVA"
144 case "ONA":
145 return "ONA"
146 case "SPECIAL":
147 return "Special"
148 case "MUSIC":
149 return "Music"
150 default:
151 return strings.ReplaceAll(format, "_", " ")
152 }
153}
154
155func formatEpisodeCountHint(episodes int) string {
156 if episodes > 0 {
157 return fmt.Sprintf("%d episodes", episodes)
158 }
159 return "unknown episode count"
160}
161
162func ManualProviderSearchHint(config *CurdConfig, entry *Entry, query, subOrDub string) string {
163 title := strings.TrimSpace(query)
164 mediaType := ""
165 episodes := 0
166
167 if entry != nil {
168 if trackerTitle := mediaDisplayTitle(entry.Media, config); trackerTitle != "" {
169 title = trackerTitle
170 }
171 mediaType = displayMediaFormat(entry.Media.Format)
172 episodes = entry.Media.Episodes
173 }
174 if title == "" {
175 title = "unknown title"
176 }
177
178 mode := strings.ToLower(normalizeTranslationType(subOrDub))
179 parts := []string{fmt.Sprintf("Searching for %q", title)}
180 if mediaType != "" {
181 parts = append(parts, mediaType)
182 }
183 parts = append(parts, formatEpisodeCountHint(episodes))
184 if mode != "" {
185 parts = append(parts, mode)
186 }
187 return strings.Join(parts, " · ") + " — select the matching provider entry below."
188}
189
190func promptProviderSearchSelectionWithHint(config *CurdConfig, options []SelectionOption, entry *Entry, hint string) (SelectionOption, error) {
191 if strings.TrimSpace(hint) != "" {
192 CurdOut(hint)
193 }
194 return DynamicSelect(ProviderSearchOptionsForDisplay(options, entry))
195}
196
197func promptProviderSearchSelection(config *CurdConfig, options []SelectionOption, entry *Entry) (SelectionOption, error) {
198 return promptProviderSearchSelectionWithHint(config, options, entry, TrackerEpisodeHint(config, entry))
199}
internal/selection_labels_test.go added +75
@@ -0,0 +1,75 @@
1package internal
2
3import (
4 "strings"
5 "testing"
6
7 "github.com/wraient/curd/internal/providers/animepahe"
8)
9
10func TestFormatAnimeSearchLabel(t *testing.T) {
11 if got := FormatAnimeSearchLabel("Frieren", 28); got != "Frieren (28 episodes)" {
12 t.Fatalf("unexpected label: %q", got)
13 }
14 if got := FormatAnimeSearchLabel("Airing Show", 0); got != "Airing Show" {
15 t.Fatalf("unexpected label without episodes: %q", got)
16 }
17}
18
19func TestProviderSearchOptionsForDisplayMarksEpisodeMatch(t *testing.T) {
20 options := []SelectionOption{
21 {Key: "a", Label: "One Piece (1090 episodes) [allanime]", Title: "One Piece"},
22 {Key: "b", Label: "One Pace (300 episodes) [anineko]", Title: "One Pace"},
23 }
24 entry := &Entry{Media: Media{Episodes: 1090}}
25
26 display := ProviderSearchOptionsForDisplay(options, entry)
27 if display[0].Label != "One Piece (1090 episodes) [allanime] ✓" {
28 t.Fatalf("expected match marker on first option, got %q", display[0].Label)
29 }
30 if display[1].Label != "One Pace (300 episodes) [anineko]" {
31 t.Fatalf("expected unchanged second option, got %q", display[1].Label)
32 }
33}
34
35func TestManualProviderSearchHint(t *testing.T) {
36 entry := &Entry{
37 Media: Media{
38 Format: "TV",
39 Episodes: 24,
40 Title: AnimeTitle{
41 Romaji: "Frieren",
42 },
43 },
44 }
45 hint := ManualProviderSearchHint(&CurdConfig{SubOrDub: "sub"}, entry, "frieren", "sub")
46 if !strings.Contains(hint, `Searching for "Frieren"`) {
47 t.Fatalf("unexpected hint: %q", hint)
48 }
49 if !strings.Contains(hint, "TV") || !strings.Contains(hint, "24 episodes") || !strings.Contains(hint, "sub") {
50 t.Fatalf("expected type, episode count, and mode in hint: %q", hint)
51 }
52}
53
54func TestManualProviderSearchEnabled(t *testing.T) {
55 if ManualProviderSearchEnabled(&CurdConfig{ManualProviderSearch: true}) != true {
56 t.Fatal("expected manual provider search to be enabled")
57 }
58 if ManualProviderSearchEnabled(&CurdConfig{}) != false {
59 t.Fatal("expected manual provider search to be disabled by default")
60 }
61}
62
63func TestEnsureEpisodeCountInLabelUsesExtraData(t *testing.T) {
64 option := SelectionOption{
65 Key: "session",
66 Label: "Frieren [animepahe]",
67 Title: "Frieren",
68 ExtraData: animepahe.SearchItem{Title: "Frieren", Episodes: 28},
69 }
70
71 display := ensureEpisodeCountInLabel(option)
72 if display.Label != "Frieren (28 episodes) [animepahe]" {
73 t.Fatalf("unexpected label: %q", display.Label)
74 }
75}
internal/tracking.go +1 −1
@@ -70,7 +70,7 @@ func UsesDualRemoteTracking(config *CurdConfig) bool {
70 70
71func trackingCategoryEnabled(config *CurdConfig, key string) bool { 71func trackingCategoryEnabled(config *CurdConfig, key string) bool {
72 switch key { 72 switch key {
73 case "CURRENT", "ALL", "UNTRACKED", "CONTINUE_LAST", "PROVIDER": 73 case "CURRENT", "ALL", "UNTRACKED", "CONTINUE_LAST", "REMAP_PROVIDER", "PROVIDER":
74 return true 74 return true
75 case "UPDATE", "PLANNING", "COMPLETED", "PAUSED", "DROPPED", "REWATCHING": 75 case "UPDATE", "PLANNING", "COMPLETED", "PAUSED", "DROPPED", "REWATCHING":
76 return UsesRemoteTracking(config) 76 return UsesRemoteTracking(config)