Commit 447310e3ba

447310e3baa5b19e2c6b99aac66d56646e7c14bb

parent: b08c42f0d4

Unregistered key

Rushikesh Gaikwad <81632222+Wraient@users.noreply.github.com> · 2026-03-31 15:53 UTC
committer: <noreply@github.com>

Add: Rewatching Support (#84)

Layout: unified · split

internal/anilist.go +120 −37
@@ -454,6 +454,17 @@ func GetUserData(token string, userID int) (map[string]interface{}, error) {
454 status 454 status
455 score 455 score
456 progress 456 progress
457 repeat
458 startedAt {
459 year
460 month
461 day
462 }
463 completedAt {
464 year
465 month
466 day
467 }
457 } 468 }
458 } 469 }
459 } 470 }
@@ -495,6 +506,17 @@ func GetUserDataPreview(token string, userID int) (map[string]interface{}, error
495 status 506 status
496 score 507 score
497 progress 508 progress
509 repeat
510 startedAt {
511 year
512 month
513 day
514 }
515 completedAt {
516 year
517 month
518 day
519 }
498 } 520 }
499 } 521 }
500 } 522 }
@@ -562,26 +584,7 @@ func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []m
562 584
563// Function to update anime progress 585// Function to update anime progress
564func UpdateAnimeProgress(token string, mediaID, progress int) error { 586func UpdateAnimeProgress(token string, mediaID, progress int) error {
565 url := "https://graphql.anilist.co" 587 err := SaveAnimeListEntry(token, mediaID, nil, &progress, nil, nil, nil)
566 query := `
567 mutation($mediaId: Int, $progress: Int) {
568 SaveMediaListEntry(mediaId: $mediaId, progress: $progress) {
569 id
570 progress
571 }
572 }`
573
574 variables := map[string]interface{}{
575 "mediaId": mediaID,
576 "progress": progress,
577 }
578
579 headers := map[string]string{
580 "Authorization": "Bearer " + token,
581 "Content-Type": "application/json",
582 }
583
584 _, err := makePostRequest(url, query, variables, headers)
585 if err != nil { 588 if err != nil {
586 return err 589 return err
587 } 590 }
@@ -591,18 +594,85 @@ func UpdateAnimeProgress(token string, mediaID, progress int) error {
591} 594}
592 595
593func UpdateAnimeStatus(token string, mediaID int, status string) error { 596func UpdateAnimeStatus(token string, mediaID int, status string) error {
597 err := SaveAnimeListEntry(token, mediaID, &status, nil, nil, nil, nil)
598 if err != nil {
599 return fmt.Errorf("failed to update anime status: %w", err)
600 }
601
602 statusMap := map[string]string{
603 "CURRENT": "Currently Watching",
604 "COMPLETED": "Completed",
605 "PAUSED": "On Hold",
606 "DROPPED": "Dropped",
607 "PLANNING": "Plan to Watch",
608 "REPEATING": "Rewatching",
609 }
610
611 CurdOut(fmt.Sprintf("Anime status updated to: %s", statusMap[status]))
612 return nil
613}
614
615func SaveAnimeListEntry(token string, mediaID int, status *string, progress *int, repeat *int, startedAt *FuzzyDate, completedAt *FuzzyDate) error {
594 url := "https://graphql.anilist.co" 616 url := "https://graphql.anilist.co"
595 query := ` 617 query := `
596 mutation($mediaId: Int, $status: MediaListStatus) { 618 mutation(
597 SaveMediaListEntry(mediaId: $mediaId, status: $status) { 619 $mediaId: Int
620 $status: MediaListStatus
621 $progress: Int
622 $repeat: Int
623 $startedAt: FuzzyDateInput
624 $completedAt: FuzzyDateInput
625 ) {
626 SaveMediaListEntry(
627 mediaId: $mediaId
628 status: $status
629 progress: $progress
630 repeat: $repeat
631 startedAt: $startedAt
632 completedAt: $completedAt
633 ) {
598 id 634 id
599 status 635 status
636 progress
637 repeat
638 startedAt {
639 year
640 month
641 day
642 }
643 completedAt {
644 year
645 month
646 day
647 }
600 } 648 }
601 }` 649 }`
602 650
603 variables := map[string]interface{}{ 651 variables := map[string]interface{}{
604 "mediaId": mediaID, 652 "mediaId": mediaID,
605 "status": status, 653 }
654 if status != nil {
655 variables["status"] = *status
656 }
657 if progress != nil {
658 variables["progress"] = *progress
659 }
660 if repeat != nil {
661 variables["repeat"] = *repeat
662 }
663 if startedAt != nil && (startedAt.Year != 0 || startedAt.Month != 0 || startedAt.Day != 0) {
664 variables["startedAt"] = map[string]int{
665 "year": startedAt.Year,
666 "month": startedAt.Month,
667 "day": startedAt.Day,
668 }
669 }
670 if completedAt != nil && (completedAt.Year != 0 || completedAt.Month != 0 || completedAt.Day != 0) {
671 variables["completedAt"] = map[string]int{
672 "year": completedAt.Year,
673 "month": completedAt.Month,
674 "day": completedAt.Day,
675 }
606 } 676 }
607 677
608 headers := map[string]string{ 678 headers := map[string]string{
@@ -612,21 +682,17 @@ func UpdateAnimeStatus(token string, mediaID int, status string) error {
612 682
613 _, err := makePostRequest(url, query, variables, headers) 683 _, err := makePostRequest(url, query, variables, headers)
614 if err != nil { 684 if err != nil {
615 return fmt.Errorf("failed to update anime status: %w", err) 685 return err
616 }
617
618 statusMap := map[string]string{
619 "CURRENT": "Currently Watching",
620 "COMPLETED": "Completed",
621 "PAUSED": "On Hold",
622 "DROPPED": "Dropped",
623 "PLANNING": "Plan to Watch",
624 } 686 }
625
626 CurdOut(fmt.Sprintf("Anime status updated to: %s", statusMap[status]))
627 return nil 687 return nil
628} 688}
629 689
690func CompleteAnimeRewatch(token string, anime Anime) error {
691 status := "COMPLETED"
692 repeat := anime.Repeat + 1
693 return SaveAnimeListEntry(token, anime.AnilistId, &status, nil, &repeat, &anime.StartedAt, &anime.CompletedAt)
694}
695
630// Function to rate an anime on AniList 696// Function to rate an anime on AniList
631func RateAnime(token string, mediaID int) error { 697func RateAnime(token string, mediaID int) error {
632 var score float64 698 var score float64
@@ -755,6 +821,19 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
755 return "" 821 return ""
756 } 822 }
757 823
824 parseFuzzyDate := func(value interface{}) FuzzyDate {
825 dateMap, ok := value.(map[string]interface{})
826 if !ok || dateMap == nil {
827 return FuzzyDate{}
828 }
829
830 return FuzzyDate{
831 Year: toInt(dateMap["year"]),
832 Month: toInt(dateMap["month"]),
833 Day: toInt(dateMap["day"]),
834 }
835 }
836
758 // Access the list entries in the input map 837 // Access the list entries in the input map
759 if input["data"] == nil { 838 if input["data"] == nil {
760 Log("Anilist request failed") 839 Log("Anilist request failed")
@@ -783,9 +862,12 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
783 }, 862 },
784 Status: safeString(media["status"]), 863 Status: safeString(media["status"]),
785 }, 864 },
786 Progress: toInt(entryData["progress"]), 865 Progress: toInt(entryData["progress"]),
787 Score: entryData["score"].(float64), 866 Repeat: toInt(entryData["repeat"]),
788 Status: safeString(entryData["status"]), // Ensure status is fetched safely 867 Score: entryData["score"].(float64),
868 Status: safeString(entryData["status"]), // Ensure status is fetched safely
869 StartedAt: parseFuzzyDate(entryData["startedAt"]),
870 CompletedAt: parseFuzzyDate(entryData["completedAt"]),
789 } 871 }
790 872
791 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 873 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
@@ -1086,6 +1168,7 @@ func AddAnimeToList(animeID int, status string, token string) error {
1086 "PAUSED": "On Hold", 1168 "PAUSED": "On Hold",
1087 "DROPPED": "Dropped", 1169 "DROPPED": "Dropped",
1088 "PLANNING": "Plan to Watch", 1170 "PLANNING": "Plan to Watch",
1171 "REPEATING": "Rewatching",
1089 } 1172 }
1090 1173
1091 CurdOut(fmt.Sprintf("Anime added to: %s", statusMap[status])) 1174 CurdOut(fmt.Sprintf("Anime added to: %s", statusMap[status]))
internal/curd.go +97 −43
@@ -726,6 +726,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
726 var err error 726 var err error
727 var anilistUserData map[string]interface{} 727 var anilistUserData map[string]interface{}
728 var anilistUserDataPreview map[string]interface{} 728 var anilistUserDataPreview map[string]interface{}
729 var startingRewatch bool
729 730
730 // Filter anime list based on selected category 731 // Filter anime list based on selected category
731 var animeListOptions []SelectionOption 732 var animeListOptions []SelectionOption
@@ -763,6 +764,8 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
763 764
764 // Navigation loop for the entire setup process 765 // Navigation loop for the entire setup process
765 for { 766 for {
767 startingRewatch = false
768
766 // If continueLast flag is set, directly get the last watched anime 769 // If continueLast flag is set, directly get the last watched anime
767 if anime.Ep.ContinueLast { 770 if anime.Ep.ContinueLast {
768 // Get the last anime ID from the curd_id file 771 // Get the last anime ID from the curd_id file
@@ -966,10 +969,47 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
966 anime.Title = selectedAnilistAnime.Media.Title 969 anime.Title = selectedAnilistAnime.Media.Title
967 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes 970 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
968 anime.IsAiring = selectedAnilistAnime.Media.Status == "RELEASING" || selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED" 971 anime.IsAiring = selectedAnilistAnime.Media.Status == "RELEASING" || selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED"
972 anime.Rewatching = selectedAnilistAnime.Status == "REPEATING"
973 anime.Repeat = selectedAnilistAnime.Repeat
974 anime.StartedAt = selectedAnilistAnime.StartedAt
975 anime.CompletedAt = selectedAnilistAnime.CompletedAt
969 anime.Ep.Number = selectedAnilistAnime.Progress + 1 976 anime.Ep.Number = selectedAnilistAnime.Progress + 1
970 var animeList []SelectionOption 977 var animeList []SelectionOption
971 userQuery = anime.Title.Romaji 978 userQuery = anime.Title.Romaji
972 979
980 if selectedAnilistAnime.Status == "COMPLETED" {
981 status := "REPEATING"
982 progress := 0
983 err = SaveAnimeListEntry(user.Token, anime.AnilistId, &status, &progress, nil, &anime.StartedAt, &anime.CompletedAt)
984 if err != nil {
985 Log(fmt.Sprintf("Error starting anime rewatch: %v", err))
986 ExitCurd(fmt.Errorf("Failed to move anime to rewatching"))
987 }
988
989 anime.Rewatching = true
990 anime.Ep.Number = 1
991 anime.Ep.Player.PlaybackTime = 0
992 anime.Ep.Resume = false
993 startingRewatch = true
994 CurdOut("Moved anime to Rewatching and restarting from episode 1.")
995
996 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
997 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
998 if err != nil {
999 Log("Error refreshing anime list: " + err.Error())
1000 ExitCurd(err)
1001 }
1002 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
1003 } else {
1004 anilistUserData, err = GetUserData(user.Token, user.Id)
1005 if err != nil {
1006 Log("Error refreshing anime list: " + err.Error())
1007 ExitCurd(err)
1008 }
1009 user.AnimeList = ParseAnimeList(anilistUserData)
1010 }
1011 }
1012
973 // if anime not found in database, find it in animeList 1013 // if anime not found in database, find it in animeList
974 if animePointer == nil { 1014 if animePointer == nil {
975 Log("Anime not found in database, searching in animeList...") 1015 Log("Anime not found in database, searching in animeList...")
@@ -1013,7 +1053,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1013 matches := malRegex.FindStringSubmatch(option.Thumbnail) 1053 matches := malRegex.FindStringSubmatch(option.Thumbnail)
1014 if len(matches) > 1 { 1054 if len(matches) > 1 {
1015 fileName := matches[1] 1055 fileName := matches[1]
1016 1056
1017 // Fetch Jikan pictures lazily (only once) 1057 // Fetch Jikan pictures lazily (only once)
1018 if !fetchedJikan { 1058 if !fetchedJikan {
1019 if anime.MalId == 0 { 1059 if anime.MalId == 0 {
@@ -1094,6 +1134,11 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1094 } 1134 }
1095 } 1135 }
1096 1136
1137 if startingRewatch {
1138 anime.Ep.Player.PlaybackTime = 0
1139 anime.Ep.Resume = false
1140 }
1141
1097 if selectedAllanimeAnime.Key == "-1" { 1142 if selectedAllanimeAnime.Key == "-1" {
1098 ExitCurd(nil) 1143 ExitCurd(nil)
1099 } 1144 }
@@ -1106,6 +1151,17 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1106 break 1151 break
1107 } 1152 }
1108 } 1153 }
1154 if !isInWatchingList {
1155 for _, entry := range user.AnimeList.Rewatching {
1156 if entry.Media.ID == anime.AnilistId {
1157 isInWatchingList = true
1158 break
1159 }
1160 }
1161 }
1162 if anime.Rewatching {
1163 isInWatchingList = true
1164 }
1109 1165
1110 if !isInWatchingList { 1166 if !isInWatchingList {
1111 // Create options for the prompt 1167 // Create options for the prompt
@@ -1444,7 +1500,10 @@ func getEntriesByCategory(list AnimeList, category string) []Entry {
1444 allEntries = append(allEntries, list.Rewatching...) 1500 allEntries = append(allEntries, list.Rewatching...)
1445 return allEntries 1501 return allEntries
1446 case "CURRENT": 1502 case "CURRENT":
1447 return list.Watching 1503 currentEntries := make([]Entry, 0, len(list.Watching)+len(list.Rewatching))
1504 currentEntries = append(currentEntries, list.Watching...)
1505 currentEntries = append(currentEntries, list.Rewatching...)
1506 return currentEntries
1448 case "COMPLETED": 1507 case "COMPLETED":
1449 return list.Completed 1508 return list.Completed
1450 case "PAUSED": 1509 case "PAUSED":
@@ -1541,15 +1600,12 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string
1541 Log("Error updating local database on quit: " + err.Error()) 1600 Log("Error updating local database on quit: " + err.Error())
1542 } 1601 }
1543 1602
1544 // Update Anilist progress if not rewatching 1603 go func() {
1545 if !anime.Rewatching { 1604 err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number)
1546 go func() { 1605 if err != nil {
1547 err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number) 1606 Log("Error updating Anilist progress on quit: " + err.Error())
1548 if err != nil { 1607 }
1549 Log("Error updating Anilist progress on quit: " + err.Error()) 1608 }()
1550 }
1551 }()
1552 }
1553 1609
1554 CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched)) 1610 CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched))
1555 } else { 1611 } else {
@@ -1571,15 +1627,12 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string
1571 Log("Error updating local database with completed episode: " + err.Error()) 1627 Log("Error updating local database with completed episode: " + err.Error())
1572 } 1628 }
1573 1629
1574 // Update Anilist progress for the completed episode if not rewatching 1630 go func() {
1575 if !anime.Rewatching { 1631 err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number)
1576 go func() { 1632 if err != nil {
1577 err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number) 1633 Log("Error updating Anilist progress: " + err.Error())
1578 if err != nil { 1634 }
1579 Log("Error updating Anilist progress: " + err.Error()) 1635 }()
1580 }
1581 }()
1582 }
1583 1636
1584 // Increment to next episode and update database with next episode number and 0 playback time 1637 // Increment to next episode and update database with next episode number and 0 playback time
1585 anime.Ep.Number++ 1638 anime.Ep.Number++
@@ -1641,14 +1694,11 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
1641 // Handle scoring and completion for the last episode 1694 // Handle scoring and completion for the last episode
1642 HandleLastEpisodeCompletion(userCurdConfig, anime, userToken) 1695 HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
1643 1696
1644 // Update Anilist progress for the last episode if not rewatching 1697 err := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1645 if !anime.Rewatching { 1698 if err != nil {
1646 err := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode) 1699 Log("Error updating Anilist progress: " + err.Error())
1647 if err != nil {
1648 Log("Error updating Anilist progress: " + err.Error())
1649 }
1650 // Note: UpdateAnimeProgress already outputs a message on success
1651 } 1700 }
1701 // Note: UpdateAnimeProgress already outputs a message on success
1652 1702
1653 CurdOut("Series completed!") 1703 CurdOut("Series completed!")
1654 ExitCurd(nil) 1704 ExitCurd(nil)
@@ -1688,15 +1738,12 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
1688 Log("Error updating local database: " + err.Error()) 1738 Log("Error updating local database: " + err.Error())
1689 } 1739 }
1690 1740
1691 // Update Anilist progress for the previous episode if not rewatching 1741 go func() {
1692 if !anime.Rewatching { 1742 err = UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1693 go func() { 1743 if err != nil {
1694 err = UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode) 1744 Log("Error updating Anilist progress: " + err.Error())
1695 if err != nil { 1745 }
1696 Log("Error updating Anilist progress: " + err.Error()) 1746 }()
1697 }
1698 }()
1699 }
1700 1747
1701 // Output message to user 1748 // Output message to user
1702 CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number)) 1749 CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
@@ -1729,14 +1776,21 @@ func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userT
1729 // Back (-2) and no are treated as skip 1776 // Back (-2) and no are treated as skip
1730 } 1777 }
1731 1778
1732 // Update anime status to completed on AniList 1779 // Update anime status to completed on AniList.
1733 // This is done regardless of scoring preference 1780 // For rewatches, preserve the original completion date and only increment repeat count.
1734 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !anime.Rewatching && !anime.IsAiring { 1781 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !anime.IsAiring {
1735 err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED") 1782 if anime.Rewatching {
1736 if err != nil { 1783 err := CompleteAnimeRewatch(userToken, *anime)
1737 Log("Error updating anime status to completed: " + err.Error()) 1784 if err != nil {
1785 Log("Error completing anime rewatch: " + err.Error())
1786 }
1787 } else {
1788 err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED")
1789 if err != nil {
1790 Log("Error updating anime status to completed: " + err.Error())
1791 }
1792 // Note: UpdateAnimeStatus already outputs a message on success
1738 } 1793 }
1739 // Note: UpdateAnimeStatus already outputs a message on success
1740 } 1794 }
1741 1795
1742 // Check for sequel after completion (only if this is the last episode) 1796 // Check for sequel after completion (only if this is the last episode)
internal/structs.go +17 −5
@@ -14,11 +14,20 @@ type Anime struct {
14 MalId int `json:"mal_id"` 14 MalId int `json:"mal_id"`
15 AnilistId int `json:"anilist_id"` // Assuming you have an Anilist ID in your struct 15 AnilistId int `json:"anilist_id"` // Assuming you have an Anilist ID in your struct
16 Rewatching bool 16 Rewatching bool
17 Repeat int
18 StartedAt FuzzyDate
19 CompletedAt FuzzyDate
17 AllanimeId string // Can be populated as necessary 20 AllanimeId string // Can be populated as necessary
18 FillerEpisodes []int 21 FillerEpisodes []int
19 IsAiring bool 22 IsAiring bool
20} 23}
21 24
25type FuzzyDate struct {
26 Year int `json:"year"`
27 Month int `json:"month"`
28 Day int `json:"day"`
29}
30
22type Skip struct { 31type Skip struct {
23 Start int `json:"start"` 32 Start int `json:"start"`
24 End int `json:"end"` 33 End int `json:"end"`
@@ -99,11 +108,14 @@ type Media struct {
99} 108}
100 109
101type Entry struct { 110type Entry struct {
102 Media Media `json:"media"` 111 Media Media `json:"media"`
103 Progress int `json:"progress"` 112 Progress int `json:"progress"`
104 Score float64 `json:"score"` 113 Repeat int `json:"repeat"`
105 Status string `json:"status"` 114 Score float64 `json:"score"`
106 CoverImage string `json:"coverImage"` 115 Status string `json:"status"`
116 StartedAt FuzzyDate `json:"startedAt"`
117 CompletedAt FuzzyDate `json:"completedAt"`
118 CoverImage string `json:"coverImage"`
107} 119}
108 120
109type AnimeList struct { 121type AnimeList struct {