Commit 510721859d

510721859da1b85f1c135bad0c319b35f59a0767

parent: f14e379019

Unsigned

justchokingaround <ivanonarch@tutanota.com> · 2025-02-08 19:35 UTC

fix: handle currently airing anime episodes correctly

- Add IsAiring field to track airing status of anime
- Improve GetAnimeDataByID to fetch and handle airing status
- Fix completion logic for currently airing shows

Layout: unified · split

cmd/curd/main.go +19 −11
@@ -5,10 +5,11 @@ import (
5 "fmt" 5 "fmt"
6 "os" 6 "os"
7 "path/filepath" 7 "path/filepath"
8 "strconv"
9 "runtime" 8 "runtime"
9 "strconv"
10 "sync" 10 "sync"
11 "time" 11 "time"
12
12 "github.com/wraient/curd/internal" 13 "github.com/wraient/curd/internal"
13) 14)
14 15
@@ -475,7 +476,7 @@ func main() {
475 }() 476 }()
476 477
477 // Skip OP and ED and Save MPV Speed 478 // Skip OP and ED and Save MPV Speed
478 skipLoop: 479 skipLoop:
479 for { 480 for {
480 select { 481 select {
481 case <-skipLoopDone: 482 case <-skipLoopDone:
@@ -520,17 +521,24 @@ func main() {
520 }() 521 }()
521 522
522 anime.Ep.IsCompleted = false 523 anime.Ep.IsCompleted = false
523 // internal.CurdOut(anime.Ep.Number, anime.TotalEpisodes, &userCurdConfig) 524 // Only mark as complete and prompt for rating if we've reached the total episodes
524 if anime.Ep.Number-1 == anime.TotalEpisodes && userCurdConfig.ScoreOnCompletion { 525 // AND the anime is not currently airing (total episodes > 0)
525 anime.Ep.Number = anime.Ep.Number - 1 526 if anime.Ep.Number-1 == anime.TotalEpisodes && userCurdConfig.ScoreOnCompletion && anime.TotalEpisodes > 0 {
526 internal.CurdOut("Completed anime.") 527 // Get updated anime data to check if it's still airing
527 err = internal.RateAnime(user.Token, anime.AnilistId) 528 updatedAnime, err := internal.GetAnimeDataByID(anime.AnilistId, user.Token)
528 if err != nil { 529 if err != nil {
529 internal.Log("Error rating anime: "+err.Error(), logFile) 530 internal.Log("Error getting updated anime data: "+err.Error(), logFile)
530 internal.CurdOut("Error rating anime: " + err.Error()) 531 } else if !updatedAnime.IsAiring {
532 anime.Ep.Number = anime.Ep.Number - 1
533 internal.CurdOut("Completed anime.")
534 err = internal.RateAnime(user.Token, anime.AnilistId)
535 if err != nil {
536 internal.Log("Error rating anime: "+err.Error(), logFile)
537 internal.CurdOut("Error rating anime: " + err.Error())
538 }
539 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.AllanimeId)
540 internal.ExitCurd(nil)
531 } 541 }
532 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.AllanimeId)
533 internal.ExitCurd(nil)
534 } 542 }
535 } 543 }
536 if anime.Rewatching && anime.Ep.IsCompleted && anime.Ep.Number-1 == anime.TotalEpisodes { 544 if anime.Rewatching && anime.Ep.IsCompleted && anime.Ep.Number-1 == anime.TotalEpisodes {
internal/anilist.go +44 −61
@@ -5,7 +5,6 @@ import (
5 "encoding/json" 5 "encoding/json"
6 "fmt" 6 "fmt"
7 "io" 7 "io"
8 "io/ioutil"
9 "net/http" 8 "net/http"
10 "os" 9 "os"
11 "path/filepath" 10 "path/filepath"
@@ -33,7 +32,7 @@ func GetAnimeMap(animeList AnimeList) map[string]string {
33 for _, entry := range entries { 32 for _, entry := range entries {
34 // Only include entries with a non-empty English title 33 // Only include entries with a non-empty English title
35 34
36 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" { 35 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
37 animeMap[strconv.Itoa(entry.Media.ID)] = entry.Media.Title.English 36 animeMap[strconv.Itoa(entry.Media.ID)] = entry.Media.Title.English
38 } else { 37 } else {
39 animeMap[strconv.Itoa(entry.Media.ID)] = entry.Media.Title.Romaji 38 animeMap[strconv.Itoa(entry.Media.ID)] = entry.Media.Title.Romaji
@@ -63,12 +62,12 @@ func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
63 Log(fmt.Sprintf("AnimeNameLanguage: ", userCurdConfig.AnimeNameLanguage), logFile) 62 Log(fmt.Sprintf("AnimeNameLanguage: ", userCurdConfig.AnimeNameLanguage), logFile)
64 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" { 63 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
65 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{ 64 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
66 Title: entry.Media.Title.English, 65 Title: entry.Media.Title.English,
67 CoverImage: entry.CoverImage, 66 CoverImage: entry.CoverImage,
68 } 67 }
69 } else { 68 } else {
70 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{ 69 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
71 Title: entry.Media.Title.Romaji, 70 Title: entry.Media.Title.Romaji,
72 CoverImage: entry.CoverImage, 71 CoverImage: entry.CoverImage,
73 } 72 }
74 } 73 }
@@ -459,9 +458,9 @@ func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []m
459 458
460 if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) { 459 if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) {
461 result := map[string]interface{}{ 460 result := map[string]interface{}{
462 "id": media["id"], 461 "id": media["id"],
463 "progress": entry.(map[string]interface{})["progress"], 462 "progress": entry.(map[string]interface{})["progress"],
464 "romaji_title": romajiTitle, 463 "romaji_title": romajiTitle,
465 "english_title": englishTitle, 464 "english_title": englishTitle,
466 "episodes": episodes, 465 "episodes": episodes,
467 "duration": duration, 466 "duration": duration,
@@ -609,7 +608,7 @@ func makePostRequest(url, query string, variables map[string]interface{}, header
609 return nil, fmt.Errorf("failed to create request: %w", err) 608 return nil, fmt.Errorf("failed to create request: %w", err)
610 } 609 }
611 610
612 req.Header.Set("Content-Type", "application/json") // <-- Important! 611 req.Header.Set("Content-Type", "application/json") // <-- Important!
613 for key, value := range headers { 612 for key, value := range headers {
614 req.Header.Set(key, value) 613 req.Header.Set(key, value)
615 } 614 }
@@ -691,9 +690,9 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
691 Episodes: toInt(media["episodes"]), 690 Episodes: toInt(media["episodes"]),
692 ID: toInt(media["id"]), 691 ID: toInt(media["id"]),
693 Title: AnimeTitle{ 692 Title: AnimeTitle{
694 English: safeString(media["title"].(map[string]interface{})["english"]), 693 English: safeString(media["title"].(map[string]interface{})["english"]),
695 Romaji: safeString(media["title"].(map[string]interface{})["romaji"]), 694 Romaji: safeString(media["title"].(map[string]interface{})["romaji"]),
696 Japanese: safeString(media["title"].(map[string]interface{})["native"]), 695 Japanese: safeString(media["title"].(map[string]interface{})["native"]),
697 }, 696 },
698 }, 697 },
699 Progress: toInt(entryData["progress"]), 698 Progress: toInt(entryData["progress"]),
@@ -763,78 +762,62 @@ func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error)
763} 762}
764 763
765// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token 764// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token
766func GetAnimeDataByID(anilistID int, token string) (Anime, error) { 765func GetAnimeDataByID(id int, token string) (Anime, error) {
766 url := "https://graphql.anilist.co"
767 query := ` 767 query := `
768 query ($id: Int) { 768 query ($id: Int) {
769 Media (id: $id, type: ANIME) { 769 Media(id: $id, type: ANIME) {
770 id 770 id
771 title {
772 romaji
773 english
774 native
775 }
776 episodes 771 episodes
777 duration
778 status 772 status
773 nextAiringEpisode {
774 episode
775 }
779 } 776 }
780 } 777 }`
781 ` 778
782
783 variables := map[string]interface{}{ 779 variables := map[string]interface{}{
784 "id": anilistID, 780 "id": id,
785 } 781 }
786 782
787 jsonValue, _ := json.Marshal(map[string]interface{}{ 783 headers := map[string]string{
788 "query": query, 784 "Authorization": "Bearer " + token,
789 "variables": variables, 785 "Content-Type": "application/json",
790 }) 786 }
791 787
792 req, err := http.NewRequest("POST", "https://graphql.anilist.co", bytes.NewBuffer(jsonValue)) 788 response, err := makePostRequest(url, query, variables, headers)
793 if err != nil { 789 if err != nil {
794 return Anime{}, fmt.Errorf("error creating request: %v", err) 790 return Anime{}, fmt.Errorf("failed to get anime data: %w", err)
795 } 791 }
796 792
797 req.Header.Set("Content-Type", "application/json") 793 data, ok := response["data"].(map[string]interface{})
798 req.Header.Set("Authorization", "Bearer "+token) 794 if !ok {
795 return Anime{}, fmt.Errorf("invalid response format: data field missing")
796 }
799 797
800 client := &http.Client{} 798 media, ok := data["Media"].(map[string]interface{})
801 resp, err := client.Do(req) 799 if !ok {
802 if err != nil { 800 return Anime{}, fmt.Errorf("invalid response format: Media field missing")
803 return Anime{}, fmt.Errorf("error sending request: %v", err)
804 } 801 }
805 defer resp.Body.Close()
806 802
807 body, err := ioutil.ReadAll(resp.Body) 803 anime := Anime{
808 if err != nil { 804 AnilistId: id,
809 return Anime{}, fmt.Errorf("error reading response: %v", err) 805 IsAiring: false,
810 } 806 }
811 807
812 var result struct { 808 // Safely handle episodes field which might be nil for currently airing shows
813 Data struct { 809 if episodes, ok := media["episodes"].(float64); ok {
814 Media struct { 810 anime.TotalEpisodes = int(episodes)
815 ID int `json:"id"`
816 Title AnimeTitle `json:"title"`
817 Episodes int `json:"episodes"`
818 Duration int `json:"duration"`
819 Status string `json:"status"`
820 CoverImage struct {
821 Large string `json:"large"`
822 } `json:"coverImage"`
823 Genres []string `json:"genres"`
824 AverageScore int `json:"averageScore"`
825 } `json:"Media"`
826 } `json:"data"`
827 } 811 }
828 812
829 if err := json.Unmarshal(body, &result); err != nil { 813 // Check status
830 return Anime{}, fmt.Errorf("error unmarshaling JSON: %v", err) 814 if status, ok := media["status"].(string); ok {
815 anime.IsAiring = status == "RELEASING"
831 } 816 }
832 817
833 anime := Anime{ 818 // Double check with nextAiringEpisode
834 AnilistId: result.Data.Media.ID, 819 if nextEp, ok := media["nextAiringEpisode"].(map[string]interface{}); ok && nextEp != nil {
835 Title: result.Data.Media.Title, 820 anime.IsAiring = true
836 TotalEpisodes: result.Data.Media.Episodes,
837 CoverImage: result.Data.Media.CoverImage.Large,
838 } 821 }
839 822
840 return anime, nil 823 return anime, nil
internal/structs.go +13 −12
@@ -7,15 +7,16 @@ type AnimeTitle struct {
7} 7}
8 8
9type Anime struct { 9type Anime struct {
10 Title AnimeTitle `json:"title"` 10 Title AnimeTitle `json:"title"`
11 Ep Episode `json:"ep"` 11 Ep Episode `json:"ep"`
12 CoverImage string `json:"url"` // Assuming this field corresponds to the cover image URL 12 CoverImage string `json:"url"` // Assuming this field corresponds to the cover image URL
13 TotalEpisodes int `json:"total_episodes"` // If provided by the API 13 TotalEpisodes int `json:"total_episodes"` // If provided by the API
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 AllanimeId string // Can be populated as necessary 17 AllanimeId string // Can be populated as necessary
18 FillerEpisodes []int 18 FillerEpisodes []int
19 IsAiring bool
19} 20}
20 21
21type Skip struct { 22type Skip struct {
@@ -37,7 +38,7 @@ type Episode struct {
37 Started bool `json:"started"` 38 Started bool `json:"started"`
38 Duration int `json:"duration"` 39 Duration int `json:"duration"`
39 Links []string `json:"links"` 40 Links []string `json:"links"`
40 NextEpisode NextEpisode `json:"next_episode"` 41 NextEpisode NextEpisode `json:"next_episode"`
41 IsFiller bool `json:"filler"` 42 IsFiller bool `json:"filler"`
42 IsRecap bool `json:"recap"` 43 IsRecap bool `json:"recap"`
43 Aired string `json:"aired"` 44 Aired string `json:"aired"`
@@ -48,8 +49,8 @@ type Episode struct {
48} 49}
49 50
50type NextEpisode struct { 51type NextEpisode struct {
51 Number int 52 Number int
52 Links []string 53 Links []string
53} 54}
54 55
55type playingVideo struct { 56type playingVideo struct {