Commit 536146363c
Unsigned
Layout: unified · split
Build/curd-windows-build.iss +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | [Setup] |
| 2 | 2 | AppName=Curd Installer |
| 3 | AppVersion=1.4.0 | |
| 3 | AppVersion=1.5.1 | |
| 4 | 4 | DefaultDirName={userappdata}\Curd |
| 5 | 5 | PrivilegesRequired=lowest |
| 6 | 6 | AllowNoIcons=yes |
cmd/curd/main.go +53 −55
| @@ -273,9 +273,8 @@ func main() { | ||
| 273 | 273 | // Start curd (loop while episode is playing) |
| 274 | 274 | for { |
| 275 | 275 | // Check if current episode is filler/recap |
| 276 | err = internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime) | |
| 277 | if err != nil { | |
| 278 | internal.Log("Error getting episode data, assuming non-filler: " + err.Error()) | |
| 276 | if episodeErr := internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime); episodeErr != nil { | |
| 277 | internal.Log("Error getting episode data, assuming non-filler: " + episodeErr.Error()) | |
| 279 | 278 | break // Break the loop and continue with playback |
| 280 | 279 | } |
| 281 | 280 | |
| @@ -305,7 +304,7 @@ func main() { | ||
| 305 | 304 | internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, internal.GetAnimeName(anime), internal.GetProvider().Name()) |
| 306 | 305 | |
| 307 | 306 | // Check if we've reached the end of the series |
| 308 | if anime.Ep.Number > anime.TotalEpisodes { | |
| 307 | if anime.TotalEpisodes > 0 && anime.Ep.Number > anime.TotalEpisodes { | |
| 309 | 308 | internal.CurdOut("Reached end of series") |
| 310 | 309 | internal.ExitCurd(nil) |
| 311 | 310 | } |
| @@ -356,9 +355,8 @@ func main() { | ||
| 356 | 355 | // Get episode data |
| 357 | 356 | go func() { |
| 358 | 357 | defer wg.Done() |
| 359 | err = internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime) | |
| 360 | if err != nil { | |
| 361 | internal.Log("Error getting episode data: " + err.Error()) | |
| 358 | if episodeErr := internal.GetEpisodeData(anime.MalId, anime.Ep.Number, &anime); episodeErr != nil { | |
| 359 | internal.Log("Error getting episode data: " + episodeErr.Error()) | |
| 362 | 360 | } else { |
| 363 | 361 | internal.Log(anime) |
| 364 | 362 | |
| @@ -437,7 +435,11 @@ func main() { | ||
| 437 | 435 | } |
| 438 | 436 | } |
| 439 | 437 | |
| 440 | 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 | } | |
| 441 | 443 | |
| 442 | 444 | // Simple seek detection: position gap > 5 seconds |
| 443 | 445 | hasSeekEvent := false |
| @@ -486,14 +488,15 @@ func main() { | ||
| 486 | 488 | } |
| 487 | 489 | |
| 488 | 490 | // Force update on seek events to bypass Discord's internal filtering |
| 491 | var presenceErr error | |
| 489 | 492 | if hasSeekEvent { |
| 490 | err = internal.DiscordPresenceWithForce(anime, currentPauseState, currentPos, totalDuration, userCurdConfig.DiscordClientId, true) | |
| 493 | presenceErr = internal.DiscordPresenceWithForce(anime, currentPauseState, currentPos, totalDuration, userCurdConfig.DiscordClientId, true) | |
| 491 | 494 | } else { |
| 492 | err = internal.DiscordPresence(anime, currentPauseState, currentPos, totalDuration, userCurdConfig.DiscordClientId) | |
| 495 | presenceErr = internal.DiscordPresence(anime, currentPauseState, currentPos, totalDuration, userCurdConfig.DiscordClientId) | |
| 493 | 496 | } |
| 494 | 497 | |
| 495 | if err != nil { | |
| 496 | internal.Log("Error setting Discord presence: " + err.Error()) | |
| 498 | if presenceErr != nil { | |
| 499 | internal.Log("Error setting Discord presence: " + presenceErr.Error()) | |
| 497 | 500 | } |
| 498 | 501 | |
| 499 | 502 | lastKnownPauseState = currentPauseState |
| @@ -511,9 +514,8 @@ func main() { | ||
| 511 | 514 | |
| 512 | 515 | // Get skip times Parallel |
| 513 | 516 | go func() { |
| 514 | err = internal.GetAndParseAniSkipData(anime.MalId, anime.Ep.Number, 1, &anime) | |
| 515 | if err != nil { | |
| 516 | internal.Log("Error getting and parsing AniSkip data: " + err.Error()) | |
| 517 | if skipErr := internal.GetAndParseAniSkipData(anime.MalId, anime.Ep.Number, 1, &anime); skipErr != nil { | |
| 518 | internal.Log("Error getting and parsing AniSkip data: " + skipErr.Error()) | |
| 517 | 519 | } |
| 518 | 520 | internal.Log(anime.Ep.SkipTimes) |
| 519 | 521 | }() |
| @@ -543,12 +545,15 @@ func main() { | ||
| 543 | 545 | } |
| 544 | 546 | pauseState := false |
| 545 | 547 | if isPaused != nil { |
| 546 | 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 | } | |
| 547 | 553 | } |
| 548 | 554 | internal.Log("Initializing Discord presence with real video duration") |
| 549 | err = internal.DiscordPresence(anime, pauseState, currentPos, anime.Ep.Duration, userCurdConfig.DiscordClientId) | |
| 550 | if err != nil { | |
| 551 | internal.Log("Discord presence error: " + err.Error()) | |
| 555 | if presenceErr := internal.DiscordPresence(anime, pauseState, currentPos, anime.Ep.Duration, userCurdConfig.DiscordClientId); presenceErr != nil { | |
| 556 | internal.Log("Discord presence error: " + presenceErr.Error()) | |
| 552 | 557 | } |
| 553 | 558 | } |
| 554 | 559 | } else { |
| @@ -636,9 +641,8 @@ func main() { | ||
| 636 | 641 | |
| 637 | 642 | // Update Anilist progress if not rewatching |
| 638 | 643 | if !anime.Rewatching { |
| 639 | err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number) | |
| 640 | if err != nil { | |
| 641 | internal.Log("Error updating Anilist progress on quit: " + err.Error()) | |
| 644 | if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil { | |
| 645 | internal.Log("Error updating Anilist progress on quit: " + progressErr.Error()) | |
| 642 | 646 | } else { |
| 643 | 647 | internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number)) |
| 644 | 648 | } |
| @@ -687,16 +691,14 @@ func main() { | ||
| 687 | 691 | // Set the playback speed |
| 688 | 692 | if userCurdConfig.SaveMpvSpeed { |
| 689 | 693 | speedCmd := []interface{}{"set_property", "speed", anime.Ep.Player.Speed} |
| 690 | _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, speedCmd) | |
| 691 | if err != nil { | |
| 692 | internal.Log("Error setting playback speed: " + err.Error()) | |
| 694 | if _, speedErr := internal.MPVSendCommand(anime.Ep.Player.SocketPath, speedCmd); speedErr != nil { | |
| 695 | internal.Log("Error setting playback speed: " + speedErr.Error()) | |
| 693 | 696 | } |
| 694 | 697 | } |
| 695 | 698 | |
| 696 | 699 | // Apply OP/ED Chapters |
| 697 | err = internal.SendSkipTimesToMPV(&anime) | |
| 698 | if err != nil { | |
| 699 | internal.Log("Error sending skip times to MPV: " + err.Error()) | |
| 700 | if skipErr := internal.SendSkipTimesToMPV(&anime); skipErr != nil { | |
| 701 | internal.Log("Error sending skip times to MPV: " + skipErr.Error()) | |
| 700 | 702 | } |
| 701 | 703 | } |
| 702 | 704 | |
| @@ -714,9 +716,8 @@ func main() { | ||
| 714 | 716 | |
| 715 | 717 | anime.Ep.Player.PlaybackTime = int(animePosition + 0.5) // Round to nearest integer |
| 716 | 718 | // Update Local Database |
| 717 | 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()) | |
| 718 | if err != nil { | |
| 719 | internal.Log("Error updating local database: " + err.Error()) | |
| 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 { | |
| 720 | internal.Log("Error updating local database: " + updateErr.Error()) | |
| 720 | 721 | } |
| 721 | 722 | } |
| 722 | 723 | |
| @@ -764,9 +765,8 @@ func main() { | ||
| 764 | 765 | |
| 765 | 766 | // Update Anilist progress if not rewatching |
| 766 | 767 | if !anime.Rewatching { |
| 767 | err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number) | |
| 768 | if err != nil { | |
| 769 | internal.Log("Error updating Anilist progress on quit: " + err.Error()) | |
| 768 | if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil { | |
| 769 | internal.Log("Error updating Anilist progress on quit: " + progressErr.Error()) | |
| 770 | 770 | } else { |
| 771 | 771 | internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number)) |
| 772 | 772 | } |
| @@ -784,9 +784,8 @@ func main() { | ||
| 784 | 784 | |
| 785 | 785 | // Update Anilist progress if not rewatching |
| 786 | 786 | if !anime.Rewatching { |
| 787 | err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number) | |
| 788 | if err != nil { | |
| 789 | internal.Log("Error updating Anilist progress on completion: " + err.Error()) | |
| 787 | if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil { | |
| 788 | internal.Log("Error updating Anilist progress on completion: " + progressErr.Error()) | |
| 790 | 789 | } else { |
| 791 | 790 | internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number)) |
| 792 | 791 | } |
| @@ -846,11 +845,12 @@ func main() { | ||
| 846 | 845 | internal.SeekMPV(anime.Ep.Player.SocketPath, anime.Ep.SkipTimes.Ed.End) |
| 847 | 846 | } |
| 848 | 847 | } |
| 849 | _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"}) | |
| 850 | if err == nil && anime.Ep.Started { | |
| 851 | anime.Ep.Player.Speed, err = internal.GetMPVPlaybackSpeed(anime.Ep.Player.SocketPath) | |
| 852 | if err != nil { | |
| 853 | internal.Log("Failed to get mpv speed " + err.Error()) | |
| 848 | if _, positionErr := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"}); positionErr == nil && anime.Ep.Started { | |
| 849 | speed, speedErr := internal.GetMPVPlaybackSpeed(anime.Ep.Player.SocketPath) | |
| 850 | if speedErr != nil { | |
| 851 | internal.Log("Failed to get mpv speed " + speedErr.Error()) | |
| 852 | } else { | |
| 853 | anime.Ep.Player.Speed = speed | |
| 854 | 854 | } |
| 855 | 855 | } |
| 856 | 856 | } |
| @@ -873,22 +873,21 @@ func main() { | ||
| 873 | 873 | if anime.Ep.IsCompleted && !anime.Rewatching { |
| 874 | 874 | // Update progress for both regular episodes and skipped fillers |
| 875 | 875 | if anime.TotalEpisodes > 0 && anime.Ep.Number-1 != anime.TotalEpisodes { |
| 876 | go func() { | |
| 876 | progressEpisode := anime.Ep.Number - 1 | |
| 877 | go func(episode int) { | |
| 877 | 878 | // Update progress for regular episodes |
| 878 | err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number-1) | |
| 879 | if err != nil { | |
| 880 | internal.Log("Error updating Anilist progress: " + err.Error()) | |
| 879 | if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, episode); progressErr != nil { | |
| 880 | internal.Log("Error updating Anilist progress: " + progressErr.Error()) | |
| 881 | 881 | } |
| 882 | }() | |
| 882 | }(progressEpisode) | |
| 883 | 883 | } else { |
| 884 | 884 | // Update progress for last episode |
| 885 | 885 | |
| 886 | 886 | // Exit MPV |
| 887 | 887 | internal.ExitMPV(anime.Ep.Player.SocketPath) |
| 888 | 888 | |
| 889 | err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number-1) | |
| 890 | if err != nil { | |
| 891 | internal.Log("Error updating Anilist progress: " + err.Error()) | |
| 889 | if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number-1); progressErr != nil { | |
| 890 | internal.Log("Error updating Anilist progress: " + progressErr.Error()) | |
| 892 | 891 | } |
| 893 | 892 | } |
| 894 | 893 | |
| @@ -904,10 +903,9 @@ func main() { | ||
| 904 | 903 | } else if !updatedAnime.IsAiring { |
| 905 | 904 | anime.Ep.Number = anime.Ep.Number - 1 |
| 906 | 905 | internal.CurdOut("Completed anime.") |
| 907 | err = internal.RateAnime(user.Token, anime.AnilistId) | |
| 908 | if err != nil { | |
| 909 | internal.Log("Error rating anime: " + err.Error()) | |
| 910 | internal.CurdOut("Error rating anime: " + err.Error()) | |
| 906 | if rateErr := internal.RateAnime(user.Token, anime.AnilistId); rateErr != nil { | |
| 907 | internal.Log("Error rating anime: " + rateErr.Error()) | |
| 908 | internal.CurdOut("Error rating anime: " + rateErr.Error()) | |
| 911 | 909 | } |
| 912 | 910 | internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.ProviderId) |
| 913 | 911 | internal.ExitCurd(nil) |
| @@ -949,7 +947,7 @@ func main() { | ||
| 949 | 947 | |
| 950 | 948 | // If we still don't have links, get them now |
| 951 | 949 | if len(anime.Ep.Links) == 0 { |
| 952 | links, err := internal.GetEpisodeURL(userCurdConfig, anime.ProviderId, anime.Ep.Number) | |
| 950 | links, _, err := internal.GetEpisodeURLForPlayback(userCurdConfig, anime.ProviderId, anime.Ep.Number) | |
| 953 | 951 | if err != nil { |
| 954 | 952 | internal.Log("Failed to get episode links: " + err.Error()) |
| 955 | 953 | internal.CurdOut("Failed to get episode links. Try again later.") |
go.mod +1 −1
| @@ -7,6 +7,7 @@ require ( | ||
| 7 | 7 | github.com/charmbracelet/bubbletea v1.3.3 |
| 8 | 8 | github.com/charmbracelet/lipgloss v1.0.0 |
| 9 | 9 | github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4 |
| 10 | github.com/go-rod/rod v0.116.2 | |
| 10 | 11 | github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c |
| 11 | 12 | github.com/tr1xem/go-discordrpc v1.0.0 |
| 12 | 13 | ) |
| @@ -16,7 +17,6 @@ require ( | ||
| 16 | 17 | github.com/charmbracelet/x/ansi v0.8.0 // indirect |
| 17 | 18 | github.com/charmbracelet/x/term v0.2.1 // indirect |
| 18 | 19 | github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect |
| 19 | github.com/go-rod/rod v0.116.2 // indirect | |
| 20 | 20 | github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect |
| 21 | 21 | github.com/godbus/dbus/v5 v5.1.0 // indirect |
| 22 | 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 | 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 | |
| 27 | func 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 | 46 | // GetAnimeMap takes an AnimeList and returns a map with media.id as key and media.title.english as value. |
| 28 | 47 | func GetAnimeMap(animeList AnimeList) map[string]string { |
| 29 | 48 | animeMap := make(map[string]string) |
| @@ -32,13 +51,7 @@ func GetAnimeMap(animeList AnimeList) map[string]string { | ||
| 32 | 51 | // Helper function to populate the map from a slice of entries |
| 33 | 52 | populateMap := func(entries []Entry) { |
| 34 | 53 | for _, entry := range entries { |
| 35 | // Only include entries with a non-empty English title | |
| 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 | } | |
| 54 | animeMap[strconv.Itoa(entry.Media.ID)] = mediaDisplayTitle(entry.Media, userCurdConfig) | |
| 42 | 55 | } |
| 43 | 56 | } |
| 44 | 57 | |
| @@ -61,19 +74,9 @@ func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview { | ||
| 61 | 74 | // Helper function to populate the map from a slice of entries |
| 62 | 75 | populateMap := func(entries []Entry) { |
| 63 | 76 | for _, entry := range entries { |
| 64 | // Only include entries with a non-empty English title | |
| 65 | Log(fmt.Errorf("AnimeNameLanguage: %v", userCurdConfig.AnimeNameLanguage)) | |
| 66 | ||
| 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 | animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{ | |
| 78 | Title: mediaDisplayTitle(entry.Media, userCurdConfig), | |
| 79 | CoverImage: entry.CoverImage, | |
| 77 | 80 | } |
| 78 | 81 | } |
| 79 | 82 | } |
| @@ -138,7 +141,10 @@ func min3(a, b, c int) int { | ||
| 138 | 141 | } |
| 139 | 142 | |
| 140 | 143 | func 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 | 148 | for attempt := 0; attempt < 5; attempt++ { |
| 143 | 149 | req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) |
| 144 | 150 | if err != nil { |
| @@ -169,6 +175,13 @@ func doAniListSearchRequest(url string, requestBody []byte, token string) ([]byt | ||
| 169 | 175 | if resp.StatusCode != http.StatusOK { |
| 170 | 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 | 185 | return body, nil |
| 173 | 186 | } |
| 174 | 187 | |
| @@ -346,11 +359,24 @@ func GetAnilistUserID(token string) (int, string, error) { | ||
| 346 | 359 | return 0, "", err |
| 347 | 360 | } |
| 348 | 361 | |
| 349 | data := response["data"].(map[string]interface{})["Viewer"].(map[string]interface{}) | |
| 350 | userID := int(data["id"].(float64)) | |
| 351 | userName := data["name"].(string) | |
| 362 | data, ok := response["data"].(map[string]interface{}) | |
| 363 | if !ok { | |
| 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 | 382 | // Function to add an anime to the watching list |
| @@ -401,8 +427,19 @@ func GetAnimeMalID(anilistMediaID int) (int, error) { | ||
| 401 | 427 | return 0, err |
| 402 | 428 | } |
| 403 | 429 | |
| 404 | malID := int(response["data"].(map[string]interface{})["Media"].(map[string]interface{})["idMal"].(float64)) | |
| 405 | return malID, nil | |
| 430 | data, ok := response["data"].(map[string]interface{}) | |
| 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 | 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 | 464 | return 0, "", err |
| 428 | 465 | } |
| 429 | 466 | |
| 430 | data := response["data"].(map[string]interface{})["Media"].(map[string]interface{}) | |
| 431 | malID := int(data["idMal"].(float64)) | |
| 432 | imageURL := data["coverImage"].(map[string]interface{})["large"].(string) | |
| 467 | data, ok := response["data"].(map[string]interface{}) | |
| 468 | if !ok { | |
| 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 | 484 | return malID, imageURL, nil |
| 435 | 485 | } |
| @@ -572,20 +622,52 @@ func LoadJSONFile(filePath string) (map[string]interface{}, error) { | ||
| 572 | 622 | func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []map[string]interface{} { |
| 573 | 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 | 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 | 646 | for _, entry := range entries { |
| 579 | media := entry.(map[string]interface{})["media"].(map[string]interface{}) | |
| 580 | romajiTitle := media["title"].(map[string]interface{})["romaji"].(string) | |
| 581 | englishTitle := media["title"].(map[string]interface{})["english"].(string) | |
| 582 | episodes := int(media["episodes"].(float64)) | |
| 583 | duration := int(media["duration"].(float64)) | |
| 647 | entryMap, ok := entry.(map[string]interface{}) | |
| 648 | if !ok { | |
| 649 | continue | |
| 650 | } | |
| 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 | 667 | if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) { |
| 586 | 668 | result := map[string]interface{}{ |
| 587 | 669 | "id": media["id"], |
| 588 | "progress": entry.(map[string]interface{})["progress"], | |
| 670 | "progress": entryMap["progress"], | |
| 589 | 671 | "romaji_title": romajiTitle, |
| 590 | 672 | "english_title": englishTitle, |
| 591 | 673 | "episodes": episodes, |
| @@ -790,7 +872,10 @@ func makePostRequest(url, query string, variables map[string]interface{}, header | ||
| 790 | 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 | 879 | for attempt := 0; attempt < 5; attempt++ { |
| 795 | 880 | req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) |
| 796 | 881 | if err != nil { |
| @@ -828,6 +913,10 @@ func makePostRequest(url, query string, variables map[string]interface{}, header | ||
| 828 | 913 | if err := json.Unmarshal(body, &responseData); err != nil { |
| 829 | 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 | 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 | 973 | // Access the list entries in the input map |
| 880 | 974 | if input["data"] == nil { |
| 881 | 975 | Log("Anilist request failed") |
| 882 | CurdOut("Anilist request failed") | |
| 883 | ExitCurd(fmt.Errorf("Anilist request failed")) | |
| 884 | 976 | return animeList |
| 885 | 977 | } |
| 886 | data := input["data"].(map[string]interface{}) | |
| 887 | mediaList := data["MediaListCollection"].(map[string]interface{})["lists"].([]interface{}) | |
| 978 | data, ok := input["data"].(map[string]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 | 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 | 1004 | for _, entry := range entries { |
| 893 | entryData := entry.(map[string]interface{}) | |
| 894 | media := entryData["media"].(map[string]interface{}) | |
| 1005 | entryData, ok := entry.(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 | 1014 | animeEntry := Entry{ |
| 896 | 1015 | ListID: toInt(entryData["id"]), |
| 897 | 1016 | Media: Media{ |
| @@ -900,20 +1019,22 @@ func ParseAnimeList(input map[string]interface{}) AnimeList { | ||
| 900 | 1019 | ID: toInt(media["id"]), |
| 901 | 1020 | MalID: toInt(media["idMal"]), |
| 902 | 1021 | Title: AnimeTitle{ |
| 903 | English: safeString(media["title"].(map[string]interface{})["english"]), | |
| 904 | Romaji: safeString(media["title"].(map[string]interface{})["romaji"]), | |
| 905 | Japanese: safeString(media["title"].(map[string]interface{})["native"]), | |
| 1022 | English: safeString(title["english"]), | |
| 1023 | Romaji: safeString(title["romaji"]), | |
| 1024 | Japanese: safeString(title["native"]), | |
| 906 | 1025 | }, |
| 907 | 1026 | Status: safeString(media["status"]), |
| 908 | 1027 | }, |
| 909 | 1028 | Progress: toInt(entryData["progress"]), |
| 910 | 1029 | Repeat: toInt(entryData["repeat"]), |
| 911 | Score: entryData["score"].(float64), | |
| 912 | 1030 | Status: safeString(entryData["status"]), // Ensure status is fetched safely |
| 913 | 1031 | StartedAt: parseFuzzyDate(entryData["startedAt"]), |
| 914 | 1032 | CompletedAt: parseFuzzyDate(entryData["completedAt"]), |
| 915 | 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 | 1039 | if coverImage, ok := media["coverImage"].(map[string]interface{}); ok { |
| 919 | 1040 | animeEntry.CoverImage = safeString(coverImage["large"]) |
internal/anilist_cache.go +2 −8
| @@ -267,10 +267,7 @@ func buildCategorySelectionOptions(list AnimeList, category string) []SelectionO | ||
| 267 | 267 | options := make([]SelectionOption, 0) |
| 268 | 268 | |
| 269 | 269 | for _, entry := range getEntriesByCategory(list, category) { |
| 270 | title := entry.Media.Title.English | |
| 271 | if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { | |
| 272 | title = entry.Media.Title.Romaji | |
| 273 | } | |
| 270 | title := mediaDisplayTitle(entry.Media, userCurdConfig) | |
| 274 | 271 | |
| 275 | 272 | options = append(options, SelectionOption{ |
| 276 | 273 | Key: strconv.Itoa(entry.Media.ID), |
| @@ -286,10 +283,7 @@ func buildCategoryPreviewOptions(list AnimeList, category string) map[string]Rof | ||
| 286 | 283 | options := make(map[string]RofiSelectPreview) |
| 287 | 284 | |
| 288 | 285 | for _, entry := range getEntriesByCategory(list, category) { |
| 289 | title := entry.Media.Title.English | |
| 290 | if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { | |
| 291 | title = entry.Media.Title.Romaji | |
| 292 | } | |
| 286 | title := mediaDisplayTitle(entry.Media, userCurdConfig) | |
| 293 | 287 | |
| 294 | 288 | options[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{ |
| 295 | 289 | Title: title, |
internal/anime_list.go +5
| @@ -139,6 +139,11 @@ func searchAnimeByMode(query, mode, preferredMode string) ([]SelectionOption, er | ||
| 139 | 139 | // Debug: Log the response status and first part of the body |
| 140 | 140 | Log(fmt.Sprintf("Response Status: %s", resp.Status)) |
| 141 | 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 | } | |
| 142 | 147 | |
| 143 | 148 | // Parse the JSON response |
| 144 | 149 | var response response |
internal/aniskip.go +1 −1
| @@ -30,7 +30,7 @@ func GetAniSkipData(animeMalId int, episode int) (string, error) { | ||
| 30 | 30 | baseURL := "https://api.aniskip.com/v1/skip-times" |
| 31 | 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 | 34 | if err != nil { |
| 35 | 35 | Log(fmt.Errorf("error fetching data from AniSkip API: %w", err)) |
| 36 | 36 | return "", fmt.Errorf("error fetching data from AniSkip API: %w", err) |
internal/config.go +43 −15
| @@ -122,8 +122,25 @@ func GetGlobalConfig() *CurdConfig { | ||
| 122 | 122 | return globalConfig |
| 123 | 123 | } |
| 124 | 124 | |
| 125 | func useEnglishAnimeNames(config *CurdConfig) bool { | |
| 126 | return config == nil || strings.EqualFold(strings.TrimSpace(config.AnimeNameLanguage), "english") | |
| 127 | } | |
| 128 | ||
| 125 | 129 | // Helper function to parse string array from config |
| 126 | 130 | func 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 | ||
| 127 | 144 | // Remove brackets and split by comma |
| 128 | 145 | value = strings.TrimPrefix(value, "[") |
| 129 | 146 | value = strings.TrimSuffix(value, "]") |
| @@ -172,7 +189,9 @@ func LoadConfig(configPath string) (CurdConfig, error) { | ||
| 172 | 189 | // Check AddMissingOptions setting first |
| 173 | 190 | addMissing := true |
| 174 | 191 | if val, exists := configMap["AddMissingOptions"]; exists { |
| 175 | addMissing, _ = strconv.ParseBool(val) | |
| 192 | if parsed, parseErr := strconv.ParseBool(val); parseErr == nil { | |
| 193 | addMissing = parsed | |
| 194 | } | |
| 176 | 195 | } |
| 177 | 196 | |
| 178 | 197 | _, hadTrackingRemote := configMap["TrackingRemote"] |
| @@ -323,7 +342,7 @@ func authenticateWithBrowser(tokenPath string) (string, error) { | ||
| 323 | 342 | "code": {code}, |
| 324 | 343 | } |
| 325 | 344 | |
| 326 | resp, err := http.PostForm(tokenURL, data) | |
| 345 | resp, err := sharedHTTPClient.PostForm(tokenURL, data) | |
| 327 | 346 | if err != nil { |
| 328 | 347 | errCh <- fmt.Errorf("failed to exchange code for token: %w", err) |
| 329 | 348 | return |
| @@ -581,25 +600,34 @@ func SaveConfigToFile(path string, configMap map[string]string) error { | ||
| 581 | 600 | func PopulateConfig(configMap map[string]string) CurdConfig { |
| 582 | 601 | config := CurdConfig{} |
| 583 | 602 | configValue := reflect.ValueOf(&config).Elem() |
| 603 | defaults := defaultConfigMap() | |
| 584 | 604 | |
| 585 | 605 | for i := 0; i < configValue.NumField(); i++ { |
| 586 | 606 | field := configValue.Type().Field(i) |
| 587 | 607 | tag := field.Tag.Get("config") |
| 588 | 608 | |
| 589 | if value, exists := configMap[tag]; exists { | |
| 590 | fieldValue := configValue.FieldByName(field.Name) | |
| 591 | ||
| 592 | if fieldValue.CanSet() { | |
| 593 | switch fieldValue.Kind() { | |
| 594 | case reflect.String: | |
| 595 | fieldValue.SetString(value) | |
| 596 | case reflect.Int: | |
| 597 | intVal, _ := strconv.Atoi(value) | |
| 598 | fieldValue.SetInt(int64(intVal)) | |
| 599 | case reflect.Bool: | |
| 600 | boolVal, _ := strconv.ParseBool(value) | |
| 601 | fieldValue.SetBool(boolVal) | |
| 609 | value, exists := configMap[tag] | |
| 610 | if !exists || value == "" { | |
| 611 | value = defaults[tag] | |
| 612 | } | |
| 613 | fieldValue := configValue.FieldByName(field.Name) | |
| 614 | ||
| 615 | if fieldValue.CanSet() { | |
| 616 | switch fieldValue.Kind() { | |
| 617 | case reflect.String: | |
| 618 | fieldValue.SetString(value) | |
| 619 | case reflect.Int: | |
| 620 | intVal, err := strconv.Atoi(value) | |
| 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]) | |
| 602 | 629 | } |
| 630 | fieldValue.SetBool(boolVal) | |
| 603 | 631 | } |
| 604 | 632 | } |
| 605 | 633 | } |
internal/curd.go +127 −124
| @@ -1,7 +1,6 @@ | ||
| 1 | 1 | package internal |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | "bufio" | |
| 5 | 4 | "crypto/md5" |
| 6 | 5 | "encoding/json" |
| 7 | 6 | "fmt" |
| @@ -63,8 +62,12 @@ func EditConfig(configFilePath string) { | ||
| 63 | 62 | |
| 64 | 63 | // ClearLogFile removes all contents from the specified log file |
| 65 | 64 | func ClearLogFile(logFile string) error { |
| 66 | // Open the file with truncate flag to clear its contents | |
| 67 | file, err := os.OpenFile(logFile, os.O_WRONLY|os.O_TRUNC, 0666) | |
| 65 | if err := os.MkdirAll(filepath.Dir(logFile), 0755); err != nil { | |
| 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 | 71 | if err != nil { |
| 69 | 72 | return fmt.Errorf("failed to open log file: %w", err) |
| 70 | 73 | } |
| @@ -137,7 +140,9 @@ func ExitCurd(err error) { | ||
| 137 | 140 | RestoreScreen() |
| 138 | 141 | |
| 139 | 142 | anime := GetGlobalAnime() |
| 143 | socketPath := "" | |
| 140 | 144 | if (anime != nil) && (anime.Ep.Player.SocketPath != "") { |
| 145 | socketPath = anime.Ep.Player.SocketPath | |
| 141 | 146 | _, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"}) |
| 142 | 147 | if err != nil { |
| 143 | 148 | Log("Error closing MPV: " + err.Error()) |
| @@ -146,7 +151,7 @@ func ExitCurd(err error) { | ||
| 146 | 151 | |
| 147 | 152 | CurdOut("Have a great day!") |
| 148 | 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 | 155 | CurdOut(fmt.Sprintf("Error: %v", err)) |
| 151 | 156 | if runtime.GOOS == "windows" { |
| 152 | 157 | fmt.Println("Press Enter to exit") |
| @@ -381,7 +386,7 @@ updateOptionLoop: | ||
| 381 | 386 | fmt.Scanln(&progress) |
| 382 | 387 | } |
| 383 | 388 | |
| 384 | progressNum, err := strconv.Atoi(progress) | |
| 389 | progressNum, err := parseNonNegativeIntInput(progress, "progress") | |
| 385 | 390 | if err != nil { |
| 386 | 391 | Log(fmt.Sprintf("Failed to convert progress to number: %v", err)) |
| 387 | 392 | ExitCurd(fmt.Errorf("Failed to convert progress to number")) |
| @@ -464,7 +469,7 @@ func UpdateCurd(repo, fileName string) error { | ||
| 464 | 469 | tmpPath := executablePath + ".tmp" |
| 465 | 470 | |
| 466 | 471 | // Download the curd executable |
| 467 | resp, err := http.Get(url) | |
| 472 | resp, err := sharedHTTPClient.Get(url) | |
| 468 | 473 | if err != nil { |
| 469 | 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 | 533 | var err error |
| 529 | 534 | var anilistSelectedOption SelectionOption |
| 530 | 535 | |
| 531 | if userCurdConfig.RofiSelection { | |
| 532 | userInput, err := GetUserInputFromRofi("Enter the anime name") | |
| 533 | if err != nil { | |
| 534 | Log("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) | |
| 536 | query, err = promptText(userCurdConfig, "Enter the anime name", false) | |
| 537 | if err != nil { | |
| 538 | Log("Error getting user input: " + err.Error()) | |
| 539 | ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) | |
| 543 | 540 | } |
| 544 | 541 | if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { |
| 545 | 542 | animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token) |
| @@ -559,6 +556,10 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA | ||
| 559 | 556 | } else { |
| 560 | 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 | 564 | if anilistSelectedOption.Key == "-1" { |
| 564 | 565 | ExitCurd(nil) |
| @@ -569,10 +570,6 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA | ||
| 569 | 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 | 573 | animeID, err := strconv.Atoi(anilistSelectedOption.Key) |
| 577 | 574 | if err != nil { |
| 578 | 575 | Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err)) |
| @@ -917,7 +914,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | ||
| 917 | 914 | anime.Repeat = selectedAnilistAnime.Repeat |
| 918 | 915 | anime.StartedAt = selectedAnilistAnime.StartedAt |
| 919 | 916 | anime.CompletedAt = selectedAnilistAnime.CompletedAt |
| 920 | anime.Ep.Number = selectedAnilistAnime.Progress + 1 | |
| 917 | anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress) | |
| 921 | 918 | var animeList []SelectionOption |
| 922 | 919 | userQuery = anime.Title.Romaji |
| 923 | 920 | |
| @@ -1003,19 +1000,10 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | ||
| 1003 | 1000 | if len(animeList) == 0 { |
| 1004 | 1001 | for { |
| 1005 | 1002 | var manualQuery string |
| 1006 | if userCurdConfig.RofiSelection { | |
| 1007 | 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)) | |
| 1008 | if err != nil { | |
| 1009 | Log("Error getting user input: " + err.Error()) | |
| 1010 | ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) | |
| 1011 | } | |
| 1012 | manualQuery = userInput | |
| 1013 | } else { | |
| 1014 | CurdOut(fmt.Sprintf("No results found for '%s'.", userQuery)) | |
| 1015 | CurdOut("Press Enter to search with AniList name, or enter a custom name to search on AllAnime:") | |
| 1016 | reader := bufio.NewReader(os.Stdin) | |
| 1017 | input, _ := reader.ReadString('\n') | |
| 1018 | manualQuery = strings.TrimSpace(input) | |
| 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) | |
| 1004 | if err != nil { | |
| 1005 | Log("Error getting user input: " + err.Error()) | |
| 1006 | ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) | |
| 1019 | 1007 | } |
| 1020 | 1008 | |
| 1021 | 1009 | // If empty, use original AniList name |
| @@ -1162,13 +1150,24 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | ||
| 1162 | 1150 | } |
| 1163 | 1151 | animeUrl := fmt.Sprintf("https://animepahe.pw/anime/%s", animeRef.Session) |
| 1164 | 1152 | Log(fmt.Sprintf("Fetching %s to check exact AniList meta tag...", animeUrl)) |
| 1165 | req, _ := http.NewRequest("GET", animeUrl, nil) | |
| 1166 | 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") | |
| 1153 | req, err := newAnimepahePageRequest(animeUrl) | |
| 1154 | if err != nil { | |
| 1155 | Log(fmt.Sprintf("Failed to build animepahe detail request %s: %v", animeUrl, err)) | |
| 1156 | continue | |
| 1157 | } | |
| 1167 | 1158 | |
| 1168 | 1159 | resp, err := sharedHTTPClient.Do(req) |
| 1169 | if err == nil && resp.StatusCode == 200 { | |
| 1170 | body, _ := io.ReadAll(resp.Body) | |
| 1171 | resp.Body.Close() | |
| 1160 | if err != nil { | |
| 1161 | Log(fmt.Sprintf("Failed to fetch animepahe detail page %s: %v", animeUrl, err)) | |
| 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 { | |
| 1172 | 1171 | bodyStr := string(body) |
| 1173 | 1172 | |
| 1174 | 1173 | metaTag := fmt.Sprintf(`<meta name="anilist" content="%s">`, targetAnilistID) |
| @@ -1231,6 +1230,9 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | ||
| 1231 | 1230 | if anime.ProviderId == "" { |
| 1232 | 1231 | CurdOut("We didn't find any matches. Please select manually.") |
| 1233 | 1232 | selectedAllanimeAnime, err := DynamicSelect(animeList) |
| 1233 | if err != nil { | |
| 1234 | ExitCurd(fmt.Errorf("No anime available")) | |
| 1235 | } | |
| 1234 | 1236 | |
| 1235 | 1237 | if selectedAllanimeAnime.Key == "-1" { |
| 1236 | 1238 | ExitCurd(nil) |
| @@ -1246,9 +1248,6 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | ||
| 1246 | 1248 | continue |
| 1247 | 1249 | } |
| 1248 | 1250 | |
| 1249 | if err != nil { | |
| 1250 | ExitCurd(fmt.Errorf("No anime available")) | |
| 1251 | } | |
| 1252 | 1251 | anime.ProviderId = selectedAllanimeAnime.Key |
| 1253 | 1252 | } |
| 1254 | 1253 | } |
| @@ -1264,7 +1263,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | ||
| 1264 | 1263 | } |
| 1265 | 1264 | |
| 1266 | 1265 | // If local history episode is ahead of AniList upstream, prompt user |
| 1267 | anilistEpisode := selectedAnilistAnime.Progress + 1 | |
| 1266 | anilistEpisode := nextEpisodeFromProgress(selectedAnilistAnime.Progress) | |
| 1268 | 1267 | if animePointer.Ep.Number > anilistEpisode { |
| 1269 | 1268 | trackerLabel := RemoteTrackingDisplayName(userCurdConfig) |
| 1270 | 1269 | Log(fmt.Sprintf("Local history episode (%d) is ahead of %s episode (%d), prompting user", animePointer.Ep.Number, trackerLabel, anilistEpisode)) |
| @@ -1289,7 +1288,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | ||
| 1289 | 1288 | anime.Ep.Number = animePointer.Ep.Number |
| 1290 | 1289 | anime.Ep.Resume = true |
| 1291 | 1290 | } else if selectedOption.Key == "use_anilist" { |
| 1292 | // Use remote episode number (already set from selectedAnilistAnime.Progress + 1) | |
| 1291 | // Use remote next-episode number (already set from selectedAnilistAnime.Progress + 1) | |
| 1293 | 1292 | anime.Ep.Number = anilistEpisode |
| 1294 | 1293 | anime.Ep.Player.PlaybackTime = 0 |
| 1295 | 1294 | anime.Ep.Resume = false |
| @@ -1371,8 +1370,9 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | ||
| 1371 | 1370 | |
| 1372 | 1371 | // If upstream is ahead, update the episode number |
| 1373 | 1372 | if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil { |
| 1374 | if temp_anime.Progress > anime.Ep.Number { | |
| 1375 | anime.Ep.Number = temp_anime.Progress | |
| 1373 | upstreamNextEpisode := nextEpisodeFromProgress(temp_anime.Progress) | |
| 1374 | if upstreamNextEpisode > anime.Ep.Number { | |
| 1375 | anime.Ep.Number = upstreamNextEpisode | |
| 1376 | 1376 | anime.Ep.Player.PlaybackTime = 0 |
| 1377 | 1377 | anime.Ep.Resume = false |
| 1378 | 1378 | } |
| @@ -1392,7 +1392,18 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | ||
| 1392 | 1392 | } |
| 1393 | 1393 | |
| 1394 | 1394 | if anime.TotalEpisodes == 0 { // If failed to get anime data |
| 1395 | 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.") | |
| 1396 | 1407 | animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub) |
| 1397 | 1408 | if err != nil { |
| 1398 | 1409 | CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err)) |
| @@ -1412,21 +1423,14 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | ||
| 1412 | 1423 | if anime.TotalEpisodes == 0 { |
| 1413 | 1424 | CurdOut("Still unable to determine total episodes.") |
| 1414 | 1425 | CurdOut(fmt.Sprintf("Your %s progress: %d", RemoteTrackingDisplayName(userCurdConfig), selectedAnilistAnime.Progress)) |
| 1415 | var episodeNumber int | |
| 1416 | if userCurdConfig.RofiSelection { | |
| 1417 | userInput, err := GetUserInputFromRofi("Enter the episode you want to start from") | |
| 1418 | if err != nil { | |
| 1419 | Log("Error getting user input: " + err.Error()) | |
| 1420 | ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) | |
| 1421 | } | |
| 1422 | episodeNumber, err = strconv.Atoi(userInput) | |
| 1423 | } else { | |
| 1424 | fmt.Print("Enter the episode you want to start from: ") | |
| 1425 | fmt.Scanln(&episodeNumber) | |
| 1426 | episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, "Enter the episode you want to start from") | |
| 1427 | if err != nil { | |
| 1428 | Log("Invalid episode input: " + err.Error()) | |
| 1429 | ExitCurd(fmt.Errorf("Invalid episode number")) | |
| 1426 | 1430 | } |
| 1427 | 1431 | anime.Ep.Number = episodeNumber |
| 1428 | 1432 | } else { |
| 1429 | anime.Ep.Number = selectedAnilistAnime.Progress + 1 | |
| 1433 | anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress) | |
| 1430 | 1434 | } |
| 1431 | 1435 | } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases |
| 1432 | 1436 | Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number)) |
| @@ -1442,7 +1446,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | ||
| 1442 | 1446 | fmt.Printf("Would like to start the anime from beginning? (y/n)\n") |
| 1443 | 1447 | fmt.Scanln(&answer) |
| 1444 | 1448 | } |
| 1445 | if answer == "y" { | |
| 1449 | if isAffirmativeAnswer(answer) { | |
| 1446 | 1450 | anime.Ep.Number = 1 |
| 1447 | 1451 | } else { |
| 1448 | 1452 | anime.Ep.Number = anime.TotalEpisodes |
| @@ -1596,17 +1600,14 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string { | ||
| 1596 | 1600 | RestoreScreen() |
| 1597 | 1601 | os.Exit(1) |
| 1598 | 1602 | } |
| 1599 | if userCurdConfig.RofiSelection { | |
| 1600 | userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1])) | |
| 1601 | if err != nil { | |
| 1602 | Log("Error getting user input: " + err.Error()) | |
| 1603 | ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) | |
| 1604 | } | |
| 1605 | anime.Ep.Number, err = strconv.Atoi(userInput) | |
| 1606 | } else { | |
| 1607 | CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1])) | |
| 1608 | fmt.Scanln(&anime.Ep.Number) | |
| 1603 | episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1])) | |
| 1604 | if err != nil { | |
| 1605 | Log("Invalid episode input: " + err.Error()) | |
| 1606 | CurdOut("Invalid episode number") | |
| 1607 | RestoreScreen() | |
| 1608 | os.Exit(1) | |
| 1609 | 1609 | } |
| 1610 | anime.Ep.Number = episodeNumber | |
| 1610 | 1611 | link, _, err = GetEpisodeURLForPlayback(*userCurdConfig, anime.ProviderId, anime.Ep.Number) |
| 1611 | 1612 | if err != nil { |
| 1612 | 1613 | CurdOut("Failed to get episode link") |
| @@ -1791,23 +1792,32 @@ func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error { | ||
| 1791 | 1792 | } |
| 1792 | 1793 | |
| 1793 | 1794 | // Download file if it doesn't exist |
| 1794 | resp, err := http.Get(baseURL + fileName) | |
| 1795 | resp, err := sharedHTTPClient.Get(baseURL + fileName) | |
| 1795 | 1796 | if err != nil { |
| 1796 | 1797 | return fmt.Errorf("failed to download %s: %v", fileName, err) |
| 1797 | 1798 | } |
| 1798 | 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 | } | |
| 1799 | 1803 | |
| 1800 | 1804 | // Create the file |
| 1801 | 1805 | out, err := os.Create(filePath) |
| 1802 | 1806 | if err != nil { |
| 1807 | resp.Body.Close() | |
| 1803 | 1808 | return fmt.Errorf("failed to create file %s: %v", fileName, err) |
| 1804 | 1809 | } |
| 1805 | defer out.Close() | |
| 1806 | 1810 | |
| 1807 | 1811 | // Write the content |
| 1808 | 1812 | if _, err := io.Copy(out, resp.Body); err != nil { |
| 1813 | resp.Body.Close() | |
| 1814 | out.Close() | |
| 1809 | 1815 | return fmt.Errorf("failed to write file %s: %v", fileName, err) |
| 1810 | 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 | } | |
| 1811 | 1821 | } |
| 1812 | 1822 | |
| 1813 | 1823 | return nil |
| @@ -1850,11 +1860,20 @@ func NextEpisodePromptCLI(userCurdConfig *CurdConfig) bool { | ||
| 1850 | 1860 | |
| 1851 | 1861 | // Show the next episode number that will be started |
| 1852 | 1862 | nextEpisodeNum := anime.Ep.Number + 1 |
| 1853 | 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 | } | |
| 1854 | 1869 | |
| 1855 | 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 | } | |
| 1856 | 1875 | options := []SelectionOption{ |
| 1857 | {Key: "yes", Label: fmt.Sprintf("Yes, continue to episode %d", nextEpisodeNum)}, | |
| 1876 | {Key: "yes", Label: label}, | |
| 1858 | 1877 | } |
| 1859 | 1878 | |
| 1860 | 1879 | // Use DynamicSelect for CLI mode |
| @@ -1889,11 +1908,20 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string | ||
| 1889 | 1908 | |
| 1890 | 1909 | // Show the next episode number that will be started |
| 1891 | 1910 | nextEpisodeNum := anime.Ep.Number + 1 |
| 1892 | 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 | } | |
| 1893 | 1917 | |
| 1894 | 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 | } | |
| 1895 | 1923 | options := []SelectionOption{ |
| 1896 | {Key: "yes", Label: "Yes, start next episode now"}, | |
| 1924 | {Key: "yes", Label: label}, | |
| 1897 | 1925 | } |
| 1898 | 1926 | |
| 1899 | 1927 | // Use DynamicSelect for CLI mode |
| @@ -1921,18 +1949,17 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string | ||
| 1921 | 1949 | } |
| 1922 | 1950 | |
| 1923 | 1951 | // Update local database |
| 1924 | err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime), GetProvider().Name()) | |
| 1925 | if err != nil { | |
| 1926 | Log("Error updating local database on quit: " + err.Error()) | |
| 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 { | |
| 1953 | Log("Error updating local database on quit: " + updateErr.Error()) | |
| 1927 | 1954 | } |
| 1928 | 1955 | |
| 1929 | 1956 | if !(anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && anime.Rewatching) { |
| 1930 | go func() { | |
| 1931 | err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number) | |
| 1932 | if err != nil { | |
| 1933 | Log("Error updating Anilist progress on quit: " + err.Error()) | |
| 1957 | completedEpisode := anime.Ep.Number | |
| 1958 | go func(progressEpisode int) { | |
| 1959 | if progressErr := UpdateAnimeProgress(userToken, anime.AnilistId, progressEpisode); progressErr != nil { | |
| 1960 | Log("Error updating Anilist progress on quit: " + progressErr.Error()) | |
| 1934 | 1961 | } |
| 1935 | }() | |
| 1962 | }(completedEpisode) | |
| 1936 | 1963 | } |
| 1937 | 1964 | |
| 1938 | 1965 | CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched)) |
| @@ -1948,40 +1975,12 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string | ||
| 1948 | 1975 | if selectedOption.Key == "yes" { |
| 1949 | 1976 | // User wants to start next episode immediately |
| 1950 | 1977 | anime.Ep.IsCompleted = true |
| 1951 | ||
| 1952 | // Update database with completed episode first | |
| 1953 | err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime), GetProvider().Name()) | |
| 1954 | if err != nil { | |
| 1955 | Log("Error updating local database with completed episode: " + err.Error()) | |
| 1956 | } | |
| 1957 | ||
| 1958 | go func() { | |
| 1959 | err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number) | |
| 1960 | if err != nil { | |
| 1961 | Log("Error updating Anilist progress: " + err.Error()) | |
| 1962 | } | |
| 1963 | }() | |
| 1964 | ||
| 1965 | // Increment to next episode and update database with next episode number and 0 playback time | |
| 1966 | anime.Ep.Number++ | |
| 1967 | ||
| 1968 | // Use prefetched links if available for the next episode | |
| 1969 | if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) { | |
| 1970 | anime.Ep.Links = anime.Ep.NextEpisode.Links | |
| 1971 | Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number)) | |
| 1972 | } else { | |
| 1973 | // Clear links to force fetching new ones | |
| 1974 | anime.Ep.Links = []string{} | |
| 1975 | Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number)) | |
| 1976 | } | |
| 1977 | ||
| 1978 | err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, GetAnimeName(*anime), GetProvider().Name()) | |
| 1979 | if err != nil { | |
| 1980 | Log("Error updating local database with next episode: " + err.Error()) | |
| 1978 | socketPath := anime.Ep.Player.SocketPath | |
| 1979 | if anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes { | |
| 1980 | ExitMPV(socketPath) | |
| 1981 | 1981 | } |
| 1982 | ||
| 1983 | CurdOut("Starting next episode now...") | |
| 1984 | ExitMPV(anime.Ep.Player.SocketPath) | |
| 1982 | StartNextEpisode(anime, userCurdConfig, databaseFile, userToken) | |
| 1983 | ExitMPV(socketPath) | |
| 1985 | 1984 | return // Exit this function, let the main loop handle next episode |
| 1986 | 1985 | } |
| 1987 | 1986 | } |
| @@ -1993,10 +1992,15 @@ func NextEpisodePromptRofi(userCurdConfig *CurdConfig) bool { | ||
| 1993 | 1992 | |
| 1994 | 1993 | // Show the next episode number that will be started |
| 1995 | 1994 | nextEpisodeNum := anime.Ep.Number + 1 |
| 1995 | isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes | |
| 1996 | 1996 | |
| 1997 | 1997 | // Create options for the selection |
| 1998 | label := fmt.Sprintf("Yes, start episode %d", nextEpisodeNum) | |
| 1999 | if isLastKnownEpisode { | |
| 2000 | label = "Yes, finish series" | |
| 2001 | } | |
| 1998 | 2002 | options := []SelectionOption{ |
| 1999 | {Key: "yes", Label: fmt.Sprintf("Yes, start episode %d", nextEpisodeNum)}, | |
| 2003 | {Key: "yes", Label: label}, | |
| 2000 | 2004 | } |
| 2001 | 2005 | |
| 2002 | 2006 | // Use DynamicSelect for Rofi mode |
| @@ -2069,9 +2073,8 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str | ||
| 2069 | 2073 | } |
| 2070 | 2074 | |
| 2071 | 2075 | go func() { |
| 2072 | err = UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode) | |
| 2073 | if err != nil { | |
| 2074 | Log("Error updating Anilist progress: " + err.Error()) | |
| 2076 | if progressErr := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode); progressErr != nil { | |
| 2077 | Log("Error updating Anilist progress: " + progressErr.Error()) | |
| 2075 | 2078 | } |
| 2076 | 2079 | }() |
| 2077 | 2080 | |
internal/episode_list.go +4 −1
| @@ -35,7 +35,7 @@ type episodesResponse struct { | ||
| 35 | 35 | func getAllAnimeEpisodesList(showID, mode string) ([]string, error) { |
| 36 | 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 | 40 | // Build POST request body |
| 41 | 41 | requestBody, err := json.Marshal(map[string]interface{}{ |
| @@ -68,6 +68,9 @@ func getAllAnimeEpisodesList(showID, mode string) ([]string, error) { | ||
| 68 | 68 | Log(fmt.Sprint("Error reading response body:", err)) |
| 69 | 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 | 75 | // Parse the JSON response |
| 73 | 76 | var response episodesResponse |
internal/episode_url.go +19 −25
| @@ -224,6 +224,10 @@ func extractLinks(provider_id string) map[string]interface{} { | ||
| 224 | 224 | Log(fmt.Sprint("Error reading response:", err)) |
| 225 | 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 | 232 | // Parse the JSON response |
| 229 | 233 | err = json.Unmarshal(body, &videoData) |
| @@ -473,6 +477,9 @@ func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) { | ||
| 473 | 477 | if err != nil { |
| 474 | 478 | return nil, fmt.Errorf("failed to read persisted query response: %w", err) |
| 475 | 479 | } |
| 480 | if !httpStatusOK(resp.StatusCode) { | |
| 481 | return nil, httpStatusError("allanime episode persisted query", resp.StatusCode, body) | |
| 482 | } | |
| 476 | 483 | |
| 477 | 484 | var response allanimeResponse |
| 478 | 485 | if err := json.Unmarshal(body, &response); err != nil { |
| @@ -512,6 +519,9 @@ func getEpisodeURLForMode(id, mode string, epNo int) ([]string, error) { | ||
| 512 | 519 | if err != nil { |
| 513 | 520 | return nil, fmt.Errorf("failed to read response body: %w", err) |
| 514 | 521 | } |
| 522 | if !httpStatusOK(resp.StatusCode) { | |
| 523 | return nil, httpStatusError("allanime episode fallback query", resp.StatusCode, body) | |
| 524 | } | |
| 515 | 525 | |
| 516 | 526 | if err := json.Unmarshal(body, &response); err != nil { |
| 517 | 527 | Log(fmt.Sprint("Error parsing fallback JSON: ", err)) |
| @@ -558,7 +568,7 @@ func getLinksFromSourceUrls(sourceUrls []allanimeSource) ([]string, error) { | ||
| 558 | 568 | } |
| 559 | 569 | |
| 560 | 570 | decodedURL := decodeProviderID(sourceURL[2:]) |
| 561 | if strings.Contains(decodedURL, LinkPriorities[0]) { | |
| 571 | if len(LinkPriorities) > 0 && strings.Contains(decodedURL, LinkPriorities[0]) { | |
| 562 | 572 | priority := url.Priority |
| 563 | 573 | if priority > highestPriority { |
| 564 | 574 | highestPriority = priority |
| @@ -591,7 +601,6 @@ func getLinksFromURLs(validURLs []string) ([]string, error) { | ||
| 591 | 601 | |
| 592 | 602 | highPriorityLink := make(chan []string, 1) |
| 593 | 603 | |
| 594 | remainingURLs := len(validURLs) | |
| 595 | 604 | for i, sourceUrl := range validURLs { |
| 596 | 605 | go func(idx int, url string) { |
| 597 | 606 | decodedProviderID := decodeProviderID(url[2:]) |
| @@ -634,8 +643,12 @@ func getLinksFromURLs(validURLs []string) ([]string, error) { | ||
| 634 | 643 | } |
| 635 | 644 | |
| 636 | 645 | // Check if any of the extracted links are high priority |
| 646 | priorityDomains := LinkPriorities | |
| 647 | if len(priorityDomains) > 3 { | |
| 648 | priorityDomains = priorityDomains[:3] | |
| 649 | } | |
| 637 | 650 | for _, link := range links { |
| 638 | for _, domain := range LinkPriorities[:3] { | |
| 651 | for _, domain := range priorityDomains { | |
| 639 | 652 | if strings.Contains(link, domain) { |
| 640 | 653 | // Found high priority link, send it immediately |
| 641 | 654 | select { |
| @@ -663,8 +676,6 @@ func getLinksFromURLs(validURLs []string) ([]string, error) { | ||
| 663 | 676 | // First, try to get a high priority link |
| 664 | 677 | select { |
| 665 | 678 | case links := <-highPriorityLink: |
| 666 | // Continue extracting other links in background | |
| 667 | go collectRemainingResults(results, orderedResults, &successCount, &collectedErrors, remainingURLs) | |
| 668 | 679 | return links, nil |
| 669 | 680 | case <-time.After(2 * time.Second): // Wait only briefly for high priority link |
| 670 | 681 | // No high priority link found quickly, proceed with normal collection |
| @@ -672,9 +683,11 @@ func getLinksFromURLs(validURLs []string) ([]string, error) { | ||
| 672 | 683 | |
| 673 | 684 | // Continue with existing result collection logic |
| 674 | 685 | // Collect results maintaining order |
| 675 | for successCount < len(validURLs) { | |
| 686 | completedCount := 0 | |
| 687 | for completedCount < len(validURLs) { | |
| 676 | 688 | select { |
| 677 | 689 | case res := <-results: |
| 690 | completedCount++ | |
| 678 | 691 | if res.err != nil { |
| 679 | 692 | Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err)) |
| 680 | 693 | collectedErrors = append(collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err)) |
| @@ -707,25 +720,6 @@ func getLinksFromURLs(validURLs []string) ([]string, error) { | ||
| 707 | 720 | return allLinks, nil |
| 708 | 721 | } |
| 709 | 722 | |
| 710 | // Helper function to collect remaining results in background | |
| 711 | func collectRemainingResults(results chan result, orderedResults [][]string, successCount *int, collectedErrors *[]error, remainingURLs int) { | |
| 712 | for *successCount < remainingURLs { | |
| 713 | select { | |
| 714 | case res := <-results: | |
| 715 | if res.err != nil { | |
| 716 | Log(fmt.Sprintf("Error processing URL %d: %v", res.index+1, res.err)) | |
| 717 | *collectedErrors = append(*collectedErrors, fmt.Errorf("URL %d: %w", res.index+1, res.err)) | |
| 718 | } else { | |
| 719 | orderedResults[res.index] = res.links | |
| 720 | *successCount++ | |
| 721 | Log(fmt.Sprintf("Successfully processed URL %d/%d", res.index+1, remainingURLs)) | |
| 722 | } | |
| 723 | case <-time.After(10 * time.Second): | |
| 724 | return | |
| 725 | } | |
| 726 | } | |
| 727 | } | |
| 728 | ||
| 729 | 723 | // converts the ordered slice of link slices into a single slice |
| 730 | 724 | func flattenResults(results [][]string) []string { |
| 731 | 725 | var totalLen int |
internal/filler_list.go +2 −1
| @@ -29,12 +29,13 @@ func FetchFillerEpisodes(malID int) ([]int, error) { | ||
| 29 | 29 | for { |
| 30 | 30 | <-rateLimiter.C // Wait for rate limit |
| 31 | 31 | url := fmt.Sprintf("%s?page=%d", baseURL, page) |
| 32 | resp, err := http.Get(url) | |
| 32 | resp, err := sharedHTTPClient.Get(url) | |
| 33 | 33 | if err != nil { |
| 34 | 34 | return nil, fmt.Errorf("error fetching episodes: %v", err) |
| 35 | 35 | } |
| 36 | 36 | |
| 37 | 37 | if resp.StatusCode == http.StatusTooManyRequests { |
| 38 | resp.Body.Close() | |
| 38 | 39 | // Wait for 2 seconds and retry |
| 39 | 40 | time.Sleep(2 * time.Second) |
| 40 | 41 | continue |
internal/http_client.go +17
| @@ -1,9 +1,11 @@ | ||
| 1 | 1 | package internal |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | "fmt" | |
| 4 | 5 | "net/http" |
| 5 | 6 | "net/http/cookiejar" |
| 6 | 7 | "net/url" |
| 8 | "strings" | |
| 7 | 9 | "time" |
| 8 | 10 | ) |
| 9 | 11 | |
| @@ -15,6 +17,21 @@ func SetCookiesForAnimepahe(u *url.URL, cookies []*http.Cookie) { | ||
| 15 | 17 | } |
| 16 | 18 | } |
| 17 | 19 | |
| 20 | func httpStatusOK(statusCode int) bool { | |
| 21 | return statusCode >= http.StatusOK && statusCode < http.StatusMultipleChoices | |
| 22 | } | |
| 23 | ||
| 24 | func 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 | ||
| 18 | 35 | func init() { |
| 19 | 36 | jar, _ := cookiejar.New(nil) |
| 20 | 37 | sharedHTTPClient = &http.Client{ |
internal/input.go added +77
| @@ -0,0 +1,77 @@ | ||
| 1 | package internal | |
| 2 | ||
| 3 | import ( | |
| 4 | "bufio" | |
| 5 | "fmt" | |
| 6 | "io" | |
| 7 | "os" | |
| 8 | "strconv" | |
| 9 | "strings" | |
| 10 | ) | |
| 11 | ||
| 12 | func 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 | ||
| 21 | func 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 | ||
| 40 | func 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 | ||
| 51 | func 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 | ||
| 62 | func 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 | ||
| 70 | func 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 | 5 | "fmt" |
| 6 | 6 | "io" |
| 7 | 7 | "net/http" |
| 8 | "time" | |
| 8 | 9 | ) |
| 9 | 10 | |
| 10 | 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 | 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 | 88 | resp, err := client.Do(req) |
| 85 | 89 | if err != nil { |
| 86 | 90 | return nil, fmt.Errorf("failed to send GET request: %w", err) |
internal/localTracking.go +98 −73
| @@ -1,7 +1,6 @@ | ||
| 1 | 1 | package internal |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | "bufio" | |
| 5 | 4 | "encoding/csv" |
| 6 | 5 | "fmt" |
| 7 | 6 | "os" |
| @@ -21,7 +20,6 @@ func LocalAddAnime(databaseFile string, anilistID int, allanimeID string, watchi | ||
| 21 | 20 | defer file.Close() |
| 22 | 21 | |
| 23 | 22 | writer := csv.NewWriter(file) |
| 24 | defer writer.Flush() | |
| 25 | 23 | |
| 26 | 24 | err = writer.Write([]string{ |
| 27 | 25 | strconv.Itoa(anilistID), |
| @@ -33,9 +31,14 @@ func LocalAddAnime(databaseFile string, anilistID int, allanimeID string, watchi | ||
| 33 | 31 | }) |
| 34 | 32 | if err != nil { |
| 35 | 33 | CurdOut(fmt.Sprintf("Error writing to file: %v", err)) |
| 36 | } else { | |
| 37 | CurdOut("Written to file") | |
| 34 | return | |
| 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 | |
| 41 | 44 | func normalizeLocalProviderID(providerName, providerID, animeName string) string { |
| @@ -74,8 +77,15 @@ func LocalDeleteAnime(databaseFile string, anilistID int, allanimeID string) { | ||
| 74 | 77 | |
| 75 | 78 | // Filter out the anime entry |
| 76 | 79 | for _, row := range records { |
| 77 | aid, _ := strconv.Atoi(row[0]) // Anilist ID | |
| 78 | if aid != anilistID || row[1] != allanimeID { | |
| 80 | anime := parseAnimeRow(row) | |
| 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 | 89 | animeList = append(animeList, row) |
| 80 | 90 | } |
| 81 | 91 | } |
| @@ -89,11 +99,14 @@ func LocalDeleteAnime(databaseFile string, anilistID int, allanimeID string) { | ||
| 89 | 99 | defer fileWrite.Close() |
| 90 | 100 | |
| 91 | 101 | writer := csv.NewWriter(fileWrite) |
| 92 | defer writer.Flush() | |
| 93 | ||
| 94 | 102 | err = writer.WriteAll(animeList) |
| 95 | 103 | if err != nil { |
| 96 | 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 | 163 | return nil |
| 151 | 164 | } |
| 152 | 165 | |
| 153 | anilistID, _ := strconv.Atoi(row[0]) | |
| 154 | watchingEpisode, _ := strconv.Atoi(row[2]) | |
| 155 | playbackTime, _ := strconv.Atoi(row[3]) | |
| 156 | animeDuration, _ := strconv.Atoi(row[4]) | |
| 166 | anilistID, ok := parseRequiredLocalInt(row[0], "AniList ID", row) | |
| 167 | if !ok { | |
| 168 | return nil | |
| 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 | 195 | anime := &Anime{ |
| 159 | 196 | AnilistId: anilistID, |
| @@ -165,38 +202,46 @@ func parseAnimeRow(row []string) *Anime { | ||
| 165 | 202 | }, |
| 166 | 203 | Duration: animeDuration, |
| 167 | 204 | }, |
| 168 | } | |
| 169 | ||
| 170 | if len(row) >= 7 { | |
| 171 | anime.ProviderName = row[5] | |
| 172 | anime.Title = AnimeTitle{ | |
| 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 | } | |
| 205 | ProviderName: providerName, | |
| 206 | Title: AnimeTitle{ | |
| 207 | English: animeName, | |
| 208 | Romaji: animeName, | |
| 209 | }, | |
| 188 | 210 | } |
| 189 | 211 | |
| 190 | 212 | return anime |
| 191 | 213 | } |
| 192 | 214 | |
| 215 | func parseLocalInt(value string) int { | |
| 216 | parsed, _ := strconv.Atoi(strings.TrimSpace(value)) | |
| 217 | return parsed | |
| 218 | } | |
| 219 | ||
| 220 | func 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 | 229 | // Function to get the anime name (English or Romaji) from an Anime struct |
| 194 | 230 | func GetAnimeName(anime Anime) string { |
| 195 | 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 | 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 | 247 | // Function to update or add a new anime entry |
| @@ -251,7 +296,6 @@ func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, wat | ||
| 251 | 296 | defer file.Close() |
| 252 | 297 | |
| 253 | 298 | writer := csv.NewWriter(file) |
| 254 | defer writer.Flush() | |
| 255 | 299 | |
| 256 | 300 | for _, anime := range animeList { |
| 257 | 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 | 311 | if err := writer.Write(record); err != nil { |
| 268 | 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 | 323 | return nil |
| 273 | 324 | } |
| 274 | 325 | |
| @@ -297,16 +348,10 @@ func WatchUntracked(userCurdConfig *CurdConfig) { | ||
| 297 | 348 | // Anime search and selection loop |
| 298 | 349 | for { |
| 299 | 350 | // Get anime name from user |
| 300 | if userCurdConfig.RofiSelection { | |
| 301 | userInput, err := GetUserInputFromRofi("Enter the anime name") | |
| 302 | if err != nil { | |
| 303 | Log("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) | |
| 351 | query, err = promptText(userCurdConfig, "Enter the anime name", false) | |
| 352 | if err != nil { | |
| 353 | Log("Error getting user input: " + err.Error()) | |
| 354 | ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) | |
| 310 | 355 | } |
| 311 | 356 | |
| 312 | 357 | // Search for the anime |
| @@ -320,19 +365,10 @@ func WatchUntracked(userCurdConfig *CurdConfig) { | ||
| 320 | 365 | // Prompt user for manual query |
| 321 | 366 | for { |
| 322 | 367 | var manualQuery string |
| 323 | if userCurdConfig.RofiSelection { | |
| 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)) | |
| 325 | if err != nil { | |
| 326 | Log("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) | |
| 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) | |
| 369 | if err != nil { | |
| 370 | Log("Error getting user input: " + err.Error()) | |
| 371 | ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) | |
| 336 | 372 | } |
| 337 | 373 | |
| 338 | 374 | // If empty, use original query name |
| @@ -380,21 +416,10 @@ func WatchUntracked(userCurdConfig *CurdConfig) { | ||
| 380 | 416 | } |
| 381 | 417 | |
| 382 | 418 | // Get episode number |
| 383 | var episodeNumber int | |
| 384 | if userCurdConfig.RofiSelection { | |
| 385 | userInput, err := GetUserInputFromRofi("Enter the episode number") | |
| 386 | if err != nil { | |
| 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) | |
| 419 | episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, "Enter the episode number") | |
| 420 | if err != nil { | |
| 421 | Log(fmt.Sprintf("Invalid episode number: %v", err)) | |
| 422 | ExitCurd(fmt.Errorf("Invalid episode number")) | |
| 398 | 423 | } |
| 399 | 424 | |
| 400 | 425 | anime.Ep.Number = episodeNumber |
internal/logic_regression_test.go added +293
| @@ -0,0 +1,293 @@ | ||
| 1 | package internal | |
| 2 | ||
| 3 | import ( | |
| 4 | "os" | |
| 5 | "path/filepath" | |
| 6 | "testing" | |
| 7 | ||
| 8 | tea "github.com/charmbracelet/bubbletea" | |
| 9 | ) | |
| 10 | ||
| 11 | func 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 | ||
| 34 | func 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 | ||
| 64 | func 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 | ||
| 77 | func 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 | ||
| 95 | func 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 | ||
| 107 | func 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 | ||
| 124 | func 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 | ||
| 135 | func 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 | ||
| 141 | func 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 | ||
| 155 | func 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 | ||
| 173 | func 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 | ||
| 184 | func 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 | ||
| 201 | func 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 | ||
| 211 | func 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 | ||
| 227 | func 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 | ||
| 237 | func 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 | ||
| 251 | func 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 | ||
| 262 | func 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 | ||
| 271 | func 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 | ||
| 278 | func 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 | 209 | if err := json.Unmarshal(body, &token); err != nil { |
| 210 | 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 | 215 | token.ExpiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second) |
| 213 | 216 | if err := saveToken(tokenPath, &token); err != nil { |
| 214 | 217 | return "", err |
| @@ -380,6 +383,8 @@ func authenticateMyAnimeListWithBrowser(config *CurdConfig, tokenPath string) (s | ||
| 380 | 383 | return exchangeMyAnimeListAuthorizationCode(config, tokenPath, codeVerifier, code) |
| 381 | 384 | } |
| 382 | 385 | |
| 386 | var authenticateMyAnimeList = authenticateMyAnimeListWithBrowser | |
| 387 | ||
| 383 | 388 | func refreshMyAnimeListToken(config *CurdConfig, tokenPath string, refreshToken string) (*OAuthToken, error) { |
| 384 | 389 | clientID, clientSecret := myAnimeListClientCredentials(config) |
| 385 | 390 | if clientID == "" { |
| @@ -422,6 +427,12 @@ func refreshMyAnimeListToken(config *CurdConfig, tokenPath string, refreshToken | ||
| 422 | 427 | if err := json.Unmarshal(body, &token); err != nil { |
| 423 | 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 | 436 | token.ExpiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second) |
| 426 | 437 | if err := saveToken(tokenPath, &token); err != nil { |
| 427 | 438 | return nil, err |
| @@ -434,11 +445,31 @@ func refreshMyAnimeListToken(config *CurdConfig, tokenPath string, refreshToken | ||
| 434 | 445 | return &token, nil |
| 435 | 446 | } |
| 436 | 447 | |
| 448 | func 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 | ||
| 437 | 467 | func GetMyAnimeListAccessToken(config *CurdConfig) (string, error) { |
| 438 | 468 | tokenPath := myAnimeListTokenPath(config) |
| 439 | 469 | token, err := loadToken(tokenPath) |
| 440 | 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 | 474 | if isTokenValid(token) { |
| 444 | 475 | if user := GetGlobalUser(); user != nil { |
| @@ -447,18 +478,15 @@ func GetMyAnimeListAccessToken(config *CurdConfig) (string, error) { | ||
| 447 | 478 | return token.AccessToken, nil |
| 448 | 479 | } |
| 449 | 480 | if token.RefreshToken == "" { |
| 450 | return "", fmt.Errorf("MyAnimeList token has expired and cannot be refreshed") | |
| 451 | } | |
| 452 | refreshed, err := refreshMyAnimeListToken(config, tokenPath, token.RefreshToken) | |
| 453 | if err != nil { | |
| 454 | return "", err | |
| 481 | Log("MyAnimeList token is expired and has no refresh token, starting login") | |
| 482 | return renewMyAnimeListAccessToken(config, tokenPath, token, "expired token") | |
| 455 | 483 | } |
| 456 | return refreshed.AccessToken, nil | |
| 484 | return renewMyAnimeListAccessToken(config, tokenPath, token, "expired token") | |
| 457 | 485 | } |
| 458 | 486 | |
| 459 | 487 | func ChangeMyAnimeListToken(config *CurdConfig, user *User) error { |
| 460 | 488 | tokenPath := myAnimeListTokenPath(config) |
| 461 | accessToken, err := authenticateMyAnimeListWithBrowser(config, tokenPath) | |
| 489 | accessToken, err := authenticateMyAnimeList(config, tokenPath) | |
| 462 | 490 | if err != nil { |
| 463 | 491 | return err |
| 464 | 492 | } |
| @@ -520,15 +548,22 @@ func myAnimeListRequest(config *CurdConfig, method, requestURL string, form url. | ||
| 520 | 548 | } |
| 521 | 549 | |
| 522 | 550 | if resp.StatusCode == http.StatusUnauthorized && attempt == 0 { |
| 523 | storedToken, tokenErr := loadToken(myAnimeListTokenPath(config)) | |
| 551 | tokenPath := myAnimeListTokenPath(config) | |
| 552 | storedToken, tokenErr := loadToken(tokenPath) | |
| 524 | 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) | |
| 528 | if refreshErr != nil { | |
| 529 | return refreshErr | |
| 562 | accessToken, renewErr := renewMyAnimeListAccessToken(config, tokenPath, storedToken, "unauthorized API response") | |
| 563 | if renewErr != nil { | |
| 564 | return renewErr | |
| 530 | 565 | } |
| 531 | token = refreshed.AccessToken | |
| 566 | token = accessToken | |
| 532 | 567 | continue |
| 533 | 568 | } |
| 534 | 569 | |
| @@ -556,9 +591,12 @@ func parseMyAnimeListDate(value string) FuzzyDate { | ||
| 556 | 591 | return FuzzyDate{} |
| 557 | 592 | } |
| 558 | 593 | |
| 559 | year, _ := strconv.Atoi(parts[0]) | |
| 560 | month, _ := strconv.Atoi(parts[1]) | |
| 561 | day, _ := strconv.Atoi(parts[2]) | |
| 594 | year, yearErr := strconv.Atoi(parts[0]) | |
| 595 | month, monthErr := strconv.Atoi(parts[1]) | |
| 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 | 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 | 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 | 757 | media := Media{ |
| 715 | ID: int(mediaData["id"].(float64)), | |
| 758 | ID: int(aniListID), | |
| 716 | 759 | MalID: malID, |
| 717 | 760 | Episodes: 0, |
| 718 | 761 | Duration: 0, |
| @@ -823,8 +866,12 @@ func lookupAniListMediaByMalIDs(malIDs []int) (map[int]aniListMediaLookupResult, | ||
| 823 | 866 | if !ok || rawMedia == nil { |
| 824 | 867 | continue |
| 825 | 868 | } |
| 869 | aniListID, ok := rawMedia["id"].(float64) | |
| 870 | if !ok || aniListID == 0 { | |
| 871 | continue | |
| 872 | } | |
| 826 | 873 | media := Media{ |
| 827 | ID: int(rawMedia["id"].(float64)), | |
| 874 | ID: int(aniListID), | |
| 828 | 875 | MalID: malID, |
| 829 | 876 | Episodes: 0, |
| 830 | 877 | Duration: 0, |
internal/myanimelist_token_test.go added +183
| @@ -0,0 +1,183 @@ | ||
| 1 | package internal | |
| 2 | ||
| 3 | import ( | |
| 4 | "io" | |
| 5 | "net/http" | |
| 6 | "net/url" | |
| 7 | "strings" | |
| 8 | "testing" | |
| 9 | "time" | |
| 10 | ) | |
| 11 | ||
| 12 | type roundTripFunc func(*http.Request) (*http.Response, error) | |
| 13 | ||
| 14 | func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { | |
| 15 | return f(req) | |
| 16 | } | |
| 17 | ||
| 18 | func 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 | ||
| 27 | func 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 | ||
| 40 | func 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 | ||
| 84 | func 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 | ||
| 123 | func 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 | 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 | 185 | nextArg := strings.ToLower(strings.TrimSpace(args[i+1])) |
| 182 | 186 | if strings.Contains(nextArg, "referer:") { |
| 183 | 187 | return true |
| @@ -241,6 +245,16 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string, | ||
| 241 | 245 | var err error |
| 242 | 246 | |
| 243 | 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 | 259 | // Add custom MPV arguments from config if they exist |
| 246 | 260 | if userConfig.MpvArgs != nil { |
| @@ -486,17 +500,36 @@ func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, e | ||
| 486 | 500 | continue // Try again |
| 487 | 501 | } |
| 488 | 502 | |
| 489 | // Success! | |
| 490 | if data, exists := response["data"]; exists { | |
| 491 | return data, nil | |
| 503 | data, responseErr := mpvResponseData(response) | |
| 504 | if responseErr != 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 | 512 | // All retries failed |
| 497 | 513 | return nil, fmt.Errorf("command failed after %d attempts: %w", maxRetries, lastErr) |
| 498 | 514 | } |
| 499 | 515 | |
| 516 | func 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 | ||
| 500 | 533 | func SeekMPV(ipcSocketPath string, time int) (interface{}, error) { |
| 501 | 534 | command := []interface{}{"seek", time, "absolute"} |
| 502 | 535 | return MPVSendCommand(ipcSocketPath, command) |
| @@ -747,7 +780,11 @@ func StartMPVEventListener(ipcSocketPath string, eventCallback func(string, inte | ||
| 747 | 780 | |
| 748 | 781 | // Handle both events and property changes |
| 749 | 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 | 788 | Log(fmt.Sprintf("Event type detected: %s", eventType)) |
| 752 | 789 | |
| 753 | 790 | // Handle specific MPV events |
| @@ -773,7 +810,11 @@ func StartMPVEventListener(ipcSocketPath string, eventCallback func(string, inte | ||
| 773 | 810 | case "property-change": |
| 774 | 811 | if name, exists := response["name"]; exists { |
| 775 | 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 | 818 | Log(fmt.Sprintf("MPV PROPERTY CHANGE EVENT - %s: %v", propertyName, data)) |
| 778 | 819 | |
| 779 | 820 | // Call the callback with the event details |
internal/provider.go +80 −1
| @@ -1,5 +1,11 @@ | ||
| 1 | 1 | package internal |
| 2 | 2 | |
| 3 | import ( | |
| 4 | "fmt" | |
| 5 | "strconv" | |
| 6 | "strings" | |
| 7 | ) | |
| 8 | ||
| 3 | 9 | // Provider interface defines methods for an anime provider. |
| 4 | 10 | type Provider interface { |
| 5 | 11 | Name() string |
| @@ -16,7 +22,7 @@ func GetProvider() Provider { | ||
| 16 | 22 | return CurrentProvider |
| 17 | 23 | } |
| 18 | 24 | config := GetGlobalConfig() |
| 19 | if config != nil && config.Provider == "animepahe" { | |
| 25 | if config != nil && strings.EqualFold(strings.TrimSpace(config.Provider), "animepahe") { | |
| 20 | 26 | CurrentProvider = &AnimepaheProvider{} |
| 21 | 27 | } else { |
| 22 | 28 | CurrentProvider = &AllanimeProvider{} |
| @@ -33,6 +39,79 @@ func EpisodesList(showID, mode string) ([]string, error) { | ||
| 33 | 39 | return GetProvider().EpisodesList(showID, mode) |
| 34 | 40 | } |
| 35 | 41 | |
| 42 | func GetProviderTotalEpisodes(showID, mode string) (int, error) { | |
| 43 | return getProviderTotalEpisodes(GetProvider(), showID, mode) | |
| 44 | } | |
| 45 | ||
| 46 | func 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 | ||
| 82 | func inferProviderTotalEpisodes(providerName string, episodes []string) int { | |
| 83 | if strings.EqualFold(providerName, "animepahe") { | |
| 84 | return countUsableEpisodeEntries(episodes) | |
| 85 | } | |
| 86 | return inferTotalEpisodesFromEpisodeList(episodes) | |
| 87 | } | |
| 88 | ||
| 89 | func 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 | ||
| 103 | func 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 | ||
| 36 | 115 | func GetEpisodeURL(config CurdConfig, id string, epNo int) ([]string, error) { |
| 37 | 116 | return GetProvider().GetEpisodeURL(config, id, epNo) |
| 38 | 117 | } |
internal/provider_animepahe.go +138 −40
| @@ -19,6 +19,7 @@ import ( | ||
| 19 | 19 | ) |
| 20 | 20 | |
| 21 | 21 | var animepaheCookiesBypassed bool |
| 22 | var solveAnimepaheBrowserChallenge = solveAnimepaheBrowserChallengeWithRod | |
| 22 | 23 | |
| 23 | 24 | func getCookieFilePath() string { |
| 24 | 25 | return filepath.Join(GetStoragePath(), "animepahe_cookies.json") |
| @@ -38,16 +39,40 @@ func loadCookies() []*http.Cookie { | ||
| 38 | 39 | return nil |
| 39 | 40 | } |
| 40 | 41 | var cookies []*http.Cookie |
| 41 | json.Unmarshal(b, &cookies) | |
| 42 | if err := json.Unmarshal(b, &cookies); err != nil { | |
| 43 | return nil | |
| 44 | } | |
| 42 | 45 | return cookies |
| 43 | 46 | } |
| 44 | 47 | |
| 45 | func checkCookiesValid() bool { | |
| 46 | req, _ := http.NewRequest("GET", "https://animepahe.pw/api?m=search&q=test", nil) | |
| 48 | func newAnimepaheAPIRequest(rawURL string) (*http.Request, error) { | |
| 49 | req, err := http.NewRequest("GET", rawURL, nil) | |
| 50 | if err != nil { | |
| 51 | return nil, err | |
| 52 | } | |
| 47 | 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 | 54 | req.Header.Set("Referer", "https://animepahe.pw/") |
| 49 | 55 | req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") |
| 50 | 56 | req.Header.Set("X-Requested-With", "XMLHttpRequest") |
| 57 | return req, nil | |
| 58 | } | |
| 59 | ||
| 60 | func 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 | ||
| 71 | func 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 | 77 | resp, err := sharedHTTPClient.Do(req) |
| 53 | 78 | if err != nil { |
| @@ -55,15 +80,45 @@ func checkCookiesValid() bool { | ||
| 55 | 80 | } |
| 56 | 81 | defer resp.Body.Close() |
| 57 | 82 | |
| 83 | body, err := io.ReadAll(resp.Body) | |
| 84 | if err != nil { | |
| 85 | return false | |
| 86 | } | |
| 58 | 87 | if resp.StatusCode != 200 { |
| 59 | 88 | return false |
| 60 | 89 | } |
| 90 | if isAnimepaheChallengeBody(body) { | |
| 91 | return false | |
| 92 | } | |
| 61 | 93 | |
| 62 | 94 | contentType := resp.Header.Get("Content-Type") |
| 63 | 95 | return strings.Contains(contentType, "application/json") |
| 64 | 96 | } |
| 65 | 97 | |
| 66 | func (p *AnimepaheProvider) ensureBypass() error { | |
| 98 | func 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 | ||
| 108 | func 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 | ||
| 115 | func (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 | 122 | if animepaheCookiesBypassed { |
| 68 | 123 | return nil |
| 69 | 124 | } |
| @@ -81,9 +136,38 @@ func (p *AnimepaheProvider) ensureBypass() error { | ||
| 81 | 136 | Log("Cached Animepahe session expired. Requesting new session...") |
| 82 | 137 | } |
| 83 | 138 | |
| 139 | return p.refreshBypass() | |
| 140 | } | |
| 141 | ||
| 142 | func (p *AnimepaheProvider) refreshBypass() error { | |
| 84 | 143 | u, _ := url.Parse("https://animepahe.pw") |
| 85 | var httpCookies []*http.Cookie | |
| 144 | animepaheCookiesBypassed = false | |
| 145 | if err := os.Remove(getCookieFilePath()); err != nil && !os.IsNotExist(err) { | |
| 146 | Log(fmt.Sprintf("Failed to remove cached Animepahe cookies: %v", err)) | |
| 147 | } | |
| 148 | ||
| 86 | 149 | CurdOut("Animepahe needs a browser challenge before Curd can search or play. Starting a temporary headless browser...") |
| 150 | httpCookies, err := solveAnimepaheBrowserChallenge() | |
| 151 | if err != nil { | |
| 152 | CurdOut("Animepahe browser challenge failed. Try again later or switch provider.") | |
| 153 | return fmt.Errorf("animepahe browser challenge failed: %w", err) | |
| 154 | } | |
| 155 | if len(httpCookies) == 0 { | |
| 156 | return fmt.Errorf("animepahe browser challenge returned no cookies") | |
| 157 | } | |
| 158 | SetCookiesForAnimepahe(u, httpCookies) | |
| 159 | ||
| 160 | if !checkCookiesValid() { | |
| 161 | return fmt.Errorf("bypassed cookies are still invalid") | |
| 162 | } | |
| 163 | ||
| 164 | saveCookies(httpCookies) | |
| 165 | animepaheCookiesBypassed = true | |
| 166 | CurdOut("Successfully bypassed DDoS-Guard.") | |
| 167 | return nil | |
| 168 | } | |
| 169 | ||
| 170 | func solveAnimepaheBrowserChallengeWithRod() (httpCookies []*http.Cookie, err error) { | |
| 87 | 171 | if err := rod.Try(func() { |
| 88 | 172 | l := launcher.New().Headless(true) |
| 89 | 173 | defer l.Cleanup() |
| @@ -112,19 +196,9 @@ func (p *AnimepaheProvider) ensureBypass() error { | ||
| 112 | 196 | }) |
| 113 | 197 | } |
| 114 | 198 | }); err != nil { |
| 115 | CurdOut("Animepahe browser challenge failed. Try again later or switch provider.") | |
| 116 | return fmt.Errorf("animepahe browser challenge failed: %w", err) | |
| 117 | } | |
| 118 | SetCookiesForAnimepahe(u, httpCookies) | |
| 119 | ||
| 120 | if !checkCookiesValid() { | |
| 121 | return fmt.Errorf("bypassed cookies are still invalid") | |
| 199 | return nil, err | |
| 122 | 200 | } |
| 123 | ||
| 124 | saveCookies(httpCookies) | |
| 125 | animepaheCookiesBypassed = true | |
| 126 | CurdOut("Successfully bypassed DDoS-Guard.") | |
| 127 | return nil | |
| 201 | return httpCookies, nil | |
| 128 | 202 | } |
| 129 | 203 | |
| 130 | 204 | type AnimepaheProvider struct{} |
| @@ -255,11 +329,10 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption, | ||
| 255 | 329 | // animepahe doesn't distinguish sub/dub at the search level |
| 256 | 330 | searchUrl := fmt.Sprintf("https://animepahe.pw/api?m=search&q=%s", url.QueryEscape(query)) |
| 257 | 331 | |
| 258 | req, _ := http.NewRequest("GET", searchUrl, nil) | |
| 259 | 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") | |
| 260 | req.Header.Set("Referer", "https://animepahe.pw/") | |
| 261 | req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") | |
| 262 | req.Header.Set("X-Requested-With", "XMLHttpRequest") | |
| 332 | req, err := newAnimepaheAPIRequest(searchUrl) | |
| 333 | if err != nil { | |
| 334 | return nil, err | |
| 335 | } | |
| 263 | 336 | |
| 264 | 337 | resp, err := sharedHTTPClient.Do(req) |
| 265 | 338 | if err != nil { |
| @@ -271,6 +344,9 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption, | ||
| 271 | 344 | if err != nil { |
| 272 | 345 | return nil, err |
| 273 | 346 | } |
| 347 | if !httpStatusOK(resp.StatusCode) { | |
| 348 | return nil, httpStatusError("animepahe search", resp.StatusCode, body) | |
| 349 | } | |
| 274 | 350 | |
| 275 | 351 | var searchResp animepaheSearchResponse |
| 276 | 352 | err = json.Unmarshal(body, &searchResp) |
| @@ -318,14 +394,14 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error) | ||
| 318 | 394 | |
| 319 | 395 | var allEpisodes []int |
| 320 | 396 | page := 1 |
| 397 | challengeRetried := false | |
| 321 | 398 | |
| 322 | 399 | for { |
| 323 | 400 | epUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", apiID, page) |
| 324 | req, _ := http.NewRequest("GET", epUrl, nil) | |
| 325 | 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") | |
| 326 | req.Header.Set("Referer", "https://animepahe.pw/") | |
| 327 | req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") | |
| 328 | req.Header.Set("X-Requested-With", "XMLHttpRequest") | |
| 401 | req, err := newAnimepaheAPIRequest(epUrl) | |
| 402 | if err != nil { | |
| 403 | return nil, err | |
| 404 | } | |
| 329 | 405 | |
| 330 | 406 | resp, err := sharedHTTPClient.Do(req) |
| 331 | 407 | if err != nil { |
| @@ -337,6 +413,20 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error) | ||
| 337 | 413 | if err != nil { |
| 338 | 414 | return nil, err |
| 339 | 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 | } | |
| 340 | 430 | |
| 341 | 431 | var epsResp animepaheEpisodesResponse |
| 342 | 432 | err = json.Unmarshal(body, &epsResp) |
| @@ -393,11 +483,10 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | ||
| 393 | 483 | page := 1 |
| 394 | 484 | for { |
| 395 | 485 | reqUrl := fmt.Sprintf("https://animepahe.pw/api?m=release&id=%s&sort=episode_asc&page=%d", apiID, page) |
| 396 | req, _ := http.NewRequest("GET", reqUrl, nil) | |
| 397 | 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") | |
| 398 | req.Header.Set("Referer", "https://animepahe.pw/") | |
| 399 | req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") | |
| 400 | req.Header.Set("X-Requested-With", "XMLHttpRequest") | |
| 486 | req, err := newAnimepaheAPIRequest(reqUrl) | |
| 487 | if err != nil { | |
| 488 | return nil, err | |
| 489 | } | |
| 401 | 490 | |
| 402 | 491 | resp, err := sharedHTTPClient.Do(req) |
| 403 | 492 | if err != nil { |
| @@ -409,6 +498,9 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | ||
| 409 | 498 | if err != nil { |
| 410 | 499 | return nil, err |
| 411 | 500 | } |
| 501 | if !httpStatusOK(resp.StatusCode) { | |
| 502 | return nil, httpStatusError("animepahe episode lookup", resp.StatusCode, body) | |
| 503 | } | |
| 412 | 504 | |
| 413 | 505 | var epsResp animepaheEpisodesResponse |
| 414 | 506 | err = json.Unmarshal(body, &epsResp) |
| @@ -436,10 +528,10 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | ||
| 436 | 528 | // player page: https://animepahe.pw/play/<anime_session>/<episode_session> |
| 437 | 529 | // stream links in player page: <button type=\"button\" data-src=\"https://kwik.cx/e/Jwd0hMNswksj\" |
| 438 | 530 | playerUrl := fmt.Sprintf("https://animepahe.pw/play/%s/%s", animeRef.Session, episodeSession) |
| 439 | req, _ := http.NewRequest("GET", playerUrl, nil) | |
| 440 | 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") | |
| 441 | req.Header.Set("Referer", "https://animepahe.pw/") | |
| 442 | req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8") | |
| 531 | req, err := newAnimepahePageRequest(playerUrl) | |
| 532 | if err != nil { | |
| 533 | return nil, err | |
| 534 | } | |
| 443 | 535 | |
| 444 | 536 | resp, err := sharedHTTPClient.Do(req) |
| 445 | 537 | if err != nil { |
| @@ -451,6 +543,9 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | ||
| 451 | 543 | if err != nil { |
| 452 | 544 | return nil, err |
| 453 | 545 | } |
| 546 | if !httpStatusOK(resp.StatusCode) { | |
| 547 | return nil, httpStatusError("animepahe player page", resp.StatusCode, body) | |
| 548 | } | |
| 454 | 549 | |
| 455 | 550 | bodyStr := string(body) |
| 456 | 551 | type streamLink struct { |
| @@ -537,10 +632,10 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | ||
| 537 | 632 | } |
| 538 | 633 | |
| 539 | 634 | func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) { |
| 540 | req, _ := http.NewRequest("GET", kwikUrl, nil) | |
| 541 | 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") | |
| 542 | req.Header.Set("Referer", "https://animepahe.pw/") | |
| 543 | req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8") | |
| 635 | req, err := newAnimepahePageRequest(kwikUrl) | |
| 636 | if err != nil { | |
| 637 | return "", err | |
| 638 | } | |
| 544 | 639 | |
| 545 | 640 | resp, err := sharedHTTPClient.Do(req) |
| 546 | 641 | if err != nil { |
| @@ -552,6 +647,9 @@ func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) { | ||
| 552 | 647 | if err != nil { |
| 553 | 648 | return "", err |
| 554 | 649 | } |
| 650 | if !httpStatusOK(resp.StatusCode) { | |
| 651 | return "", httpStatusError("kwik stream page", resp.StatusCode, body) | |
| 652 | } | |
| 555 | 653 | bodyStr := string(body) |
| 556 | 654 | |
| 557 | 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 @@ | ||
| 1 | package internal | |
| 2 | ||
| 3 | import ( | |
| 4 | "io" | |
| 5 | "net/http" | |
| 6 | "net/http/cookiejar" | |
| 7 | "os" | |
| 8 | "strings" | |
| 9 | "testing" | |
| 10 | ) | |
| 11 | ||
| 12 | const animepaheChallengeHTML = `<!doctype html><html><head><title>DDoS-Guard</title></head><body>Checking your browser</body></html>` | |
| 13 | ||
| 14 | func 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 | ||
| 27 | func 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 | ||
| 47 | func 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 | ||
| 103 | func 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 | ||
| 144 | func 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 +35 −8
| @@ -100,7 +100,8 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { | ||
| 100 | 100 | case tea.KeyMsg: |
| 101 | 101 | switch msg.String() { |
| 102 | 102 | case "ctrl+c": |
| 103 | // Return quit selection option directly | |
| 103 | m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}} | |
| 104 | m.selected = 0 | |
| 104 | 105 | return m, tea.Quit |
| 105 | 106 | case "esc": |
| 106 | 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 | 141 | m.scrollOffset-- |
| 141 | 142 | } |
| 142 | 143 | case "enter": |
| 144 | if len(m.filteredKeys) == 0 { | |
| 145 | return m, nil | |
| 146 | } | |
| 143 | 147 | if m.filteredKeys[m.selected].Key == "add_new" { |
| 144 | 148 | CurdOut("Adding a new anime...") |
| 145 | 149 | m.filteredKeys[m.selected] = SelectionOption{Label: "add_new", Key: "0"} |
| @@ -242,7 +246,11 @@ func (m Model) View() string { | ||
| 242 | 246 | // visibleItemsCount calculates how many options fit in the terminal |
| 243 | 247 | func (m Model) visibleItemsCount() int { |
| 244 | 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 | 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 | |
| 337 | 345 | func 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 | 352 | optMap := make(map[string]SelectionOption) |
| 340 | 353 | for _, opt := range options { |
| 341 | 354 | optMap[opt.Key] = opt |
| @@ -501,6 +514,10 @@ func parsePreviewSelection(rawSelection string, selectionOptions []SelectionOpti | ||
| 501 | 514 | } |
| 502 | 515 | |
| 503 | 516 | func downloadToCache(imageURL string) (string, error) { |
| 517 | if strings.TrimSpace(imageURL) == "" { | |
| 518 | return "", fmt.Errorf("image URL is empty") | |
| 519 | } | |
| 520 | ||
| 504 | 521 | cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images") |
| 505 | 522 | if err := os.MkdirAll(cacheDir, 0755); err != nil { |
| 506 | 523 | return "", fmt.Errorf("failed to create cache directory: %w", err) |
| @@ -511,28 +528,38 @@ func downloadToCache(imageURL string) (string, error) { | ||
| 511 | 528 | cachePath := filepath.Join(cacheDir, filename) |
| 512 | 529 | |
| 513 | 530 | // Check if file already exists in cache |
| 514 | if _, err := os.Stat(cachePath); err == nil { | |
| 515 | return cachePath, nil | |
| 531 | if info, err := os.Stat(cachePath); err == nil { | |
| 532 | if info.Size() > 0 { | |
| 533 | return cachePath, nil | |
| 534 | } | |
| 535 | _ = os.Remove(cachePath) | |
| 516 | 536 | } |
| 517 | 537 | |
| 518 | 538 | // Download the image |
| 519 | resp, err := http.Get(imageURL) | |
| 539 | resp, err := sharedHTTPClient.Get(imageURL) | |
| 520 | 540 | if err != nil { |
| 521 | 541 | return "", err |
| 522 | 542 | } |
| 523 | 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 | 548 | file, err := os.Create(cachePath) |
| 526 | 549 | if err != nil { |
| 527 | 550 | return "", err |
| 528 | 551 | } |
| 529 | defer file.Close() | |
| 530 | 552 | |
| 531 | 553 | _, err = io.Copy(file, resp.Body) |
| 532 | 554 | if err != nil { |
| 555 | file.Close() | |
| 533 | 556 | os.Remove(cachePath) // Clean up on error |
| 534 | 557 | return "", err |
| 535 | 558 | } |
| 559 | if err := file.Close(); err != nil { | |
| 560 | os.Remove(cachePath) | |
| 561 | return "", err | |
| 562 | } | |
| 536 | 563 | |
| 537 | 564 | return cachePath, nil |
| 538 | 565 | } |
| @@ -637,7 +664,7 @@ func dynamicSelectInternal(options []SelectionOption, refreshConfig *SelectionRe | ||
| 637 | 664 | options = sortHomeMenuOptions(options) |
| 638 | 665 | } |
| 639 | 666 | |
| 640 | if GetGlobalConfig().RofiSelection { | |
| 667 | if config := GetGlobalConfig(); config != nil && config.RofiSelection { | |
| 641 | 668 | return RofiSelectWithRefresh(options, isHomeMenu, refreshConfig) |
| 642 | 669 | } |
| 643 | 670 | |
internal/tracking.go +34 −4
| @@ -176,18 +176,32 @@ func promptTrackingInput(prompt string, allowEmpty bool) (string, error) { | ||
| 176 | 176 | |
| 177 | 177 | func promptAnimeScoreValue() (float64, error) { |
| 178 | 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 | ||
| 179 | 190 | if config != nil && config.RofiSelection { |
| 180 | 191 | userInput, err := GetUserInputFromRofi("Enter a score for the anime (0-10)") |
| 181 | 192 | if err != nil { |
| 182 | 193 | return 0, err |
| 183 | 194 | } |
| 184 | return strconv.ParseFloat(strings.TrimSpace(userInput), 64) | |
| 195 | return parseScore(userInput) | |
| 185 | 196 | } |
| 186 | 197 | |
| 187 | 198 | fmt.Println("Rate this anime: ") |
| 188 | var score float64 | |
| 189 | fmt.Scanln(&score) | |
| 190 | return score, nil | |
| 199 | reader := bufio.NewReader(os.Stdin) | |
| 200 | input, err := reader.ReadString('\n') | |
| 201 | if err != nil { | |
| 202 | return 0, err | |
| 203 | } | |
| 204 | return parseScore(input) | |
| 191 | 205 | } |
| 192 | 206 | |
| 193 | 207 | func ensureMyAnimeListCredentialsConfigured(config *CurdConfig) error { |
| @@ -282,6 +296,13 @@ func localAnimeListFromHistory(history []Anime) AnimeList { | ||
| 282 | 296 | return list |
| 283 | 297 | } |
| 284 | 298 | |
| 299 | func nextEpisodeFromProgress(progress int) int { | |
| 300 | if progress < 0 { | |
| 301 | return 1 | |
| 302 | } | |
| 303 | return progress + 1 | |
| 304 | } | |
| 305 | ||
| 285 | 306 | func BuildLocalAnimeList(storagePath string) AnimeList { |
| 286 | 307 | historyPath := filepath.Join(os.ExpandEnv(storagePath), "curd_history.txt") |
| 287 | 308 | return localAnimeListFromHistory(LocalGetAllAnime(historyPath)) |
| @@ -477,9 +498,15 @@ func mergeAnimeEntries(existing, incoming Entry) Entry { | ||
| 477 | 498 | func mergeAnimeLists(primary, secondary AnimeList) AnimeList { |
| 478 | 499 | merged := make(map[int]Entry) |
| 479 | 500 | for _, entry := range getEntriesByCategory(primary, "ALL") { |
| 501 | if entry.Media.ID == 0 { | |
| 502 | continue | |
| 503 | } | |
| 480 | 504 | merged[entry.Media.ID] = entry |
| 481 | 505 | } |
| 482 | 506 | for _, entry := range getEntriesByCategory(secondary, "ALL") { |
| 507 | if entry.Media.ID == 0 { | |
| 508 | continue | |
| 509 | } | |
| 483 | 510 | if existing, ok := merged[entry.Media.ID]; ok { |
| 484 | 511 | merged[entry.Media.ID] = mergeAnimeEntries(existing, entry) |
| 485 | 512 | continue |
| @@ -510,6 +537,9 @@ func mergeAnimeLists(primary, secondary AnimeList) AnimeList { | ||
| 510 | 537 | func mapEntriesByMediaID(list AnimeList) map[int]Entry { |
| 511 | 538 | entries := make(map[int]Entry) |
| 512 | 539 | for _, entry := range getEntriesByCategory(list, "ALL") { |
| 540 | if entry.Media.ID == 0 { | |
| 541 | continue | |
| 542 | } | |
| 513 | 543 | entries[entry.Media.ID] = entry |
| 514 | 544 | } |
| 515 | 545 | return entries |
internal/user_intent_regression_test.go +123 −4
| @@ -2,8 +2,10 @@ package internal | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "bytes" |
| 5 | "encoding/json" | |
| 5 | 6 | "errors" |
| 6 | 7 | "io" |
| 8 | "net/http" | |
| 7 | 9 | "os" |
| 8 | 10 | "path/filepath" |
| 9 | 11 | "strings" |
| @@ -11,18 +13,35 @@ import ( | ||
| 11 | 13 | ) |
| 12 | 14 | |
| 13 | 15 | type fakePlaybackProvider struct { |
| 14 | linksByMode map[string][]string | |
| 15 | errByMode map[string]error | |
| 16 | modes []string | |
| 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 | |
| 17 | 23 | } |
| 18 | 24 | |
| 19 | func (p *fakePlaybackProvider) Name() string { return "fake" } | |
| 25 | func (p *fakePlaybackProvider) Name() string { | |
| 26 | if p.name != "" { | |
| 27 | return p.name | |
| 28 | } | |
| 29 | return "fake" | |
| 30 | } | |
| 20 | 31 | |
| 21 | 32 | func (p *fakePlaybackProvider) SearchAnime(query, mode string) ([]SelectionOption, error) { |
| 22 | 33 | return nil, nil |
| 23 | 34 | } |
| 24 | 35 | |
| 25 | 36 | func (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 | } | |
| 26 | 45 | return []string{"1"}, nil |
| 27 | 46 | } |
| 28 | 47 | |
| @@ -53,6 +72,106 @@ func withProvider(t *testing.T, provider Provider) { | ||
| 53 | 72 | }) |
| 54 | 73 | } |
| 55 | 74 | |
| 75 | func 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 | ||
| 83 | func 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 | ||
| 104 | func 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 | ||
| 125 | func 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 | ||
| 143 | func 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 | ||
| 56 | 175 | func captureStdout(t *testing.T, fn func()) string { |
| 57 | 176 | t.Helper() |
| 58 | 177 | |