Commit 1f990ab703

1f990ab703a90d8bbfc9c57b48f16655fb077742

parent: 2e6bc671f0

Unsigned

Wraient <wraient.911@gmail.com> · 2026-01-01 23:02 UTC

Fix: Back Button in random cases

Layout: unified · split

internal/curd.go +360 −320
@@ -652,6 +652,11 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
652 ExitCurd(nil) 652 ExitCurd(nil)
653 } 653 }
654 654
655 // Handle back button - return to caller
656 if anilistSelectedOption.Key == "-2" {
657 return SelectionOption{Key: "-2", Label: "Back"}
658 }
659
655 if err != nil { 660 if err != nil {
656 Log(fmt.Sprintf("No anime available: %v", err)) 661 Log(fmt.Sprintf("No anime available: %v", err))
657 ExitCurd(fmt.Errorf("No anime available")) 662 ExitCurd(fmt.Errorf("No anime available"))
@@ -685,6 +690,11 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
685 ExitCurd(nil) 690 ExitCurd(nil)
686 } 691 }
687 692
693 // Handle back button - return to caller
694 if categorySelection.Key == "-2" {
695 return SelectionOption{Key: "-2", Label: "Back"}
696 }
697
688 err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key) 698 err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
689 if err != nil { 699 if err != nil {
690 Log(fmt.Sprintf("Failed to add anime to list: %v", err)) 700 Log(fmt.Sprintf("Failed to add anime to list: %v", err))
@@ -750,398 +760,427 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
750 var userQuery string 760 var userQuery string
751 _ = selectedAllanimeAnime // Used later in the function 761 _ = selectedAllanimeAnime // Used later in the function
752 762
753 // If continueLast flag is set, directly get the last watched anime 763 // Navigation loop for the entire setup process
754 if anime.Ep.ContinueLast { 764 for {
755 // Get the last anime ID from the curd_id file 765 // If continueLast flag is set, directly get the last watched anime
756 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id") 766 if anime.Ep.ContinueLast {
757 idBytes, err := os.ReadFile(idFilePath) 767 // Get the last anime ID from the curd_id file
758 if err != nil { 768 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
759 Log("Error reading curd_id file: " + err.Error()) 769 idBytes, err := os.ReadFile(idFilePath)
760 ExitCurd(fmt.Errorf("No last watched anime found")) 770 if err != nil {
761 } 771 Log("Error reading curd_id file: " + err.Error())
762 772 ExitCurd(fmt.Errorf("No last watched anime found"))
763 anilistID, err := strconv.Atoi(string(idBytes)) 773 }
764 if err != nil {
765 Log("Error converting anilist ID: " + err.Error())
766 ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
767 }
768
769 // Find the anime in database
770 animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
771 if animePointer == nil {
772 ExitCurd(fmt.Errorf("Last watched anime not found in database"))
773 }
774
775 // Set the anime details
776 anime.AnilistId = animePointer.AnilistId
777 anilistSelectedOption.Key = strconv.Itoa(animePointer.AnilistId)
778 // anime.AllanimeId = animePointer.AllanimeId
779 // anime.Title = animePointer.Title
780 // anime.Ep.Number = animePointer.Ep.Number
781 // anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
782 // anime.Ep.Resume = true
783
784 } else {
785 // Navigation loop for category and anime selection
786 categorySelectionLoop:
787 for {
788 // Skip category selection if Current flag is set
789 var categorySelection SelectionOption
790 if userCurdConfig.CurrentCategory {
791 categorySelection = SelectionOption{
792 Key: "CURRENT",
793 Label: "Currently Watching",
794 }
795 } else {
796 // Create category selection map
797 // Get ordered categories
798 orderedCategories := getOrderedCategories(userCurdConfig)
799 774
800 // Use DynamicSelect with ordered categories directly 775 anilistID, err := strconv.Atoi(string(idBytes))
801 categorySelection, err = DynamicSelect(orderedCategories) 776 if err != nil {
777 Log("Error converting anilist ID: " + err.Error())
778 ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
779 }
802 780
803 if err != nil { 781 // Find the anime in database
804 Log(fmt.Sprintf("Failed to select category: %v", err)) 782 animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
805 ExitCurd(fmt.Errorf("Failed to select category")) 783 if animePointer == nil {
806 } 784 ExitCurd(fmt.Errorf("Last watched anime not found in database"))
785 }
807 786
808 if categorySelection.Key == "-1" { 787 // Set the anime details
809 ExitCurd(nil) 788 anime.AnilistId = animePointer.AnilistId
810 } 789 anilistSelectedOption.Key = strconv.Itoa(animePointer.AnilistId)
790 // anime.AllanimeId = animePointer.AllanimeId
791 // anime.Title = animePointer.Title
792 // anime.Ep.Number = animePointer.Ep.Number
793 // anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
794 // anime.Ep.Resume = true
811 795
812 // Handle options 796 } else {
813 if categorySelection.Key == "UPDATE" { 797 // Navigation loop for category and anime selection
814 ClearScreen() 798 categorySelectionLoop:
815 UpdateAnimeEntry(userCurdConfig, user) 799 for {
816 // If UpdateAnimeEntry returns, user pressed back - continue to category selection 800 // Skip category selection if Current flag is set
817 ClearScreen() 801 var categorySelection SelectionOption
818 continue categorySelectionLoop 802 if userCurdConfig.CurrentCategory {
819 } else if categorySelection.Key == "UNTRACKED" { 803 categorySelection = SelectionOption{
820 ClearScreen() 804 Key: "CURRENT",
821 WatchUntracked(userCurdConfig) 805 Label: "Currently Watching",
822 // If WatchUntracked returns, user pressed back OR watched is done- continue to category selection 806 }
823 ClearScreen() 807 } else {
824 continue categorySelectionLoop 808 // Create category selection map
825 } else if categorySelection.Key == "CONTINUE_LAST" { 809 // Get ordered categories
826 anime.Ep.ContinueLast = true 810 orderedCategories := getOrderedCategories(userCurdConfig)
827 }
828 811
829 ClearScreen() 812 // Use DynamicSelect with ordered categories directly
830 } 813 categorySelection, err = DynamicSelect(orderedCategories)
831 814
832 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 815 if err != nil {
833 animeListMapPreview = make(map[string]RofiSelectPreview) 816 Log(fmt.Sprintf("Failed to select category: %v", err))
834 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) { 817 ExitCurd(fmt.Errorf("Failed to select category"))
835 title := entry.Media.Title.English
836 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
837 title = entry.Media.Title.Romaji
838 }
839 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
840 Title: title,
841 CoverImage: entry.CoverImage,
842 } 818 }
843 } 819
844 } else { 820 if categorySelection.Key == "-1" {
845 animeListOptions = make([]SelectionOption, 0) 821 ExitCurd(nil)
846 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
847 title := entry.Media.Title.English
848 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
849 title = entry.Media.Title.Romaji
850 } 822 }
851 animeListOptions = append(animeListOptions, SelectionOption{
852 Key: strconv.Itoa(entry.Media.ID),
853 Label: title,
854 })
855 }
856 }
857 823
858 // Anime selection loop (for back navigation) 824 if categorySelection.Key == "-2" {
859 animeSelectionLoop: 825 continue
860 for {
861 if anime.Ep.ContinueLast {
862 // Get the last watched anime ID from the curd_id file
863 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
864 curdIDBytes, err := os.ReadFile(curdIDPath)
865 if err != nil {
866 Log(fmt.Sprintf("Error reading curd_id file: %v", err))
867 ExitCurd(fmt.Errorf("Error reading curd_id file"))
868 } 826 }
869 827
870 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes))) 828 // Handle options
871 if err != nil { 829 if categorySelection.Key == "UPDATE" {
872 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err)) 830 ClearScreen()
873 ExitCurd(fmt.Errorf("Error converting curd_id to integer")) 831 UpdateAnimeEntry(userCurdConfig, user)
832 // If UpdateAnimeEntry returns, user pressed back - continue to category selection
833 ClearScreen()
834 continue categorySelectionLoop
835 } else if categorySelection.Key == "UNTRACKED" {
836 ClearScreen()
837 WatchUntracked(userCurdConfig)
838 // If WatchUntracked returns, user pressed back OR watched is done- continue to category selection
839 ClearScreen()
840 continue categorySelectionLoop
841 } else if categorySelection.Key == "CONTINUE_LAST" {
842 anime.Ep.ContinueLast = true
874 } 843 }
875 844
876 anime.AnilistId = lastWatchedID 845 ClearScreen()
877 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
878 break categorySelectionLoop
879 } 846 }
880 847
881 // Select anime to watch (Anilist)
882 var err error
883 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 848 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
884 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true) 849 animeListMapPreview = make(map[string]RofiSelectPreview)
850 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
851 title := entry.Media.Title.English
852 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
853 title = entry.Media.Title.Romaji
854 }
855 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
856 Title: title,
857 CoverImage: entry.CoverImage,
858 }
859 }
885 } else { 860 } else {
886 // Add "Add new anime" option to the slice 861 animeListOptions = make([]SelectionOption, 0)
887 tempOptions := make([]SelectionOption, len(animeListOptions)) 862 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
888 copy(tempOptions, animeListOptions) 863 title := entry.Media.Title.English
889 tempOptions = append(tempOptions, SelectionOption{ 864 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
890 Key: "add_new", 865 title = entry.Media.Title.Romaji
891 Label: "Add new anime", 866 }
892 }) 867 animeListOptions = append(animeListOptions, SelectionOption{
893 868 Key: strconv.Itoa(entry.Media.ID),
894 anilistSelectedOption, err = DynamicSelect(tempOptions) 869 Label: title,
895 } 870 })
896 if err != nil { 871 }
897 Log(fmt.Sprintf("Error selecting anime: %v", err))
898 ExitCurd(fmt.Errorf("Error selecting anime"))
899 } 872 }
900 873
901 Log(anilistSelectedOption) 874 // Anime selection loop (for back navigation)
875 animeSelectionLoop:
876 for {
877 if anime.Ep.ContinueLast {
878 // Get the last watched anime ID from the curd_id file
879 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
880 curdIDBytes, err := os.ReadFile(curdIDPath)
881 if err != nil {
882 Log(fmt.Sprintf("Error reading curd_id file: %v", err))
883 ExitCurd(fmt.Errorf("Error reading curd_id file"))
884 }
902 885
903 if anilistSelectedOption.Key == "-1" { 886 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
904 ExitCurd(nil) 887 if err != nil {
905 } 888 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err))
889 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
890 }
891
892 anime.AnilistId = lastWatchedID
893 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
894 break categorySelectionLoop
895 }
896
897 // Select anime to watch (Anilist)
898 var err error
899 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
900 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
901 } else {
902 // Add "Add new anime" option to the slice
903 tempOptions := make([]SelectionOption, len(animeListOptions))
904 copy(tempOptions, animeListOptions)
905 tempOptions = append(tempOptions, SelectionOption{
906 Key: "add_new",
907 Label: "Add new anime",
908 })
909
910 anilistSelectedOption, err = DynamicSelect(tempOptions)
911 }
912 if err != nil {
913 Log(fmt.Sprintf("Error selecting anime: %v", err))
914 ExitCurd(fmt.Errorf("Error selecting anime"))
915 }
916
917 Log(anilistSelectedOption)
906 918
907 // Handle back navigation - go back to category selection 919 if anilistSelectedOption.Key == "-1" {
908 if anilistSelectedOption.Key == "-2" {
909 if userCurdConfig.CurrentCategory {
910 // If CurrentCategory is forced, back means quit
911 ExitCurd(nil) 920 ExitCurd(nil)
912 } 921 }
913 ClearScreen()
914 continue categorySelectionLoop
915 }
916 922
917 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" { 923 // Handle back navigation - go back to category selection
918 addResult := AddNewAnime(userCurdConfig, anime, user, databaseAnimes) 924 if anilistSelectedOption.Key == "-2" {
919 if addResult.Key == "-2" { 925 if userCurdConfig.CurrentCategory {
920 // Back from add new anime goes to anime selection 926 // If CurrentCategory is forced, back means quit
927 ExitCurd(nil)
928 }
921 ClearScreen() 929 ClearScreen()
922 continue animeSelectionLoop 930 continue categorySelectionLoop
923 } 931 }
924 anilistSelectedOption = addResult
925 }
926 932
927 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key) 933 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
928 if err != nil { 934 addResult := AddNewAnime(userCurdConfig, anime, user, databaseAnimes)
929 Log(fmt.Sprintf("Error converting Anilist ID: %v", err)) 935 if addResult.Key == "-2" {
930 ExitCurd(fmt.Errorf("Error converting Anilist ID")) 936 // Back from add new anime goes to anime selection
931 } 937 ClearScreen()
938 continue animeSelectionLoop
939 }
940 anilistSelectedOption = addResult
941 }
942
943 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
944 if err != nil {
945 Log(fmt.Sprintf("Error converting Anilist ID: %v", err))
946 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
947 }
932 948
933 // Successfully selected anime, break out of both loops 949 // Successfully selected anime, break out of both loops
934 break categorySelectionLoop 950 break categorySelectionLoop
951 }
935 } 952 }
936 } 953 }
937 } 954 // Find anime in Local history
938 // Find anime in Local history 955 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
939 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
940 956
941 // Get anime entry 957 // Get anime entry
942 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key) 958 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
943 if err != nil { 959 if err != nil {
944 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err)) 960 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err))
945 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist")) 961 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
946 } 962 }
947 963
948 // Set anime entry 964 // Set anime entry
949 anime.Title = selectedAnilistAnime.Media.Title 965 anime.Title = selectedAnilistAnime.Media.Title
950 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes 966 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
951 anime.Ep.Number = selectedAnilistAnime.Progress + 1 967 anime.Ep.Number = selectedAnilistAnime.Progress + 1
952 var animeList []SelectionOption 968 var animeList []SelectionOption
953 userQuery = anime.Title.Romaji 969 userQuery = anime.Title.Romaji
954 970
955 // if anime not found in database, find it in animeList 971 // if anime not found in database, find it in animeList
956 if animePointer == nil { 972 if animePointer == nil {
957 Log("Anime not found in database, searching in animeList...") 973 Log("Anime not found in database, searching in animeList...")
958 // Get Anime list (All anime) 974 // Get Anime list (All anime)
959 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub)) 975 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
960 976
961 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub) 977 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
962 if err != nil { 978 if err != nil {
963 Log(fmt.Sprintf("Failed to select anime: %v", err)) 979 Log(fmt.Sprintf("Failed to select anime: %v", err))
964 ExitCurd(fmt.Errorf("Failed to select anime")) 980 ExitCurd(fmt.Errorf("Failed to select anime"))
965 } 981 }
966 if len(animeList) == 0 { 982 if len(animeList) == 0 {
967 ExitCurd(fmt.Errorf("No results found.")) 983 ExitCurd(fmt.Errorf("No results found."))
968 } 984 }
969 985
970 // find anime in animeList by searching through the options 986 // find anime in animeList by searching through the options
971 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes) 987 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes)
972 found := false 988 found := false
973 for i, option := range animeList { 989 for i, option := range animeList {
974 Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s'", i, option.Key, option.Label)) 990 Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s'", i, option.Key, option.Label))
975 if option.Label == targetLabel { 991 if option.Label == targetLabel {
976 anime.AllanimeId = option.Key 992 anime.AllanimeId = option.Key
977 Log(fmt.Sprintf("Found exact match! Setting AllanimeId to: %s", anime.AllanimeId)) 993 Log(fmt.Sprintf("Found exact match! Setting AllanimeId to: %s", anime.AllanimeId))
978 found = true 994 found = true
979 break 995 break
996 }
980 } 997 }
981 }
982 998
983 if !found { 999 if !found {
984 Log(fmt.Sprintf("No exact match found for label '%s'. Will require manual selection.", targetLabel)) 1000 Log(fmt.Sprintf("No exact match found for label '%s'. Will require manual selection.", targetLabel))
985 } 1001 }
986 1002
987 // If unable to get Allanime id automatically get manually 1003 // If unable to get Allanime id automatically get manually
988 if anime.AllanimeId == "" { 1004 if anime.AllanimeId == "" {
989 CurdOut("Failed to automatically select anime") 1005 CurdOut("Failed to automatically select anime")
990 selectedAllanimeAnime, err := DynamicSelect(animeList) 1006 selectedAllanimeAnime, err := DynamicSelect(animeList)
991 1007
992 if selectedAllanimeAnime.Key == "-1" { 1008 if selectedAllanimeAnime.Key == "-1" {
993 ExitCurd(nil) 1009 ExitCurd(nil)
994 } 1010 }
995 1011
996 if err != nil { 1012 // Handle back button - go back to main menu
997 ExitCurd(fmt.Errorf("No anime available")) 1013 if selectedAllanimeAnime.Key == "-2" {
1014 CurdOut("Going back to main menu...")
1015 RestoreScreen()
1016 if anime.Ep.ContinueLast {
1017 anime.Ep.ContinueLast = false
1018 }
1019 continue
1020 }
1021
1022 if err != nil {
1023 ExitCurd(fmt.Errorf("No anime available"))
1024 }
1025 anime.AllanimeId = selectedAllanimeAnime.Key
1026 }
1027 } else {
1028 // if anime found in database, use it
1029 anime.AllanimeId = animePointer.AllanimeId
1030 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
1031 if anime.Ep.Number == animePointer.Ep.Number {
1032 anime.Ep.Resume = true
998 } 1033 }
999 anime.AllanimeId = selectedAllanimeAnime.Key
1000 }
1001 } else {
1002 // if anime found in database, use it
1003 anime.AllanimeId = animePointer.AllanimeId
1004 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
1005 if anime.Ep.Number == animePointer.Ep.Number {
1006 anime.Ep.Resume = true
1007 } 1034 }
1008 }
1009
1010 if selectedAllanimeAnime.Key == "-1" {
1011 ExitCurd(nil)
1012 }
1013 1035
1014 // If anime is not in watching list, prompt user to add it into watching list 1036 if selectedAllanimeAnime.Key == "-1" {
1015 isInWatchingList := false 1037 ExitCurd(nil)
1016 for _, entry := range user.AnimeList.Watching {
1017 if entry.Media.ID == anime.AnilistId {
1018 isInWatchingList = true
1019 break
1020 } 1038 }
1021 }
1022 1039
1023 if !isInWatchingList { 1040 // If anime is not in watching list, prompt user to add it into watching list
1024 // Create options for the prompt 1041 isInWatchingList := false
1025 options := []SelectionOption{ 1042 for _, entry := range user.AnimeList.Watching {
1026 {Key: "yes", Label: "Add to watching list"}, 1043 if entry.Media.ID == anime.AnilistId {
1027 {Key: "no", Label: "Continue without adding"}, 1044 isInWatchingList = true
1045 break
1046 }
1028 } 1047 }
1029 1048
1030 var selectedOption SelectionOption 1049 if !isInWatchingList {
1031 var err error 1050 // Create options for the prompt
1051 options := []SelectionOption{
1052 {Key: "yes", Label: "Add to watching list"},
1053 {Key: "no", Label: "Continue without adding"},
1054 }
1032 1055
1033 // Use rofi for selection 1056 var selectedOption SelectionOption
1034 selectedOption, err = DynamicSelect(options) 1057 var err error
1035 if err != nil {
1036 Log("Error in selection: " + err.Error())
1037 ExitCurd(err)
1038 }
1039 1058
1040 if selectedOption.Key == "yes" { 1059 // Use rofi for selection
1041 err = AddAnimeToWatchingList(anime.AnilistId, user.Token) 1060 selectedOption, err = DynamicSelect(options)
1042 if err != nil { 1061 if err != nil {
1043 Log("Error adding anime to watching list: " + err.Error()) 1062 Log("Error in selection: " + err.Error())
1044 ExitCurd(err) 1063 ExitCurd(err)
1045 } 1064 }
1046 // Refresh user's anime list after adding 1065
1047 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 1066 if selectedOption.Key == "yes" {
1048 anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id) 1067 err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
1049 if err != nil { 1068 if err != nil {
1050 Log("Error refreshing anime list: " + err.Error()) 1069 Log("Error adding anime to watching list: " + err.Error())
1051 ExitCurd(err) 1070 ExitCurd(err)
1052 } 1071 }
1053 user.AnimeList = ParseAnimeList(anilistUserDataPreview) 1072 // Refresh user's anime list after adding
1054 } else { 1073 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
1055 anilistUserData, err := GetUserData(user.Token, user.Id) 1074 anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id)
1056 if err != nil { 1075 if err != nil {
1057 Log("Error refreshing anime list: " + err.Error()) 1076 Log("Error refreshing anime list: " + err.Error())
1058 ExitCurd(err) 1077 ExitCurd(err)
1078 }
1079 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
1080 } else {
1081 anilistUserData, err := GetUserData(user.Token, user.Id)
1082 if err != nil {
1083 Log("Error refreshing anime list: " + err.Error())
1084 ExitCurd(err)
1085 }
1086 user.AnimeList = ParseAnimeList(anilistUserData)
1059 } 1087 }
1060 user.AnimeList = ParseAnimeList(anilistUserData) 1088 } else if selectedOption.Key == "-1" {
1089 ExitCurd(nil)
1090 } else if selectedOption.Key == "-2" {
1091 // Handle back button - go back to main menu
1092 CurdOut("Going back to main menu...")
1093 RestoreScreen()
1094 // If we were continuing last, disable it so we go to menu next loop
1095 if anime.Ep.ContinueLast {
1096 anime.Ep.ContinueLast = false
1097 }
1098 continue
1061 } 1099 }
1062 } else if selectedOption.Key == "-1" {
1063 ExitCurd(nil)
1064 } 1100 }
1065 }
1066 1101
1067 // If upstream is ahead, update the episode number 1102 // If upstream is ahead, update the episode number
1068 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil { 1103 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
1069 if temp_anime.Progress > anime.Ep.Number { 1104 if temp_anime.Progress > anime.Ep.Number {
1070 anime.Ep.Number = temp_anime.Progress 1105 anime.Ep.Number = temp_anime.Progress
1071 anime.Ep.Player.PlaybackTime = 0 1106 anime.Ep.Player.PlaybackTime = 0
1072 anime.Ep.Resume = false 1107 anime.Ep.Resume = false
1108 }
1073 } 1109 }
1074 }
1075 1110
1076 if anime.TotalEpisodes == 0 { 1111 if anime.TotalEpisodes == 0 {
1077 // Get updated anime data 1112 // Get updated anime data
1078 Log(selectedAllanimeAnime) 1113 Log(selectedAllanimeAnime)
1079 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token) 1114 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
1080 Log(updatedAnime) 1115 Log(updatedAnime)
1081 if err != nil { 1116 if err != nil {
1082 Log(fmt.Sprintf("Error getting updated anime data: %v", err)) 1117 Log(fmt.Sprintf("Error getting updated anime data: %v", err))
1083 } else { 1118 } else {
1084 anime.TotalEpisodes = updatedAnime.TotalEpisodes 1119 anime.TotalEpisodes = updatedAnime.TotalEpisodes
1085 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes)) 1120 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
1121 }
1086 } 1122 }
1087 }
1088 1123
1089 if anime.TotalEpisodes == 0 { // If failed to get anime data 1124 if anime.TotalEpisodes == 0 { // If failed to get anime data
1090 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.") 1125 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
1091 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub) 1126 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
1092 if err != nil { 1127 if err != nil {
1093 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err)) 1128 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
1094 } else { 1129 } else {
1095 for _, option := range animeList { 1130 for _, option := range animeList {
1096 if option.Key == anime.AllanimeId { 1131 if option.Key == anime.AllanimeId {
1097 // Extract total episodes from the label 1132 // Extract total episodes from the label
1098 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 { 1133 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 {
1099 anime.TotalEpisodes, _ = strconv.Atoi(matches[1]) 1134 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
1100 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes)) 1135 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
1101 break 1136 break
1137 }
1102 } 1138 }
1103 } 1139 }
1104 } 1140 }
1105 }
1106 1141
1107 if anime.TotalEpisodes == 0 { 1142 if anime.TotalEpisodes == 0 {
1108 CurdOut("Still unable to determine total episodes.") 1143 CurdOut("Still unable to determine total episodes.")
1109 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress)) 1144 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
1110 var episodeNumber int 1145 var episodeNumber int
1146 if userCurdConfig.RofiSelection {
1147 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
1148 if err != nil {
1149 Log("Error getting user input: " + err.Error())
1150 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1151 }
1152 episodeNumber, err = strconv.Atoi(userInput)
1153 } else {
1154 fmt.Print("Enter the episode you want to start from: ")
1155 fmt.Scanln(&episodeNumber)
1156 }
1157 anime.Ep.Number = episodeNumber
1158 } else {
1159 anime.Ep.Number = selectedAnilistAnime.Progress + 1
1160 }
1161 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
1162 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
1163 var answer string
1111 if userCurdConfig.RofiSelection { 1164 if userCurdConfig.RofiSelection {
1112 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from") 1165 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
1113 if err != nil { 1166 if err != nil {
1114 Log("Error getting user input: " + err.Error()) 1167 Log("Error getting user input: " + err.Error())
1115 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) 1168 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1116 } 1169 }
1117 episodeNumber, err = strconv.Atoi(userInput) 1170 answer = userInput
1118 } else { 1171 } else {
1119 fmt.Print("Enter the episode you want to start from: ") 1172 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
1120 fmt.Scanln(&episodeNumber) 1173 fmt.Scanln(&answer)
1121 } 1174 }
1122 anime.Ep.Number = episodeNumber 1175 if answer == "y" {
1123 } else { 1176 anime.Ep.Number = 1
1124 anime.Ep.Number = selectedAnilistAnime.Progress + 1 1177 } else {
1125 } 1178 anime.Ep.Number = anime.TotalEpisodes
1126 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
1127 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
1128 var answer string
1129 if userCurdConfig.RofiSelection {
1130 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
1131 if err != nil {
1132 Log("Error getting user input: " + err.Error())
1133 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1134 } 1179 }
1135 answer = userInput
1136 } else {
1137 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
1138 fmt.Scanln(&answer)
1139 }
1140 if answer == "y" {
1141 anime.Ep.Number = 1
1142 } else {
1143 anime.Ep.Number = anime.TotalEpisodes
1144 } 1180 }
1181
1182 // If we reached here successfully, break the loop
1183 break
1145 } 1184 }
1146} 1185}
1147 1186
@@ -1381,8 +1420,8 @@ func NextEpisodePromptCLI(userCurdConfig *CurdConfig) bool {
1381 1420
1382 Log(fmt.Sprintf("CLI User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label)) 1421 Log(fmt.Sprintf("CLI User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1383 1422
1384 if selectedOption.Key == "-1" { 1423 if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1385 // User selected to quit via the built-in quit option 1424 // User selected to quit/back via the built-in option
1386 CurdOut("Exiting") 1425 CurdOut("Exiting")
1387 return false 1426 return false
1388 } 1427 }
@@ -1420,8 +1459,8 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string
1420 1459
1421 Log(fmt.Sprintf("CLI Continuous User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label)) 1460 Log(fmt.Sprintf("CLI Continuous User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1422 1461
1423 if selectedOption.Key == "-1" { 1462 if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1424 // User selected to quit via the built-in quit option 1463 // User selected to quit/back via the built-in option
1425 1464
1426 // Check completion percentage 1465 // Check completion percentage
1427 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration) 1466 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
@@ -1626,6 +1665,7 @@ func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userT
1626 CurdOut("Anime rated successfully!") 1665 CurdOut("Anime rated successfully!")
1627 } 1666 }
1628 } 1667 }
1668 // Back (-2) and no are treated as skip
1629 1669
1630 // Update anime status to completed on AniList 1670 // Update anime status to completed on AniList
1631 if !anime.Rewatching { 1671 if !anime.Rewatching {