Commit 5a96f87c35

5a96f87c3545079b1a58a7c89d750f42e3810729

parent: 22fcf0fd56

Unregistered key

Rushikesh Gaikwad <81632222+Wraient@users.noreply.github.com> · 2026-05-26 15:10 UTC
committer: <noreply@github.com>

Refactor: selection menu and improve input validation and error handling (#97)

* Remove hard-coded anime selection
* Require explicit audio fallback
* Ask before replaying completed anime
* Preview tracker sync changes
* Shorten progress conflict prompt
* Confirm guessed provider matches
* Offer actions for unreleased anime

* Let users choose sequel actions

* Track MAL import dismissal
* Add intent regression coverage
* Refactor selection menu and tracking logic; improve error handling and input validation

- Update selection menu to handle Ctrl+C for quitting and ensure safe handling of empty selections.
- Enhance visible items count calculation to prevent negative values.
- Improve sorting of home menu options with nil config checks.
- Add validation for empty image URLs in download cache function.
- Refactor anime score input handling to include validation for score range.
- Introduce utility functions for reading and parsing user input.
- Implement tests for new input validation and provider functionality.
- Add tests for MyAnimeList token management and Animepahe provider interactions.
- Ensure proper handling of DDoS challenges in Animepahe episode retrieval.

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.4.0 3AppVersion=1.5.1
4DefaultDirName={userappdata}\Curd 4DefaultDirName={userappdata}\Curd
5PrivilegesRequired=lowest 5PrivilegesRequired=lowest
6AllowNoIcons=yes 6AllowNoIcons=yes
cmd/curd/main.go +56 −55
@@ -217,6 +217,9 @@ func main() {
217 } 217 }
218 218
219 anime.Ep.Player.Speed = 1.0 219 anime.Ep.Player.Speed = 1.0
220 if userCurdConfig.DiscordPresence {
221 internal.CurdOut("Starting Discord broadcast.")
222 }
220 223
221 // Get filler list concurrently 224 // Get filler list concurrently
222 go func() { 225 go func() {
@@ -270,9 +273,8 @@ func main() {
270 // Start curd (loop while episode is playing) 273 // Start curd (loop while episode is playing)
271 for { 274 for {
272 // Check if current episode is filler/recap 275 // Check if current episode is filler/recap
273 err = internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime) 276 if episodeErr := internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime); episodeErr != nil {
274 if err != nil { 277 internal.Log("Error getting episode data, assuming non-filler: " + episodeErr.Error())
275 internal.Log("Error getting episode data, assuming non-filler: " + err.Error())
276 break // Break the loop and continue with playback 278 break // Break the loop and continue with playback
277 } 279 }
278 280
@@ -302,7 +304,7 @@ func main() {
302 internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, internal.GetAnimeName(anime), internal.GetProvider().Name()) 304 internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, internal.GetAnimeName(anime), internal.GetProvider().Name())
303 305
304 // Check if we've reached the end of the series 306 // Check if we've reached the end of the series
305 if anime.Ep.Number > anime.TotalEpisodes { 307 if anime.TotalEpisodes > 0 && anime.Ep.Number > anime.TotalEpisodes {
306 internal.CurdOut("Reached end of series") 308 internal.CurdOut("Reached end of series")
307 internal.ExitCurd(nil) 309 internal.ExitCurd(nil)
308 } 310 }
@@ -353,9 +355,8 @@ func main() {
353 // Get episode data 355 // Get episode data
354 go func() { 356 go func() {
355 defer wg.Done() 357 defer wg.Done()
356 err = internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime) 358 if episodeErr := internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime); episodeErr != nil {
357 if err != nil { 359 internal.Log("Error getting episode data: " + episodeErr.Error())
358 internal.Log("Error getting episode data: " + err.Error())
359 } else { 360 } else {
360 internal.Log(anime) 361 internal.Log(anime)
361 362
@@ -434,7 +435,11 @@ func main() {
434 } 435 }
435 } 436 }
436 437
437 currentPauseState := isPaused.(bool) 438 currentPauseState, ok := isPaused.(bool)
439 if !ok {
440 internal.Log(fmt.Sprintf("Error: pause state is not a bool (%T)", isPaused))
441 currentPauseState = true
442 }
438 443
439 // Simple seek detection: position gap > 5 seconds 444 // Simple seek detection: position gap > 5 seconds
440 hasSeekEvent := false 445 hasSeekEvent := false
@@ -483,14 +488,15 @@ func main() {
483 } 488 }
484 489
485 // Force update on seek events to bypass Discord's internal filtering 490 // Force update on seek events to bypass Discord's internal filtering
491 var presenceErr error
486 if hasSeekEvent { 492 if hasSeekEvent {
487 err = internal.DiscordPresenceWithForce(anime, currentPauseState, currentPos, totalDuration, userCurdConfig.DiscordClientId, true) 493 presenceErr = internal.DiscordPresenceWithForce(anime, currentPauseState, currentPos, totalDuration, userCurdConfig.DiscordClientId, true)
488 } else { 494 } else {
489 err = internal.DiscordPresence(anime, currentPauseState, currentPos, totalDuration, userCurdConfig.DiscordClientId) 495 presenceErr = internal.DiscordPresence(anime, currentPauseState, currentPos, totalDuration, userCurdConfig.DiscordClientId)
490 } 496 }
491 497
492 if err != nil { 498 if presenceErr != nil {
493 internal.Log("Error setting Discord presence: " + err.Error()) 499 internal.Log("Error setting Discord presence: " + presenceErr.Error())
494 } 500 }
495 501
496 lastKnownPauseState = currentPauseState 502 lastKnownPauseState = currentPauseState
@@ -508,9 +514,8 @@ func main() {
508 514
509 // Get skip times Parallel 515 // Get skip times Parallel
510 go func() { 516 go func() {
511 err = internal.GetAndParseAniSkipData(anime.MalId, anime.Ep.Number, 1, &anime) 517 if skipErr := internal.GetAndParseAniSkipData(anime.MalId, anime.Ep.Number, 1, &anime); skipErr != nil {
512 if err != nil { 518 internal.Log("Error getting and parsing AniSkip data: " + skipErr.Error())
513 internal.Log("Error getting and parsing AniSkip data: " + err.Error())
514 } 519 }
515 internal.Log(anime.Ep.SkipTimes) 520 internal.Log(anime.Ep.SkipTimes)
516 }() 521 }()
@@ -540,12 +545,15 @@ func main() {
540 } 545 }
541 pauseState := false 546 pauseState := false
542 if isPaused != nil { 547 if isPaused != nil {
543 pauseState = isPaused.(bool) 548 if value, ok := isPaused.(bool); ok {
549 pauseState = value
550 } else {
551 internal.Log(fmt.Sprintf("Error: pause state is not a bool (%T)", isPaused))
552 }
544 } 553 }
545 internal.Log("Initializing Discord presence with real video duration") 554 internal.Log("Initializing Discord presence with real video duration")
546 err = internal.DiscordPresence(anime, pauseState, currentPos, anime.Ep.Duration, userCurdConfig.DiscordClientId) 555 if presenceErr := internal.DiscordPresence(anime, pauseState, currentPos, anime.Ep.Duration, userCurdConfig.DiscordClientId); presenceErr != nil {
547 if err != nil { 556 internal.Log("Discord presence error: " + presenceErr.Error())
548 internal.Log("Discord presence error: " + err.Error())
549 } 557 }
550 } 558 }
551 } else { 559 } else {
@@ -633,9 +641,8 @@ func main() {
633 641
634 // Update Anilist progress if not rewatching 642 // Update Anilist progress if not rewatching
635 if !anime.Rewatching { 643 if !anime.Rewatching {
636 err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number) 644 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil {
637 if err != nil { 645 internal.Log("Error updating Anilist progress on quit: " + progressErr.Error())
638 internal.Log("Error updating Anilist progress on quit: " + err.Error())
639 } else { 646 } else {
640 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number)) 647 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
641 } 648 }
@@ -684,16 +691,14 @@ func main() {
684 // Set the playback speed 691 // Set the playback speed
685 if userCurdConfig.SaveMpvSpeed { 692 if userCurdConfig.SaveMpvSpeed {
686 speedCmd := []interface{}{"set_property", "speed", anime.Ep.Player.Speed} 693 speedCmd := []interface{}{"set_property", "speed", anime.Ep.Player.Speed}
687 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, speedCmd) 694 if _, speedErr := internal.MPVSendCommand(anime.Ep.Player.SocketPath, speedCmd); speedErr != nil {
688 if err != nil { 695 internal.Log("Error setting playback speed: " + speedErr.Error())
689 internal.Log("Error setting playback speed: " + err.Error())
690 } 696 }
691 } 697 }
692 698
693 // Apply OP/ED Chapters 699 // Apply OP/ED Chapters
694 err = internal.SendSkipTimesToMPV(&anime) 700 if skipErr := internal.SendSkipTimesToMPV(&anime); skipErr != nil {
695 if err != nil { 701 internal.Log("Error sending skip times to MPV: " + skipErr.Error())
696 internal.Log("Error sending skip times to MPV: " + err.Error())
697 } 702 }
698 } 703 }
699 704
@@ -711,9 +716,8 @@ func main() {
711 716
712 anime.Ep.Player.PlaybackTime = int(animePosition + 0.5) // Round to nearest integer 717 anime.Ep.Player.PlaybackTime = int(animePosition + 0.5) // Round to nearest integer
713 // Update Local Database 718 // Update Local Database
714 err = internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime), internal.GetProvider().Name()) 719 if updateErr := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime), internal.GetProvider().Name()); updateErr != nil {
715 if err != nil { 720 internal.Log("Error updating local database: " + updateErr.Error())
716 internal.Log("Error updating local database: " + err.Error())
717 } 721 }
718 } 722 }
719 723
@@ -761,9 +765,8 @@ func main() {
761 765
762 // Update Anilist progress if not rewatching 766 // Update Anilist progress if not rewatching
763 if !anime.Rewatching { 767 if !anime.Rewatching {
764 err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number) 768 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil {
765 if err != nil { 769 internal.Log("Error updating Anilist progress on quit: " + progressErr.Error())
766 internal.Log("Error updating Anilist progress on quit: " + err.Error())
767 } else { 770 } else {
768 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number)) 771 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
769 } 772 }
@@ -781,9 +784,8 @@ func main() {
781 784
782 // Update Anilist progress if not rewatching 785 // Update Anilist progress if not rewatching
783 if !anime.Rewatching { 786 if !anime.Rewatching {
784 err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number) 787 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil {
785 if err != nil { 788 internal.Log("Error updating Anilist progress on completion: " + progressErr.Error())
786 internal.Log("Error updating Anilist progress on completion: " + err.Error())
787 } else { 789 } else {
788 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number)) 790 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
789 } 791 }
@@ -843,11 +845,12 @@ func main() {
843 internal.SeekMPV(anime.Ep.Player.SocketPath, anime.Ep.SkipTimes.Ed.End) 845 internal.SeekMPV(anime.Ep.Player.SocketPath, anime.Ep.SkipTimes.Ed.End)
844 } 846 }
845 } 847 }
846 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"}) 848 if _, positionErr := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"}); positionErr == nil && anime.Ep.Started {
847 if err == nil && anime.Ep.Started { 849 speed, speedErr := internal.GetMPVPlaybackSpeed(anime.Ep.Player.SocketPath)
848 anime.Ep.Player.Speed, err = internal.GetMPVPlaybackSpeed(anime.Ep.Player.SocketPath) 850 if speedErr != nil {
849 if err != nil { 851 internal.Log("Failed to get mpv speed " + speedErr.Error())
850 internal.Log("Failed to get mpv speed " + err.Error()) 852 } else {
853 anime.Ep.Player.Speed = speed
851 } 854 }
852 } 855 }
853 } 856 }
@@ -870,22 +873,21 @@ func main() {
870 if anime.Ep.IsCompleted && !anime.Rewatching { 873 if anime.Ep.IsCompleted && !anime.Rewatching {
871 // Update progress for both regular episodes and skipped fillers 874 // Update progress for both regular episodes and skipped fillers
872 if anime.TotalEpisodes > 0 && anime.Ep.Number-1 != anime.TotalEpisodes { 875 if anime.TotalEpisodes > 0 && anime.Ep.Number-1 != anime.TotalEpisodes {
873 go func() { 876 progressEpisode := anime.Ep.Number - 1
877 go func(episode int) {
874 // Update progress for regular episodes 878 // Update progress for regular episodes
875 err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number-1) 879 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, episode); progressErr != nil {
876 if err != nil { 880 internal.Log("Error updating Anilist progress: " + progressErr.Error())
877 internal.Log("Error updating Anilist progress: " + err.Error())
878 } 881 }
879 }() 882 }(progressEpisode)
880 } else { 883 } else {
881 // Update progress for last episode 884 // Update progress for last episode
882 885
883 // Exit MPV 886 // Exit MPV
884 internal.ExitMPV(anime.Ep.Player.SocketPath) 887 internal.ExitMPV(anime.Ep.Player.SocketPath)
885 888
886 err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number-1) 889 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number-1); progressErr != nil {
887 if err != nil { 890 internal.Log("Error updating Anilist progress: " + progressErr.Error())
888 internal.Log("Error updating Anilist progress: " + err.Error())
889 } 891 }
890 } 892 }
891 893
@@ -901,10 +903,9 @@ func main() {
901 } else if !updatedAnime.IsAiring { 903 } else if !updatedAnime.IsAiring {
902 anime.Ep.Number = anime.Ep.Number - 1 904 anime.Ep.Number = anime.Ep.Number - 1
903 internal.CurdOut("Completed anime.") 905 internal.CurdOut("Completed anime.")
904 err = internal.RateAnime(user.Token, anime.AnilistId) 906 if rateErr := internal.RateAnime(user.Token, anime.AnilistId); rateErr != nil {
905 if err != nil { 907 internal.Log("Error rating anime: " + rateErr.Error())
906 internal.Log("Error rating anime: " + err.Error()) 908 internal.CurdOut("Error rating anime: " + rateErr.Error())
907 internal.CurdOut("Error rating anime: " + err.Error())
908 } 909 }
909 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.ProviderId) 910 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.ProviderId)
910 internal.ExitCurd(nil) 911 internal.ExitCurd(nil)
@@ -946,7 +947,7 @@ func main() {
946 947
947 // If we still don't have links, get them now 948 // If we still don't have links, get them now
948 if len(anime.Ep.Links) == 0 { 949 if len(anime.Ep.Links) == 0 {
949 links, err := internal.GetEpisodeURL(userCurdConfig, anime.ProviderId, anime.Ep.Number) 950 links, _, err := internal.GetEpisodeURLForPlayback(userCurdConfig, anime.ProviderId, anime.Ep.Number)
950 if err != nil { 951 if err != nil {
951 internal.Log("Failed to get episode links: " + err.Error()) 952 internal.Log("Failed to get episode links: " + err.Error())
952 internal.CurdOut("Failed to get episode links. Try again later.") 953 internal.CurdOut("Failed to get episode links. Try again later.")
go.mod +1 −1
@@ -7,6 +7,7 @@ require (
7 github.com/charmbracelet/bubbletea v1.3.3 7 github.com/charmbracelet/bubbletea v1.3.3
8 github.com/charmbracelet/lipgloss v1.0.0 8 github.com/charmbracelet/lipgloss v1.0.0
9 github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4 9 github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4
10 github.com/go-rod/rod v0.116.2
10 github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c 11 github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c
11 github.com/tr1xem/go-discordrpc v1.0.0 12 github.com/tr1xem/go-discordrpc v1.0.0
12) 13)
@@ -16,7 +17,6 @@ require (
16 github.com/charmbracelet/x/ansi v0.8.0 // indirect 17 github.com/charmbracelet/x/ansi v0.8.0 // indirect
17 github.com/charmbracelet/x/term v0.2.1 // indirect 18 github.com/charmbracelet/x/term v0.2.1 // indirect
18 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect 19 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
19 github.com/go-rod/rod v0.116.2 // indirect
20 github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect 20 github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect
21 github.com/godbus/dbus/v5 v5.1.0 // indirect 21 github.com/godbus/dbus/v5 v5.1.0 // indirect
22 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect 22 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
internal/anilist.go +171 −50
@@ -24,6 +24,25 @@ func FindKeyByValue(m map[string]string, value string) (string, error) {
24 return "", fmt.Errorf("no key with value %v", value) // Return empty string and false if the value is not found 24 return "", fmt.Errorf("no key with value %v", value) // Return empty string and false if the value is not found
25} 25}
26 26
27func mediaDisplayTitle(media Media, config *CurdConfig) string {
28 if media.Title.English != "" && useEnglishAnimeNames(config) {
29 return media.Title.English
30 }
31 if media.Title.Romaji != "" {
32 return media.Title.Romaji
33 }
34 if media.Title.English != "" {
35 return media.Title.English
36 }
37 if media.Title.Japanese != "" {
38 return media.Title.Japanese
39 }
40 if media.ID != 0 {
41 return strconv.Itoa(media.ID)
42 }
43 return "Unknown Anime"
44}
45
27// GetAnimeMap takes an AnimeList and returns a map with media.id as key and media.title.english as value. 46// GetAnimeMap takes an AnimeList and returns a map with media.id as key and media.title.english as value.
28func GetAnimeMap(animeList AnimeList) map[string]string { 47func GetAnimeMap(animeList AnimeList) map[string]string {
29 animeMap := make(map[string]string) 48 animeMap := make(map[string]string)
@@ -32,13 +51,7 @@ func GetAnimeMap(animeList AnimeList) map[string]string {
32 // Helper function to populate the map from a slice of entries 51 // Helper function to populate the map from a slice of entries
33 populateMap := func(entries []Entry) { 52 populateMap := func(entries []Entry) {
34 for _, entry := range entries { 53 for _, entry := range entries {
35 // Only include entries with a non-empty English title 54 animeMap[strconv.Itoa(entry.Media.ID)] = mediaDisplayTitle(entry.Media, userCurdConfig)
36
37 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
38 animeMap[strconv.Itoa(entry.Media.ID)] = entry.Media.Title.English
39 } else {
40 animeMap[strconv.Itoa(entry.Media.ID)] = entry.Media.Title.Romaji
41 }
42 } 55 }
43 } 56 }
44 57
@@ -61,19 +74,9 @@ func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
61 // Helper function to populate the map from a slice of entries 74 // Helper function to populate the map from a slice of entries
62 populateMap := func(entries []Entry) { 75 populateMap := func(entries []Entry) {
63 for _, entry := range entries { 76 for _, entry := range entries {
64 // Only include entries with a non-empty English title 77 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
65 Log(fmt.Errorf("AnimeNameLanguage: %v", userCurdConfig.AnimeNameLanguage)) 78 Title: mediaDisplayTitle(entry.Media, userCurdConfig),
66 79 CoverImage: entry.CoverImage,
67 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
68 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
69 Title: entry.Media.Title.English,
70 CoverImage: entry.CoverImage,
71 }
72 } else {
73 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
74 Title: entry.Media.Title.Romaji,
75 CoverImage: entry.CoverImage,
76 }
77 } 80 }
78 } 81 }
79 } 82 }
@@ -138,7 +141,10 @@ func min3(a, b, c int) int {
138} 141}
139 142
140func doAniListSearchRequest(url string, requestBody []byte, token string) ([]byte, error) { 143func doAniListSearchRequest(url string, requestBody []byte, token string) ([]byte, error) {
141 client := &http.Client{} 144 client := sharedHTTPClient
145 if client == nil {
146 client = &http.Client{Timeout: 15 * time.Second}
147 }
142 for attempt := 0; attempt < 5; attempt++ { 148 for attempt := 0; attempt < 5; attempt++ {
143 req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) 149 req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
144 if err != nil { 150 if err != nil {
@@ -169,6 +175,13 @@ func doAniListSearchRequest(url string, requestBody []byte, token string) ([]byt
169 if resp.StatusCode != http.StatusOK { 175 if resp.StatusCode != http.StatusOK {
170 return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body)) 176 return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body))
171 } 177 }
178 var envelope map[string]interface{}
179 if err := json.Unmarshal(body, &envelope); err == nil {
180 if rawErrors, exists := envelope["errors"]; exists {
181 errorBody, _ := json.Marshal(rawErrors)
182 return nil, fmt.Errorf("graphql errors: %s", strings.TrimSpace(string(errorBody)))
183 }
184 }
172 return body, nil 185 return body, nil
173 } 186 }
174 187
@@ -346,11 +359,24 @@ func GetAnilistUserID(token string) (int, string, error) {
346 return 0, "", err 359 return 0, "", err
347 } 360 }
348 361
349 data := response["data"].(map[string]interface{})["Viewer"].(map[string]interface{}) 362 data, ok := response["data"].(map[string]interface{})
350 userID := int(data["id"].(float64)) 363 if !ok {
351 userName := data["name"].(string) 364 return 0, "", fmt.Errorf("invalid AniList viewer response: data field missing")
365 }
366 viewer, ok := data["Viewer"].(map[string]interface{})
367 if !ok || viewer == nil {
368 return 0, "", fmt.Errorf("invalid AniList viewer response: Viewer field missing")
369 }
370 userIDFloat, ok := viewer["id"].(float64)
371 if !ok {
372 return 0, "", fmt.Errorf("invalid AniList viewer response: id field missing")
373 }
374 userName, _ := viewer["name"].(string)
375 if userName == "" {
376 return 0, "", fmt.Errorf("invalid AniList viewer response: name field missing")
377 }
352 378
353 return userID, userName, nil 379 return int(userIDFloat), userName, nil
354} 380}
355 381
356// Function to add an anime to the watching list 382// Function to add an anime to the watching list
@@ -401,8 +427,19 @@ func GetAnimeMalID(anilistMediaID int) (int, error) {
401 return 0, err 427 return 0, err
402 } 428 }
403 429
404 malID := int(response["data"].(map[string]interface{})["Media"].(map[string]interface{})["idMal"].(float64)) 430 data, ok := response["data"].(map[string]interface{})
405 return malID, nil 431 if !ok {
432 return 0, fmt.Errorf("invalid AniList media response: data field missing")
433 }
434 media, ok := data["Media"].(map[string]interface{})
435 if !ok || media == nil {
436 return 0, fmt.Errorf("AniList media %d not found", anilistMediaID)
437 }
438 malID, ok := media["idMal"].(float64)
439 if !ok || malID == 0 {
440 return 0, fmt.Errorf("AniList media %d has no MyAnimeList ID", anilistMediaID)
441 }
442 return int(malID), nil
406} 443}
407 444
408// This function retrieves the MAL ID and cover image URL for an anime from AniList 445// This function retrieves the MAL ID and cover image URL for an anime from AniList
@@ -427,9 +464,22 @@ func GetAnimeIDAndImage(anilistMediaID int) (int, string, error) {
427 return 0, "", err 464 return 0, "", err
428 } 465 }
429 466
430 data := response["data"].(map[string]interface{})["Media"].(map[string]interface{}) 467 data, ok := response["data"].(map[string]interface{})
431 malID := int(data["idMal"].(float64)) 468 if !ok {
432 imageURL := data["coverImage"].(map[string]interface{})["large"].(string) 469 return 0, "", fmt.Errorf("invalid AniList media response: data field missing")
470 }
471 media, ok := data["Media"].(map[string]interface{})
472 if !ok || media == nil {
473 return 0, "", fmt.Errorf("AniList media %d not found", anilistMediaID)
474 }
475 malID := 0
476 if value, ok := media["idMal"].(float64); ok {
477 malID = int(value)
478 }
479 imageURL := ""
480 if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
481 imageURL = safeAniListString(coverImage["large"])
482 }
433 483
434 return malID, imageURL, nil 484 return malID, imageURL, nil
435} 485}
@@ -572,20 +622,52 @@ func LoadJSONFile(filePath string) (map[string]interface{}, error) {
572func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []map[string]interface{} { 622func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []map[string]interface{} {
573 results := []map[string]interface{}{} 623 results := []map[string]interface{}{}
574 624
575 lists := jsonData["data"].(map[string]interface{})["MediaListCollection"].(map[string]interface{})["lists"].([]interface{}) 625 data, ok := jsonData["data"].(map[string]interface{})
626 if !ok {
627 return results
628 }
629 collection, ok := data["MediaListCollection"].(map[string]interface{})
630 if !ok {
631 return results
632 }
633 lists, ok := collection["lists"].([]interface{})
634 if !ok {
635 return results
636 }
576 for _, list := range lists { 637 for _, list := range lists {
577 entries := list.(map[string]interface{})["entries"].([]interface{}) 638 listMap, ok := list.(map[string]interface{})
639 if !ok {
640 continue
641 }
642 entries, ok := listMap["entries"].([]interface{})
643 if !ok {
644 continue
645 }
578 for _, entry := range entries { 646 for _, entry := range entries {
579 media := entry.(map[string]interface{})["media"].(map[string]interface{}) 647 entryMap, ok := entry.(map[string]interface{})
580 romajiTitle := media["title"].(map[string]interface{})["romaji"].(string) 648 if !ok {
581 englishTitle := media["title"].(map[string]interface{})["english"].(string) 649 continue
582 episodes := int(media["episodes"].(float64)) 650 }
583 duration := int(media["duration"].(float64)) 651 media, ok := entryMap["media"].(map[string]interface{})
652 if !ok {
653 continue
654 }
655 title, _ := media["title"].(map[string]interface{})
656 romajiTitle := safeAniListString(title["romaji"])
657 englishTitle := safeAniListString(title["english"])
658 episodes := 0
659 if value, ok := media["episodes"].(float64); ok {
660 episodes = int(value)
661 }
662 duration := 0
663 if value, ok := media["duration"].(float64); ok {
664 duration = int(value)
665 }
584 666
585 if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) { 667 if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) {
586 result := map[string]interface{}{ 668 result := map[string]interface{}{
587 "id": media["id"], 669 "id": media["id"],
588 "progress": entry.(map[string]interface{})["progress"], 670 "progress": entryMap["progress"],
589 "romaji_title": romajiTitle, 671 "romaji_title": romajiTitle,
590 "english_title": englishTitle, 672 "english_title": englishTitle,
591 "episodes": episodes, 673 "episodes": episodes,
@@ -790,7 +872,10 @@ func makePostRequest(url, query string, variables map[string]interface{}, header
790 return nil, fmt.Errorf("failed to marshal request body: %w", err) 872 return nil, fmt.Errorf("failed to marshal request body: %w", err)
791 } 873 }
792 874
793 client := &http.Client{} 875 client := sharedHTTPClient
876 if client == nil {
877 client = &http.Client{Timeout: 15 * time.Second}
878 }
794 for attempt := 0; attempt < 5; attempt++ { 879 for attempt := 0; attempt < 5; attempt++ {
795 req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) 880 req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
796 if err != nil { 881 if err != nil {
@@ -828,6 +913,10 @@ func makePostRequest(url, query string, variables map[string]interface{}, header
828 if err := json.Unmarshal(body, &responseData); err != nil { 913 if err := json.Unmarshal(body, &responseData); err != nil {
829 return nil, fmt.Errorf("failed to unmarshal response: %w", err) 914 return nil, fmt.Errorf("failed to unmarshal response: %w", err)
830 } 915 }
916 if rawErrors, exists := responseData["errors"]; exists {
917 errorBody, _ := json.Marshal(rawErrors)
918 return nil, fmt.Errorf("graphql errors: %s", strings.TrimSpace(string(errorBody)))
919 }
831 920
832 return responseData, nil 921 return responseData, nil
833 } 922 }
@@ -876,22 +965,52 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
876 } 965 }
877 } 966 }
878 967
968 if input == nil {
969 Log("AniList response is nil")
970 return animeList
971 }
972
879 // Access the list entries in the input map 973 // Access the list entries in the input map
880 if input["data"] == nil { 974 if input["data"] == nil {
881 Log("Anilist request failed") 975 Log("Anilist request failed")
882 CurdOut("Anilist request failed")
883 ExitCurd(fmt.Errorf("Anilist request failed"))
884 return animeList 976 return animeList
885 } 977 }
886 data := input["data"].(map[string]interface{}) 978 data, ok := input["data"].(map[string]interface{})
887 mediaList := data["MediaListCollection"].(map[string]interface{})["lists"].([]interface{}) 979 if !ok {
980 Log("AniList response data field is invalid")
981 return animeList
982 }
983 collection, ok := data["MediaListCollection"].(map[string]interface{})
984 if !ok {
985 Log("AniList response MediaListCollection field is invalid")
986 return animeList
987 }
988 mediaList, ok := collection["lists"].([]interface{})
989 if !ok {
990 Log("AniList response lists field is invalid")
991 return animeList
992 }
888 993
889 for _, list := range mediaList { 994 for _, list := range mediaList {
890 entries := list.(map[string]interface{})["entries"].([]interface{}) 995 listData, ok := list.(map[string]interface{})
996 if !ok {
997 continue
998 }
999 entries, ok := listData["entries"].([]interface{})
1000 if !ok {
1001 continue
1002 }
891 1003
892 for _, entry := range entries { 1004 for _, entry := range entries {
893 entryData := entry.(map[string]interface{}) 1005 entryData, ok := entry.(map[string]interface{})
894 media := entryData["media"].(map[string]interface{}) 1006 if !ok {
1007 continue
1008 }
1009 media, ok := entryData["media"].(map[string]interface{})
1010 if !ok {
1011 continue
1012 }
1013 title, _ := media["title"].(map[string]interface{})
895 animeEntry := Entry{ 1014 animeEntry := Entry{
896 ListID: toInt(entryData["id"]), 1015 ListID: toInt(entryData["id"]),
897 Media: Media{ 1016 Media: Media{
@@ -900,20 +1019,22 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
900 ID: toInt(media["id"]), 1019 ID: toInt(media["id"]),
901 MalID: toInt(media["idMal"]), 1020 MalID: toInt(media["idMal"]),
902 Title: AnimeTitle{ 1021 Title: AnimeTitle{
903 English: safeString(media["title"].(map[string]interface{})["english"]), 1022 English: safeString(title["english"]),
904 Romaji: safeString(media["title"].(map[string]interface{})["romaji"]), 1023 Romaji: safeString(title["romaji"]),
905 Japanese: safeString(media["title"].(map[string]interface{})["native"]), 1024 Japanese: safeString(title["native"]),
906 }, 1025 },
907 Status: safeString(media["status"]), 1026 Status: safeString(media["status"]),
908 }, 1027 },
909 Progress: toInt(entryData["progress"]), 1028 Progress: toInt(entryData["progress"]),
910 Repeat: toInt(entryData["repeat"]), 1029 Repeat: toInt(entryData["repeat"]),
911 Score: entryData["score"].(float64),
912 Status: safeString(entryData["status"]), // Ensure status is fetched safely 1030 Status: safeString(entryData["status"]), // Ensure status is fetched safely
913 StartedAt: parseFuzzyDate(entryData["startedAt"]), 1031 StartedAt: parseFuzzyDate(entryData["startedAt"]),
914 CompletedAt: parseFuzzyDate(entryData["completedAt"]), 1032 CompletedAt: parseFuzzyDate(entryData["completedAt"]),
915 UpdatedAt: time.Unix(int64(toInt(entryData["updatedAt"])), 0).UTC(), 1033 UpdatedAt: time.Unix(int64(toInt(entryData["updatedAt"])), 0).UTC(),
916 } 1034 }
1035 if score, ok := entryData["score"].(float64); ok {
1036 animeEntry.Score = score
1037 }
917 1038
918 if coverImage, ok := media["coverImage"].(map[string]interface{}); ok { 1039 if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
919 animeEntry.CoverImage = safeString(coverImage["large"]) 1040 animeEntry.CoverImage = safeString(coverImage["large"])
internal/anilist_cache.go +2 −8
@@ -267,10 +267,7 @@ func buildCategorySelectionOptions(list AnimeList, category string) []SelectionO
267 options := make([]SelectionOption, 0) 267 options := make([]SelectionOption, 0)
268 268
269 for _, entry := range getEntriesByCategory(list, category) { 269 for _, entry := range getEntriesByCategory(list, category) {
270 title := entry.Media.Title.English 270 title := mediaDisplayTitle(entry.Media, userCurdConfig)
271 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
272 title = entry.Media.Title.Romaji
273 }
274 271
275 options = append(options, SelectionOption{ 272 options = append(options, SelectionOption{
276 Key: strconv.Itoa(entry.Media.ID), 273 Key: strconv.Itoa(entry.Media.ID),
@@ -286,10 +283,7 @@ func buildCategoryPreviewOptions(list AnimeList, category string) map[string]Rof
286 options := make(map[string]RofiSelectPreview) 283 options := make(map[string]RofiSelectPreview)
287 284
288 for _, entry := range getEntriesByCategory(list, category) { 285 for _, entry := range getEntriesByCategory(list, category) {
289 title := entry.Media.Title.English 286 title := mediaDisplayTitle(entry.Media, userCurdConfig)
290 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
291 title = entry.Media.Title.Romaji
292 }
293 287
294 options[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{ 288 options[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
295 Title: title, 289 Title: title,
internal/anime_list.go +6 −32
@@ -57,38 +57,7 @@ func alternateTranslationType(mode string) string {
57 57
58func searchAllAnime(query, mode string) ([]SelectionOption, error) { 58func searchAllAnime(query, mode string) ([]SelectionOption, error) {
59 preferredMode := normalizeTranslationType(mode) 59 preferredMode := normalizeTranslationType(mode)
60 alternateMode := alternateTranslationType(preferredMode) 60 return searchAnimeByMode(query, preferredMode, preferredMode)
61
62 preferredResults, preferredErr := searchAnimeByMode(query, preferredMode, preferredMode)
63 alternateResults, alternateErr := searchAnimeByMode(query, alternateMode, preferredMode)
64
65 if preferredErr != nil {
66 Log(fmt.Sprintf("Failed searching %s results for %q: %v", preferredMode, query, preferredErr))
67 }
68 if alternateErr != nil {
69 Log(fmt.Sprintf("Failed searching %s results for %q: %v", alternateMode, query, alternateErr))
70 }
71
72 if preferredErr != nil && alternateErr != nil {
73 return nil, preferredErr
74 }
75
76 animeList := make([]SelectionOption, 0, len(preferredResults)+len(alternateResults))
77 seen := make(map[string]struct{}, len(preferredResults)+len(alternateResults))
78
79 for _, option := range preferredResults {
80 animeList = append(animeList, option)
81 seen[option.Key] = struct{}{}
82 }
83
84 for _, option := range alternateResults {
85 if _, exists := seen[option.Key]; exists {
86 continue
87 }
88 animeList = append(animeList, option)
89 }
90
91 return animeList, nil
92} 61}
93 62
94func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, error) { 63func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, error) {
@@ -170,6 +139,11 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er
170 // Debug: Log the response status and first part of the body 139 // Debug: Log the response status and first part of the body
171 Log(fmt.Sprintf("Response Status: %s", resp.Status)) 140 Log(fmt.Sprintf("Response Status: %s", resp.Status))
172 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)]))) 141 Log(fmt.Sprintf("Response Body (first 500 chars): %s", string(body[:min(len(body), 500)])))
142 if !httpStatusOK(resp.StatusCode) {
143 err := httpStatusError("allanime search", resp.StatusCode, body)
144 Log(err)
145 return animeList, err
146 }
173 147
174 // Parse the JSON response 148 // Parse the JSON response
175 var response response 149 var response response
internal/aniskip.go +1 −1
@@ -30,7 +30,7 @@ func GetAniSkipData(animeMalId int, episode int) (string, error) {
30 baseURL := "https://api.aniskip.com/v1/skip-times" 30 baseURL := "https://api.aniskip.com/v1/skip-times"
31 url := fmt.Sprintf("%s/%d/%d?types=op&types=ed", baseURL, animeMalId, episode) 31 url := fmt.Sprintf("%s/%d/%d?types=op&types=ed", baseURL, animeMalId, episode)
32 32
33 resp, err := http.Get(url) 33 resp, err := sharedHTTPClient.Get(url)
34 if err != nil { 34 if err != nil {
35 Log(fmt.Errorf("error fetching data from AniSkip API: %w", err)) 35 Log(fmt.Errorf("error fetching data from AniSkip API: %w", err))
36 return "", fmt.Errorf("error fetching data from AniSkip API: %w", err) 36 return "", fmt.Errorf("error fetching data from AniSkip API: %w", err)
internal/bench_test.go added +93
@@ -0,0 +1,93 @@
1package internal
2
3import (
4 "fmt"
5 "testing"
6 "time"
7)
8
9func benchmarkAnimeList(size int) AnimeList {
10 list := AnimeList{}
11 for i := 0; i < size; i++ {
12 entry := Entry{
13 Media: Media{
14 ID: i + 1,
15 MalID: 1000 + i,
16 Title: AnimeTitle{
17 English: fmt.Sprintf("Anime %d", i+1),
18 Romaji: fmt.Sprintf("Anime %d", i+1),
19 },
20 },
21 Status: "CURRENT",
22 Progress: i % 24,
23 Score: float64(i % 10),
24 UpdatedAt: time.Date(2026, 1, 1, 0, 0, i%60, 0, time.UTC),
25 }
26 switch i % 5 {
27 case 0:
28 list.Watching = append(list.Watching, entry)
29 case 1:
30 entry.Status = "COMPLETED"
31 list.Completed = append(list.Completed, entry)
32 case 2:
33 entry.Status = "PAUSED"
34 list.Paused = append(list.Paused, entry)
35 case 3:
36 entry.Status = "PLANNING"
37 list.Planning = append(list.Planning, entry)
38 default:
39 entry.Status = "DROPPED"
40 list.Dropped = append(list.Dropped, entry)
41 }
42 }
43 return list
44}
45
46func BenchmarkBuildDualRemoteSyncPlan(b *testing.B) {
47 aniList := benchmarkAnimeList(1000)
48 myAnimeList := benchmarkAnimeList(1000)
49 for i := range myAnimeList.Watching {
50 myAnimeList.Watching[i].Progress += 1
51 myAnimeList.Watching[i].UpdatedAt = myAnimeList.Watching[i].UpdatedAt.Add(time.Hour)
52 }
53
54 b.ReportAllocs()
55 b.ResetTimer()
56 for i := 0; i < b.N; i++ {
57 _ = buildDualRemoteSyncPlan(aniList, myAnimeList)
58 }
59}
60
61func BenchmarkMergeAnimeLists(b *testing.B) {
62 aniList := benchmarkAnimeList(1000)
63 myAnimeList := benchmarkAnimeList(1000)
64
65 b.ReportAllocs()
66 b.ResetTimer()
67 for i := 0; i < b.N; i++ {
68 _ = mergeAnimeLists(aniList, myAnimeList)
69 }
70}
71
72func BenchmarkSortAllanimeSourcesByPriority(b *testing.B) {
73 sources := make([]allanimeSource, 0, 1000)
74 for i := 0; i < 1000; i++ {
75 sources = append(sources, allanimeSource{
76 SourceUrl: fmt.Sprintf("https://example.com/%d.mp4", i),
77 SourceName: "Yt-mp4",
78 Priority: float64((i * 37) % 100),
79 })
80 }
81
82 b.ReportAllocs()
83 b.ResetTimer()
84 for i := 0; i < b.N; i++ {
85 _ = sortAllanimeSourcesByPriority(sources)
86 }
87}
88
89func BenchmarkLevenshteinAnimeTitles(b *testing.B) {
90 for i := 0; i < b.N; i++ {
91 _ = levenshtein("Sousou no Frieren Beyond Journey's End", "Frieren Beyond Journey's End")
92 }
93}
internal/config.go +102 −72
@@ -38,35 +38,36 @@ type AnilistToken struct {
38 38
39// CurdConfig struct with field names that match the config keys 39// CurdConfig struct with field names that match the config keys
40type CurdConfig struct { 40type CurdConfig struct {
41 Player string `config:"Player"` 41 Player string `config:"Player"`
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 StoragePath string `config:"StoragePath"` 45 StoragePath string `config:"StoragePath"`
46 AnimeNameLanguage string `config:"AnimeNameLanguage"` 46 AnimeNameLanguage string `config:"AnimeNameLanguage"`
47 MenuOrder string `config:"MenuOrder"` 47 MenuOrder string `config:"MenuOrder"`
48 PercentageToMarkComplete int `config:"PercentageToMarkComplete"` 48 PercentageToMarkComplete int `config:"PercentageToMarkComplete"`
49 NextEpisodePrompt bool `config:"NextEpisodePrompt"` 49 NextEpisodePrompt bool `config:"NextEpisodePrompt"`
50 SkipOp bool `config:"SkipOp"` 50 SkipOp bool `config:"SkipOp"`
51 SkipEd bool `config:"SkipEd"` 51 SkipEd bool `config:"SkipEd"`
52 SkipFiller bool `config:"SkipFiller"` 52 SkipFiller bool `config:"SkipFiller"`
53 ImagePreview bool `config:"ImagePreview"` 53 ImagePreview bool `config:"ImagePreview"`
54 SkipRecap bool `config:"SkipRecap"` 54 SkipRecap bool `config:"SkipRecap"`
55 RofiSelection bool `config:"RofiSelection"` 55 RofiSelection bool `config:"RofiSelection"`
56 CurrentCategory bool `config:"CurrentCategory"` 56 CurrentCategory bool `config:"CurrentCategory"`
57 ScoreOnCompletion bool `config:"ScoreOnCompletion"` 57 ScoreOnCompletion bool `config:"ScoreOnCompletion"`
58 SaveMpvSpeed bool `config:"SaveMpvSpeed"` 58 SaveMpvSpeed bool `config:"SaveMpvSpeed"`
59 AddMissingOptions bool `config:"AddMissingOptions"` 59 AddMissingOptions bool `config:"AddMissingOptions"`
60 AlternateScreen bool `config:"AlternateScreen"` 60 AlternateScreen bool `config:"AlternateScreen"`
61 DiscordPresence bool `config:"DiscordPresence"` 61 DiscordPresence bool `config:"DiscordPresence"`
62 DiscordClientId string `config:"DiscordClientId"` 62 DiscordClientId string `config:"DiscordClientId"`
63 Provider string `config:"Provider"` 63 Provider string `config:"Provider"`
64 TrackingLocal bool `config:"TrackingLocal"` 64 TrackingLocal bool `config:"TrackingLocal"`
65 TrackingRemote string `config:"TrackingRemote"` 65 TrackingRemote string `config:"TrackingRemote"`
66 TrackingConfigured bool `config:"TrackingConfigured"` 66 TrackingConfigured bool `config:"TrackingConfigured"`
67 MyAnimeListClientID string `config:"MyAnimeListClientID"` 67 MyAnimeListClientID string `config:"MyAnimeListClientID"`
68 MyAnimeListClientSecret string `config:"MyAnimeListClientSecret"` 68 MyAnimeListClientSecret string `config:"MyAnimeListClientSecret"`
69 MyAnimeListImported bool `config:"MyAnimeListImported"` 69 MyAnimeListImported bool `config:"MyAnimeListImported"`
70 MyAnimeListImportDismissed bool `config:"MyAnimeListImportDismissed"`
70} 71}
71 72
72func GetStoragePath() string { 73func GetStoragePath() string {
@@ -79,34 +80,35 @@ func GetStoragePath() string {
79// Default configuration values as a map 80// Default configuration values as a map
80func defaultConfigMap() map[string]string { 81func defaultConfigMap() map[string]string {
81 return map[string]string{ 82 return map[string]string{
82 "Player": "mpv", 83 "Player": "mpv",
83 "MpvArgs": "[]", 84 "MpvArgs": "[]",
84 "StoragePath": "$HOME/.local/share/curd", 85 "StoragePath": "$HOME/.local/share/curd",
85 "AnimeNameLanguage": "english", 86 "AnimeNameLanguage": "english",
86 "SubsLanguage": "english", 87 "SubsLanguage": "english",
87 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,TRACKER,PROVIDER", 88 "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,TRACKER,PROVIDER",
88 "SubOrDub": "sub", 89 "SubOrDub": "sub",
89 "PercentageToMarkComplete": "85", 90 "PercentageToMarkComplete": "85",
90 "NextEpisodePrompt": "false", 91 "NextEpisodePrompt": "false",
91 "SkipOp": "true", 92 "SkipOp": "true",
92 "SkipEd": "true", 93 "SkipEd": "true",
93 "SkipFiller": "true", 94 "SkipFiller": "true",
94 "SkipRecap": "true", 95 "SkipRecap": "true",
95 "RofiSelection": "false", 96 "RofiSelection": "false",
96 "ImagePreview": "false", 97 "ImagePreview": "false",
97 "ScoreOnCompletion": "true", 98 "ScoreOnCompletion": "true",
98 "SaveMpvSpeed": "true", 99 "SaveMpvSpeed": "true",
99 "AddMissingOptions": "true", 100 "AddMissingOptions": "true",
100 "AlternateScreen": "true", 101 "AlternateScreen": "true",
101 "DiscordPresence": "true", 102 "DiscordPresence": "true",
102 "DiscordClientId": "1287457464148820089", 103 "DiscordClientId": "1287457464148820089",
103 "Provider": "allanime", 104 "Provider": "allanime",
104 "TrackingLocal": "true", 105 "TrackingLocal": "true",
105 "TrackingRemote": "anilist", 106 "TrackingRemote": "anilist",
106 "TrackingConfigured": "false", 107 "TrackingConfigured": "false",
107 "MyAnimeListClientID": "f76d4c827152327b60654285d221222c", 108 "MyAnimeListClientID": "f76d4c827152327b60654285d221222c",
108 "MyAnimeListClientSecret": "", 109 "MyAnimeListClientSecret": "",
109 "MyAnimeListImported": "false", 110 "MyAnimeListImported": "false",
111 "MyAnimeListImportDismissed": "false",
110 } 112 }
111} 113}
112 114
@@ -120,8 +122,25 @@ func GetGlobalConfig() *CurdConfig {
120 return globalConfig 122 return globalConfig
121} 123}
122 124
125func useEnglishAnimeNames(config *CurdConfig) bool {
126 return config == nil || strings.EqualFold(strings.TrimSpace(config.AnimeNameLanguage), "english")
127}
128
123// Helper function to parse string array from config 129// Helper function to parse string array from config
124func parseStringArray(value string) []string { 130func parseStringArray(value string) []string {
131 value = strings.TrimSpace(value)
132 var parsed []string
133 if err := json.Unmarshal([]byte(value), &parsed); err == nil {
134 result := make([]string, 0, len(parsed))
135 for _, part := range parsed {
136 part = strings.TrimSpace(part)
137 if part != "" {
138 result = append(result, part)
139 }
140 }
141 return result
142 }
143
125 // Remove brackets and split by comma 144 // Remove brackets and split by comma
126 value = strings.TrimPrefix(value, "[") 145 value = strings.TrimPrefix(value, "[")
127 value = strings.TrimSuffix(value, "]") 146 value = strings.TrimSuffix(value, "]")
@@ -170,7 +189,9 @@ func LoadConfig(configPath string) (CurdConfig, error) {
170 // Check AddMissingOptions setting first 189 // Check AddMissingOptions setting first
171 addMissing := true 190 addMissing := true
172 if val, exists := configMap["AddMissingOptions"]; exists { 191 if val, exists := configMap["AddMissingOptions"]; exists {
173 addMissing, _ = strconv.ParseBool(val) 192 if parsed, parseErr := strconv.ParseBool(val); parseErr == nil {
193 addMissing = parsed
194 }
174 } 195 }
175 196
176 _, hadTrackingRemote := configMap["TrackingRemote"] 197 _, hadTrackingRemote := configMap["TrackingRemote"]
@@ -321,7 +342,7 @@ func authenticateWithBrowser(tokenPath string) (string, error) {
321 "code": {code}, 342 "code": {code},
322 } 343 }
323 344
324 resp, err := http.PostForm(tokenURL, data) 345 resp, err := sharedHTTPClient.PostForm(tokenURL, data)
325 if err != nil { 346 if err != nil {
326 errCh <- fmt.Errorf("failed to exchange code for token: %w", err) 347 errCh <- fmt.Errorf("failed to exchange code for token: %w", err)
327 return 348 return
@@ -579,25 +600,34 @@ func SaveConfigToFile(path string, configMap map[string]string) error {
579func PopulateConfig(configMap map[string]string) CurdConfig { 600func PopulateConfig(configMap map[string]string) CurdConfig {
580 config := CurdConfig{} 601 config := CurdConfig{}
581 configValue := reflect.ValueOf(&config).Elem() 602 configValue := reflect.ValueOf(&config).Elem()
603 defaults := defaultConfigMap()
582 604
583 for i := 0; i < configValue.NumField(); i++ { 605 for i := 0; i < configValue.NumField(); i++ {
584 field := configValue.Type().Field(i) 606 field := configValue.Type().Field(i)
585 tag := field.Tag.Get("config") 607 tag := field.Tag.Get("config")
586 608
587 if value, exists := configMap[tag]; exists { 609 value, exists := configMap[tag]
588 fieldValue := configValue.FieldByName(field.Name) 610 if !exists || value == "" {
589 611 value = defaults[tag]
590 if fieldValue.CanSet() { 612 }
591 switch fieldValue.Kind() { 613 fieldValue := configValue.FieldByName(field.Name)
592 case reflect.String: 614
593 fieldValue.SetString(value) 615 if fieldValue.CanSet() {
594 case reflect.Int: 616 switch fieldValue.Kind() {
595 intVal, _ := strconv.Atoi(value) 617 case reflect.String:
596 fieldValue.SetInt(int64(intVal)) 618 fieldValue.SetString(value)
597 case reflect.Bool: 619 case reflect.Int:
598 boolVal, _ := strconv.ParseBool(value) 620 intVal, err := strconv.Atoi(value)
599 fieldValue.SetBool(boolVal) 621 if err != nil {
622 intVal, _ = strconv.Atoi(defaults[tag])
623 }
624 fieldValue.SetInt(int64(intVal))
625 case reflect.Bool:
626 boolVal, err := strconv.ParseBool(value)
627 if err != nil {
628 boolVal, _ = strconv.ParseBool(defaults[tag])
600 } 629 }
630 fieldValue.SetBool(boolVal)
601 } 631 }
602 } 632 }
603 } 633 }
internal/curd.go +398 −317
@@ -1,7 +1,6 @@
1package internal 1package internal
2 2
3import ( 3import (
4 "bufio"
5 "crypto/md5" 4 "crypto/md5"
6 "encoding/json" 5 "encoding/json"
7 "fmt" 6 "fmt"
@@ -63,8 +62,12 @@ func EditConfig(configFilePath string) {
63 62
64// ClearLogFile removes all contents from the specified log file 63// ClearLogFile removes all contents from the specified log file
65func ClearLogFile(logFile string) error { 64func ClearLogFile(logFile string) error {
66 // Open the file with truncate flag to clear its contents 65 if err := os.MkdirAll(filepath.Dir(logFile), 0755); err != nil {
67 file, err := os.OpenFile(logFile, os.O_WRONLY|os.O_TRUNC, 0666) 66 return fmt.Errorf("failed to create log directory: %w", err)
67 }
68
69 // Open the file with truncate flag to clear its contents.
70 file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
68 if err != nil { 71 if err != nil {
69 return fmt.Errorf("failed to open log file: %w", err) 72 return fmt.Errorf("failed to open log file: %w", err)
70 } 73 }
@@ -137,7 +140,9 @@ func ExitCurd(err error) {
137 RestoreScreen() 140 RestoreScreen()
138 141
139 anime := GetGlobalAnime() 142 anime := GetGlobalAnime()
143 socketPath := ""
140 if (anime != nil) && (anime.Ep.Player.SocketPath != "") { 144 if (anime != nil) && (anime.Ep.Player.SocketPath != "") {
145 socketPath = anime.Ep.Player.SocketPath
141 _, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"}) 146 _, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
142 if err != nil { 147 if err != nil {
143 Log("Error closing MPV: " + err.Error()) 148 Log("Error closing MPV: " + err.Error())
@@ -146,7 +151,7 @@ func ExitCurd(err error) {
146 151
147 CurdOut("Have a great day!") 152 CurdOut("Have a great day!")
148 // If the error is not about the connection refused, print the error 153 // If the error is not about the connection refused, print the error
149 if err != nil && !strings.Contains(err.Error(), "dial unix "+anime.Ep.Player.SocketPath+": connect: connection refused") { 154 if err != nil && (socketPath == "" || !strings.Contains(err.Error(), "dial unix "+socketPath+": connect: connection refused")) {
150 CurdOut(fmt.Sprintf("Error: %v", err)) 155 CurdOut(fmt.Sprintf("Error: %v", err))
151 if runtime.GOOS == "windows" { 156 if runtime.GOOS == "windows" {
152 fmt.Println("Press Enter to exit") 157 fmt.Println("Press Enter to exit")
@@ -381,7 +386,7 @@ updateOptionLoop:
381 fmt.Scanln(&progress) 386 fmt.Scanln(&progress)
382 } 387 }
383 388
384 progressNum, err := strconv.Atoi(progress) 389 progressNum, err := parseNonNegativeIntInput(progress, "progress")
385 if err != nil { 390 if err != nil {
386 Log(fmt.Sprintf("Failed to convert progress to number: %v", err)) 391 Log(fmt.Sprintf("Failed to convert progress to number: %v", err))
387 ExitCurd(fmt.Errorf("Failed to convert progress to number")) 392 ExitCurd(fmt.Errorf("Failed to convert progress to number"))
@@ -464,7 +469,7 @@ func UpdateCurd(repo, fileName string) error {
464 tmpPath := executablePath + ".tmp" 469 tmpPath := executablePath + ".tmp"
465 470
466 // Download the curd executable 471 // Download the curd executable
467 resp, err := http.Get(url) 472 resp, err := sharedHTTPClient.Get(url)
468 if err != nil { 473 if err != nil {
469 return fmt.Errorf("failed to download file: %v", err) 474 return fmt.Errorf("failed to download file: %v", err)
470 } 475 }
@@ -528,18 +533,10 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
528 var err error 533 var err error
529 var anilistSelectedOption SelectionOption 534 var anilistSelectedOption SelectionOption
530 535
531 if userCurdConfig.RofiSelection { 536 query, err = promptText(userCurdConfig, "Enter the anime name", false)
532 userInput, err := GetUserInputFromRofi("Enter the anime name") 537 if err != nil {
533 if err != nil { 538 Log("Error getting user input: " + err.Error())
534 Log("Error getting user input: " + err.Error()) 539 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
535 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
536 }
537 query = userInput
538 } else {
539 CurdOut("Enter the anime name:")
540 reader := bufio.NewReader(os.Stdin)
541 input, _ := reader.ReadString('\n')
542 query = strings.TrimSpace(input)
543 } 540 }
544 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 541 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
545 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token) 542 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
@@ -559,6 +556,10 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
559 } else { 556 } else {
560 anilistSelectedOption, err = DynamicSelect(animeOptions) 557 anilistSelectedOption, err = DynamicSelect(animeOptions)
561 } 558 }
559 if err != nil {
560 Log(fmt.Sprintf("No anime available: %v", err))
561 ExitCurd(fmt.Errorf("No anime available"))
562 }
562 563
563 if anilistSelectedOption.Key == "-1" { 564 if anilistSelectedOption.Key == "-1" {
564 ExitCurd(nil) 565 ExitCurd(nil)
@@ -569,10 +570,6 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
569 return SelectionOption{Key: "-2", Label: "Back"} 570 return SelectionOption{Key: "-2", Label: "Back"}
570 } 571 }
571 572
572 if err != nil {
573 Log(fmt.Sprintf("No anime available: %v", err))
574 ExitCurd(fmt.Errorf("No anime available"))
575 }
576 animeID, err := strconv.Atoi(anilistSelectedOption.Key) 573 animeID, err := strconv.Atoi(anilistSelectedOption.Key)
577 if err != nil { 574 if err != nil {
578 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err)) 575 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err))
@@ -897,9 +894,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
897 } 894 }
898 895
899 if selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED" { 896 if selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED" {
900 CurdOut("This anime is not yet released. Cannot play.") 897 handleUnreleasedAnime(userCurdConfig, user, anime, *selectedAnilistAnime)
901 time.Sleep(2 * time.Second)
902 anime.Ep.ContinueLast = false
903 ClearScreen() 898 ClearScreen()
904 continue 899 continue
905 } 900 }
@@ -919,27 +914,64 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
919 anime.Repeat = selectedAnilistAnime.Repeat 914 anime.Repeat = selectedAnilistAnime.Repeat
920 anime.StartedAt = selectedAnilistAnime.StartedAt 915 anime.StartedAt = selectedAnilistAnime.StartedAt
921 anime.CompletedAt = selectedAnilistAnime.CompletedAt 916 anime.CompletedAt = selectedAnilistAnime.CompletedAt
922 anime.Ep.Number = selectedAnilistAnime.Progress + 1 917 anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
923 var animeList []SelectionOption 918 var animeList []SelectionOption
924 userQuery = anime.Title.Romaji 919 userQuery = anime.Title.Romaji
925 920
926 if selectedAnilistAnime.Status == "COMPLETED" { 921 if selectedAnilistAnime.Status == "COMPLETED" {
927 err = StartAnimeRewatch(user.Token, *anime) 922 CurdOut("This anime is completed. Start rewatch from episode 1? Continue without updating tracker? Open details?")
923 selectedOption, err := promptSelect([]SelectionOption{
924 {Key: "rewatch", Label: "Start rewatch from episode 1"},
925 {Key: "continue", Label: "Continue without updating tracker"},
926 {Key: "details", Label: "Open details"},
927 })
928 if err != nil { 928 if err != nil {
929 Log(fmt.Sprintf("Error starting anime rewatch: %v", err)) 929 Log(fmt.Sprintf("Error in completed anime prompt: %v", err))
930 ExitCurd(fmt.Errorf("Failed to move anime to rewatching")) 930 ExitCurd(fmt.Errorf("Failed to select completed anime action"))
931 } 931 }
932 932
933 anime.Rewatching = true 933 switch selectedOption.Key {
934 anime.Ep.Number = 1 934 case "rewatch":
935 anime.Ep.Player.PlaybackTime = 0 935 err = StartAnimeRewatch(user.Token, *anime)
936 anime.Ep.Resume = false 936 if err != nil {
937 startingRewatch = true 937 Log(fmt.Sprintf("Error starting anime rewatch: %v", err))
938 CurdOut("Moved anime to Rewatching and restarting from episode 1.") 938 ExitCurd(fmt.Errorf("Failed to move anime to rewatching"))
939 }
939 940
940 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil { 941 anime.Rewatching = true
941 Log("Error refreshing anime list: " + err.Error()) 942 anime.SkipRemoteSync = false
942 ExitCurd(err) 943 anime.Ep.Number = 1
944 anime.Ep.Player.PlaybackTime = 0
945 anime.Ep.Resume = false
946 startingRewatch = true
947 CurdOut("Moved anime to Rewatching and restarting from episode 1.")
948
949 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
950 Log("Error refreshing anime list: " + err.Error())
951 ExitCurd(err)
952 }
953 case "continue":
954 anime.Rewatching = false
955 anime.SkipRemoteSync = true
956 anime.Ep.Number = 1
957 anime.Ep.Player.PlaybackTime = 0
958 anime.Ep.Resume = false
959 startingRewatch = true
960 CurdOut("Starting episode 1 without updating your tracker.")
961 case "details":
962 url := fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId)
963 CurdOut(fmt.Sprintf("Opening %s", url))
964 if err := browser.OpenURL(url); err != nil {
965 Log(fmt.Sprintf("Error opening browser: %v", err))
966 CurdOut("Failed to open browser.")
967 }
968 anime.Ep.ContinueLast = false
969 continue
970 case "-1":
971 ExitCurd(nil)
972 default:
973 anime.Ep.ContinueLast = false
974 continue
943 } 975 }
944 } 976 }
945 977
@@ -968,19 +1000,10 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
968 if len(animeList) == 0 { 1000 if len(animeList) == 0 {
969 for { 1001 for {
970 var manualQuery string 1002 var manualQuery string
971 if userCurdConfig.RofiSelection { 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 AllAnime.", userQuery), true)
972 userInput, err := GetUserInputFromRofi(fmt.Sprintf("No results found for '%s'. Press Enter to search with AniList name, or enter a custom name to search on AllAnime.", userQuery)) 1004 if err != nil {
973 if err != nil { 1005 Log("Error getting user input: " + err.Error())
974 Log("Error getting user input: " + err.Error()) 1006 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
975 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
976 }
977 manualQuery = userInput
978 } else {
979 CurdOut(fmt.Sprintf("No results found for '%s'.", userQuery))
980 CurdOut("Press Enter to search with AniList name, or enter a custom name to search on AllAnime:")
981 reader := bufio.NewReader(os.Stdin)
982 input, _ := reader.ReadString('\n')
983 manualQuery = strings.TrimSpace(input)
984 } 1007 }
985 1008
986 // If empty, use original AniList name 1009 // If empty, use original AniList name
@@ -1127,13 +1150,24 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1127 } 1150 }
1128 animeUrl := fmt.Sprintf("https://animepahe.pw/anime/%s", animeRef.Session) 1151 animeUrl := fmt.Sprintf("https://animepahe.pw/anime/%s", animeRef.Session)
1129 Log(fmt.Sprintf("Fetching %s to check exact AniList meta tag...", animeUrl)) 1152 Log(fmt.Sprintf("Fetching %s to check exact AniList meta tag...", animeUrl))
1130 req, _ := http.NewRequest("GET", animeUrl, nil) 1153 req, err := newAnimepahePageRequest(animeUrl)
1131 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") 1154 if err != nil {
1155 Log(fmt.Sprintf("Failed to build animepahe detail request %s: %v", animeUrl, err))
1156 continue
1157 }
1132 1158
1133 resp, err := sharedHTTPClient.Do(req) 1159 resp, err := sharedHTTPClient.Do(req)
1134 if err == nil && resp.StatusCode == 200 { 1160 if err != nil {
1135 body, _ := io.ReadAll(resp.Body) 1161 Log(fmt.Sprintf("Failed to fetch animepahe detail page %s: %v", animeUrl, err))
1136 resp.Body.Close() 1162 continue
1163 }
1164 body, readErr := io.ReadAll(resp.Body)
1165 resp.Body.Close()
1166 if readErr != nil {
1167 Log(fmt.Sprintf("Failed to read animepahe detail page %s: %v", animeUrl, readErr))
1168 continue
1169 }
1170 if resp.StatusCode == http.StatusOK {
1137 bodyStr := string(body) 1171 bodyStr := string(body)
1138 1172
1139 metaTag := fmt.Sprintf(`<meta name="anilist" content="%s">`, targetAnilistID) 1173 metaTag := fmt.Sprintf(`<meta name="anilist" content="%s">`, targetAnilistID)
@@ -1166,6 +1200,11 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1166 found = true 1200 found = true
1167 } else if bestMatch != nil { 1201 } else if bestMatch != nil {
1168 Log(fmt.Sprintf("Highest match score was %d (needed 100 for Animepahe exact meta tag match). Not selecting automatically to prevent false positives.", highestScore)) 1202 Log(fmt.Sprintf("Highest match score was %d (needed 100 for Animepahe exact meta tag match). Not selecting automatically to prevent false positives.", highestScore))
1203 if confirmProviderMatch(*bestMatch, "Animepahe metadata") {
1204 anime.ProviderId = bestMatch.Key
1205 Log(fmt.Sprintf("User confirmed Animepahe match. Setting ProviderId to: %s", anime.ProviderId))
1206 found = true
1207 }
1169 } 1208 }
1170 } 1209 }
1171 1210
@@ -1174,9 +1213,11 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1174 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes) 1213 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes)
1175 for _, option := range animeList { 1214 for _, option := range animeList {
1176 if fmt.Sprintf("%s (%d episodes)", option.Title, selectedAnilistAnime.Media.Episodes) == targetLabel { 1215 if fmt.Sprintf("%s (%d episodes)", option.Title, selectedAnilistAnime.Media.Episodes) == targetLabel {
1177 anime.ProviderId = option.Key 1216 if confirmProviderMatch(option, "title and episode count") {
1178 Log(fmt.Sprintf("Found exact text match! Setting ProviderId to: %s", anime.ProviderId)) 1217 anime.ProviderId = option.Key
1179 found = true 1218 Log(fmt.Sprintf("User confirmed exact text match. Setting ProviderId to: %s", anime.ProviderId))
1219 found = true
1220 }
1180 break 1221 break
1181 } 1222 }
1182 } 1223 }
@@ -1189,6 +1230,9 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1189 if anime.ProviderId == "" { 1230 if anime.ProviderId == "" {
1190 CurdOut("We didn't find any matches. Please select manually.") 1231 CurdOut("We didn't find any matches. Please select manually.")
1191 selectedAllanimeAnime, err := DynamicSelect(animeList) 1232 selectedAllanimeAnime, err := DynamicSelect(animeList)
1233 if err != nil {
1234 ExitCurd(fmt.Errorf("No anime available"))
1235 }
1192 1236
1193 if selectedAllanimeAnime.Key == "-1" { 1237 if selectedAllanimeAnime.Key == "-1" {
1194 ExitCurd(nil) 1238 ExitCurd(nil)
@@ -1204,9 +1248,6 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1204 continue 1248 continue
1205 } 1249 }
1206 1250
1207 if err != nil {
1208 ExitCurd(fmt.Errorf("No anime available"))
1209 }
1210 anime.ProviderId = selectedAllanimeAnime.Key 1251 anime.ProviderId = selectedAllanimeAnime.Key
1211 } 1252 }
1212 } 1253 }
@@ -1222,15 +1263,15 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1222 } 1263 }
1223 1264
1224 // If local history episode is ahead of AniList upstream, prompt user 1265 // If local history episode is ahead of AniList upstream, prompt user
1225 anilistEpisode := selectedAnilistAnime.Progress + 1 1266 anilistEpisode := nextEpisodeFromProgress(selectedAnilistAnime.Progress)
1226 if animePointer.Ep.Number > anilistEpisode { 1267 if animePointer.Ep.Number > anilistEpisode {
1227 trackerLabel := RemoteTrackingDisplayName(userCurdConfig) 1268 trackerLabel := RemoteTrackingDisplayName(userCurdConfig)
1228 Log(fmt.Sprintf("Local history episode (%d) is ahead of %s episode (%d), prompting user", animePointer.Ep.Number, trackerLabel, anilistEpisode)) 1269 Log(fmt.Sprintf("Local history episode (%d) is ahead of %s episode (%d), prompting user", animePointer.Ep.Number, trackerLabel, anilistEpisode))
1229 options := []SelectionOption{ 1270 options := []SelectionOption{
1230 {Key: "update_upstream", Label: fmt.Sprintf("Update %s to episode %d (local history)", trackerLabel, animePointer.Ep.Number-1)}, 1271 {Key: "update_upstream", Label: fmt.Sprintf("Use Curd episode %d", animePointer.Ep.Number)},
1231 {Key: "use_anilist", Label: fmt.Sprintf("Use %s episode %d", trackerLabel, anilistEpisode)}, 1272 {Key: "use_anilist", Label: fmt.Sprintf("Use %s episode %d", trackerLabel, anilistEpisode)},
1232 } 1273 }
1233 CurdOut(fmt.Sprintf("Local history (ep %d) is ahead of %s (ep %d).", animePointer.Ep.Number, trackerLabel, anilistEpisode)) 1274 CurdOut(fmt.Sprintf("Curd has episode %d. %s has episode %d. Pick one.", animePointer.Ep.Number, trackerLabel, anilistEpisode))
1234 selectedOption, err := DynamicSelect(options) 1275 selectedOption, err := DynamicSelect(options)
1235 if err != nil { 1276 if err != nil {
1236 Log("Error in episode conflict selection: " + err.Error()) 1277 Log("Error in episode conflict selection: " + err.Error())
@@ -1247,7 +1288,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1247 anime.Ep.Number = animePointer.Ep.Number 1288 anime.Ep.Number = animePointer.Ep.Number
1248 anime.Ep.Resume = true 1289 anime.Ep.Resume = true
1249 } else if selectedOption.Key == "use_anilist" { 1290 } else if selectedOption.Key == "use_anilist" {
1250 // Use remote episode number (already set from selectedAnilistAnime.Progress + 1) 1291 // Use remote next-episode number (already set from selectedAnilistAnime.Progress + 1)
1251 anime.Ep.Number = anilistEpisode 1292 anime.Ep.Number = anilistEpisode
1252 anime.Ep.Player.PlaybackTime = 0 1293 anime.Ep.Player.PlaybackTime = 0
1253 anime.Ep.Resume = false 1294 anime.Ep.Resume = false
@@ -1286,7 +1327,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1286 isInWatchingList = true 1327 isInWatchingList = true
1287 } 1328 }
1288 1329
1289 if UsesRemoteTracking(userCurdConfig) && !isInWatchingList { 1330 if ShouldWriteRemoteTracking(userCurdConfig, anime) && !isInWatchingList {
1290 // Create options for the prompt 1331 // Create options for the prompt
1291 options := []SelectionOption{ 1332 options := []SelectionOption{
1292 {Key: "yes", Label: "Add to watching list"}, 1333 {Key: "yes", Label: "Add to watching list"},
@@ -1329,8 +1370,9 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1329 1370
1330 // If upstream is ahead, update the episode number 1371 // If upstream is ahead, update the episode number
1331 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil { 1372 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
1332 if temp_anime.Progress > anime.Ep.Number { 1373 upstreamNextEpisode := nextEpisodeFromProgress(temp_anime.Progress)
1333 anime.Ep.Number = temp_anime.Progress 1374 if upstreamNextEpisode > anime.Ep.Number {
1375 anime.Ep.Number = upstreamNextEpisode
1334 anime.Ep.Player.PlaybackTime = 0 1376 anime.Ep.Player.PlaybackTime = 0
1335 anime.Ep.Resume = false 1377 anime.Ep.Resume = false
1336 } 1378 }
@@ -1350,7 +1392,18 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1350 } 1392 }
1351 1393
1352 if anime.TotalEpisodes == 0 { // If failed to get anime data 1394 if anime.TotalEpisodes == 0 { // If failed to get anime data
1353 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.") 1395 CurdOut("AniList/MAL did not return total episodes. Attempting to retrieve from provider episode list.")
1396 providerTotal, err := GetProviderTotalEpisodes(anime.ProviderId, userCurdConfig.SubOrDub)
1397 if err != nil {
1398 Log(fmt.Sprintf("Failed to retrieve total episodes from provider episode list: %v", err))
1399 } else {
1400 anime.TotalEpisodes = providerTotal
1401 CurdOut(fmt.Sprintf("Retrieved total episodes from provider: %d", anime.TotalEpisodes))
1402 }
1403 }
1404
1405 if anime.TotalEpisodes == 0 { // If provider episode list did not have a usable total
1406 CurdOut("Attempting to retrieve total episodes from anime search results.")
1354 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub) 1407 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
1355 if err != nil { 1408 if err != nil {
1356 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err)) 1409 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
@@ -1370,21 +1423,14 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1370 if anime.TotalEpisodes == 0 { 1423 if anime.TotalEpisodes == 0 {
1371 CurdOut("Still unable to determine total episodes.") 1424 CurdOut("Still unable to determine total episodes.")
1372 CurdOut(fmt.Sprintf("Your %s progress: %d", RemoteTrackingDisplayName(userCurdConfig), selectedAnilistAnime.Progress)) 1425 CurdOut(fmt.Sprintf("Your %s progress: %d", RemoteTrackingDisplayName(userCurdConfig), selectedAnilistAnime.Progress))
1373 var episodeNumber int 1426 episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, "Enter the episode you want to start from")
1374 if userCurdConfig.RofiSelection { 1427 if err != nil {
1375 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from") 1428 Log("Invalid episode input: " + err.Error())
1376 if err != nil { 1429 ExitCurd(fmt.Errorf("Invalid episode number"))
1377 Log("Error getting user input: " + err.Error())
1378 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1379 }
1380 episodeNumber, err = strconv.Atoi(userInput)
1381 } else {
1382 fmt.Print("Enter the episode you want to start from: ")
1383 fmt.Scanln(&episodeNumber)
1384 } 1430 }
1385 anime.Ep.Number = episodeNumber 1431 anime.Ep.Number = episodeNumber
1386 } else { 1432 } else {
1387 anime.Ep.Number = selectedAnilistAnime.Progress + 1 1433 anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
1388 } 1434 }
1389 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases 1435 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
1390 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number)) 1436 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
@@ -1400,7 +1446,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1400 fmt.Printf("Would like to start the anime from beginning? (y/n)\n") 1446 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
1401 fmt.Scanln(&answer) 1447 fmt.Scanln(&answer)
1402 } 1448 }
1403 if answer == "y" { 1449 if isAffirmativeAnswer(answer) {
1404 anime.Ep.Number = 1 1450 anime.Ep.Number = 1
1405 } else { 1451 } else {
1406 anime.Ep.Number = anime.TotalEpisodes 1452 anime.Ep.Number = anime.TotalEpisodes
@@ -1431,6 +1477,77 @@ func WriteTokenToFile(token string, filePath string) error {
1431 return nil 1477 return nil
1432} 1478}
1433 1479
1480func handleUnreleasedAnime(userCurdConfig *CurdConfig, user *User, anime *Anime, entry Entry) {
1481 title := entry.Media.Title.Romaji
1482 if userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" && entry.Media.Title.English != "" {
1483 title = entry.Media.Title.English
1484 }
1485 if title == "" {
1486 title = strconv.Itoa(entry.Media.ID)
1487 }
1488
1489 CurdOut(fmt.Sprintf("%s is not released yet.", title))
1490 options := []SelectionOption{}
1491 if UsesRemoteTracking(userCurdConfig) {
1492 options = append(options, SelectionOption{Key: "planning", Label: "Add to Plan to Watch"})
1493 }
1494 options = append(options,
1495 SelectionOption{Key: "details", Label: "Open AniList details"},
1496 SelectionOption{Key: "back", Label: "Back to list"},
1497 )
1498
1499 selected, err := promptSelect(options)
1500 if err != nil {
1501 Log(fmt.Sprintf("Error in unreleased anime prompt: %v", err))
1502 anime.Ep.ContinueLast = false
1503 return
1504 }
1505
1506 switch selected.Key {
1507 case "planning":
1508 if err := AddAnimeToList(entry.Media.ID, "PLANNING", user.Token); err != nil {
1509 Log(fmt.Sprintf("Error adding unreleased anime to planning: %v", err))
1510 CurdOut("Failed to add to Plan to Watch.")
1511 } else {
1512 CurdOut("Added to Plan to Watch.")
1513 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
1514 Log("Error refreshing anime list: " + err.Error())
1515 }
1516 }
1517 case "details":
1518 url := fmt.Sprintf("https://anilist.co/anime/%d", entry.Media.ID)
1519 CurdOut(fmt.Sprintf("Opening %s", url))
1520 if err := browser.OpenURL(url); err != nil {
1521 Log(fmt.Sprintf("Error opening browser: %v", err))
1522 CurdOut("Failed to open browser.")
1523 }
1524 case "-1":
1525 ExitCurd(nil)
1526 }
1527 anime.Ep.ContinueLast = false
1528}
1529
1530func confirmProviderMatch(option SelectionOption, reason string) bool {
1531 label := option.Label
1532 if label == "" {
1533 label = option.Title
1534 }
1535 if label == "" {
1536 label = option.Key
1537 }
1538
1539 CurdOut(fmt.Sprintf("Provider match found by %s: %s", reason, label))
1540 selected, err := promptSelect([]SelectionOption{
1541 {Key: "use", Label: "Use this match"},
1542 {Key: "manual", Label: "Select manually"},
1543 })
1544 if err != nil {
1545 Log(fmt.Sprintf("Error confirming provider match: %v", err))
1546 return false
1547 }
1548 return selected.Key == "use"
1549}
1550
1434func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string { 1551func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1435 if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil { 1552 if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil {
1436 Log(fmt.Sprintf("Failed to resolve provider id: %v", err)) 1553 Log(fmt.Sprintf("Failed to resolve provider id: %v", err))
@@ -1452,17 +1569,17 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1452 anime.Ep.Links = anime.Ep.NextEpisode.Links 1569 anime.Ep.Links = anime.Ep.NextEpisode.Links
1453 } else { 1570 } else {
1454 // Get episode link 1571 // Get episode link
1455 link, err := GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number) 1572 link, playbackMode, err := GetEpisodeURLForPlayback(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
1456 if len(link) > 0 { 1573 if len(link) > 0 {
1457 Log(fmt.Sprintf("Links details: %+v", link)) 1574 Log(fmt.Sprintf("Links details (%s): %+v", playbackMode, link))
1458 } 1575 }
1459 if err != nil { 1576 if err != nil {
1460 linkErr := err 1577 linkErr := err
1461 Log(fmt.Sprintf("GetEpisodeURL failed: %v", linkErr)) 1578 Log(fmt.Sprintf("GetEpisodeURL failed: %v", linkErr))
1462 if reselectProviderAnime(userCurdConfig, anime, linkErr) { 1579 if reselectProviderAnime(userCurdConfig, anime, linkErr) {
1463 link, err = GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number) 1580 link, playbackMode, err = GetEpisodeURLForPlayback(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
1464 if err == nil { 1581 if err == nil {
1465 Log(fmt.Sprintf("Successfully retrieved episode link after provider reselect. Links count: %d", len(link))) 1582 Log(fmt.Sprintf("Successfully retrieved %s episode link after provider reselect. Links count: %d", playbackMode, len(link)))
1466 anime.Ep.Links = link 1583 anime.Ep.Links = link
1467 goto episodeLinksReady 1584 goto episodeLinksReady
1468 } 1585 }
@@ -1483,24 +1600,21 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1483 RestoreScreen() 1600 RestoreScreen()
1484 os.Exit(1) 1601 os.Exit(1)
1485 } 1602 }
1486 if userCurdConfig.RofiSelection { 1603 episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1487 userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1])) 1604 if err != nil {
1488 if err != nil { 1605 Log("Invalid episode input: " + err.Error())
1489 Log("Error getting user input: " + err.Error()) 1606 CurdOut("Invalid episode number")
1490 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) 1607 RestoreScreen()
1491 } 1608 os.Exit(1)
1492 anime.Ep.Number, err = strconv.Atoi(userInput)
1493 } else {
1494 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1495 fmt.Scanln(&anime.Ep.Number)
1496 } 1609 }
1497 link, err = GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number) 1610 anime.Ep.Number = episodeNumber
1611 link, _, err = GetEpisodeURLForPlayback(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
1498 if err != nil { 1612 if err != nil {
1499 CurdOut("Failed to get episode link") 1613 CurdOut("Failed to get episode link")
1500 os.Exit(1) 1614 os.Exit(1)
1501 } 1615 }
1502 } else { 1616 } else {
1503 Log(fmt.Sprintf("Successfully retrieved episode link on first try. Links count: %d", len(link))) 1617 Log(fmt.Sprintf("Successfully retrieved %s episode link on first try. Links count: %d", playbackMode, len(link)))
1504 } 1618 }
1505 anime.Ep.Links = link 1619 anime.Ep.Links = link
1506 } 1620 }
@@ -1643,7 +1757,7 @@ func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason erro
1643 } 1757 }
1644 1758
1645 CurdOut("The saved Animepahe mapping is stale. Please select the anime again.") 1759 CurdOut("The saved Animepahe mapping is stale. Please select the anime again.")
1646 selected, err := DynamicSelect(options) 1760 selected, err := promptSelect(options)
1647 if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" { 1761 if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" {
1648 if err != nil { 1762 if err != nil {
1649 Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err)) 1763 Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err))
@@ -1678,23 +1792,32 @@ func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1678 } 1792 }
1679 1793
1680 // Download file if it doesn't exist 1794 // Download file if it doesn't exist
1681 resp, err := http.Get(baseURL + fileName) 1795 resp, err := sharedHTTPClient.Get(baseURL + fileName)
1682 if err != nil { 1796 if err != nil {
1683 return fmt.Errorf("failed to download %s: %v", fileName, err) 1797 return fmt.Errorf("failed to download %s: %v", fileName, err)
1684 } 1798 }
1685 defer resp.Body.Close() 1799 if resp.StatusCode != http.StatusOK {
1800 resp.Body.Close()
1801 return fmt.Errorf("failed to download %s: received status code %d", fileName, resp.StatusCode)
1802 }
1686 1803
1687 // Create the file 1804 // Create the file
1688 out, err := os.Create(filePath) 1805 out, err := os.Create(filePath)
1689 if err != nil { 1806 if err != nil {
1807 resp.Body.Close()
1690 return fmt.Errorf("failed to create file %s: %v", fileName, err) 1808 return fmt.Errorf("failed to create file %s: %v", fileName, err)
1691 } 1809 }
1692 defer out.Close()
1693 1810
1694 // Write the content 1811 // Write the content
1695 if _, err := io.Copy(out, resp.Body); err != nil { 1812 if _, err := io.Copy(out, resp.Body); err != nil {
1813 resp.Body.Close()
1814 out.Close()
1696 return fmt.Errorf("failed to write file %s: %v", fileName, err) 1815 return fmt.Errorf("failed to write file %s: %v", fileName, err)
1697 } 1816 }
1817 resp.Body.Close()
1818 if err := out.Close(); err != nil {
1819 return fmt.Errorf("failed to close file %s: %v", fileName, err)
1820 }
1698 } 1821 }
1699 1822
1700 return nil 1823 return nil
@@ -1737,11 +1860,20 @@ func NextEpisodePromptCLI(userCurdConfig *CurdConfig) bool {
1737 1860
1738 // Show the next episode number that will be started 1861 // Show the next episode number that will be started
1739 nextEpisodeNum := anime.Ep.Number + 1 1862 nextEpisodeNum := anime.Ep.Number + 1
1740 CurdOut(fmt.Sprintf("Start next episode (%d)?", nextEpisodeNum)) 1863 isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1864 if isLastKnownEpisode {
1865 CurdOut("Finish this series?")
1866 } else {
1867 CurdOut(fmt.Sprintf("Start next episode (%d)?", nextEpisodeNum))
1868 }
1741 1869
1742 // Create options for the selection - no "quit" option since it's built into selection menu 1870 // Create options for the selection - no "quit" option since it's built into selection menu
1871 label := fmt.Sprintf("Yes, continue to episode %d", nextEpisodeNum)
1872 if isLastKnownEpisode {
1873 label = "Yes, finish series"
1874 }
1743 options := []SelectionOption{ 1875 options := []SelectionOption{
1744 {Key: "yes", Label: fmt.Sprintf("Yes, continue to episode %d", nextEpisodeNum)}, 1876 {Key: "yes", Label: label},
1745 } 1877 }
1746 1878
1747 // Use DynamicSelect for CLI mode 1879 // Use DynamicSelect for CLI mode
@@ -1776,11 +1908,20 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string
1776 1908
1777 // Show the next episode number that will be started 1909 // Show the next episode number that will be started
1778 nextEpisodeNum := anime.Ep.Number + 1 1910 nextEpisodeNum := anime.Ep.Number + 1
1779 CurdOut(fmt.Sprintf("Continue to next episode (%d) or quit?", nextEpisodeNum)) 1911 isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1912 if isLastKnownEpisode {
1913 CurdOut("Finish this series or quit?")
1914 } else {
1915 CurdOut(fmt.Sprintf("Continue to next episode (%d) or quit?", nextEpisodeNum))
1916 }
1780 1917
1781 // Create options for the selection - no "quit" option since it's built into selection menu 1918 // Create options for the selection - no "quit" option since it's built into selection menu
1919 label := "Yes, start next episode now"
1920 if isLastKnownEpisode {
1921 label = "Yes, finish series"
1922 }
1782 options := []SelectionOption{ 1923 options := []SelectionOption{
1783 {Key: "yes", Label: "Yes, start next episode now"}, 1924 {Key: "yes", Label: label},
1784 } 1925 }
1785 1926
1786 // Use DynamicSelect for CLI mode 1927 // Use DynamicSelect for CLI mode
@@ -1808,18 +1949,17 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string
1808 } 1949 }
1809 1950
1810 // Update local database 1951 // Update local database
1811 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime), GetProvider().Name()) 1952 if updateErr := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime), GetProvider().Name()); updateErr != nil {
1812 if err != nil { 1953 Log("Error updating local database on quit: " + updateErr.Error())
1813 Log("Error updating local database on quit: " + err.Error())
1814 } 1954 }
1815 1955
1816 if !(anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && anime.Rewatching) { 1956 if !(anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && anime.Rewatching) {
1817 go func() { 1957 completedEpisode := anime.Ep.Number
1818 err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number) 1958 go func(progressEpisode int) {
1819 if err != nil { 1959 if progressErr := UpdateAnimeProgress(userToken, anime.AnilistId, progressEpisode); progressErr != nil {
1820 Log("Error updating Anilist progress on quit: " + err.Error()) 1960 Log("Error updating Anilist progress on quit: " + progressErr.Error())
1821 } 1961 }
1822 }() 1962 }(completedEpisode)
1823 } 1963 }
1824 1964
1825 CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched)) 1965 CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched))
@@ -1835,40 +1975,12 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string
1835 if selectedOption.Key == "yes" { 1975 if selectedOption.Key == "yes" {
1836 // User wants to start next episode immediately 1976 // User wants to start next episode immediately
1837 anime.Ep.IsCompleted = true 1977 anime.Ep.IsCompleted = true
1838 1978 socketPath := anime.Ep.Player.SocketPath
1839 // Update database with completed episode first 1979 if anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes {
1840 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime), GetProvider().Name()) 1980 ExitMPV(socketPath)
1841 if err != nil {
1842 Log("Error updating local database with completed episode: " + err.Error())
1843 } 1981 }
1844 1982 StartNextEpisode(anime, userCurdConfig, databaseFile, userToken)
1845 go func() { 1983 ExitMPV(socketPath)
1846 err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number)
1847 if err != nil {
1848 Log("Error updating Anilist progress: " + err.Error())
1849 }
1850 }()
1851
1852 // Increment to next episode and update database with next episode number and 0 playback time
1853 anime.Ep.Number++
1854
1855 // Use prefetched links if available for the next episode
1856 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1857 anime.Ep.Links = anime.Ep.NextEpisode.Links
1858 Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number))
1859 } else {
1860 // Clear links to force fetching new ones
1861 anime.Ep.Links = []string{}
1862 Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
1863 }
1864
1865 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, GetAnimeName(*anime), GetProvider().Name())
1866 if err != nil {
1867 Log("Error updating local database with next episode: " + err.Error())
1868 }
1869
1870 CurdOut("Starting next episode now...")
1871 ExitMPV(anime.Ep.Player.SocketPath)
1872 return // Exit this function, let the main loop handle next episode 1984 return // Exit this function, let the main loop handle next episode
1873 } 1985 }
1874 } 1986 }
@@ -1880,10 +1992,15 @@ func NextEpisodePromptRofi(userCurdConfig *CurdConfig) bool {
1880 1992
1881 // Show the next episode number that will be started 1993 // Show the next episode number that will be started
1882 nextEpisodeNum := anime.Ep.Number + 1 1994 nextEpisodeNum := anime.Ep.Number + 1
1995 isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1883 1996
1884 // Create options for the selection 1997 // Create options for the selection
1998 label := fmt.Sprintf("Yes, start episode %d", nextEpisodeNum)
1999 if isLastKnownEpisode {
2000 label = "Yes, finish series"
2001 }
1885 options := []SelectionOption{ 2002 options := []SelectionOption{
1886 {Key: "yes", Label: fmt.Sprintf("Yes, start episode %d", nextEpisodeNum)}, 2003 {Key: "yes", Label: label},
1887 } 2004 }
1888 2005
1889 // Use DynamicSelect for Rofi mode 2006 // Use DynamicSelect for Rofi mode
@@ -1956,9 +2073,8 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
1956 } 2073 }
1957 2074
1958 go func() { 2075 go func() {
1959 err = UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode) 2076 if progressErr := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode); progressErr != nil {
1960 if err != nil { 2077 Log("Error updating Anilist progress: " + progressErr.Error())
1961 Log("Error updating Anilist progress: " + err.Error())
1962 } 2078 }
1963 }() 2079 }()
1964 2080
@@ -1968,9 +2084,14 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
1968 2084
1969// HandleLastEpisodeCompletion handles scoring and completion for the last episode 2085// HandleLastEpisodeCompletion handles scoring and completion for the last episode
1970func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) { 2086func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
1971 // Check if this is the last episode and scoring is enabled 2087 if anime.TotalEpisodes <= 0 || anime.Ep.Number != anime.TotalEpisodes {
1972 if userCurdConfig.ScoreOnCompletion && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !anime.IsAiring { 2088 return
1973 // Prompt user to score the anime 2089 }
2090
2091 summary := []string{}
2092 canWriteRemote := ShouldWriteRemoteTracking(userCurdConfig, anime)
2093
2094 if userCurdConfig.ScoreOnCompletion && !anime.IsAiring && canWriteRemote {
1974 CurdOut("You've completed this anime! Would you like to rate it?") 2095 CurdOut("You've completed this anime! Would you like to rate it?")
1975 2096
1976 scoreOptions := []SelectionOption{ 2097 scoreOptions := []SelectionOption{
@@ -1986,46 +2107,60 @@ func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userT
1986 if err != nil { 2107 if err != nil {
1987 Log(fmt.Sprintf("Error rating anime: %v", err)) 2108 Log(fmt.Sprintf("Error rating anime: %v", err))
1988 CurdOut("Failed to rate anime") 2109 CurdOut("Failed to rate anime")
2110 summary = append(summary, "rating failed")
1989 } else { 2111 } else {
1990 CurdOut("Anime rated successfully!") 2112 CurdOut("Anime rated successfully!")
2113 summary = append(summary, "rating saved")
1991 } 2114 }
2115 } else {
2116 summary = append(summary, "rating skipped")
1992 } 2117 }
1993 // Back (-2) and no are treated as skip 2118 // Back (-2) and no are treated as skip
2119 } else {
2120 summary = append(summary, "rating skipped")
1994 } 2121 }
1995 2122
1996 // Update anime status to completed on AniList. 2123 if !anime.IsAiring && canWriteRemote {
1997 // For rewatches, preserve the original completion date and only increment repeat count.
1998 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !anime.IsAiring {
1999 if anime.Rewatching { 2124 if anime.Rewatching {
2000 err := CompleteAnimeRewatch(userToken, *anime) 2125 err := CompleteAnimeRewatch(userToken, *anime)
2001 if err != nil { 2126 if err != nil {
2002 Log("Error completing anime rewatch: " + err.Error()) 2127 Log("Error completing anime rewatch: " + err.Error())
2128 summary = append(summary, "rewatch completion failed")
2129 } else {
2130 summary = append(summary, "rewatch completed")
2003 } 2131 }
2004 } else { 2132 } else {
2005 err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED") 2133 err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED")
2006 if err != nil { 2134 if err != nil {
2007 Log("Error updating anime status to completed: " + err.Error()) 2135 Log("Error updating anime status to completed: " + err.Error())
2136 summary = append(summary, "status update failed")
2137 } else {
2138 summary = append(summary, "marked completed")
2008 } 2139 }
2009 // Note: UpdateAnimeStatus already outputs a message on success
2010 } 2140 }
2141 } else if !anime.IsAiring {
2142 summary = append(summary, "tracker updates skipped")
2011 } 2143 }
2012 2144
2013 // Check for sequel after completion (only if this is the last episode) 2145 if sequelSummary := handleSequelCheck(userCurdConfig, anime, userToken); sequelSummary != "" {
2014 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes { 2146 summary = append(summary, sequelSummary)
2015 handleSequelCheck(userCurdConfig, anime, userToken) 2147 }
2148 if len(summary) > 0 {
2149 CurdOut("Completion summary: " + strings.Join(summary, "; "))
2016 } 2150 }
2017} 2151}
2018 2152
2019// handleSequelCheck checks for sequels and prompts the user accordingly 2153// handleSequelCheck checks for sequels and prompts the user accordingly
2020func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken string) { 2154func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken string) (summary string) {
2021 if !UsesRemoteTracking(userCurdConfig) { 2155 if !ShouldWriteRemoteTracking(userCurdConfig, anime) {
2022 return 2156 return "sequel check skipped"
2023 } 2157 }
2024 2158
2025 // Recover from any panics in this function to prevent crashes 2159 // Recover from any panics in this function to prevent crashes
2026 defer func() { 2160 defer func() {
2027 if r := recover(); r != nil { 2161 if r := recover(); r != nil {
2028 Log(fmt.Sprintf("Recovered from panic in handleSequelCheck: %v", r)) 2162 Log(fmt.Sprintf("Recovered from panic in handleSequelCheck: %v", r))
2163 summary = "sequel check failed"
2029 } 2164 }
2030 }() 2165 }()
2031 2166
@@ -2033,200 +2168,146 @@ func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken strin
2033 sequels, err := GetAnimeSequel(anime.AnilistId, userToken) 2168 sequels, err := GetAnimeSequel(anime.AnilistId, userToken)
2034 if err != nil { 2169 if err != nil {
2035 Log(fmt.Sprintf("Error fetching sequel information: %v", err)) 2170 Log(fmt.Sprintf("Error fetching sequel information: %v", err))
2036 return 2171 return "sequel check failed"
2037 } 2172 }
2038 2173
2039 if len(sequels) == 0 { 2174 if len(sequels) == 0 {
2040 Log("No sequel found for this anime") 2175 Log("No sequel found for this anime")
2041 return 2176 return "no sequel found"
2042 } 2177 }
2043 2178
2179 sequel := &sequels[0]
2044 if len(sequels) > 1 { 2180 if len(sequels) > 1 {
2045 CurdOut("Multiple sequels found for this anime.") 2181 selectedSequel, ok := selectSequel(userCurdConfig, sequels)
2046 options := []SelectionOption{ 2182 if !ok {
2047 {Key: "yes", Label: "Open AniList page to view sequels"}, 2183 return "sequel skipped"
2048 {Key: "no", Label: "Ignore"},
2049 } 2184 }
2185 sequel = selectedSequel
2186 }
2050 2187
2051 selectedOption, err := DynamicSelect(options) 2188 return promptSequelAction(userCurdConfig, sequel, userToken)
2052 if err != nil { 2189}
2053 Log(fmt.Sprintf("Error in multiple sequel prompt: %v", err))
2054 return
2055 }
2056 2190
2057 if selectedOption.Key == "yes" { 2191func selectSequel(userCurdConfig *CurdConfig, sequels []SequelInfo) (*SequelInfo, bool) {
2058 url := fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId) 2192 CurdOut("Multiple sequels found.")
2059 CurdOut(fmt.Sprintf("Opening %s", url)) 2193 options := make([]SelectionOption, 0, len(sequels)+1)
2060 if err := browser.OpenURL(url); err != nil { 2194 for i := range sequels {
2061 Log(fmt.Sprintf("Error opening browser: %v", err)) 2195 title := sequelDisplayTitle(userCurdConfig, &sequels[i])
2062 CurdOut("Failed to open browser.") 2196 status := strings.ToLower(strings.ReplaceAll(sequels[i].Status, "_", " "))
2063 } 2197 options = append(options, SelectionOption{
2064 } 2198 Key: strconv.Itoa(i),
2065 return 2199 Label: fmt.Sprintf("%s (%s)", title, status),
2200 })
2066 } 2201 }
2202 options = append(options, SelectionOption{Key: "skip", Label: "Skip"})
2067 2203
2068 sequel := &sequels[0] 2204 selected, err := promptSelect(options)
2069 2205 if err != nil {
2070 // Get sequel title based on user's language preference 2206 Log(fmt.Sprintf("Error selecting sequel: %v", err))
2071 sequelTitle := sequel.Title.Romaji 2207 return nil, false
2072 if sequel.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" { 2208 }
2073 sequelTitle = sequel.Title.English 2209 if selected.Key == "skip" || selected.Key == "-1" || selected.Key == "-2" {
2210 return nil, false
2211 }
2212 index, err := strconv.Atoi(selected.Key)
2213 if err != nil || index < 0 || index >= len(sequels) {
2214 return nil, false
2074 } 2215 }
2216 return &sequels[index], true
2217}
2075 2218
2076 Log(fmt.Sprintf("Found sequel: %s (ID: %d)", sequelTitle, sequel.ID)) 2219func sequelDisplayTitle(userCurdConfig *CurdConfig, sequel *SequelInfo) string {
2220 if sequel == nil {
2221 return ""
2222 }
2223 if userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" && sequel.Title.English != "" {
2224 return sequel.Title.English
2225 }
2226 if sequel.Title.Romaji != "" {
2227 return sequel.Title.Romaji
2228 }
2229 return strconv.Itoa(sequel.ID)
2230}
2077 2231
2078 // Check if sequel is not yet released 2232func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToken string) string {
2079 if sequel.Status == "NOT_YET_RELEASED" { 2233 if sequel == nil {
2080 CurdOut(fmt.Sprintf("A sequel '%s' is announced but not yet released.", sequelTitle)) 2234 return ""
2081 return
2082 } 2235 }
2083 2236
2237 sequelTitle := sequelDisplayTitle(userCurdConfig, sequel)
2238 Log(fmt.Sprintf("Found sequel: %s (ID: %d)", sequelTitle, sequel.ID))
2239
2084 currentUser := GetGlobalUser() 2240 currentUser := GetGlobalUser()
2085 userAnimeList := AnimeList{} 2241 userAnimeList := AnimeList{}
2086 if currentUser != nil { 2242 if currentUser != nil {
2087 userAnimeList = currentUser.AnimeList 2243 userAnimeList = currentUser.AnimeList
2088 } 2244 }
2089 if !hasAnyEntries(userAnimeList) { 2245 sequelStatus, isInList := "", false
2090 Log("Tracked anime list is empty, skipping sequel list check") 2246 if hasAnyEntries(userAnimeList) {
2091 promptSequelNotInList(sequel, sequelTitle, userToken, anime) 2247 sequelStatus, isInList = FindSequelInAnimeList(userAnimeList, sequel.ID)
2092 return
2093 } 2248 }
2094 sequelStatus, isInList := FindSequelInAnimeList(userAnimeList, sequel.ID)
2095
2096 if !isInList {
2097 // Sequel is not in any list - ask if user wants to add it
2098 CurdOut(fmt.Sprintf("A sequel is available: %s", sequelTitle))
2099 2249
2100 options := []SelectionOption{ 2250 if isInList {
2101 {Key: "watching", Label: "Add to Watching list"}, 2251 CurdOut(fmt.Sprintf("Sequel found: %s (%s)", sequelTitle, sequelStatus))
2102 {Key: "planning", Label: "Add to Plan to Watch"},
2103 {Key: "skip", Label: "No thanks"},
2104 }
2105
2106 selectedOption, err := DynamicSelect(options)
2107 if err != nil {
2108 Log(fmt.Sprintf("Error in sequel prompt: %v", err))
2109 return
2110 }
2111
2112 switch selectedOption.Key {
2113 case "watching":
2114 err = AddAnimeToList(sequel.ID, "CURRENT", userToken)
2115 if err != nil {
2116 Log(fmt.Sprintf("Error adding sequel to watching list: %v", err))
2117 CurdOut("Failed to add sequel to watching list")
2118 } else {
2119 CurdOut(fmt.Sprintf("Added '%s' to your Watching list!", sequelTitle))
2120 }
2121 case "planning":
2122 err = AddAnimeToList(sequel.ID, "PLANNING", userToken)
2123 if err != nil {
2124 Log(fmt.Sprintf("Error adding sequel to planning list: %v", err))
2125 CurdOut("Failed to add sequel to Plan to Watch")
2126 } else {
2127 CurdOut(fmt.Sprintf("Added '%s' to your Plan to Watch list!", sequelTitle))
2128 }
2129 case "skip", "-1":
2130 Log("User declined to add sequel")
2131 }
2132 } else { 2252 } else {
2133 // Sequel is already in a list 2253 CurdOut(fmt.Sprintf("Sequel found: %s", sequelTitle))
2134 switch sequelStatus { 2254 }
2135 case "CURRENT":
2136 // Already in watching list
2137 CurdOut(fmt.Sprintf("The sequel '%s' is already in your Watching list!", sequelTitle))
2138
2139 case "PLANNING":
2140 // In planning list - ask if user wants to move to watching
2141 CurdOut(fmt.Sprintf("The sequel '%s' is in your Plan to Watch list. Move to Watching?", sequelTitle))
2142
2143 options := []SelectionOption{
2144 {Key: "yes", Label: "Yes, move to Watching list"},
2145 {Key: "no", Label: "No, keep in Plan to Watch"},
2146 }
2147
2148 selectedOption, err := DynamicSelect(options)
2149 if err != nil {
2150 Log(fmt.Sprintf("Error in sequel planning prompt: %v", err))
2151 return
2152 }
2153
2154 if selectedOption.Key == "yes" {
2155 err = AddAnimeToList(sequel.ID, "CURRENT", userToken)
2156 if err != nil {
2157 Log(fmt.Sprintf("Error moving sequel to watching list: %v", err))
2158 CurdOut("Failed to move sequel to Watching list")
2159 } else {
2160 CurdOut(fmt.Sprintf("Moved '%s' to Watching list!", sequelTitle))
2161 }
2162 }
2163
2164 case "COMPLETED":
2165 CurdOut(fmt.Sprintf("You've already completed the sequel '%s'!", sequelTitle))
2166
2167 case "PAUSED", "DROPPED":
2168 CurdOut(fmt.Sprintf("The sequel '%s' is in your %s list.", sequelTitle, sequelStatus))
2169
2170 options := []SelectionOption{
2171 {Key: "yes", Label: "Move to Watching list"},
2172 {Key: "no", Label: "No thanks"},
2173 }
2174
2175 selectedOption, err := DynamicSelect(options)
2176 if err != nil {
2177 Log(fmt.Sprintf("Error in sequel resume prompt: %v", err))
2178 return
2179 }
2180 2255
2181 if selectedOption.Key == "yes" { 2256 options := []SelectionOption{}
2182 err = AddAnimeToList(sequel.ID, "CURRENT", userToken) 2257 if sequel.Status != "NOT_YET_RELEASED" {
2183 if err != nil { 2258 if !isInList || sequelStatus == "PLANNING" || sequelStatus == "PAUSED" || sequelStatus == "DROPPED" {
2184 Log(fmt.Sprintf("Error moving sequel to watching list: %v", err)) 2259 options = append(options, SelectionOption{Key: "watching", Label: "Add to Watching"})
2185 CurdOut("Failed to move sequel to Watching list")
2186 } else {
2187 CurdOut(fmt.Sprintf("Moved '%s' to Watching list!", sequelTitle))
2188 }
2189 }
2190 } 2260 }
2191 } 2261 }
2192} 2262 if !isInList || sequelStatus != "PLANNING" {
2193 2263 options = append(options, SelectionOption{Key: "planning", Label: "Add to Plan to Watch"})
2194// promptSequelNotInList prompts user to add sequel when we can't check their list
2195func promptSequelNotInList(sequel *SequelInfo, sequelTitle string, userToken string, anime *Anime) {
2196 CurdOut(fmt.Sprintf("A sequel is available: %s", sequelTitle))
2197
2198 options := []SelectionOption{
2199 {Key: "watching", Label: "Add to Watching list"},
2200 {Key: "planning", Label: "Add to Plan to Watch"},
2201 {Key: "skip", Label: "No thanks"},
2202 } 2264 }
2265 options = append(options,
2266 SelectionOption{Key: "details", Label: "Open AniList details"},
2267 SelectionOption{Key: "skip", Label: "Skip"},
2268 )
2203 2269
2204 selectedOption, err := DynamicSelect(options) 2270 selected, err := promptSelect(options)
2205 if err != nil { 2271 if err != nil {
2206 Log(fmt.Sprintf("Error in sequel prompt: %v", err)) 2272 Log(fmt.Sprintf("Error in sequel action prompt: %v", err))
2207 return 2273 return "sequel action failed"
2208 } 2274 }
2209 2275
2210 switch selectedOption.Key { 2276 switch selected.Key {
2211 case "watching": 2277 case "watching":
2212 err = AddAnimeToList(sequel.ID, "CURRENT", userToken) 2278 if err := AddAnimeToList(sequel.ID, "CURRENT", userToken); err != nil {
2213 if err != nil {
2214 Log(fmt.Sprintf("Error adding sequel to watching list: %v", err)) 2279 Log(fmt.Sprintf("Error adding sequel to watching list: %v", err))
2215 CurdOut("Failed to add sequel to watching list") 2280 CurdOut("Failed to add sequel to Watching.")
2281 return "sequel add failed"
2216 } else { 2282 } else {
2217 CurdOut(fmt.Sprintf("Added '%s' to your Watching list!", sequelTitle)) 2283 CurdOut(fmt.Sprintf("Added '%s' to Watching.", sequelTitle))
2284 return "sequel added to Watching"
2218 } 2285 }
2219 case "planning": 2286 case "planning":
2220 err = AddAnimeToList(sequel.ID, "PLANNING", userToken) 2287 if err := AddAnimeToList(sequel.ID, "PLANNING", userToken); err != nil {
2221 if err != nil {
2222 Log(fmt.Sprintf("Error adding sequel to planning list: %v", err)) 2288 Log(fmt.Sprintf("Error adding sequel to planning list: %v", err))
2223 CurdOut("Failed to add sequel to Plan to Watch") 2289 CurdOut("Failed to add sequel to Plan to Watch.")
2290 return "sequel add failed"
2224 } else { 2291 } else {
2225 CurdOut(fmt.Sprintf("Added '%s' to your Plan to Watch list!", sequelTitle)) 2292 CurdOut(fmt.Sprintf("Added '%s' to Plan to Watch.", sequelTitle))
2293 return "sequel added to Plan to Watch"
2294 }
2295 case "details":
2296 url := sequel.SiteURL
2297 if url == "" {
2298 url = fmt.Sprintf("https://anilist.co/anime/%d", sequel.ID)
2299 }
2300 CurdOut(fmt.Sprintf("Opening %s", url))
2301 if err := browser.OpenURL(url); err != nil {
2302 Log(fmt.Sprintf("Error opening browser: %v", err))
2303 CurdOut("Failed to open browser.")
2304 return "sequel details failed"
2226 } 2305 }
2227 case "skip", "-1": 2306 return "sequel details opened"
2228 Log("User declined to add sequel") 2307 case "skip", "-1", "-2":
2308 Log("User skipped sequel action")
2229 } 2309 }
2310 return "sequel skipped"
2230} 2311}
2231 2312
2232// ChangeProvider allows the user to switch the anime provider 2313// ChangeProvider allows the user to switch the anime provider
internal/episode_list.go +5 −9
@@ -35,7 +35,7 @@ type episodesResponse struct {
35func getAllAnimeEpisodesList(showID, mode string) ([]string, error) { 35func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
36 preferredMode := normalizeTranslationType(mode) 36 preferredMode := normalizeTranslationType(mode)
37 37
38 episodesListGql := `query ($showId String!) { show( _id: $showId ) { _id availableEpisodesDetail }}` 38 episodesListGql := `query ($showId: String!) { show( _id: $showId ) { _id availableEpisodesDetail }}`
39 39
40 // Build POST request body 40 // Build POST request body
41 requestBody, err := json.Marshal(map[string]interface{}{ 41 requestBody, err := json.Marshal(map[string]interface{}{
@@ -68,6 +68,9 @@ func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
68 Log(fmt.Sprint("Error reading response body:", err)) 68 Log(fmt.Sprint("Error reading response body:", err))
69 return nil, err 69 return nil, err
70 } 70 }
71 if !httpStatusOK(resp.StatusCode) {
72 return nil, httpStatusError("allanime episode list", resp.StatusCode, body)
73 }
71 74
72 // Parse the JSON response 75 // Parse the JSON response
73 var response episodesResponse 76 var response episodesResponse
@@ -80,14 +83,7 @@ func getAllAnimeEpisodesList(showID, mode string) ([]string, error) {
80 // Extract and sort the episodes 83 // Extract and sort the episodes
81 episodes := extractEpisodes(response.Data.Show.AvailableEpisodesDetail, preferredMode) 84 episodes := extractEpisodes(response.Data.Show.AvailableEpisodesDetail, preferredMode)
82 if len(episodes) == 0 { 85 if len(episodes) == 0 {
83 fallbackMode := alternateTranslationType(preferredMode) 86 return episodes, fmt.Errorf("no %s episodes found for anime %s", preferredMode, showID)
84 episodes = extractEpisodes(response.Data.Show.AvailableEpisodesDetail, fallbackMode)
85 if len(episodes) > 0 {
86 Log(fmt.Sprintf("Falling back to %s episode list for anime %s", fallbackMode, showID))
87 }
88 }
89 if len(episodes) == 0 {
90 return episodes, fmt.Errorf("no episodes found for anime %s", showID)
91 } 87 }
92 return episodes, nil 88 return episodes, nil
93} 89}
internal/episode_url.go +20 −82
@@ -224,6 +224,10 @@ func extractLinks(provider_id string) map[string]interface{} {
224 Log(fmt.Sprint("Error reading response:", err)) 224 Log(fmt.Sprint("Error reading response:", err))
225 return videoData 225 return videoData
226 } 226 }
227 if !httpStatusOK(resp.StatusCode) {
228 Log(httpStatusError("allanime source extractor", resp.StatusCode, body))
229 return videoData
230 }
227 231
228 // Parse the JSON response 232 // Parse the JSON response
229 err = json.Unmarshal(body, &videoData) 233 err = json.Unmarshal(body, &videoData)
@@ -421,63 +425,7 @@ func extractFilemoonLinks(videoData map[string]interface{}) []string {
421// - error: an error if the episode is not found or if there is an issue during the search. 425// - error: an error if the episode is not found or if there is an issue during the search.
422func getAllanimeEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) { 426func getAllanimeEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
423 preferredMode := normalizeTranslationType(config.SubOrDub) 427 preferredMode := normalizeTranslationType(config.SubOrDub)
424 fallbackMode := alternateTranslationType(preferredMode) 428 return getEpisodeURLForMode(id, preferredMode, epNo)
425
426 type modeResult struct {
427 mode string
428 links []string
429 err error
430 }
431
432 ch := make(chan modeResult, 2)
433
434 go func() {
435 links, err := getEpisodeURLForMode(id, preferredMode, epNo)
436 ch <- modeResult{mode: preferredMode, links: links, err: err}
437 }()
438
439 go func() {
440 links, err := getEpisodeURLForMode(id, fallbackMode, epNo)
441 ch <- modeResult{mode: fallbackMode, links: links, err: err}
442 }()
443
444 var preferredRes, fallbackRes modeResult
445 hasPreferredRes := false
446 hasFallbackRes := false
447 for i := 0; i < 2; i++ {
448 res := <-ch
449
450 if res.mode == preferredMode {
451 preferredRes = res
452 hasPreferredRes = true
453 if res.err == nil && len(res.links) > 0 {
454 return res.links, nil
455 }
456 continue
457 }
458
459 if res.mode == fallbackMode {
460 fallbackRes = res
461 hasFallbackRes = true
462 }
463 }
464
465 if hasPreferredRes && preferredRes.err == nil && len(preferredRes.links) > 0 {
466 return preferredRes.links, nil
467 }
468 if hasFallbackRes && fallbackRes.err == nil && len(fallbackRes.links) > 0 {
469 Log(fmt.Sprintf("Falling back to %s for anime %s episode %d", fallbackMode, id, epNo))
470 return fallbackRes.links, nil
471 }
472
473 if hasPreferredRes && preferredRes.err != nil {
474 return nil, preferredRes.err
475 }
476 if hasFallbackRes && fallbackRes.err != nil {
477 return nil, fallbackRes.err
478 }
479
480 return nil, fmt.Errorf("no valid links found for anime %s episode %d", id, epNo)
481} 429}
482 430
483func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) { 431func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
@@ -529,6 +477,9 @@ func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
529 if err != nil { 477 if err != nil {
530 return nil, fmt.Errorf("failed to read persisted query response: %w", err) 478 return nil, fmt.Errorf("failed to read persisted query response: %w", err)
531 } 479 }
480 if !httpStatusOK(resp.StatusCode) {
481 return nil, httpStatusError("allanime episode persisted query", resp.StatusCode, body)
482 }
532 483
533 var response allanimeResponse 484 var response allanimeResponse
534 if err := json.Unmarshal(body, &response); err != nil { 485 if err := json.Unmarshal(body, &response); err != nil {
@@ -568,6 +519,9 @@ func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) {
568 if err != nil { 519 if err != nil {
569 return nil, fmt.Errorf("failed to read response body: %w", err) 520 return nil, fmt.Errorf("failed to read response body: %w", err)
570 } 521 }
522 if !httpStatusOK(resp.StatusCode) {
523 return nil, httpStatusError("allanime episode fallback query", resp.StatusCode, body)
524 }
571 525
572 if err := json.Unmarshal(body, &response); err != nil { 526 if err := json.Unmarshal(body, &response); err != nil {
573 Log(fmt.Sprint("Error parsing fallback JSON: ", err)) 527 Log(fmt.Sprint("Error parsing fallback JSON: ", err))
@@ -614,7 +568,7 @@ func getLinksFromSourceUrls(sourceUrls []allanimeSource) ([]string, error) {
614 } 568 }
615 569
616 decodedURL := decodeProviderID(sourceURL[2:]) 570 decodedURL := decodeProviderID(sourceURL[2:])
617 if strings.Contains(decodedURL, LinkPriorities[0]) { 571 if len(LinkPriorities) > 0 && strings.Contains(decodedURL, LinkPriorities[0]) {
618 priority := url.Priority 572 priority := url.Priority
619 if priority > highestPriority { 573 if priority > highestPriority {
620 highestPriority = priority 574 highestPriority = priority
@@ -647,7 +601,6 @@ func getLinksFromURLs(validURLs []string) ([]string, error) {
647 601
648 highPriorityLink := make(chan []string, 1) 602 highPriorityLink := make(chan []string, 1)
649 603
650 remainingURLs := len(validURLs)
651 for i, sourceUrl := range validURLs { 604 for i, sourceUrl := range validURLs {
652 go func(idx int, url string) { 605 go func(idx int, url string) {
653 decodedProviderID := decodeProviderID(url[2:]) 606 decodedProviderID := decodeProviderID(url[2:])
@@ -690,8 +643,12 @@ func getLinksFromURLs(validURLs []string) ([]string, error) {
690 } 643 }
691 644
692 // Check if any of the extracted links are high priority 645 // Check if any of the extracted links are high priority
646 priorityDomains := LinkPriorities
647 if len(priorityDomains) > 3 {
648 priorityDomains = priorityDomains[:3]
649 }
693 for _, link := range links { 650 for _, link := range links {
694 for _, domain := range LinkPriorities[:3] { 651 for _, domain := range priorityDomains {
695 if strings.Contains(link, domain) { 652 if strings.Contains(link, domain) {
696 // Found high priority link, send it immediately 653 // Found high priority link, send it immediately
697 select { 654 select {
@@ -719,8 +676,6 @@ func getLinksFromURLs(validURLs []string) ([]string, error) {
719 // First, try to get a high priority link 676 // First, try to get a high priority link
720 select { 677 select {
721 case links := <-highPriorityLink: 678 case links := <-highPriorityLink:
722 // Continue extracting other links in background
723 go collectRemainingResults(results, orderedResults, &successCount, &collectedErrors, remainingURLs)
724 return links, nil 679 return links, nil
725 case <-time.After(2 * time.Second): // Wait only briefly for high priority link 680 case <-time.After(2 * time.Second): // Wait only briefly for high priority link
726 // No high priority link found quickly, proceed with normal collection 681 // No high priority link found quickly, proceed with normal collection
@@ -728,9 +683,11 @@ func getLinksFromURLs(validURLs []string) ([]string, error) {
728 683
729 // Continue with existing result collection logic 684 // Continue with existing result collection logic
730 // Collect results maintaining order 685 // Collect results maintaining order
731 for successCount < len(validURLs) { 686 completedCount := 0
687 for completedCount < len(validURLs) {
732 select { 688 select {
733 case res := <-results: 689 case res := <-results:
690 completedCount++
734 if res.err != nil { 691 if res.err != nil {
735 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err)) 692 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
736 collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err)) 693 collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
@@ -763,25 +720,6 @@ func getLinksFromURLs(validURLs []string) ([]string, error) {
763 return allLinks, nil 720 return allLinks, nil
764} 721}
765 722
766// Helper function to collect remaining results in background
767func collectRemainingResults(results chan result, orderedResults [][]string, successCount *int, collectedErrors *[]error, remainingURLs int) {
768 for *successCount < remainingURLs {
769 select {
770 case res := <-results:
771 if res.err != nil {
772 Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err))
773 *collectedErrors = append(*collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err))
774 } else {
775 orderedResults[res.index] = res.links
776 *successCount++
777 Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, remainingURLs))
778 }
779 case <-time.After(10 * time.Second):
780 return
781 }
782 }
783}
784
785// converts the ordered slice of link slices into a single slice 723// converts the ordered slice of link slices into a single slice
786func flattenResults(results [][]string) []string { 724func flattenResults(results [][]string) []string {
787 var totalLen int 725 var totalLen int
internal/filler_list.go +2 −1
@@ -29,12 +29,13 @@ func FetchFillerEpisodes(malID int) ([]int, error) {
29 for { 29 for {
30 <-rateLimiter.C // Wait for rate limit 30 <-rateLimiter.C // Wait for rate limit
31 url := fmt.Sprintf("%s?page=%d", baseURL, page) 31 url := fmt.Sprintf("%s?page=%d", baseURL, page)
32 resp, err := http.Get(url) 32 resp, err := sharedHTTPClient.Get(url)
33 if err != nil { 33 if err != nil {
34 return nil, fmt.Errorf("error fetching episodes: %v", err) 34 return nil, fmt.Errorf("error fetching episodes: %v", err)
35 } 35 }
36 36
37 if resp.StatusCode == http.StatusTooManyRequests { 37 if resp.StatusCode == http.StatusTooManyRequests {
38 resp.Body.Close()
38 // Wait for 2 seconds and retry 39 // Wait for 2 seconds and retry
39 time.Sleep(2 * time.Second) 40 time.Sleep(2 * time.Second)
40 continue 41 continue
internal/http_client.go +17
@@ -1,9 +1,11 @@
1package internal 1package internal
2 2
3import ( 3import (
4 "fmt"
4 "net/http" 5 "net/http"
5 "net/http/cookiejar" 6 "net/http/cookiejar"
6 "net/url" 7 "net/url"
8 "strings"
7 "time" 9 "time"
8) 10)
9 11
@@ -15,6 +17,21 @@ func SetCookiesForAnimepahe(u *url.URL, cookies []*http.Cookie) {
15 } 17 }
16} 18}
17 19
20func httpStatusOK(statusCode int) bool {
21 return statusCode >= http.StatusOK && statusCode < http.StatusMultipleChoices
22}
23
24func httpStatusError(context string, statusCode int, body []byte) error {
25 snippet := strings.TrimSpace(string(body))
26 if len(snippet) > 300 {
27 snippet = snippet[:300] + "..."
28 }
29 if snippet != "" {
30 return fmt.Errorf("%s failed with status %d: %s", context, statusCode, snippet)
31 }
32 return fmt.Errorf("%s failed with status %d", context, statusCode)
33}
34
18func init() { 35func init() {
19 jar, _ := cookiejar.New(nil) 36 jar, _ := cookiejar.New(nil)
20 sharedHTTPClient = &http.Client{ 37 sharedHTTPClient = &http.Client{
internal/input.go added +77
@@ -0,0 +1,77 @@
1package internal
2
3import (
4 "bufio"
5 "fmt"
6 "io"
7 "os"
8 "strconv"
9 "strings"
10)
11
12func readTrimmedStdinLine() (string, error) {
13 reader := bufio.NewReader(os.Stdin)
14 input, err := reader.ReadString('\n')
15 if err != nil && err != io.EOF {
16 return "", err
17 }
18 return strings.TrimSpace(input), nil
19}
20
21func promptText(config *CurdConfig, prompt string, allowEmpty bool) (string, error) {
22 var input string
23 var err error
24 if config != nil && config.RofiSelection {
25 input, err = GetUserInputFromRofi(prompt)
26 } else {
27 CurdOut(prompt)
28 input, err = readTrimmedStdinLine()
29 }
30 if err != nil {
31 return "", err
32 }
33 input = strings.TrimSpace(input)
34 if input == "" && !allowEmpty {
35 return "", fmt.Errorf("input cannot be empty")
36 }
37 return input, nil
38}
39
40func parseNonNegativeIntInput(input, label string) (int, error) {
41 value, err := strconv.Atoi(strings.TrimSpace(input))
42 if err != nil {
43 return 0, fmt.Errorf("invalid %s: %w", label, err)
44 }
45 if value < 0 {
46 return 0, fmt.Errorf("%s cannot be negative", label)
47 }
48 return value, nil
49}
50
51func parsePositiveIntInput(input, label string) (int, error) {
52 value, err := parseNonNegativeIntInput(input, label)
53 if err != nil {
54 return 0, err
55 }
56 if value == 0 {
57 return 0, fmt.Errorf("%s must be greater than zero", label)
58 }
59 return value, nil
60}
61
62func promptPositiveEpisodeNumber(config *CurdConfig, prompt string) (int, error) {
63 input, err := promptText(config, prompt, false)
64 if err != nil {
65 return 0, err
66 }
67 return parsePositiveIntInput(input, "episode number")
68}
69
70func isAffirmativeAnswer(answer string) bool {
71 switch strings.ToLower(strings.TrimSpace(answer)) {
72 case "y", "yes":
73 return true
74 default:
75 return false
76 }
77}
internal/jikan.go +5 −1
@@ -5,6 +5,7 @@ import (
5 "fmt" 5 "fmt"
6 "io" 6 "io"
7 "net/http" 7 "net/http"
8 "time"
8) 9)
9 10
10// GetEpisodeData fetches episode data for a given anime ID and episode number 11// GetEpisodeData fetches episode data for a given anime ID and episode number
@@ -80,7 +81,10 @@ func makeGetRequest(url string, headers map[string]string) (map[string]interface
80 req.Header.Set(key, value) 81 req.Header.Set(key, value)
81 } 82 }
82 83
83 client := &http.Client{} 84 client := sharedHTTPClient
85 if client == nil {
86 client = &http.Client{Timeout: 15 * time.Second}
87 }
84 resp, err := client.Do(req) 88 resp, err := client.Do(req)
85 if err != nil { 89 if err != nil {
86 return nil, fmt.Errorf("failed to send GET request: %w", err) 90 return nil, fmt.Errorf("failed to send GET request: %w", err)
internal/localTracking.go +99 −74
@@ -1,7 +1,6 @@
1package internal 1package internal
2 2
3import ( 3import (
4 "bufio"
5 "encoding/csv" 4 "encoding/csv"
6 "fmt" 5 "fmt"
7 "os" 6 "os"
@@ -21,7 +20,6 @@ func LocalAddAnime(databaseFile string, anilistID int, allanimeID string, watchi
21 defer file.Close() 20 defer file.Close()
22 21
23 writer := csv.NewWriter(file) 22 writer := csv.NewWriter(file)
24 defer writer.Flush()
25 23
26 err = writer.Write([]string{ 24 err = writer.Write([]string{
27 strconv.Itoa(anilistID), 25 strconv.Itoa(anilistID),
@@ -33,9 +31,14 @@ func LocalAddAnime(databaseFile string, anilistID int, allanimeID string, watchi
33 }) 31 })
34 if err != nil { 32 if err != nil {
35 CurdOut(fmt.Sprintf("Error writing to file: %v", err)) 33 CurdOut(fmt.Sprintf("Error writing to file: %v", err))
36 } else { 34 return
37 CurdOut("Written to file") 35 }
36 writer.Flush()
37 if err := writer.Error(); err != nil {
38 CurdOut(fmt.Sprintf("Error flushing file: %v", err))
39 return
38 } 40 }
41 CurdOut("Written to file")
39} 42}
40 43
41func normalizeLocalProviderID(providerName, providerID, animeName string) string { 44func normalizeLocalProviderID(providerName, providerID, animeName string) string {
@@ -74,8 +77,15 @@ func LocalDeleteAnime(databaseFile string, anilistID int, allanimeID string) {
74 77
75 // Filter out the anime entry 78 // Filter out the anime entry
76 for _, row := range records { 79 for _, row := range records {
77 aid, _ := strconv.Atoi(row[0]) // Anilist ID 80 anime := parseAnimeRow(row)
78 if aid != anilistID || row[1] != allanimeID { 81 if anime == nil {
82 CurdOut(fmt.Sprintf("Skipping invalid local history row: %v", row))
83 continue
84 }
85
86 existingProviderID := normalizeLocalProviderID(anime.ProviderName, anime.ProviderId, GetAnimeName(*anime))
87 targetProviderID := normalizeLocalProviderID(anime.ProviderName, allanimeID, GetAnimeName(*anime))
88 if anime.AnilistId != anilistID || existingProviderID != targetProviderID {
79 animeList = append(animeList, row) 89 animeList = append(animeList, row)
80 } 90 }
81 } 91 }
@@ -89,11 +99,14 @@ func LocalDeleteAnime(databaseFile string, anilistID int, allanimeID string) {
89 defer fileWrite.Close() 99 defer fileWrite.Close()
90 100
91 writer := csv.NewWriter(fileWrite) 101 writer := csv.NewWriter(fileWrite)
92 defer writer.Flush()
93
94 err = writer.WriteAll(animeList) 102 err = writer.WriteAll(animeList)
95 if err != nil { 103 if err != nil {
96 CurdOut(fmt.Sprintf("Error writing to file: %v", err)) 104 CurdOut(fmt.Sprintf("Error writing to file: %v", err))
105 return
106 }
107 writer.Flush()
108 if err := writer.Error(); err != nil {
109 CurdOut(fmt.Sprintf("Error flushing file: %v", err))
97 } 110 }
98} 111}
99 112
@@ -150,10 +163,34 @@ func parseAnimeRow(row []string) *Anime {
150 return nil 163 return nil
151 } 164 }
152 165
153 anilistID, _ := strconv.Atoi(row[0]) 166 anilistID, ok := parseRequiredLocalInt(row[0], "AniList ID", row)
154 watchingEpisode, _ := strconv.Atoi(row[2]) 167 if !ok {
155 playbackTime, _ := strconv.Atoi(row[3]) 168 return nil
156 animeDuration, _ := strconv.Atoi(row[4]) 169 }
170 watchingEpisode, ok := parseRequiredLocalInt(row[2], "episode", row)
171 if !ok {
172 return nil
173 }
174 playbackTime, ok := parseRequiredLocalInt(row[3], "playback time", row)
175 if !ok {
176 return nil
177 }
178 animeDuration := 0
179 animeName := strconv.Itoa(anilistID)
180 providerName := "allanime"
181
182 if len(row) >= 7 {
183 animeDuration = parseLocalInt(row[4])
184 providerName = row[5]
185 animeName = row[6]
186 } else if len(row) >= 6 {
187 animeDuration = parseLocalInt(row[4])
188 animeName = row[5]
189 } else if duration, err := strconv.Atoi(row[4]); err == nil {
190 animeDuration = duration
191 } else {
192 animeName = row[4]
193 }
157 194
158 anime := &Anime{ 195 anime := &Anime{
159 AnilistId: anilistID, 196 AnilistId: anilistID,
@@ -165,38 +202,46 @@ func parseAnimeRow(row []string) *Anime {
165 }, 202 },
166 Duration: animeDuration, 203 Duration: animeDuration,
167 }, 204 },
168 } 205 ProviderName: providerName,
169 206 Title: AnimeTitle{
170 if len(row) >= 7 { 207 English: animeName,
171 anime.ProviderName = row[5] 208 Romaji: animeName,
172 anime.Title = AnimeTitle{ 209 },
173 English: row[6],
174 Romaji: row[6],
175 }
176 } else if len(row) >= 6 {
177 anime.ProviderName = "allanime"
178 anime.Title = AnimeTitle{
179 English: row[5],
180 Romaji: row[5],
181 }
182 } else if len(row) == 5 {
183 anime.ProviderName = "allanime"
184 anime.Title = AnimeTitle{
185 English: row[4],
186 Romaji: row[4],
187 }
188 } 210 }
189 211
190 return anime 212 return anime
191} 213}
192 214
215func parseLocalInt(value string) int {
216 parsed, _ := strconv.Atoi(strings.TrimSpace(value))
217 return parsed
218}
219
220func parseRequiredLocalInt(value, field string, row []string) (int, bool) {
221 parsed, err := strconv.Atoi(strings.TrimSpace(value))
222 if err != nil {
223 CurdOut(fmt.Sprintf("Invalid %s in local history row %v: %v", field, row, err))
224 return 0, false
225 }
226 return parsed, true
227}
228
193// Function to get the anime name (English or Romaji) from an Anime struct 229// Function to get the anime name (English or Romaji) from an Anime struct
194func GetAnimeName(anime Anime) string { 230func GetAnimeName(anime Anime) string {
195 userCurdConfig := GetGlobalConfig() 231 userCurdConfig := GetGlobalConfig()
196 if anime.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" { 232 if anime.Title.English != "" && useEnglishAnimeNames(userCurdConfig) {
233 return anime.Title.English
234 }
235 if anime.Title.Romaji != "" {
236 return anime.Title.Romaji
237 }
238 if anime.Title.English != "" {
197 return anime.Title.English 239 return anime.Title.English
198 } 240 }
199 return anime.Title.Romaji 241 if anime.AnilistId != 0 {
242 return strconv.Itoa(anime.AnilistId)
243 }
244 return ""
200} 245}
201 246
202// Function to update or add a new anime entry 247// Function to update or add a new anime entry
@@ -251,7 +296,6 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
251 defer file.Close() 296 defer file.Close()
252 297
253 writer := csv.NewWriter(file) 298 writer := csv.NewWriter(file)
254 defer writer.Flush()
255 299
256 for _, anime := range animeList { 300 for _, anime := range animeList {
257 providerID := normalizeLocalProviderID(anime.ProviderName, anime.ProviderId, GetAnimeName(anime)) 301 providerID := normalizeLocalProviderID(anime.ProviderName, anime.ProviderId, GetAnimeName(anime))
@@ -266,9 +310,16 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat
266 } 310 }
267 if err := writer.Write(record); err != nil { 311 if err := writer.Write(record); err != nil {
268 CurdOut(fmt.Sprintf("Error writing record: %v", err)) 312 CurdOut(fmt.Sprintf("Error writing record: %v", err))
313 return err
269 } 314 }
270 } 315 }
271 316
317 writer.Flush()
318 if err := writer.Error(); err != nil {
319 CurdOut(fmt.Sprintf("Error flushing records: %v", err))
320 return err
321 }
322
272 return nil 323 return nil
273} 324}
274 325
@@ -297,16 +348,10 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
297 // Anime search and selection loop 348 // Anime search and selection loop
298 for { 349 for {
299 // Get anime name from user 350 // Get anime name from user
300 if userCurdConfig.RofiSelection { 351 query, err = promptText(userCurdConfig, "Enter the anime name", false)
301 userInput, err := GetUserInputFromRofi("Enter the anime name") 352 if err != nil {
302 if err != nil { 353 Log("Error getting user input: " + err.Error())
303 Log("Error getting user input: " + err.Error()) 354 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
304 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
305 }
306 query = userInput
307 } else {
308 CurdOut("Enter the anime name:")
309 fmt.Scanln(&query)
310 } 355 }
311 356
312 // Search for the anime 357 // Search for the anime
@@ -320,19 +365,10 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
320 // Prompt user for manual query 365 // Prompt user for manual query
321 for { 366 for {
322 var manualQuery string 367 var manualQuery string
323 if userCurdConfig.RofiSelection { 368 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)
324 userInput, err := GetUserInputFromRofi(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)) 369 if err != nil {
325 if err != nil { 370 Log("Error getting user input: " + err.Error())
326 Log("Error getting user input: " + err.Error()) 371 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
327 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
328 }
329 manualQuery = userInput
330 } else {
331 CurdOut(fmt.Sprintf("No results found for '%s'.", query))
332 CurdOut("Press Enter to search with the original name, or enter a custom name to search on AllAnime:")
333 reader := bufio.NewReader(os.Stdin)
334 input, _ := reader.ReadString('\n')
335 manualQuery = strings.TrimSpace(input)
336 } 372 }
337 373
338 // If empty, use original query name 374 // If empty, use original query name
@@ -380,28 +416,17 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
380 } 416 }
381 417
382 // Get episode number 418 // Get episode number
383 var episodeNumber int 419 episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, "Enter the episode number")
384 if userCurdConfig.RofiSelection { 420 if err != nil {
385 userInput, err := GetUserInputFromRofi("Enter the episode number") 421 Log(fmt.Sprintf("Invalid episode number: %v", err))
386 if err != nil { 422 ExitCurd(fmt.Errorf("Invalid episode number"))
387 Log("Error getting episode number: " + err.Error())
388 ExitCurd(fmt.Errorf("Error getting episode number: " + err.Error()))
389 }
390 episodeNumber, err = strconv.Atoi(userInput)
391 if err != nil {
392 Log(fmt.Sprintf("Invalid episode number: %v", err))
393 ExitCurd(fmt.Errorf("Invalid episode number"))
394 }
395 } else {
396 CurdOut("Enter the episode number:")
397 fmt.Scanln(&episodeNumber)
398 } 423 }
399 424
400 anime.Ep.Number = episodeNumber 425 anime.Ep.Number = episodeNumber
401 426
402 for { 427 for {
403 // Get episode link 428 // Get episode link
404 link, err := GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number) 429 link, _, err := GetEpisodeURLForPlayback(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
405 if err != nil { 430 if err != nil {
406 Log(fmt.Sprintf("Failed to get episode link: %v", err)) 431 Log(fmt.Sprintf("Failed to get episode link: %v", err))
407 ExitCurd(fmt.Errorf("Failed to get episode link")) 432 ExitCurd(fmt.Errorf("Failed to get episode link"))
internal/logic_regression_test.go added +293
@@ -0,0 +1,293 @@
1package internal
2
3import (
4 "os"
5 "path/filepath"
6 "testing"
7
8 tea "github.com/charmbracelet/bubbletea"
9)
10
11func TestClearLogFileCreatesParentAndTruncates(t *testing.T) {
12 logPath := filepath.Join(t.TempDir(), "missing", "debug.log")
13
14 if err := ClearLogFile(logPath); err != nil {
15 t.Fatalf("ClearLogFile should create a missing parent directory: %v", err)
16 }
17
18 if err := os.WriteFile(logPath, []byte("old log data"), 0o644); err != nil {
19 t.Fatalf("write log fixture: %v", err)
20 }
21 if err := ClearLogFile(logPath); err != nil {
22 t.Fatalf("ClearLogFile should truncate an existing log: %v", err)
23 }
24
25 info, err := os.Stat(logPath)
26 if err != nil {
27 t.Fatalf("expected log file to exist: %v", err)
28 }
29 if info.Size() != 0 {
30 t.Fatalf("expected log file to be truncated, got %d bytes", info.Size())
31 }
32}
33
34func TestParseAnimeRowHandlesLegacyRows(t *testing.T) {
35 withName := parseAnimeRow([]string{"123", "provider-id", "4", "55", "Legacy Title"})
36 if withName == nil {
37 t.Fatalf("expected legacy name row to parse")
38 }
39 if withName.Ep.Duration != 0 || withName.Title.Romaji != "Legacy Title" {
40 t.Fatalf("unexpected legacy name row parse: %+v", withName)
41 }
42
43 withDuration := parseAnimeRow([]string{"123", "provider-id", "4", "55", "24"})
44 if withDuration == nil {
45 t.Fatalf("expected legacy duration row to parse")
46 }
47 if withDuration.Ep.Duration != 24 || withDuration.Title.Romaji != "123" {
48 t.Fatalf("unexpected legacy duration row parse: %+v", withDuration)
49 }
50
51 current := parseAnimeRow([]string{"123", "provider-id", "4", "55", "24", "animepahe", "Current Title"})
52 if current == nil {
53 t.Fatalf("expected current row to parse")
54 }
55 if current.Ep.Duration != 24 || current.ProviderName != "animepahe" || current.Title.Romaji != "Current Title" {
56 t.Fatalf("unexpected current row parse: %+v", current)
57 }
58
59 if invalid := parseAnimeRow([]string{"bad-id", "provider-id", "4", "55", "24", "allanime", "Broken Title"}); invalid != nil {
60 t.Fatalf("expected invalid AniList ID row to be skipped, got %+v", invalid)
61 }
62}
63
64func TestLocalDeleteAnimeNormalizesAnimepaheIDs(t *testing.T) {
65 historyPath := filepath.Join(t.TempDir(), "history.csv")
66 if err := LocalUpdateAnime(historyPath, 123, "123:session-id", 4, 0, 24, "Current Title", "animepahe"); err != nil {
67 t.Fatalf("write animepahe history: %v", err)
68 }
69
70 LocalDeleteAnime(historyPath, 123, "123:other-session")
71
72 if entries := LocalGetAllAnime(historyPath); len(entries) != 0 {
73 t.Fatalf("expected animepahe history entry to be deleted, got %#v", entries)
74 }
75}
76
77func TestGetAnimeNameWithoutGlobalConfig(t *testing.T) {
78 previousConfig := GetGlobalConfig()
79 SetGlobalConfig(nil)
80 t.Cleanup(func() {
81 SetGlobalConfig(previousConfig)
82 })
83
84 name := GetAnimeName(Anime{Title: AnimeTitle{English: "English Title", Romaji: "Romaji Title"}})
85 if name != "English Title" {
86 t.Fatalf("expected English fallback without config, got %q", name)
87 }
88
89 name = GetAnimeName(Anime{AnilistId: 42})
90 if name != "42" {
91 t.Fatalf("expected ID fallback for empty title, got %q", name)
92 }
93}
94
95func TestNextEpisodeFromProgress(t *testing.T) {
96 if got := nextEpisodeFromProgress(0); got != 1 {
97 t.Fatalf("progress 0 should start episode 1, got %d", got)
98 }
99 if got := nextEpisodeFromProgress(7); got != 8 {
100 t.Fatalf("progress 7 should start episode 8, got %d", got)
101 }
102 if got := nextEpisodeFromProgress(-3); got != 1 {
103 t.Fatalf("negative progress should clamp to episode 1, got %d", got)
104 }
105}
106
107func TestSelectionCtrlCSelectsQuit(t *testing.T) {
108 model := &Model{
109 filteredKeys: []SelectionOption{{Key: "anime", Label: "Some Anime"}},
110 selected: 0,
111 isHomeMenu: false,
112 }
113
114 updated, _ := model.Update(tea.KeyMsg{Type: tea.KeyCtrlC})
115 finalModel, ok := updated.(*Model)
116 if !ok {
117 t.Fatalf("unexpected model type %T", updated)
118 }
119 if len(finalModel.filteredKeys) != 1 || finalModel.filteredKeys[0].Key != "-1" {
120 t.Fatalf("ctrl+c should select Quit, got %+v", finalModel.filteredKeys)
121 }
122}
123
124func TestSelectionEnterWithNoMatchesDoesNotPanic(t *testing.T) {
125 model := &Model{filteredKeys: nil, selected: 0}
126 updated, cmd := model.Update(tea.KeyMsg{Type: tea.KeyEnter})
127 if cmd != nil {
128 t.Fatalf("expected no quit command for empty selection")
129 }
130 if _, ok := updated.(*Model); !ok {
131 t.Fatalf("unexpected model type %T", updated)
132 }
133}
134
135func TestVisibleItemsCountClampsTinyTerminals(t *testing.T) {
136 if got := (Model{terminalHeight: 0}).visibleItemsCount(); got != 1 {
137 t.Fatalf("expected at least one visible item, got %d", got)
138 }
139}
140
141func TestHasMPVReferrerArgDetectsHeaderAppendForms(t *testing.T) {
142 cases := [][]string{
143 {"--http-header-fields-append=Referer: https://example.test/"},
144 {"--http-header-fields-append", "Referer: https://example.test/"},
145 {"--mpv-http-header-fields-append=Referer: https://example.test/"},
146 }
147
148 for _, args := range cases {
149 if !hasMPVReferrerArg(args) {
150 t.Fatalf("expected referrer detection for args %#v", args)
151 }
152 }
153}
154
155func TestEpisodeAndProgressInputValidation(t *testing.T) {
156 if got, err := parsePositiveIntInput("12", "episode number"); err != nil || got != 12 {
157 t.Fatalf("expected valid episode number, got %d err %v", got, err)
158 }
159 for _, input := range []string{"", "0", "-1", "one"} {
160 if _, err := parsePositiveIntInput(input, "episode number"); err == nil {
161 t.Fatalf("expected invalid episode input %q to fail", input)
162 }
163 }
164
165 if got, err := parseNonNegativeIntInput("0", "progress"); err != nil || got != 0 {
166 t.Fatalf("expected progress 0 to be valid, got %d err %v", got, err)
167 }
168 if _, err := parseNonNegativeIntInput("-1", "progress"); err == nil {
169 t.Fatalf("expected negative progress to fail")
170 }
171}
172
173func TestAffirmativeAnswerAcceptsYesVariants(t *testing.T) {
174 for _, answer := range []string{"y", "Y", " yes "} {
175 if !isAffirmativeAnswer(answer) {
176 t.Fatalf("expected %q to be affirmative", answer)
177 }
178 }
179 if isAffirmativeAnswer("no") {
180 t.Fatalf("expected no to be negative")
181 }
182}
183
184func TestPopulateConfigFallsBackToDefaultsOnInvalidValues(t *testing.T) {
185 config := PopulateConfig(map[string]string{
186 "PercentageToMarkComplete": "not-a-number",
187 "SkipOp": "not-a-bool",
188 })
189
190 if config.PercentageToMarkComplete != 85 {
191 t.Fatalf("expected default completion percentage, got %d", config.PercentageToMarkComplete)
192 }
193 if !config.SkipOp {
194 t.Fatalf("expected invalid bool to fall back to default true")
195 }
196 if config.StoragePath == "" {
197 t.Fatalf("expected absent fields to be populated from defaults")
198 }
199}
200
201func TestParseStringArrayUsesJSONBeforeLegacySplit(t *testing.T) {
202 args := parseStringArray(`["--script-opts=foo=a,b","--really-quiet"]`)
203 if len(args) != 2 {
204 t.Fatalf("expected 2 args, got %#v", args)
205 }
206 if args[0] != "--script-opts=foo=a,b" || args[1] != "--really-quiet" {
207 t.Fatalf("unexpected args parse: %#v", args)
208 }
209}
210
211func TestGetProviderNormalizesConfiguredProviderName(t *testing.T) {
212 previousProvider := CurrentProvider
213 previousConfig := GetGlobalConfig()
214 t.Cleanup(func() {
215 CurrentProvider = previousProvider
216 SetGlobalConfig(previousConfig)
217 })
218
219 CurrentProvider = nil
220 SetGlobalConfig(&CurdConfig{Provider: " AnimePahe "})
221
222 if got := GetProvider().Name(); got != "animepahe" {
223 t.Fatalf("expected animepahe provider, got %q", got)
224 }
225}
226
227func TestHTTPStatusErrorIncludesStatusAndBodySnippet(t *testing.T) {
228 err := httpStatusError("provider request", 503, []byte(" service unavailable "))
229 if err == nil {
230 t.Fatalf("expected status error")
231 }
232 if got := err.Error(); got != "provider request failed with status 503: service unavailable" {
233 t.Fatalf("unexpected status error: %q", got)
234 }
235}
236
237func TestMPVResponseDataReturnsCommandErrors(t *testing.T) {
238 if _, err := mpvResponseData(map[string]interface{}{"error": "property unavailable"}); err == nil {
239 t.Fatalf("expected MPV error field to be returned")
240 }
241
242 data, err := mpvResponseData(map[string]interface{}{"error": "success", "data": float64(12)})
243 if err != nil {
244 t.Fatalf("expected success response: %v", err)
245 }
246 if data != float64(12) {
247 t.Fatalf("unexpected MPV data: %#v", data)
248 }
249}
250
251func TestParseMyAnimeListDateRejectsInvalidValues(t *testing.T) {
252 if got := parseMyAnimeListDate("2026-05-23"); got != (FuzzyDate{Year: 2026, Month: 5, Day: 23}) {
253 t.Fatalf("unexpected parsed date: %+v", got)
254 }
255 for _, input := range []string{"bad", "2026-aa-23", "2026-13-01", "2026-01-00"} {
256 if got := parseMyAnimeListDate(input); got != (FuzzyDate{}) {
257 t.Fatalf("expected invalid date %q to return zero value, got %+v", input, got)
258 }
259 }
260}
261
262func TestParseAnimeListMalformedInputReturnsEmptyList(t *testing.T) {
263 if got := ParseAnimeList(nil); len(getEntriesByCategory(got, "ALL")) != 0 {
264 t.Fatalf("expected nil input to produce empty list")
265 }
266 if got := ParseAnimeList(map[string]interface{}{"data": nil}); len(getEntriesByCategory(got, "ALL")) != 0 {
267 t.Fatalf("expected nil data input to produce empty list")
268 }
269}
270
271func TestMediaDisplayTitleFallsBackToID(t *testing.T) {
272 title := mediaDisplayTitle(Media{ID: 42}, &CurdConfig{AnimeNameLanguage: "english"})
273 if title != "42" {
274 t.Fatalf("expected ID fallback for empty titles, got %q", title)
275 }
276}
277
278func TestMapEntriesByMediaIDSkipsZeroIDs(t *testing.T) {
279 list := AnimeList{
280 Watching: []Entry{
281 {Media: Media{ID: 0}, Progress: 1},
282 {Media: Media{ID: 10}, Progress: 2},
283 },
284 }
285
286 entries := mapEntriesByMediaID(list)
287 if len(entries) != 1 {
288 t.Fatalf("expected only valid media IDs, got %#v", entries)
289 }
290 if entries[10].Progress != 2 {
291 t.Fatalf("expected media 10 to be retained, got %#v", entries[10])
292 }
293}
internal/myanimelist.go +66 −19
@@ -209,6 +209,9 @@ func exchangeMyAnimeListAuthorizationCode(config *CurdConfig, tokenPath string,
209 if err := json.Unmarshal(body, &token); err != nil { 209 if err := json.Unmarshal(body, &token); err != nil {
210 return "", err 210 return "", err
211 } 211 }
212 if strings.TrimSpace(token.AccessToken) == "" {
213 return "", fmt.Errorf("MyAnimeList token response did not include an access token")
214 }
212 token.ExpiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second) 215 token.ExpiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second)
213 if err := saveToken(tokenPath, &token); err != nil { 216 if err := saveToken(tokenPath, &token); err != nil {
214 return "", err 217 return "", err
@@ -380,6 +383,8 @@ func authenticateMyAnimeListWithBrowser(config *CurdConfig, tokenPath string) (s
380 return exchangeMyAnimeListAuthorizationCode(config, tokenPath, codeVerifier, code) 383 return exchangeMyAnimeListAuthorizationCode(config, tokenPath, codeVerifier, code)
381} 384}
382 385
386var authenticateMyAnimeList = authenticateMyAnimeListWithBrowser
387
383func refreshMyAnimeListToken(config *CurdConfig, tokenPath string, refreshToken string) (*OAuthToken, error) { 388func refreshMyAnimeListToken(config *CurdConfig, tokenPath string, refreshToken string) (*OAuthToken, error) {
384 clientID, clientSecret := myAnimeListClientCredentials(config) 389 clientID, clientSecret := myAnimeListClientCredentials(config)
385 if clientID == "" { 390 if clientID == "" {
@@ -422,6 +427,12 @@ func refreshMyAnimeListToken(config *CurdConfig, tokenPath string, refreshToken
422 if err := json.Unmarshal(body, &token); err != nil { 427 if err := json.Unmarshal(body, &token); err != nil {
423 return nil, err 428 return nil, err
424 } 429 }
430 if strings.TrimSpace(token.AccessToken) == "" {
431 return nil, fmt.Errorf("MyAnimeList refresh response did not include an access token")
432 }
433 if strings.TrimSpace(token.RefreshToken) == "" {
434 token.RefreshToken = refreshToken
435 }
425 token.ExpiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second) 436 token.ExpiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second)
426 if err := saveToken(tokenPath, &token); err != nil { 437 if err := saveToken(tokenPath, &token); err != nil {
427 return nil, err 438 return nil, err
@@ -434,11 +445,31 @@ func refreshMyAnimeListToken(config *CurdConfig, tokenPath string, refreshToken
434 return &token, nil 445 return &token, nil
435} 446}
436 447
448func renewMyAnimeListAccessToken(config *CurdConfig, tokenPath string, token *OAuthToken, reason string) (string, error) {
449 if token != nil && strings.TrimSpace(token.RefreshToken) != "" {
450 refreshed, refreshErr := refreshMyAnimeListToken(config, tokenPath, token.RefreshToken)
451 if refreshErr == nil {
452 return refreshed.AccessToken, nil
453 }
454 Log(fmt.Sprintf("Failed to refresh MyAnimeList token after %s: %v", reason, refreshErr))
455 }
456
457 accessToken, authErr := authenticateMyAnimeList(config, tokenPath)
458 if authErr != nil {
459 return "", authErr
460 }
461 if user := GetGlobalUser(); user != nil {
462 user.Token = accessToken
463 }
464 return accessToken, nil
465}
466
437func GetMyAnimeListAccessToken(config *CurdConfig) (string, error) { 467func GetMyAnimeListAccessToken(config *CurdConfig) (string, error) {
438 tokenPath := myAnimeListTokenPath(config) 468 tokenPath := myAnimeListTokenPath(config)
439 token, err := loadToken(tokenPath) 469 token, err := loadToken(tokenPath)
440 if err != nil { 470 if err != nil {
441 return "", err 471 Log(fmt.Sprintf("Failed to load MyAnimeList token, starting login: %v", err))
472 return renewMyAnimeListAccessToken(config, tokenPath, nil, "token load failure")
442 } 473 }
443 if isTokenValid(token) { 474 if isTokenValid(token) {
444 if user := GetGlobalUser(); user != nil { 475 if user := GetGlobalUser(); user != nil {
@@ -447,18 +478,15 @@ func GetMyAnimeListAccessToken(config *CurdConfig) (string, error) {
447 return token.AccessToken, nil 478 return token.AccessToken, nil
448 } 479 }
449 if token.RefreshToken == "" { 480 if token.RefreshToken == "" {
450 return "", fmt.Errorf("MyAnimeList token has expired and cannot be refreshed") 481 Log("MyAnimeList token is expired and has no refresh token, starting login")
451 } 482 return renewMyAnimeListAccessToken(config, tokenPath, token, "expired token")
452 refreshed, err := refreshMyAnimeListToken(config, tokenPath, token.RefreshToken)
453 if err != nil {
454 return "", err
455 } 483 }
456 return refreshed.AccessToken, nil 484 return renewMyAnimeListAccessToken(config, tokenPath, token, "expired token")
457} 485}
458 486
459func ChangeMyAnimeListToken(config *CurdConfig, user *User) error { 487func ChangeMyAnimeListToken(config *CurdConfig, user *User) error {
460 tokenPath := myAnimeListTokenPath(config) 488 tokenPath := myAnimeListTokenPath(config)
461 accessToken, err := authenticateMyAnimeListWithBrowser(config, tokenPath) 489 accessToken, err := authenticateMyAnimeList(config, tokenPath)
462 if err != nil { 490 if err != nil {
463 return err 491 return err
464 } 492 }
@@ -520,15 +548,22 @@ func myAnimeListRequest(config *CurdConfig, method, requestURL string, form url.
520 } 548 }
521 549
522 if resp.StatusCode == http.StatusUnauthorized && attempt == 0 { 550 if resp.StatusCode == http.StatusUnauthorized && attempt == 0 {
523 storedToken, tokenErr := loadToken(myAnimeListTokenPath(config)) 551 tokenPath := myAnimeListTokenPath(config)
552 storedToken, tokenErr := loadToken(tokenPath)
524 if tokenErr != nil { 553 if tokenErr != nil {
525 return tokenErr 554 Log(fmt.Sprintf("Failed to load MyAnimeList token after unauthorized response, starting login: %v", tokenErr))
555 accessToken, authErr := renewMyAnimeListAccessToken(config, tokenPath, nil, "unauthorized API response")
556 if authErr != nil {
557 return authErr
558 }
559 token = accessToken
560 continue
526 } 561 }
527 refreshed, refreshErr := refreshMyAnimeListToken(config, myAnimeListTokenPath(config), storedToken.RefreshToken) 562 accessToken, renewErr := renewMyAnimeListAccessToken(config, tokenPath, storedToken, "unauthorized API response")
528 if refreshErr != nil { 563 if renewErr != nil {
529 return refreshErr 564 return renewErr
530 } 565 }
531 token = refreshed.AccessToken 566 token = accessToken
532 continue 567 continue
533 } 568 }
534 569
@@ -556,9 +591,12 @@ func parseMyAnimeListDate(value string) FuzzyDate {
556 return FuzzyDate{} 591 return FuzzyDate{}
557 } 592 }
558 593
559 year, _ := strconv.Atoi(parts[0]) 594 year, yearErr := strconv.Atoi(parts[0])
560 month, _ := strconv.Atoi(parts[1]) 595 month, monthErr := strconv.Atoi(parts[1])
561 day, _ := strconv.Atoi(parts[2]) 596 day, dayErr := strconv.Atoi(parts[2])
597 if yearErr != nil || monthErr != nil || dayErr != nil || year <= 0 || month < 1 || month > 12 || day < 1 || day > 31 {
598 return FuzzyDate{}
599 }
562 return FuzzyDate{Year: year, Month: month, Day: day} 600 return FuzzyDate{Year: year, Month: month, Day: day}
563} 601}
564 602
@@ -711,8 +749,13 @@ func lookupAniListMediaByMalID(malID int) (Media, string, error) {
711 return Media{}, "", fmt.Errorf("AniList media not found for MAL ID %d", malID) 749 return Media{}, "", fmt.Errorf("AniList media not found for MAL ID %d", malID)
712 } 750 }
713 751
752 aniListID, ok := mediaData["id"].(float64)
753 if !ok || aniListID == 0 {
754 return Media{}, "", fmt.Errorf("AniList media response for MAL ID %d is missing id", malID)
755 }
756
714 media := Media{ 757 media := Media{
715 ID: int(mediaData["id"].(float64)), 758 ID: int(aniListID),
716 MalID: malID, 759 MalID: malID,
717 Episodes: 0, 760 Episodes: 0,
718 Duration: 0, 761 Duration: 0,
@@ -823,8 +866,12 @@ func lookupAniListMediaByMalIDs(malIDs []int) (map[int]aniListMediaLookupResult,
823 if !ok || rawMedia == nil { 866 if !ok || rawMedia == nil {
824 continue 867 continue
825 } 868 }
869 aniListID, ok := rawMedia["id"].(float64)
870 if !ok || aniListID == 0 {
871 continue
872 }
826 media := Media{ 873 media := Media{
827 ID: int(rawMedia["id"].(float64)), 874 ID: int(aniListID),
828 MalID: malID, 875 MalID: malID,
829 Episodes: 0, 876 Episodes: 0,
830 Duration: 0, 877 Duration: 0,
internal/myanimelist_token_test.go added +183
@@ -0,0 +1,183 @@
1package internal
2
3import (
4 "io"
5 "net/http"
6 "net/url"
7 "strings"
8 "testing"
9 "time"
10)
11
12type roundTripFunc func(*http.Request) (*http.Response, error)
13
14func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
15 return f(req)
16}
17
18func testHTTPResponse(req *http.Request, statusCode int, body string) *http.Response {
19 return &http.Response{
20 StatusCode: statusCode,
21 Header: make(http.Header),
22 Body: io.NopCloser(strings.NewReader(body)),
23 Request: req,
24 }
25}
26
27func withMyAnimeListTokenTestHooks(t *testing.T, client *http.Client) {
28 t.Helper()
29
30 previousClient := sharedHTTPClient
31 previousAuth := authenticateMyAnimeList
32 t.Cleanup(func() {
33 sharedHTTPClient = previousClient
34 authenticateMyAnimeList = previousAuth
35 })
36
37 sharedHTTPClient = client
38}
39
40func TestRefreshMyAnimeListTokenPreservesRefreshTokenWhenResponseOmitsOne(t *testing.T) {
41 config := &CurdConfig{
42 StoragePath: t.TempDir(),
43 MyAnimeListClientID: "client-id",
44 }
45 tokenPath := myAnimeListTokenPath(config)
46 if err := saveToken(tokenPath, &OAuthToken{
47 AccessToken: "old-access",
48 RefreshToken: "keep-refresh",
49 ExpiresAt: time.Now().Add(-time.Hour),
50 }); err != nil {
51 t.Fatalf("save expired token: %v", err)
52 }
53
54 withMyAnimeListTokenTestHooks(t, &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
55 if req.URL.String() != myAnimeListTokenURL {
56 t.Fatalf("unexpected request URL: %s", req.URL.String())
57 }
58 if err := req.ParseForm(); err != nil {
59 t.Fatalf("parse refresh form: %v", err)
60 }
61 if got := req.Form.Get("refresh_token"); got != "keep-refresh" {
62 t.Fatalf("refresh token = %q, want keep-refresh", got)
63 }
64 return testHTTPResponse(req, http.StatusOK, `{"access_token":"new-access","token_type":"Bearer","expires_in":3600}`), nil
65 })})
66
67 accessToken, err := GetMyAnimeListAccessToken(config)
68 if err != nil {
69 t.Fatalf("refresh access token: %v", err)
70 }
71 if accessToken != "new-access" {
72 t.Fatalf("access token = %q, want new-access", accessToken)
73 }
74
75 storedToken, err := loadToken(tokenPath)
76 if err != nil {
77 t.Fatalf("load refreshed token: %v", err)
78 }
79 if storedToken.RefreshToken != "keep-refresh" {
80 t.Fatalf("stored refresh token = %q, want keep-refresh", storedToken.RefreshToken)
81 }
82}
83
84func TestGetMyAnimeListAccessTokenReauthenticatesWhenRefreshFails(t *testing.T) {
85 config := &CurdConfig{
86 StoragePath: t.TempDir(),
87 MyAnimeListClientID: "client-id",
88 }
89 tokenPath := myAnimeListTokenPath(config)
90 if err := saveToken(tokenPath, &OAuthToken{
91 AccessToken: "expired-access",
92 RefreshToken: "bad-refresh",
93 ExpiresAt: time.Now().Add(-time.Hour),
94 }); err != nil {
95 t.Fatalf("save expired token: %v", err)
96 }
97
98 withMyAnimeListTokenTestHooks(t, &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
99 return testHTTPResponse(req, http.StatusBadRequest, `{"error":"invalid_grant"}`), nil
100 })})
101 authenticateMyAnimeList = func(config *CurdConfig, tokenPath string) (string, error) {
102 token := &OAuthToken{
103 AccessToken: "reauth-access",
104 RefreshToken: "reauth-refresh",
105 ExpiresIn: 3600,
106 ExpiresAt: time.Now().Add(time.Hour),
107 }
108 if err := saveToken(tokenPath, token); err != nil {
109 return "", err
110 }
111 return token.AccessToken, nil
112 }
113
114 accessToken, err := GetMyAnimeListAccessToken(config)
115 if err != nil {
116 t.Fatalf("reauthenticate access token: %v", err)
117 }
118 if accessToken != "reauth-access" {
119 t.Fatalf("access token = %q, want reauth-access", accessToken)
120 }
121}
122
123func TestMyAnimeListRequestReauthenticatesWhenUnauthorizedRefreshFails(t *testing.T) {
124 config := &CurdConfig{
125 StoragePath: t.TempDir(),
126 MyAnimeListClientID: "client-id",
127 }
128 tokenPath := myAnimeListTokenPath(config)
129 if err := saveToken(tokenPath, &OAuthToken{
130 AccessToken: "revoked-access",
131 RefreshToken: "bad-refresh",
132 ExpiresAt: time.Now().Add(time.Hour),
133 }); err != nil {
134 t.Fatalf("save revoked token fixture: %v", err)
135 }
136
137 apiAttempts := 0
138 withMyAnimeListTokenTestHooks(t, &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
139 switch {
140 case req.URL.String() == myAnimeListTokenURL:
141 return testHTTPResponse(req, http.StatusBadRequest, `{"error":"invalid_grant"}`), nil
142 case strings.HasPrefix(req.URL.String(), myAnimeListAPIBaseURL):
143 apiAttempts++
144 authHeader := req.Header.Get("Authorization")
145 if apiAttempts == 1 {
146 if authHeader != "Bearer revoked-access" {
147 t.Fatalf("first API Authorization = %q, want revoked access", authHeader)
148 }
149 return testHTTPResponse(req, http.StatusUnauthorized, `{"error":"invalid_token"}`), nil
150 }
151 if authHeader != "Bearer reauth-access" {
152 t.Fatalf("retried API Authorization = %q, want reauth access", authHeader)
153 }
154 return testHTTPResponse(req, http.StatusOK, `{"id":123,"name":"tester"}`), nil
155 default:
156 t.Fatalf("unexpected request URL: %s", req.URL.String())
157 return nil, nil
158 }
159 })})
160 authenticateMyAnimeList = func(config *CurdConfig, tokenPath string) (string, error) {
161 token := &OAuthToken{
162 AccessToken: "reauth-access",
163 RefreshToken: "reauth-refresh",
164 ExpiresIn: 3600,
165 ExpiresAt: time.Now().Add(time.Hour),
166 }
167 if err := saveToken(tokenPath, token); err != nil {
168 return "", err
169 }
170 return token.AccessToken, nil
171 }
172
173 var response myAnimeListUser
174 if err := myAnimeListRequest(config, http.MethodGet, "/users/@me", url.Values{"fields": {"id,name"}}, &response); err != nil {
175 t.Fatalf("request should reauthenticate and retry: %v", err)
176 }
177 if response.ID != 123 || response.Name != "tester" {
178 t.Fatalf("unexpected response: %+v", response)
179 }
180 if apiAttempts != 2 {
181 t.Fatalf("API attempts = %d, want 2", apiAttempts)
182 }
183}
internal/player.go +48 −7
@@ -177,7 +177,11 @@ func hasMPVReferrerArg(args []string) bool {
177 return true 177 return true
178 } 178 }
179 179
180 if normalizedArg == "--http-header-fields" && i+1 < len(args) { 180 if strings.HasPrefix(normalizedArg, "--http-header-fields-append=") && strings.Contains(normalizedArg, "referer:") {
181 return true
182 }
183
184 if (normalizedArg == "--http-header-fields" || normalizedArg == "--http-header-fields-append") && i+1 < len(args) {
181 nextArg := strings.ToLower(strings.TrimSpace(args[i+1])) 185 nextArg := strings.ToLower(strings.TrimSpace(args[i+1]))
182 if strings.Contains(nextArg, "referer:") { 186 if strings.Contains(nextArg, "referer:") {
183 return true 187 return true
@@ -241,6 +245,16 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
241 var err error 245 var err error
242 246
243 userConfig := GetGlobalConfig() 247 userConfig := GetGlobalConfig()
248 if userConfig == nil {
249 defaultConfig := PopulateConfig(map[string]string{})
250 userConfig = &defaultConfig
251 }
252 if anime == nil {
253 return "", fmt.Errorf("missing anime playback state")
254 }
255 if strings.TrimSpace(link) == "" {
256 return "", fmt.Errorf("empty video link")
257 }
244 258
245 // Add custom MPV arguments from config if they exist 259 // Add custom MPV arguments from config if they exist
246 if userConfig.MpvArgs != nil { 260 if userConfig.MpvArgs != nil {
@@ -486,17 +500,36 @@ func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, e
486 continue // Try again 500 continue // Try again
487 } 501 }
488 502
489 // Success! 503 data, responseErr := mpvResponseData(response)
490 if data, exists := response["data"]; exists { 504 if responseErr != nil {
491 return data, nil 505 lastErr = responseErr
506 Log(fmt.Sprintf("MPV command error (attempt %d/%d): %v", attempt+1, maxRetries, responseErr))
507 continue
492 } 508 }
493 return nil, nil 509 return data, nil
494 } 510 }
495 511
496 // All retries failed 512 // All retries failed
497 return nil, fmt.Errorf("command failed after %d attempts: %w", maxRetries, lastErr) 513 return nil, fmt.Errorf("command failed after %d attempts: %w", maxRetries, lastErr)
498} 514}
499 515
516func mpvResponseData(response map[string]interface{}) (interface{}, error) {
517 if errorValue, exists := response["error"]; exists {
518 errorText, ok := errorValue.(string)
519 if !ok {
520 return nil, fmt.Errorf("mpv returned non-string error field: %T", errorValue)
521 }
522 if errorText != "" && errorText != "success" {
523 return nil, fmt.Errorf("mpv command error: %s", errorText)
524 }
525 }
526
527 if data, exists := response["data"]; exists {
528 return data, nil
529 }
530 return nil, nil
531}
532
500func SeekMPV(ipcSocketPath string, time int) (interface{}, error) { 533func SeekMPV(ipcSocketPath string, time int) (interface{}, error) {
501 command := []interface{}{"seek", time, "absolute"} 534 command := []interface{}{"seek", time, "absolute"}
502 return MPVSendCommand(ipcSocketPath, command) 535 return MPVSendCommand(ipcSocketPath, command)
@@ -747,7 +780,11 @@ func StartMPVEventListener(ipcSocketPath string, eventCallback func(string, inte
747 780
748 // Handle both events and property changes 781 // Handle both events and property changes
749 if event, exists := response["event"]; exists { 782 if event, exists := response["event"]; exists {
750 eventType := event.(string) 783 eventType, ok := event.(string)
784 if !ok {
785 Log(fmt.Sprintf("MPV event field is not a string: %T", event))
786 continue
787 }
751 Log(fmt.Sprintf("Event type detected: %s", eventType)) 788 Log(fmt.Sprintf("Event type detected: %s", eventType))
752 789
753 // Handle specific MPV events 790 // Handle specific MPV events
@@ -773,7 +810,11 @@ func StartMPVEventListener(ipcSocketPath string, eventCallback func(string, inte
773 case "property-change": 810 case "property-change":
774 if name, exists := response["name"]; exists { 811 if name, exists := response["name"]; exists {
775 if data, exists := response["data"]; exists { 812 if data, exists := response["data"]; exists {
776 propertyName := name.(string) 813 propertyName, ok := name.(string)
814 if !ok {
815 Log(fmt.Sprintf("Property change name is not a string: %T", name))
816 continue
817 }
777 Log(fmt.Sprintf("MPV PROPERTY CHANGE EVENT - %s: %v", propertyName, data)) 818 Log(fmt.Sprintf("MPV PROPERTY CHANGE EVENT - %s: %v", propertyName, data))
778 819
779 // Call the callback with the event details 820 // Call the callback with the event details
internal/provider.go +131 −1
@@ -1,5 +1,11 @@
1package internal 1package internal
2 2
3import (
4 "fmt"
5 "strconv"
6 "strings"
7)
8
3// Provider interface defines methods for an anime provider. 9// Provider interface defines methods for an anime provider.
4type Provider interface { 10type Provider interface {
5 Name() string 11 Name() string
@@ -16,7 +22,7 @@ func GetProvider() Provider {
16 return CurrentProvider 22 return CurrentProvider
17 } 23 }
18 config := GetGlobalConfig() 24 config := GetGlobalConfig()
19 if config != nil && config.Provider == "animepahe" { 25 if config != nil && strings.EqualFold(strings.TrimSpace(config.Provider), "animepahe") {
20 CurrentProvider = &AnimepaheProvider{} 26 CurrentProvider = &AnimepaheProvider{}
21 } else { 27 } else {
22 CurrentProvider = &AllanimeProvider{} 28 CurrentProvider = &AllanimeProvider{}
@@ -33,6 +39,130 @@ func EpisodesList(showID, mode string) ([]string, error) {
33 return GetProvider().EpisodesList(showID, mode) 39 return GetProvider().EpisodesList(showID, mode)
34} 40}
35 41
42func GetProviderTotalEpisodes(showID, mode string) (int, error) {
43 return getProviderTotalEpisodes(GetProvider(), showID, mode)
44}
45
46func getProviderTotalEpisodes(provider Provider, showID, mode string) (int, error) {
47 if provider == nil {
48 return 0, fmt.Errorf("provider is not configured")
49 }
50 if strings.TrimSpace(showID) == "" {
51 return 0, fmt.Errorf("provider id is empty")
52 }
53
54 preferredMode := normalizeTranslationType(mode)
55 lookupModes := []string{preferredMode}
56 if !strings.EqualFold(provider.Name(), "animepahe") {
57 lookupModes = append(lookupModes, alternateTranslationType(preferredMode))
58 }
59
60 bestTotal := 0
61 var lookupErrors []string
62 for _, lookupMode := range lookupModes {
63 episodes, err := provider.EpisodesList(showID, lookupMode)
64 if err != nil {
65 lookupErrors = append(lookupErrors, fmt.Sprintf("%s: %v", lookupMode, err))
66 continue
67 }
68 if total := inferProviderTotalEpisodes(provider.Name(), episodes); total > bestTotal {
69 bestTotal = total
70 }
71 }
72
73 if bestTotal > 0 {
74 return bestTotal, nil
75 }
76 if len(lookupErrors) > 0 {
77 return 0, fmt.Errorf("provider episode list lookup failed: %s", strings.Join(lookupErrors, "; "))
78 }
79 return 0, fmt.Errorf("provider returned no usable episode numbers")
80}
81
82func inferProviderTotalEpisodes(providerName string, episodes []string) int {
83 if strings.EqualFold(providerName, "animepahe") {
84 return countUsableEpisodeEntries(episodes)
85 }
86 return inferTotalEpisodesFromEpisodeList(episodes)
87}
88
89func inferTotalEpisodesFromEpisodeList(episodes []string) int {
90 total := 0
91 for _, episode := range episodes {
92 episodeNumber, err := strconv.ParseFloat(strings.TrimSpace(episode), 64)
93 if err != nil || episodeNumber <= 0 {
94 continue
95 }
96 if wholeEpisode := int(episodeNumber); wholeEpisode > total {
97 total = wholeEpisode
98 }
99 }
100 return total
101}
102
103func countUsableEpisodeEntries(episodes []string) int {
104 total := 0
105 for _, episode := range episodes {
106 episodeNumber, err := strconv.ParseFloat(strings.TrimSpace(episode), 64)
107 if err != nil || episodeNumber <= 0 {
108 continue
109 }
110 total++
111 }
112 return total
113}
114
36func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) { 115func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
37 return GetProvider().GetEpisodeURL(config, id, epNo) 116 return GetProvider().GetEpisodeURL(config, id, epNo)
38} 117}
118
119func GetEpisodeURLForPlayback(config CurdConfig, id string, epNo int) ([]string, string, error) {
120 preferredMode := normalizeTranslationType(config.SubOrDub)
121 links, err := GetEpisodeURL(config, id, epNo)
122 if err == nil && len(links) > 0 {
123 return links, preferredMode, nil
124 }
125
126 preferredErr := err
127 fallbackMode := alternateTranslationType(preferredMode)
128 fallbackConfig := config
129 fallbackConfig.SubOrDub = fallbackMode
130 fallbackLinks, fallbackErr := GetEpisodeURL(fallbackConfig, id, epNo)
131 if fallbackErr != nil || len(fallbackLinks) == 0 {
132 if preferredErr != nil {
133 return nil, preferredMode, preferredErr
134 }
135 if fallbackErr != nil {
136 return nil, preferredMode, fallbackErr
137 }
138 return nil, preferredMode, nil
139 }
140
141 CurdOut(audioFallbackPrompt(preferredMode, fallbackMode))
142 selected, selectErr := promptSelect([]SelectionOption{
143 {Key: "play", Label: "Play " + fallbackMode},
144 {Key: "cancel", Label: "Cancel"},
145 })
146 if selectErr != nil {
147 return nil, preferredMode, selectErr
148 }
149 if selected.Key != "play" {
150 if preferredErr != nil {
151 return nil, preferredMode, preferredErr
152 }
153 return nil, preferredMode, nil
154 }
155
156 return fallbackLinks, fallbackMode, nil
157}
158
159func audioFallbackPrompt(preferredMode, fallbackMode string) string {
160 return titleAudioMode(preferredMode) + " is unavailable for this episode. Play " + fallbackMode + " instead?"
161}
162
163func titleAudioMode(mode string) string {
164 if normalizeTranslationType(mode) == "dub" {
165 return "Dub"
166 }
167 return "Sub"
168}
internal/provider_animepahe.go +160 −59
@@ -19,6 +19,7 @@ import (
19) 19)
20 20
21var animepaheCookiesBypassed bool 21var animepaheCookiesBypassed bool
22var solveAnimepaheBrowserChallenge = solveAnimepaheBrowserChallengeWithRod
22 23
23func getCookieFilePath() string { 24func getCookieFilePath() string {
24 return filepath.Join(GetStoragePath(), "animepahe_cookies.json") 25 return filepath.Join(GetStoragePath(), "animepahe_cookies.json")
@@ -38,16 +39,40 @@ func loadCookies() []*http.Cookie {
38 return nil 39 return nil
39 } 40 }
40 var cookies []*http.Cookie 41 var cookies []*http.Cookie
41 json.Unmarshal(b, &cookies) 42 if err := json.Unmarshal(b, &cookies); err != nil {
43 return nil
44 }
42 return cookies 45 return cookies
43} 46}
44 47
45func checkCookiesValid() bool { 48func newAnimepaheAPIRequest(rawURL string) (*http.Request, error) {
46 req, _ := http.NewRequest("GET", "https://animepahe.pw/api?m=search&q=test", nil) 49 req, err := http.NewRequest("GET", rawURL, nil)
50 if err != nil {
51 return nil, err
52 }
47 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") 53 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
48 req.Header.Set("Referer", "https://animepahe.pw/") 54 req.Header.Set("Referer", "https://animepahe.pw/")
49 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") 55 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01")
50 req.Header.Set("X-Requested-With", "XMLHttpRequest") 56 req.Header.Set("X-Requested-With", "XMLHttpRequest")
57 return req, nil
58}
59
60func newAnimepahePageRequest(rawURL string) (*http.Request, error) {
61 req, err := http.NewRequest("GET", rawURL, nil)
62 if err != nil {
63 return nil, err
64 }
65 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
66 req.Header.Set("Referer", "https://animepahe.pw/")
67 req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
68 return req, nil
69}
70
71func checkCookiesValid() bool {
72 req, err := newAnimepaheAPIRequest("https://animepahe.pw/api?m=search&q=test")
73 if err != nil {
74 return false
75 }
51 76
52 resp, err := sharedHTTPClient.Do(req) 77 resp, err := sharedHTTPClient.Do(req)
53 if err != nil { 78 if err != nil {
@@ -55,15 +80,45 @@ func checkCookiesValid() bool {
55 } 80 }
56 defer resp.Body.Close() 81 defer resp.Body.Close()
57 82
83 body, err := io.ReadAll(resp.Body)
84 if err != nil {
85 return false
86 }
58 if resp.StatusCode != 200 { 87 if resp.StatusCode != 200 {
59 return false 88 return false
60 } 89 }
90 if isAnimepaheChallengeBody(body) {
91 return false
92 }
61 93
62 contentType := resp.Header.Get("Content-Type") 94 contentType := resp.Header.Get("Content-Type")
63 return strings.Contains(contentType, "application/json") 95 return strings.Contains(contentType, "application/json")
64} 96}
65 97
66func (p *AnimepaheProvider) ensureBypass() error { 98func isAnimepaheChallengeResponse(resp *http.Response, body []byte) bool {
99 if resp == nil {
100 return false
101 }
102 if isAnimepaheChallengeBody(body) {
103 return true
104 }
105 return resp.StatusCode == http.StatusForbidden && strings.Contains(strings.ToLower(resp.Header.Get("Server")), "ddos-guard")
106}
107
108func isAnimepaheChallengeBody(body []byte) bool {
109 normalized := strings.ToLower(string(body))
110 return strings.Contains(normalized, "ddos-guard") ||
111 strings.Contains(normalized, "/.well-known/ddos-guard/") ||
112 strings.Contains(normalized, "checking your browser")
113}
114
115func (p *AnimepaheProvider) ensureBypass() (err error) {
116 defer func() {
117 if recovered := recover(); recovered != nil {
118 err = fmt.Errorf("failed to solve Animepahe DDoS-Guard challenge: %v", recovered)
119 }
120 }()
121
67 if animepaheCookiesBypassed { 122 if animepaheCookiesBypassed {
68 return nil 123 return nil
69 } 124 }
@@ -81,36 +136,24 @@ func (p *AnimepaheProvider) ensureBypass() error {
81 Log("Cached Animepahe session expired. Requesting new session...") 136 Log("Cached Animepahe session expired. Requesting new session...")
82 } 137 }
83 138
84 CurdOut("Solving Animepahe DDoS-Guard challenge via headless browser...") 139 return p.refreshBypass()
85 140}
86 l := launcher.New().Headless(true)
87 defer l.Cleanup()
88 browser := rod.New().ControlURL(l.MustLaunch()).MustConnect()
89 defer browser.MustClose()
90
91 page := browser.MustPage("https://animepahe.pw/")
92 page.MustWaitLoad()
93 141
94 for i := 0; i < 30; i++ { 142func (p *AnimepaheProvider) refreshBypass() error {
95 info, err := page.Info() 143 u, _ := url.Parse("https://animepahe.pw")
96 if err == nil && info.Title != "DDoS-Guard" && info.Title != "Just a moment..." && info.Title != "" { 144 animepaheCookiesBypassed = false
97 break 145 if err := os.Remove(getCookieFilePath()); err != nil && !os.IsNotExist(err) {
98 } 146 Log(fmt.Sprintf("Failed to remove cached Animepahe cookies: %v", err))
99 time.Sleep(500 * time.Millisecond)
100 } 147 }
101 148
102 rodCookies, err := page.Cookies(nil) 149 CurdOut("Animepahe needs a browser challenge before Curd can search or play. Starting a temporary headless browser...")
150 httpCookies, err := solveAnimepaheBrowserChallenge()
103 if err != nil { 151 if err != nil {
104 return fmt.Errorf("failed to acquire DDoS guard cookies: %v", err) 152 CurdOut("Animepahe browser challenge failed. Try again later or switch provider.")
153 return fmt.Errorf("animepahe browser challenge failed: %w", err)
105 } 154 }
106 155 if len(httpCookies) == 0 {
107 u, _ := url.Parse("https://animepahe.pw") 156 return fmt.Errorf("animepahe browser challenge returned no cookies")
108 var httpCookies []*http.Cookie
109 for _, cookie := range rodCookies {
110 httpCookies = append(httpCookies, &http.Cookie{
111 Name: cookie.Name,
112 Value: cookie.Value,
113 })
114 } 157 }
115 SetCookiesForAnimepahe(u, httpCookies) 158 SetCookiesForAnimepahe(u, httpCookies)
116 159
@@ -124,6 +167,40 @@ func (p *AnimepaheProvider) ensureBypass() error {
124 return nil 167 return nil
125} 168}
126 169
170func solveAnimepaheBrowserChallengeWithRod() (httpCookies []*http.Cookie, err error) {
171 if err := rod.Try(func() {
172 l := launcher.New().Headless(true)
173 defer l.Cleanup()
174 browser := rod.New().ControlURL(l.MustLaunch()).MustConnect()
175 defer browser.MustClose()
176
177 page := browser.MustPage("https://animepahe.pw/")
178 page.MustWaitLoad()
179
180 for i := 0; i < 30; i++ {
181 info, err := page.Info()
182 if err == nil && info.Title != "DDoS-Guard" && info.Title != "Just a moment..." && info.Title != "" {
183 break
184 }
185 time.Sleep(500 * time.Millisecond)
186 }
187
188 rodCookies, err := page.Cookies(nil)
189 if err != nil {
190 panic(err)
191 }
192 for _, cookie := range rodCookies {
193 httpCookies = append(httpCookies, &http.Cookie{
194 Name: cookie.Name,
195 Value: cookie.Value,
196 })
197 }
198 }); err != nil {
199 return nil, err
200 }
201 return httpCookies, nil
202}
203
127type AnimepaheProvider struct{} 204type AnimepaheProvider struct{}
128 205
129func (p *AnimepaheProvider) Name() string { 206func (p *AnimepaheProvider) Name() string {
@@ -252,11 +329,10 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
252 // animepahe doesn't distinguish sub/dub at the search level 329 // animepahe doesn't distinguish sub/dub at the search level
253 searchUrl := fmt.Sprintf("https://animepahe.pw/api?m=search&q=%s", url.QueryEscape(query)) 330 searchUrl := fmt.Sprintf("https://animepahe.pw/api?m=search&q=%s", url.QueryEscape(query))
254 331
255 req, _ := http.NewRequest("GET", searchUrl, nil) 332 req, err := newAnimepaheAPIRequest(searchUrl)
256 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") 333 if err != nil {
257 req.Header.Set("Referer", "https://animepahe.pw/") 334 return nil, err
258 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") 335 }
259 req.Header.Set("X-Requested-With", "XMLHttpRequest")
260 336
261 resp, err := sharedHTTPClient.Do(req) 337 resp, err := sharedHTTPClient.Do(req)
262 if err != nil { 338 if err != nil {
@@ -268,6 +344,9 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption,
268 if err != nil { 344 if err != nil {
269 return nil, err 345 return nil, err
270 } 346 }
347 if !httpStatusOK(resp.StatusCode) {
348 return nil, httpStatusError("animepahe search", resp.StatusCode, body)
349 }
271 350
272 var searchResp animepaheSearchResponse 351 var searchResp animepaheSearchResponse
273 err = json.Unmarshal(body, &searchResp) 352 err = json.Unmarshal(body, &searchResp)
@@ -315,14 +394,14 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
315 394
316 var allEpisodes []int 395 var allEpisodes []int
317 page := 1 396 page := 1
397 challengeRetried := false
318 398
319 for { 399 for {
320 epUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", apiID, page) 400 epUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", apiID, page)
321 req, _ := http.NewRequest("GET", epUrl, nil) 401 req, err := newAnimepaheAPIRequest(epUrl)
322 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") 402 if err != nil {
323 req.Header.Set("Referer", "https://animepahe.pw/") 403 return nil, err
324 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") 404 }
325 req.Header.Set("X-Requested-With", "XMLHttpRequest")
326 405
327 resp, err := sharedHTTPClient.Do(req) 406 resp, err := sharedHTTPClient.Do(req)
328 if err != nil { 407 if err != nil {
@@ -334,6 +413,20 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error)
334 if err != nil { 413 if err != nil {
335 return nil, err 414 return nil, err
336 } 415 }
416 if isAnimepaheChallengeResponse(resp, body) {
417 if challengeRetried {
418 return nil, fmt.Errorf("animepahe episode list is still blocked by DDoS-Guard after refreshing browser session")
419 }
420 Log("Animepahe episode list returned DDoS-Guard challenge. Refreshing browser session...")
421 if err := p.refreshBypass(); err != nil {
422 return nil, err
423 }
424 challengeRetried = true
425 continue
426 }
427 if !httpStatusOK(resp.StatusCode) {
428 return nil, httpStatusError("animepahe episode list", resp.StatusCode, body)
429 }
337 430
338 var epsResp animepaheEpisodesResponse 431 var epsResp animepaheEpisodesResponse
339 err = json.Unmarshal(body, &epsResp) 432 err = json.Unmarshal(body, &epsResp)
@@ -390,11 +483,10 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int
390 page := 1 483 page := 1
391 for { 484 for {
392 reqUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", apiID, page) 485 reqUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", apiID, page)
393 req, _ := http.NewRequest("GET", reqUrl, nil) 486 req, err := newAnimepaheAPIRequest(reqUrl)
394 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") 487 if err != nil {
395 req.Header.Set("Referer", "https://animepahe.pw/") 488 return nil, err
396 req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") 489 }
397 req.Header.Set("X-Requested-With", "XMLHttpRequest")
398 490
399 resp, err := sharedHTTPClient.Do(req) 491 resp, err := sharedHTTPClient.Do(req)
400 if err != nil { 492 if err != nil {
@@ -406,6 +498,9 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int
406 if err != nil { 498 if err != nil {
407 return nil, err 499 return nil, err
408 } 500 }
501 if !httpStatusOK(resp.StatusCode) {
502 return nil, httpStatusError("animepahe episode lookup", resp.StatusCode, body)
503 }
409 504
410 var epsResp animepaheEpisodesResponse 505 var epsResp animepaheEpisodesResponse
411 err = json.Unmarshal(body, &epsResp) 506 err = json.Unmarshal(body, &epsResp)
@@ -433,10 +528,10 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int
433 // player page: https://animepahe.pw/play/<anime_session>/<episode_session> 528 // player page: https://animepahe.pw/play/<anime_session>/<episode_session>
434 // stream links in player page: <button type=\"button\" data-src=\"https://kwik.cx/e/Jwd0hMNswksj\" 529 // stream links in player page: <button type=\"button\" data-src=\"https://kwik.cx/e/Jwd0hMNswksj\"
435 playerUrl := fmt.Sprintf("https://animepahe.pw/play/%s/%s", animeRef.Session, episodeSession) 530 playerUrl := fmt.Sprintf("https://animepahe.pw/play/%s/%s", animeRef.Session, episodeSession)
436 req, _ := http.NewRequest("GET", playerUrl, nil) 531 req, err := newAnimepahePageRequest(playerUrl)
437 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") 532 if err != nil {
438 req.Header.Set("Referer", "https://animepahe.pw/") 533 return nil, err
439 req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8") 534 }
440 535
441 resp, err := sharedHTTPClient.Do(req) 536 resp, err := sharedHTTPClient.Do(req)
442 if err != nil { 537 if err != nil {
@@ -448,6 +543,9 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int
448 if err != nil { 543 if err != nil {
449 return nil, err 544 return nil, err
450 } 545 }
546 if !httpStatusOK(resp.StatusCode) {
547 return nil, httpStatusError("animepahe player page", resp.StatusCode, body)
548 }
451 549
452 bodyStr := string(body) 550 bodyStr := string(body)
453 type streamLink struct { 551 type streamLink struct {
@@ -504,18 +602,18 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int
504 sortFunc(dubLinks) 602 sortFunc(dubLinks)
505 603
506 var links []string 604 var links []string
507 if config.SubOrDub == "dub" && len(dubLinks) > 0 { 605 mode := normalizeTranslationType(config.SubOrDub)
606 if mode == "dub" {
508 for _, l := range dubLinks { 607 for _, l := range dubLinks {
509 links = append(links, l.url) 608 links = append(links, l.url)
510 } 609 }
511 } else if len(subLinks) > 0 { 610 } else {
512 for _, l := range subLinks { 611 for _, l := range subLinks {
513 links = append(links, l.url) 612 links = append(links, l.url)
514 } 613 }
515 } else if len(dubLinks) > 0 { 614 }
516 for _, l := range dubLinks { 615 if len(links) == 0 {
517 links = append(links, l.url) 616 return nil, fmt.Errorf("no %s streams found for episode %d", mode, epNo)
518 }
519 } 617 }
520 618
521 var finalLinks []string 619 var finalLinks []string
@@ -527,17 +625,17 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int
527 } 625 }
528 626
529 if len(finalLinks) == 0 { 627 if len(finalLinks) == 0 {
530 return nil, fmt.Errorf("failed to extract any stream links from kwik") 628 return nil, fmt.Errorf("failed to extract any %s stream links from kwik", mode)
531 } 629 }
532 630
533 return finalLinks, nil 631 return finalLinks, nil
534} 632}
535 633
536func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) { 634func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) {
537 req, _ := http.NewRequest("GET", kwikUrl, nil) 635 req, err := newAnimepahePageRequest(kwikUrl)
538 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") 636 if err != nil {
539 req.Header.Set("Referer", "https://animepahe.pw/") 637 return "", err
540 req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8") 638 }
541 639
542 resp, err := sharedHTTPClient.Do(req) 640 resp, err := sharedHTTPClient.Do(req)
543 if err != nil { 641 if err != nil {
@@ -549,6 +647,9 @@ func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) {
549 if err != nil { 647 if err != nil {
550 return "", err 648 return "", err
551 } 649 }
650 if !httpStatusOK(resp.StatusCode) {
651 return "", httpStatusError("kwik stream page", resp.StatusCode, body)
652 }
552 bodyStr := string(body) 653 bodyStr := string(body)
553 654
554 re := regexp.MustCompile(`eval\(function\(p,a,c,k,e,d\).*?\}\('(.*?)',(\d+),(\d+),'([^']+)'\.split\('\|'\).*?\)\)`) 655 re := regexp.MustCompile(`eval\(function\(p,a,c,k,e,d\).*?\}\('(.*?)',(\d+),(\d+),'([^']+)'\.split\('\|'\).*?\)\)`)
internal/provider_animepahe_test.go added +166
@@ -0,0 +1,166 @@
1package internal
2
3import (
4 "io"
5 "net/http"
6 "net/http/cookiejar"
7 "os"
8 "strings"
9 "testing"
10)
11
12const animepaheChallengeHTML = `<!doctype html><html><head><title>DDoS-Guard</title></head><body>Checking your browser</body></html>`
13
14func animepaheTestResponse(req *http.Request, statusCode int, body string, headers map[string]string) *http.Response {
15 resp := &http.Response{
16 StatusCode: statusCode,
17 Header: make(http.Header),
18 Body: io.NopCloser(strings.NewReader(body)),
19 Request: req,
20 }
21 for key, value := range headers {
22 resp.Header.Set(key, value)
23 }
24 return resp
25}
26
27func withAnimepaheTestHooks(t *testing.T, client *http.Client, solver func() ([]*http.Cookie, error)) {
28 t.Helper()
29
30 previousClient := sharedHTTPClient
31 previousSolver := solveAnimepaheBrowserChallenge
32 previousBypassed := animepaheCookiesBypassed
33 previousConfig := GetGlobalConfig()
34
35 t.Cleanup(func() {
36 sharedHTTPClient = previousClient
37 solveAnimepaheBrowserChallenge = previousSolver
38 animepaheCookiesBypassed = previousBypassed
39 SetGlobalConfig(previousConfig)
40 })
41
42 sharedHTTPClient = client
43 solveAnimepaheBrowserChallenge = solver
44 SetGlobalConfig(&CurdConfig{StoragePath: t.TempDir()})
45}
46
47func TestAnimepaheEpisodesListRefreshesSessionWhenReleaseEndpointReturnsChallenge(t *testing.T) {
48 jar, err := cookiejar.New(nil)
49 if err != nil {
50 t.Fatalf("create cookie jar: %v", err)
51 }
52
53 var releaseCalls int
54 var searchChecks int
55 var solverCalls int
56 client := &http.Client{Jar: jar, Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
57 switch req.URL.Query().Get("m") {
58 case "release":
59 releaseCalls++
60 if releaseCalls == 1 {
61 return animepaheTestResponse(req, http.StatusForbidden, animepaheChallengeHTML, map[string]string{
62 "Content-Type": "text/html; charset=UTF-8",
63 "Server": "ddos-guard",
64 }), nil
65 }
66 return animepaheTestResponse(req, http.StatusOK, `{"total":2,"per_page":30,"current_page":1,"last_page":1,"data":[{"episode":1},{"episode":2}]}`, map[string]string{
67 "Content-Type": "application/json",
68 }), nil
69 case "search":
70 searchChecks++
71 return animepaheTestResponse(req, http.StatusOK, `{"total":0,"per_page":8,"current_page":1,"last_page":1,"data":[]}`, map[string]string{
72 "Content-Type": "application/json",
73 }), nil
74 default:
75 t.Fatalf("unexpected animepahe request: %s", req.URL.String())
76 return nil, nil
77 }
78 })}
79 withAnimepaheTestHooks(t, client, func() ([]*http.Cookie, error) {
80 solverCalls++
81 return []*http.Cookie{{Name: "__ddg2_", Value: "fresh"}}, nil
82 })
83 animepaheCookiesBypassed = true
84
85 episodes, err := (&AnimepaheProvider{}).EpisodesList("4:session-id", "sub")
86 if err != nil {
87 t.Fatalf("expected episode list retry to succeed: %v", err)
88 }
89 if got := strings.Join(episodes, ","); got != "1,2" {
90 t.Fatalf("unexpected animepahe episodes: %s", got)
91 }
92 if releaseCalls != 2 {
93 t.Fatalf("expected release endpoint to be retried once, got %d calls", releaseCalls)
94 }
95 if searchChecks != 1 {
96 t.Fatalf("expected refreshed session validation, got %d checks", searchChecks)
97 }
98 if solverCalls != 1 {
99 t.Fatalf("expected one browser challenge refresh, got %d", solverCalls)
100 }
101}
102
103func TestAnimepaheEpisodesListReportsPersistentChallengeAfterRefresh(t *testing.T) {
104 jar, err := cookiejar.New(nil)
105 if err != nil {
106 t.Fatalf("create cookie jar: %v", err)
107 }
108
109 var releaseCalls int
110 client := &http.Client{Jar: jar, Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
111 switch req.URL.Query().Get("m") {
112 case "release":
113 releaseCalls++
114 return animepaheTestResponse(req, http.StatusForbidden, animepaheChallengeHTML, map[string]string{
115 "Content-Type": "text/html; charset=UTF-8",
116 "Server": "ddos-guard",
117 }), nil
118 case "search":
119 return animepaheTestResponse(req, http.StatusOK, `{"total":0,"per_page":8,"current_page":1,"last_page":1,"data":[]}`, map[string]string{
120 "Content-Type": "application/json",
121 }), nil
122 default:
123 t.Fatalf("unexpected animepahe request: %s", req.URL.String())
124 return nil, nil
125 }
126 })}
127 withAnimepaheTestHooks(t, client, func() ([]*http.Cookie, error) {
128 return []*http.Cookie{{Name: "__ddg2_", Value: "fresh"}}, nil
129 })
130 animepaheCookiesBypassed = true
131
132 _, err = (&AnimepaheProvider{}).EpisodesList("4:session-id", "sub")
133 if err == nil {
134 t.Fatalf("expected persistent DDoS-Guard challenge to fail")
135 }
136 if !strings.Contains(err.Error(), "still blocked by DDoS-Guard") {
137 t.Fatalf("unexpected error: %v", err)
138 }
139 if releaseCalls != 2 {
140 t.Fatalf("expected exactly one retry after challenge refresh, got %d release calls", releaseCalls)
141 }
142}
143
144func TestAnimepaheEpisodesListLiveOnePiece(t *testing.T) {
145 if os.Getenv("CURD_LIVE_ANIMEPAHE_TEST") != "1" {
146 t.Skip("set CURD_LIVE_ANIMEPAHE_TEST=1 to run live Animepahe episode-list verification")
147 }
148
149 previousConfig := GetGlobalConfig()
150 previousBypassed := animepaheCookiesBypassed
151 t.Cleanup(func() {
152 SetGlobalConfig(previousConfig)
153 animepaheCookiesBypassed = previousBypassed
154 })
155 SetGlobalConfig(&CurdConfig{StoragePath: t.TempDir()})
156 animepaheCookiesBypassed = false
157
158 episodes, err := (&AnimepaheProvider{}).EpisodesList("4:15a36fc8-73b9-8c2e-ee5f-fb1bcd4fcdc6", "sub")
159 if err != nil {
160 t.Fatalf("live Animepahe One Piece episode list failed: %v", err)
161 }
162 t.Logf("live Animepahe One Piece episode count: %d", len(episodes))
163 if len(episodes) < 1000 {
164 t.Fatalf("expected One Piece to return a large live episode list, got %d episodes", len(episodes))
165 }
166}
internal/selection_menu.go +37 −14
@@ -100,7 +100,8 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
100 case tea.KeyMsg: 100 case tea.KeyMsg:
101 switch msg.String() { 101 switch msg.String() {
102 case "ctrl+c": 102 case "ctrl+c":
103 // Return quit selection option directly 103 m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}}
104 m.selected = 0
104 return m, tea.Quit 105 return m, tea.Quit
105 case "esc": 106 case "esc":
106 // ESC: quit on home menu, go back on sub-menus 107 // ESC: quit on home menu, go back on sub-menus
@@ -140,6 +141,9 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
140 m.scrollOffset-- 141 m.scrollOffset--
141 } 142 }
142 case "enter": 143 case "enter":
144 if len(m.filteredKeys) == 0 {
145 return m, nil
146 }
143 if m.filteredKeys[m.selected].Key == "add_new" { 147 if m.filteredKeys[m.selected].Key == "add_new" {
144 CurdOut("Adding a new anime...") 148 CurdOut("Adding a new anime...")
145 m.filteredKeys[m.selected] = SelectionOption{Label: "add_new", Key: "0"} 149 m.filteredKeys[m.selected] = SelectionOption{Label: "add_new", Key: "0"}
@@ -242,7 +246,11 @@ func (m Model) View() string {
242// visibleItemsCount calculates how many options fit in the terminal 246// visibleItemsCount calculates how many options fit in the terminal
243func (m Model) visibleItemsCount() int { 247func (m Model) visibleItemsCount() int {
244 // Leave space for the filter and other UI elements 248 // Leave space for the filter and other UI elements
245 return m.terminalHeight - 4 // Adjust this number based on your terminal layout 249 count := m.terminalHeight - 4 // Adjust this number based on your terminal layout
250 if count < 1 {
251 return 1
252 }
253 return count
246} 254}
247 255
248// filterOptions filters and sorts options based on the search term 256// filterOptions filters and sorts options based on the search term
@@ -335,7 +343,12 @@ func findSelectionIndex(options []SelectionOption, previousKey string, previousL
335} 343}
336 344
337func sortHomeMenuOptions(options []SelectionOption) []SelectionOption { 345func sortHomeMenuOptions(options []SelectionOption) []SelectionOption {
338 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",") 346 config := GetGlobalConfig()
347 if config == nil || strings.TrimSpace(config.MenuOrder) == "" {
348 return options
349 }
350
351 menuOrder := strings.Split(config.MenuOrder, ",")
339 optMap := make(map[string]SelectionOption) 352 optMap := make(map[string]SelectionOption)
340 for _, opt := range options { 353 for _, opt := range options {
341 optMap[opt.Key] = opt 354 optMap[opt.Key] = opt
@@ -501,6 +514,10 @@ func parsePreviewSelection(rawSelection string, selectionOptions []SelectionOpti
501} 514}
502 515
503func downloadToCache(imageURL string) (string, error) { 516func downloadToCache(imageURL string) (string, error) {
517 if strings.TrimSpace(imageURL) == "" {
518 return "", fmt.Errorf("image URL is empty")
519 }
520
504 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images") 521 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
505 if err := os.MkdirAll(cacheDir, 0755); err != nil { 522 if err := os.MkdirAll(cacheDir, 0755); err != nil {
506 return "", fmt.Errorf("failed to create cache directory: %w", err) 523 return "", fmt.Errorf("failed to create cache directory: %w", err)
@@ -511,28 +528,38 @@ func downloadToCache(imageURL string) (string, error) {
511 cachePath := filepath.Join(cacheDir, filename) 528 cachePath := filepath.Join(cacheDir, filename)
512 529
513 // Check if file already exists in cache 530 // Check if file already exists in cache
514 if _, err := os.Stat(cachePath); err == nil { 531 if info, err := os.Stat(cachePath); err == nil {
515 return cachePath, nil 532 if info.Size() > 0 {
533 return cachePath, nil
534 }
535 _ = os.Remove(cachePath)
516 } 536 }
517 537
518 // Download the image 538 // Download the image
519 resp, err := http.Get(imageURL) 539 resp, err := sharedHTTPClient.Get(imageURL)
520 if err != nil { 540 if err != nil {
521 return "", err 541 return "", err
522 } 542 }
523 defer resp.Body.Close() 543 defer resp.Body.Close()
544 if resp.StatusCode != http.StatusOK {
545 return "", fmt.Errorf("failed to download image: status %d", resp.StatusCode)
546 }
524 547
525 file, err := os.Create(cachePath) 548 file, err := os.Create(cachePath)
526 if err != nil { 549 if err != nil {
527 return "", err 550 return "", err
528 } 551 }
529 defer file.Close()
530 552
531 _, err = io.Copy(file, resp.Body) 553 _, err = io.Copy(file, resp.Body)
532 if err != nil { 554 if err != nil {
555 file.Close()
533 os.Remove(cachePath) // Clean up on error 556 os.Remove(cachePath) // Clean up on error
534 return "", err 557 return "", err
535 } 558 }
559 if err := file.Close(); err != nil {
560 os.Remove(cachePath)
561 return "", err
562 }
536 563
537 return cachePath, nil 564 return cachePath, nil
538} 565}
@@ -624,6 +651,8 @@ func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
624 return dynamicSelectInternal(options, nil) 651 return dynamicSelectInternal(options, nil)
625} 652}
626 653
654var promptSelect = DynamicSelect
655
627func DynamicSelectWithRefresh(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) { 656func DynamicSelectWithRefresh(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
628 return dynamicSelectInternal(options, refreshConfig) 657 return dynamicSelectInternal(options, refreshConfig)
629} 658}
@@ -635,13 +664,7 @@ func dynamicSelectInternal(options []SelectionOption, refreshConfig *SelectionRe
635 options = sortHomeMenuOptions(options) 664 options = sortHomeMenuOptions(options)
636 } 665 }
637 666
638 for _, opt := range options { 667 if config := GetGlobalConfig(); config != nil && config.RofiSelection {
639 if strings.Contains(opt.Label, "Bleach (366 episodes) [animepahe]") {
640 return opt, nil
641 }
642 }
643
644 if GetGlobalConfig().RofiSelection {
645 return RofiSelectWithRefresh(options, isHomeMenu, refreshConfig) 668 return RofiSelectWithRefresh(options, isHomeMenu, refreshConfig)
646 } 669 }
647 670
internal/structs.go +1
@@ -23,6 +23,7 @@ type Anime struct {
23 ProviderName string // newly added for history migration 23 ProviderName string // newly added for history migration
24 FillerEpisodes []int 24 FillerEpisodes []int
25 IsAiring bool 25 IsAiring bool
26 SkipRemoteSync bool `json:"-"`
26} 27}
27 28
28type FuzzyDate struct { 29type FuzzyDate struct {
internal/tracking.go +218 −16
@@ -2,6 +2,7 @@ package internal
2 2
3import ( 3import (
4 "bufio" 4 "bufio"
5 "encoding/json"
5 "fmt" 6 "fmt"
6 "os" 7 "os"
7 "path/filepath" 8 "path/filepath"
@@ -29,6 +30,13 @@ func UsesRemoteTracking(config *CurdConfig) bool {
29 return normalizeRemoteTracker(config.TrackingRemote) != TrackingRemoteNone 30 return normalizeRemoteTracker(config.TrackingRemote) != TrackingRemoteNone
30} 31}
31 32
33func ShouldWriteRemoteTracking(config *CurdConfig, anime *Anime) bool {
34 if !UsesRemoteTracking(config) {
35 return false
36 }
37 return anime == nil || !anime.SkipRemoteSync
38}
39
32func UsesAniListTracking(config *CurdConfig) bool { 40func UsesAniListTracking(config *CurdConfig) bool {
33 if config == nil { 41 if config == nil {
34 return true 42 return true
@@ -134,6 +142,7 @@ func persistTrackingConfig(config *CurdConfig) error {
134 configMap["MyAnimeListClientID"] = config.MyAnimeListClientID 142 configMap["MyAnimeListClientID"] = config.MyAnimeListClientID
135 configMap["MyAnimeListClientSecret"] = config.MyAnimeListClientSecret 143 configMap["MyAnimeListClientSecret"] = config.MyAnimeListClientSecret
136 configMap["MyAnimeListImported"] = strconv.FormatBool(config.MyAnimeListImported) 144 configMap["MyAnimeListImported"] = strconv.FormatBool(config.MyAnimeListImported)
145 configMap["MyAnimeListImportDismissed"] = strconv.FormatBool(config.MyAnimeListImportDismissed)
137 146
138 return SaveConfigToFile(GlobalConfigPath, configMap) 147 return SaveConfigToFile(GlobalConfigPath, configMap)
139} 148}
@@ -167,18 +176,32 @@ func promptTrackingInput(prompt string, allowEmpty bool) (string, error) {
167 176
168func promptAnimeScoreValue() (float64, error) { 177func promptAnimeScoreValue() (float64, error) {
169 config := GetGlobalConfig() 178 config := GetGlobalConfig()
179 parseScore := func(raw string) (float64, error) {
180 score, err := strconv.ParseFloat(strings.TrimSpace(raw), 64)
181 if err != nil {
182 return 0, err
183 }
184 if score < 0 || score > 10 {
185 return 0, fmt.Errorf("score must be between 0 and 10")
186 }
187 return score, nil
188 }
189
170 if config != nil && config.RofiSelection { 190 if config != nil && config.RofiSelection {
171 userInput, err := GetUserInputFromRofi("Enter a score for the anime (0-10)") 191 userInput, err := GetUserInputFromRofi("Enter a score for the anime (0-10)")
172 if err != nil { 192 if err != nil {
173 return 0, err 193 return 0, err
174 } 194 }
175 return strconv.ParseFloat(strings.TrimSpace(userInput), 64) 195 return parseScore(userInput)
176 } 196 }
177 197
178 fmt.Println("Rate this anime: ") 198 fmt.Println("Rate this anime: ")
179 var score float64 199 reader := bufio.NewReader(os.Stdin)
180 fmt.Scanln(&score) 200 input, err := reader.ReadString('\n')
181 return score, nil 201 if err != nil {
202 return 0, err
203 }
204 return parseScore(input)
182} 205}
183 206
184func ensureMyAnimeListCredentialsConfigured(config *CurdConfig) error { 207func ensureMyAnimeListCredentialsConfigured(config *CurdConfig) error {
@@ -273,6 +296,13 @@ func localAnimeListFromHistory(history []Anime) AnimeList {
273 return list 296 return list
274} 297}
275 298
299func nextEpisodeFromProgress(progress int) int {
300 if progress < 0 {
301 return 1
302 }
303 return progress + 1
304}
305
276func BuildLocalAnimeList(storagePath string) AnimeList { 306func BuildLocalAnimeList(storagePath string) AnimeList {
277 historyPath := filepath.Join(os.ExpandEnv(storagePath), "curd_history.txt") 307 historyPath := filepath.Join(os.ExpandEnv(storagePath), "curd_history.txt")
278 return localAnimeListFromHistory(LocalGetAllAnime(historyPath)) 308 return localAnimeListFromHistory(LocalGetAllAnime(historyPath))
@@ -282,6 +312,98 @@ func hasAnyEntries(list AnimeList) bool {
282 return len(list.Watching)+len(list.Completed)+len(list.Paused)+len(list.Dropped)+len(list.Planning)+len(list.Rewatching) > 0 312 return len(list.Watching)+len(list.Completed)+len(list.Paused)+len(list.Dropped)+len(list.Planning)+len(list.Rewatching) > 0
283} 313}
284 314
315func animeListEntryCount(list AnimeList) int {
316 return len(getEntriesByCategory(list, "ALL"))
317}
318
319func countEntriesMissingMyAnimeListID(list AnimeList) int {
320 count := 0
321 for _, entry := range getEntriesByCategory(list, "ALL") {
322 if entry.Media.MalID == 0 {
323 count++
324 }
325 }
326 return count
327}
328
329func countAniListDeletes(list AnimeList) int {
330 count := 0
331 for _, entry := range getEntriesByCategory(list, "ALL") {
332 if entry.ListID != 0 {
333 count++
334 }
335 }
336 return count
337}
338
339type remoteSyncPreview struct {
340 Action string
341 AniListEntries int
342 MyAnimeListEntries int
343 Writes int
344 Deletes int
345 MissingMALIDs int
346}
347
348func confirmRemoteSync(preview remoteSyncPreview) (bool, error) {
349 if os.Getenv("CURD_TEST_AUTO_CONFIRM_REMOTE_SYNC") == "1" {
350 return true, nil
351 }
352
353 CurdOut(fmt.Sprintf("%s: AniList %d, MyAnimeList %d.", preview.Action, preview.AniListEntries, preview.MyAnimeListEntries))
354 if preview.Deletes > 0 {
355 CurdOut(fmt.Sprintf("This will write %d entries and delete %d entries.", preview.Writes, preview.Deletes))
356 } else {
357 CurdOut(fmt.Sprintf("This will write %d entries.", preview.Writes))
358 }
359 if preview.MissingMALIDs > 0 {
360 CurdOut(fmt.Sprintf("%d entries need a MyAnimeList ID lookup.", preview.MissingMALIDs))
361 }
362
363 selected, err := promptSelect([]SelectionOption{
364 {Key: "continue", Label: "Continue"},
365 {Key: "cancel", Label: "Cancel"},
366 })
367 if err != nil {
368 return false, err
369 }
370 return selected.Key == "continue", nil
371}
372
373func writeTrackingBackup(config *CurdConfig, action string, aniList, myAnimeList AnimeList) (string, error) {
374 if config == nil {
375 return "", fmt.Errorf("missing config")
376 }
377
378 backupDir := filepath.Join(os.ExpandEnv(config.StoragePath), "tracking-backups")
379 if err := os.MkdirAll(backupDir, 0755); err != nil {
380 return "", err
381 }
382
383 slug := strings.NewReplacer(" ", "-", "+", "-", ":", "", "/", "-").Replace(strings.ToLower(action))
384 backupPath := filepath.Join(backupDir, fmt.Sprintf("%s-%s.json", time.Now().Format("20060102-150405"), slug))
385 payload := struct {
386 Action string `json:"action"`
387 CreatedAt time.Time `json:"created_at"`
388 AniList AnimeList `json:"anilist"`
389 MyAnimeList AnimeList `json:"myanimelist"`
390 }{
391 Action: action,
392 CreatedAt: time.Now(),
393 AniList: aniList,
394 MyAnimeList: myAnimeList,
395 }
396
397 data, err := json.MarshalIndent(payload, "", " ")
398 if err != nil {
399 return "", err
400 }
401 if err := os.WriteFile(backupPath, data, 0644); err != nil {
402 return "", err
403 }
404 return backupPath, nil
405}
406
285func currentFuzzyDate() FuzzyDate { 407func currentFuzzyDate() FuzzyDate {
286 now := time.Now() 408 now := time.Now()
287 return FuzzyDate{ 409 return FuzzyDate{
@@ -376,9 +498,15 @@ func mergeAnimeEntries(existing, incoming Entry) Entry {
376func mergeAnimeLists(primary, secondary AnimeList) AnimeList { 498func mergeAnimeLists(primary, secondary AnimeList) AnimeList {
377 merged := make(map[int]Entry) 499 merged := make(map[int]Entry)
378 for _, entry := range getEntriesByCategory(primary, "ALL") { 500 for _, entry := range getEntriesByCategory(primary, "ALL") {
501 if entry.Media.ID == 0 {
502 continue
503 }
379 merged[entry.Media.ID] = entry 504 merged[entry.Media.ID] = entry
380 } 505 }
381 for _, entry := range getEntriesByCategory(secondary, "ALL") { 506 for _, entry := range getEntriesByCategory(secondary, "ALL") {
507 if entry.Media.ID == 0 {
508 continue
509 }
382 if existing, ok := merged[entry.Media.ID]; ok { 510 if existing, ok := merged[entry.Media.ID]; ok {
383 merged[entry.Media.ID] = mergeAnimeEntries(existing, entry) 511 merged[entry.Media.ID] = mergeAnimeEntries(existing, entry)
384 continue 512 continue
@@ -409,6 +537,9 @@ func mergeAnimeLists(primary, secondary AnimeList) AnimeList {
409func mapEntriesByMediaID(list AnimeList) map[int]Entry { 537func mapEntriesByMediaID(list AnimeList) map[int]Entry {
410 entries := make(map[int]Entry) 538 entries := make(map[int]Entry)
411 for _, entry := range getEntriesByCategory(list, "ALL") { 539 for _, entry := range getEntriesByCategory(list, "ALL") {
540 if entry.Media.ID == 0 {
541 continue
542 }
412 entries[entry.Media.ID] = entry 543 entries[entry.Media.ID] = entry
413 } 544 }
414 return entries 545 return entries
@@ -758,7 +889,7 @@ func resolveMyAnimeListID(anilistID int) (int, error) {
758func UpdateAnimeProgress(token string, mediaID, progress int) error { 889func UpdateAnimeProgress(token string, mediaID, progress int) error {
759 config := GetGlobalConfig() 890 config := GetGlobalConfig()
760 switch { 891 switch {
761 case !UsesRemoteTracking(config): 892 case !ShouldWriteRemoteTracking(config, GetGlobalAnime()):
762 return nil 893 return nil
763 case UsesDualRemoteTracking(config): 894 case UsesDualRemoteTracking(config):
764 var firstErr error 895 var firstErr error
@@ -792,7 +923,7 @@ func UpdateAnimeProgress(token string, mediaID, progress int) error {
792func UpdateAnimeStatus(token string, mediaID int, status string) error { 923func UpdateAnimeStatus(token string, mediaID int, status string) error {
793 config := GetGlobalConfig() 924 config := GetGlobalConfig()
794 switch { 925 switch {
795 case !UsesRemoteTracking(config): 926 case !ShouldWriteRemoteTracking(config, GetGlobalAnime()):
796 return nil 927 return nil
797 case UsesDualRemoteTracking(config): 928 case UsesDualRemoteTracking(config):
798 var firstErr error 929 var firstErr error
@@ -826,7 +957,7 @@ func UpdateAnimeStatus(token string, mediaID int, status string) error {
826func RateAnime(token string, mediaID int) error { 957func RateAnime(token string, mediaID int) error {
827 config := GetGlobalConfig() 958 config := GetGlobalConfig()
828 switch { 959 switch {
829 case !UsesRemoteTracking(config): 960 case !ShouldWriteRemoteTracking(config, GetGlobalAnime()):
830 return nil 961 return nil
831 case UsesDualRemoteTracking(config): 962 case UsesDualRemoteTracking(config):
832 score, err := promptAnimeScoreValue() 963 score, err := promptAnimeScoreValue()
@@ -864,7 +995,7 @@ func RateAnime(token string, mediaID int) error {
864func AddAnimeToWatchingList(animeID int, token string) error { 995func AddAnimeToWatchingList(animeID int, token string) error {
865 config := GetGlobalConfig() 996 config := GetGlobalConfig()
866 switch { 997 switch {
867 case !UsesRemoteTracking(config): 998 case !ShouldWriteRemoteTracking(config, GetGlobalAnime()):
868 return nil 999 return nil
869 case UsesDualRemoteTracking(config): 1000 case UsesDualRemoteTracking(config):
870 var firstErr error 1001 var firstErr error
@@ -898,7 +1029,7 @@ func AddAnimeToWatchingList(animeID int, token string) error {
898func CompleteAnimeRewatch(token string, anime Anime) error { 1029func CompleteAnimeRewatch(token string, anime Anime) error {
899 config := GetGlobalConfig() 1030 config := GetGlobalConfig()
900 switch { 1031 switch {
901 case !UsesRemoteTracking(config): 1032 case !ShouldWriteRemoteTracking(config, &anime):
902 return nil 1033 return nil
903 case UsesDualRemoteTracking(config): 1034 case UsesDualRemoteTracking(config):
904 var firstErr error 1035 var firstErr error
@@ -942,7 +1073,7 @@ func StartAnimeRewatch(token string, anime Anime) error {
942 startedAt := currentFuzzyDate() 1073 startedAt := currentFuzzyDate()
943 completedAt := FuzzyDate{} 1074 completedAt := FuzzyDate{}
944 switch { 1075 switch {
945 case !UsesRemoteTracking(config): 1076 case !ShouldWriteRemoteTracking(config, &anime):
946 return nil 1077 return nil
947 case UsesDualRemoteTracking(config): 1078 case UsesDualRemoteTracking(config):
948 var firstErr error 1079 var firstErr error
@@ -1000,7 +1131,7 @@ func StartAnimeRewatch(token string, anime Anime) error {
1000func AddAnimeToList(animeID int, status string, token string) error { 1131func AddAnimeToList(animeID int, status string, token string) error {
1001 config := GetGlobalConfig() 1132 config := GetGlobalConfig()
1002 switch { 1133 switch {
1003 case !UsesRemoteTracking(config): 1134 case !ShouldWriteRemoteTracking(config, GetGlobalAnime()):
1004 return nil 1135 return nil
1005 case UsesDualRemoteTracking(config): 1136 case UsesDualRemoteTracking(config):
1006 var firstErr error 1137 var firstErr error
@@ -1032,14 +1163,13 @@ func AddAnimeToList(animeID int, status string, token string) error {
1032} 1163}
1033 1164
1034func maybeImportAniListToMyAnimeList(config *CurdConfig, user *User) error { 1165func maybeImportAniListToMyAnimeList(config *CurdConfig, user *User) error {
1035 if config == nil || user == nil || !UsesMyAnimeListTracking(config) || config.MyAnimeListImported || hasAnyEntries(user.AnimeList) { 1166 if config == nil || user == nil || !UsesMyAnimeListTracking(config) || config.MyAnimeListImported || config.MyAnimeListImportDismissed || hasAnyEntries(user.AnimeList) {
1036 return nil 1167 return nil
1037 } 1168 }
1038 1169
1039 legacyTokenPath := filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json") 1170 legacyTokenPath := filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")
1040 if _, err := os.Stat(legacyTokenPath); err != nil { 1171 if _, err := os.Stat(legacyTokenPath); err != nil {
1041 config.MyAnimeListImported = true 1172 return nil
1042 return persistTrackingConfig(config)
1043 } 1173 }
1044 1174
1045 options := []SelectionOption{ 1175 options := []SelectionOption{
@@ -1048,7 +1178,7 @@ func maybeImportAniListToMyAnimeList(config *CurdConfig, user *User) error {
1048 } 1178 }
1049 1179
1050 CurdOut("AniList tracking data was found.") 1180 CurdOut("AniList tracking data was found.")
1051 selected, err := DynamicSelect(options) 1181 selected, err := promptSelect(options)
1052 if err != nil { 1182 if err != nil {
1053 return err 1183 return err
1054 } 1184 }
@@ -1060,9 +1190,12 @@ func maybeImportAniListToMyAnimeList(config *CurdConfig, user *User) error {
1060 if err := RefreshMyAnimeListUserAnimeList(config, user); err != nil { 1190 if err := RefreshMyAnimeListUserAnimeList(config, user); err != nil {
1061 return err 1191 return err
1062 } 1192 }
1193 config.MyAnimeListImported = true
1194 config.MyAnimeListImportDismissed = false
1195 return persistTrackingConfig(config)
1063 } 1196 }
1064 1197
1065 config.MyAnimeListImported = true 1198 config.MyAnimeListImportDismissed = true
1066 return persistTrackingConfig(config) 1199 return persistTrackingConfig(config)
1067} 1200}
1068 1201
@@ -1261,6 +1394,30 @@ func ReplaceMyAnimeListWithAniList(config *CurdConfig) error {
1261 if err != nil { 1394 if err != nil {
1262 return err 1395 return err
1263 } 1396 }
1397 targetList, err := FetchLatestMyAnimeList(config, &User{})
1398 if err != nil {
1399 return err
1400 }
1401 ok, err := confirmRemoteSync(remoteSyncPreview{
1402 Action: "Replace MyAnimeList with AniList",
1403 AniListEntries: animeListEntryCount(sourceList),
1404 MyAnimeListEntries: animeListEntryCount(targetList),
1405 Writes: animeListEntryCount(sourceList),
1406 Deletes: animeListEntryCount(targetList),
1407 MissingMALIDs: countEntriesMissingMyAnimeListID(sourceList),
1408 })
1409 if err != nil {
1410 return err
1411 }
1412 if !ok {
1413 CurdOut("Tracker sync cancelled.")
1414 return nil
1415 }
1416 backupPath, err := writeTrackingBackup(config, "replace-myanimelist-with-anilist", sourceList, targetList)
1417 if err != nil {
1418 return err
1419 }
1420 CurdOut(fmt.Sprintf("Tracker backup saved: %s", backupPath))
1264 if err := wipeMyAnimeListRemote(config); err != nil { 1421 if err := wipeMyAnimeListRemote(config); err != nil {
1265 return err 1422 return err
1266 } 1423 }
@@ -1276,6 +1433,30 @@ func ReplaceAniListWithMyAnimeList(config *CurdConfig) error {
1276 if err != nil { 1433 if err != nil {
1277 return err 1434 return err
1278 } 1435 }
1436 targetList, err := fetchAniListAnimeListFromToken(token)
1437 if err != nil {
1438 return err
1439 }
1440 ok, err := confirmRemoteSync(remoteSyncPreview{
1441 Action: "Replace AniList with MyAnimeList",
1442 AniListEntries: animeListEntryCount(targetList),
1443 MyAnimeListEntries: animeListEntryCount(sourceList),
1444 Writes: animeListEntryCount(sourceList),
1445 Deletes: countAniListDeletes(targetList),
1446 MissingMALIDs: countEntriesMissingMyAnimeListID(sourceList),
1447 })
1448 if err != nil {
1449 return err
1450 }
1451 if !ok {
1452 CurdOut("Tracker sync cancelled.")
1453 return nil
1454 }
1455 backupPath, err := writeTrackingBackup(config, "replace-anilist-with-myanimelist", targetList, sourceList)
1456 if err != nil {
1457 return err
1458 }
1459 CurdOut(fmt.Sprintf("Tracker backup saved: %s", backupPath))
1279 if err := wipeAniListRemote(config); err != nil { 1460 if err := wipeAniListRemote(config); err != nil {
1280 return err 1461 return err
1281 } 1462 }
@@ -1301,6 +1482,27 @@ func MergeRemoteLists(config *CurdConfig) error {
1301 } 1482 }
1302 myAnimeListUser.AnimeList = myAnimeList 1483 myAnimeListUser.AnimeList = myAnimeList
1303 1484
1485 plan := buildDualRemoteSyncPlan(aniList, myAnimeList)
1486 ok, err := confirmRemoteSync(remoteSyncPreview{
1487 Action: "Merge AniList and MyAnimeList",
1488 AniListEntries: animeListEntryCount(aniList),
1489 MyAnimeListEntries: animeListEntryCount(myAnimeList),
1490 Writes: len(plan.AniListUpdates) + len(plan.MyAnimeListUpdates),
1491 Deletes: 0,
1492 MissingMALIDs: countEntriesMissingMyAnimeListID(plan.Merged),
1493 })
1494 if err != nil {
1495 return err
1496 }
1497 if !ok {
1498 CurdOut("Tracker sync cancelled.")
1499 return nil
1500 }
1501 backupPath, err := writeTrackingBackup(config, "merge-anilist-and-myanimelist", aniList, myAnimeList)
1502 if err != nil {
1503 return err
1504 }
1505 CurdOut(fmt.Sprintf("Tracker backup saved: %s", backupPath))
1304 _, err = syncDualRemoteTrackers(config, token, aniListUser, myAnimeListUser) 1506 _, err = syncDualRemoteTrackers(config, token, aniListUser, myAnimeListUser)
1305 return err 1507 return err
1306} 1508}
internal/tracking_live_integration_test.go +29
@@ -421,12 +421,33 @@ func TestTrackerLiveRuntimeIntegration(t *testing.T) {
421 }) 421 })
422} 422}
423 423
424func TestLiveTrackerContextForcesTerminalPrompts(t *testing.T) {
425 if os.Getenv("CURD_RUN_TRACKER_LIVE_INTEGRATION") == "1" {
426 t.Skip("live integration context is covered by the live suite")
427 }
428
429 config := CurdConfig{
430 RofiSelection: true,
431 ImagePreview: true,
432 AlternateScreen: true,
433 }
434 forceTerminalTestMode(&config)
435
436 if config.RofiSelection || config.ImagePreview || config.AlternateScreen {
437 t.Fatalf("expected live tests to force terminal prompt mode, got %+v", config)
438 }
439 if !config.MyAnimeListImportDismissed {
440 t.Fatalf("expected live tests to dismiss import prompt")
441 }
442}
443
424func loadLiveTrackerTestContext(t *testing.T) (*CurdConfig, string, []liveTestAnime, func()) { 444func loadLiveTrackerTestContext(t *testing.T) (*CurdConfig, string, []liveTestAnime, func()) {
425 t.Helper() 445 t.Helper()
426 446
427 if os.Getenv("CURD_RUN_TRACKER_LIVE_INTEGRATION") != "1" { 447 if os.Getenv("CURD_RUN_TRACKER_LIVE_INTEGRATION") != "1" {
428 t.Skip("set CURD_RUN_TRACKER_LIVE_INTEGRATION=1 to run live tracker integration tests") 448 t.Skip("set CURD_RUN_TRACKER_LIVE_INTEGRATION=1 to run live tracker integration tests")
429 } 449 }
450 t.Setenv("CURD_TEST_AUTO_CONFIRM_REMOTE_SYNC", "1")
430 451
431 configPath := os.Getenv("CURD_CONFIG_PATH") 452 configPath := os.Getenv("CURD_CONFIG_PATH")
432 if configPath == "" { 453 if configPath == "" {
@@ -443,6 +464,7 @@ func loadLiveTrackerTestContext(t *testing.T) (*CurdConfig, string, []liveTestAn
443 } 464 }
444 config.TrackingConfigured = true 465 config.TrackingConfigured = true
445 config.TrackingLocal = true 466 config.TrackingLocal = true
467 forceTerminalTestMode(&config)
446 468
447 previousGlobalConfig := GetGlobalConfig() 469 previousGlobalConfig := GetGlobalConfig()
448 previousGlobalUser := GetGlobalUser() 470 previousGlobalUser := GetGlobalUser()
@@ -477,6 +499,13 @@ func loadLiveTrackerTestContext(t *testing.T) (*CurdConfig, string, []liveTestAn
477 return &config, anilistToken, resolveLiveTestAnime(t), cleanup 499 return &config, anilistToken, resolveLiveTestAnime(t), cleanup
478} 500}
479 501
502func forceTerminalTestMode(config *CurdConfig) {
503 config.RofiSelection = false
504 config.ImagePreview = false
505 config.AlternateScreen = false
506 config.MyAnimeListImportDismissed = true
507}
508
480func resolveLiveTestAnime(t *testing.T) []liveTestAnime { 509func resolveLiveTestAnime(t *testing.T) []liveTestAnime {
481 t.Helper() 510 t.Helper()
482 511
internal/user_intent_regression_test.go added +402
@@ -0,0 +1,402 @@
1package internal
2
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "io"
8 "net/http"
9 "os"
10 "path/filepath"
11 "strings"
12 "testing"
13)
14
15type fakePlaybackProvider struct {
16 name string
17 linksByMode map[string][]string
18 errByMode map[string]error
19 episodeListByMode map[string][]string
20 episodeErrByMode map[string]error
21 modes []string
22 episodeModes []string
23}
24
25func (p *fakePlaybackProvider) Name() string {
26 if p.name != "" {
27 return p.name
28 }
29 return "fake"
30}
31
32func (p *fakePlaybackProvider) SearchAnime(query, mode string) ([]SelectionOption, error) {
33 return nil, nil
34}
35
36func (p *fakePlaybackProvider) EpisodesList(showID, mode string) ([]string, error) {
37 mode = normalizeTranslationType(mode)
38 p.episodeModes = append(p.episodeModes, mode)
39 if err := p.episodeErrByMode[mode]; err != nil {
40 return nil, err
41 }
42 if episodes, ok := p.episodeListByMode[mode]; ok {
43 return episodes, nil
44 }
45 return []string{"1"}, nil
46}
47
48func (p *fakePlaybackProvider) GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) {
49 mode := normalizeTranslationType(config.SubOrDub)
50 p.modes = append(p.modes, mode)
51 if err := p.errByMode[mode]; err != nil {
52 return nil, err
53 }
54 return p.linksByMode[mode], nil
55}
56
57func withPromptSelect(t *testing.T, fn func([]SelectionOption) (SelectionOption, error)) {
58 t.Helper()
59 previous := promptSelect
60 promptSelect = fn
61 t.Cleanup(func() {
62 promptSelect = previous
63 })
64}
65
66func withProvider(t *testing.T, provider Provider) {
67 t.Helper()
68 previous := CurrentProvider
69 CurrentProvider = provider
70 t.Cleanup(func() {
71 CurrentProvider = previous
72 })
73}
74
75func TestInferTotalEpisodesFromEpisodeListUsesHighestWholeEpisode(t *testing.T) {
76 episodes := []string{"1", "12", "2", "12.5", "special", "0"}
77
78 if got := inferTotalEpisodesFromEpisodeList(episodes); got != 12 {
79 t.Fatalf("expected highest whole episode 12, got %d", got)
80 }
81}
82
83func TestGetProviderTotalEpisodesUsesHighestEpisodeAcrossModes(t *testing.T) {
84 provider := &fakePlaybackProvider{
85 episodeListByMode: map[string][]string{
86 "dub": {"1", "2", "12"},
87 "sub": {"1", "99", "100", "100.5"},
88 },
89 }
90 withProvider(t, provider)
91
92 total, err := GetProviderTotalEpisodes("one-piece-id", "dub")
93 if err != nil {
94 t.Fatalf("expected provider total lookup to succeed: %v", err)
95 }
96 if total != 100 {
97 t.Fatalf("expected highest provider episode across modes, got %d", total)
98 }
99 if got := strings.Join(provider.episodeModes, ","); got != "dub,sub" {
100 t.Fatalf("expected preferred then alternate episode lookups, got %s", got)
101 }
102}
103
104func TestGetProviderTotalEpisodesQueriesAnimepaheOnce(t *testing.T) {
105 provider := &fakePlaybackProvider{
106 name: "animepahe",
107 episodeListByMode: map[string][]string{
108 "sub": {"1", "500", "1100"},
109 },
110 }
111 withProvider(t, provider)
112
113 total, err := GetProviderTotalEpisodes("one-piece-id", "sub")
114 if err != nil {
115 t.Fatalf("expected animepahe total lookup to succeed: %v", err)
116 }
117 if total != 3 {
118 t.Fatalf("expected animepahe provider total, got %d", total)
119 }
120 if got := strings.Join(provider.episodeModes, ","); got != "sub" {
121 t.Fatalf("expected animepahe to be queried once, got %s", got)
122 }
123}
124
125func TestGetProviderTotalEpisodesReturnsLookupErrorsWhenNoEpisodesFound(t *testing.T) {
126 provider := &fakePlaybackProvider{
127 episodeErrByMode: map[string]error{
128 "sub": errors.New("no sub episodes"),
129 "dub": errors.New("no dub episodes"),
130 },
131 }
132 withProvider(t, provider)
133
134 _, err := GetProviderTotalEpisodes("show-id", "sub")
135 if err == nil {
136 t.Fatalf("expected provider total lookup to fail")
137 }
138 if !strings.Contains(err.Error(), "no sub episodes") || !strings.Contains(err.Error(), "no dub episodes") {
139 t.Fatalf("expected both lookup errors, got %v", err)
140 }
141}
142
143func TestGetAllAnimeEpisodesListUsesValidGraphQLVariableSyntax(t *testing.T) {
144 previousClient := sharedHTTPClient
145 t.Cleanup(func() {
146 sharedHTTPClient = previousClient
147 })
148
149 sharedHTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
150 var payload struct {
151 Query string `json:"query"`
152 Variables map[string]string `json:"variables"`
153 }
154 if err := json.NewDecoder(req.Body).Decode(&payload); err != nil {
155 t.Fatalf("decode allanime episode request: %v", err)
156 }
157 if !strings.Contains(payload.Query, "query ($showId: String!)") {
158 t.Fatalf("episode list query is missing valid variable syntax: %q", payload.Query)
159 }
160 if payload.Variables["showId"] != "show-id" {
161 t.Fatalf("unexpected show id variable: %#v", payload.Variables)
162 }
163 return testHTTPResponse(req, http.StatusOK, `{"data":{"show":{"_id":"show-id","availableEpisodesDetail":{"sub":[1,2,12]}}}}`), nil
164 })}
165
166 episodes, err := getAllAnimeEpisodesList("show-id", "sub")
167 if err != nil {
168 t.Fatalf("expected allanime episode list lookup to succeed: %v", err)
169 }
170 if got := strings.Join(episodes, ","); got != "1,2,12" {
171 t.Fatalf("unexpected episodes: %s", got)
172 }
173}
174
175func captureStdout(t *testing.T, fn func()) string {
176 t.Helper()
177
178 originalStdout := os.Stdout
179 reader, writer, err := os.Pipe()
180 if err != nil {
181 t.Fatalf("create stdout pipe: %v", err)
182 }
183 os.Stdout = writer
184
185 fn()
186
187 if err := writer.Close(); err != nil {
188 t.Fatalf("close stdout writer: %v", err)
189 }
190 os.Stdout = originalStdout
191
192 var buf bytes.Buffer
193 if _, err := io.Copy(&buf, reader); err != nil {
194 t.Fatalf("read captured stdout: %v", err)
195 }
196 return buf.String()
197}
198
199func TestGetEpisodeURLForPlaybackUsesPreferredAudioOnlyWhenAvailable(t *testing.T) {
200 provider := &fakePlaybackProvider{
201 linksByMode: map[string][]string{"sub": {"sub-url"}, "dub": {"dub-url"}},
202 errByMode: map[string]error{},
203 }
204 withProvider(t, provider)
205
206 links, mode, err := GetEpisodeURLForPlayback(CurdConfig{SubOrDub: "sub"}, "anime-id", 1)
207 if err != nil {
208 t.Fatalf("expected preferred audio to succeed: %v", err)
209 }
210 if mode != "sub" || len(links) != 1 || links[0] != "sub-url" {
211 t.Fatalf("unexpected playback result: mode=%q links=%v", mode, links)
212 }
213 if got := strings.Join(provider.modes, ","); got != "sub" {
214 t.Fatalf("expected only preferred mode lookup, got %s", got)
215 }
216}
217
218func TestGetEpisodeURLForPlaybackRequiresExplicitFallbackApproval(t *testing.T) {
219 provider := &fakePlaybackProvider{
220 linksByMode: map[string][]string{"dub": {"dub-url"}},
221 errByMode: map[string]error{"sub": errors.New("no sub streams")},
222 }
223 withProvider(t, provider)
224 withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
225 if len(options) != 2 || options[0].Key != "play" {
226 t.Fatalf("unexpected fallback options: %+v", options)
227 }
228 return SelectionOption{Key: "play"}, nil
229 })
230
231 links, mode, err := GetEpisodeURLForPlayback(CurdConfig{SubOrDub: "sub"}, "anime-id", 1)
232 if err != nil {
233 t.Fatalf("expected accepted fallback to succeed: %v", err)
234 }
235 if mode != "dub" || len(links) != 1 || links[0] != "dub-url" {
236 t.Fatalf("unexpected fallback result: mode=%q links=%v", mode, links)
237 }
238 if got := strings.Join(provider.modes, ","); got != "sub,dub" {
239 t.Fatalf("expected preferred then fallback lookup, got %s", got)
240 }
241}
242
243func TestGetEpisodeURLForPlaybackCancelsAudioFallback(t *testing.T) {
244 provider := &fakePlaybackProvider{
245 linksByMode: map[string][]string{"dub": {"dub-url"}},
246 errByMode: map[string]error{"sub": errors.New("no sub streams")},
247 }
248 withProvider(t, provider)
249 withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
250 return SelectionOption{Key: "cancel"}, nil
251 })
252
253 links, mode, err := GetEpisodeURLForPlayback(CurdConfig{SubOrDub: "sub"}, "anime-id", 1)
254 if err == nil {
255 t.Fatalf("expected cancelled fallback to return preferred-mode error")
256 }
257 if mode != "sub" || len(links) != 0 {
258 t.Fatalf("unexpected cancelled fallback result: mode=%q links=%v", mode, links)
259 }
260}
261
262func TestShouldWriteRemoteTrackingHonorsSessionSkip(t *testing.T) {
263 config := &CurdConfig{TrackingRemote: TrackingRemoteAniList}
264 if !ShouldWriteRemoteTracking(config, &Anime{}) {
265 t.Fatalf("expected normal remote tracking to write")
266 }
267 if ShouldWriteRemoteTracking(config, &Anime{SkipRemoteSync: true}) {
268 t.Fatalf("expected session skip flag to suppress remote writes")
269 }
270 if ShouldWriteRemoteTracking(&CurdConfig{TrackingRemote: TrackingRemoteNone}, &Anime{}) {
271 t.Fatalf("expected local-only mode to suppress remote writes")
272 }
273}
274
275func TestMaybeImportAniListToMyAnimeListDismissesWithoutMarkingImported(t *testing.T) {
276 tempDir := t.TempDir()
277 configPath := filepath.Join(tempDir, "curd.conf")
278 if err := createDefaultConfig(configPath); err != nil {
279 t.Fatalf("create config: %v", err)
280 }
281
282 previousConfigPath := GlobalConfigPath
283 GlobalConfigPath = configPath
284 t.Cleanup(func() {
285 GlobalConfigPath = previousConfigPath
286 })
287
288 config := &CurdConfig{
289 StoragePath: tempDir,
290 TrackingRemote: TrackingRemoteMyAnimeList,
291 TrackingConfigured: true,
292 MyAnimeListImported: false,
293 }
294 if err := os.WriteFile(filepath.Join(tempDir, "anilist_token.json"), []byte("legacy-token"), 0600); err != nil {
295 t.Fatalf("write token: %v", err)
296 }
297
298 withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
299 return SelectionOption{Key: "no"}, nil
300 })
301
302 if err := maybeImportAniListToMyAnimeList(config, &User{}); err != nil {
303 t.Fatalf("maybe import: %v", err)
304 }
305 if config.MyAnimeListImported {
306 t.Fatalf("declining import must not mark import completed")
307 }
308 if !config.MyAnimeListImportDismissed {
309 t.Fatalf("declining import should mark the prompt dismissed")
310 }
311}
312
313func TestWriteTrackingBackupCreatesSnapshot(t *testing.T) {
314 config := &CurdConfig{StoragePath: t.TempDir()}
315 aniList := AnimeList{Watching: []Entry{{Media: Media{ID: 1, MalID: 11}, Status: "CURRENT"}}}
316 myAnimeList := AnimeList{Planning: []Entry{{Media: Media{ID: 2, MalID: 22}, Status: "PLANNING"}}}
317
318 backupPath, err := writeTrackingBackup(config, "test action", aniList, myAnimeList)
319 if err != nil {
320 t.Fatalf("write backup: %v", err)
321 }
322 data, err := os.ReadFile(backupPath)
323 if err != nil {
324 t.Fatalf("read backup: %v", err)
325 }
326 if !strings.Contains(string(data), `"action": "test action"`) || !strings.Contains(string(data), `"id": 1`) || !strings.Contains(string(data), `"id": 2`) {
327 t.Fatalf("backup did not contain expected snapshot data: %s", string(data))
328 }
329}
330
331func TestConfirmProviderMatchRequiresUserApproval(t *testing.T) {
332 withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
333 if options[0].Key != "use" || options[1].Key != "manual" {
334 t.Fatalf("unexpected provider confirmation options: %+v", options)
335 }
336 return SelectionOption{Key: "manual"}, nil
337 })
338
339 if confirmProviderMatch(SelectionOption{Label: "Example"}, "title") {
340 t.Fatalf("manual selection should reject guessed provider match")
341 }
342}
343
344func TestSelectSequelAndUnreleasedSequelActions(t *testing.T) {
345 sequels := []SequelInfo{
346 {ID: 1, Title: AnimeTitle{Romaji: "First"}, Status: "FINISHED"},
347 {ID: 2, Title: AnimeTitle{Romaji: "Second"}, Status: "NOT_YET_RELEASED"},
348 }
349 withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
350 return SelectionOption{Key: "1"}, nil
351 })
352
353 selected, ok := selectSequel(&CurdConfig{}, sequels)
354 if !ok || selected.ID != 2 {
355 t.Fatalf("expected second sequel selection, got ok=%v selected=%+v", ok, selected)
356 }
357
358 var captured []SelectionOption
359 withPromptSelect(t, func(options []SelectionOption) (SelectionOption, error) {
360 captured = append([]SelectionOption(nil), options...)
361 return SelectionOption{Key: "skip"}, nil
362 })
363 summary := promptSequelAction(&CurdConfig{}, selected, "token")
364 if summary != "sequel skipped" {
365 t.Fatalf("expected skipped summary, got %q", summary)
366 }
367 for _, option := range captured {
368 if option.Key == "watching" {
369 t.Fatalf("not-yet-released sequel should not offer Watching action: %+v", captured)
370 }
371 }
372}
373
374func TestHandleLastEpisodeCompletionSummarizesSkippedTrackerWrites(t *testing.T) {
375 previousConfig := GetGlobalConfig()
376 config := &CurdConfig{
377 RofiSelection: false,
378 ScoreOnCompletion: true,
379 TrackingRemote: TrackingRemoteAniList,
380 }
381 SetGlobalConfig(config)
382 t.Cleanup(func() {
383 SetGlobalConfig(previousConfig)
384 })
385
386 output := captureStdout(t, func() {
387 HandleLastEpisodeCompletion(config, &Anime{
388 AnilistId: 1,
389 TotalEpisodes: 12,
390 SkipRemoteSync: true,
391 Ep: Episode{
392 Number: 12,
393 },
394 }, "token")
395 })
396
397 if !strings.Contains(output, "Completion summary:") ||
398 !strings.Contains(output, "tracker updates skipped") ||
399 !strings.Contains(output, "sequel check skipped") {
400 t.Fatalf("completion summary did not report skipped tracker writes: %q", output)
401 }
402}