Commit 3ff5478c50

3ff5478c503333d6ac719c3b38cf1ab9271f252d

parent: 65502f0d0e

Unregistered key

chokerman <44473782+justchokingaround@users.noreply.github.com> · 2025-02-14 15:30 UTC
committer: <noreply@github.com>

fix: handle currently airing anime episodes correctly (#37)

* docs: add macOS installation instructions

* 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 (
55 "fmt"
66 "os"
77 "path/filepath"
8 "strconv"
98 "runtime"
9 "strconv"
1010 "sync"
1111 "time"
12
1213 "github.com/wraient/curd/internal"
1314)
1415
@@ -475,7 +476,7 @@ func main() {
475476 }()
476477
477478 // Skip OP and ED and Save MPV Speed
478 skipLoop:
479 skipLoop:
479480 for {
480481 select {
481482 case <-skipLoopDone:
@@ -520,17 +521,24 @@ func main() {
520521 }()
521522
522523 anime.Ep.IsCompleted = false
523 // internal.CurdOut(anime.Ep.Number, anime.TotalEpisodes, &userCurdConfig)
524 if anime.Ep.Number-1 == anime.TotalEpisodes && userCurdConfig.ScoreOnCompletion {
525 anime.Ep.Number = anime.Ep.Number - 1
526 internal.CurdOut("Completed anime.")
527 err = internal.RateAnime(user.Token, anime.AnilistId)
524 // Only mark as complete and prompt for rating if we've reached the total episodes
525 // AND the anime is not currently airing (total episodes > 0)
526 if anime.Ep.Number-1 == anime.TotalEpisodes && userCurdConfig.ScoreOnCompletion && anime.TotalEpisodes > 0 {
527 // Get updated anime data to check if it's still airing
528 updatedAnime, err := internal.GetAnimeDataByID(anime.AnilistId, user.Token)
528529 if err != nil {
529 internal.Log("Error rating anime: "+err.Error(), logFile)
530 internal.CurdOut("Error rating anime: " + err.Error())
530 internal.Log("Error getting updated anime data: "+err.Error(), logFile)
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)
531541 }
532 internal.LocalDeleteAnime(databaseFile, anime.AnilistId, anime.AllanimeId)
533 internal.ExitCurd(nil)
534542 }
535543 }
536544 if anime.Rewatching && anime.Ep.IsCompleted && anime.Ep.Number-1 == anime.TotalEpisodes {
internal/anilist.go +44 −61
@@ -5,7 +5,6 @@ import (
55 "encoding/json"
66 "fmt"
77 "io"
8 "io/ioutil"
98 "net/http"
109 "os"
1110 "path/filepath"
@@ -33,7 +32,7 @@ func GetAnimeMap(animeList AnimeList) map[string]string {
3332 for _, entry := range entries {
3433 // Only include entries with a non-empty English title
3534
36 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
35 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
3736 animeMap[strconv.Itoa(entry.Media.ID)] = entry.Media.Title.English
3837 } else {
3938 animeMap[strconv.Itoa(entry.Media.ID)] = entry.Media.Title.Romaji
@@ -63,12 +62,12 @@ func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
6362 Log(fmt.Sprintf("AnimeNameLanguage: ", userCurdConfig.AnimeNameLanguage), logFile)
6463 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
6564 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
66 Title: entry.Media.Title.English,
65 Title: entry.Media.Title.English,
6766 CoverImage: entry.CoverImage,
6867 }
6968 } else {
7069 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
71 Title: entry.Media.Title.Romaji,
70 Title: entry.Media.Title.Romaji,
7271 CoverImage: entry.CoverImage,
7372 }
7473 }
@@ -459,9 +458,9 @@ func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []m
459458
460459 if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) {
461460 result := map[string]interface{}{
462 "id": media["id"],
463 "progress": entry.(map[string]interface{})["progress"],
464 "romaji_title": romajiTitle,
461 "id": media["id"],
462 "progress": entry.(map[string]interface{})["progress"],
463 "romaji_title": romajiTitle,
465464 "english_title": englishTitle,
466465 "episodes": episodes,
467466 "duration": duration,
@@ -609,7 +608,7 @@ func makePostRequest(url, query string, variables map[string]interface{}, header
609608 return nil, fmt.Errorf("failed to create request: %w", err)
610609 }
611610
612 req.Header.Set("Content-Type", "application/json") // <-- Important!
611 req.Header.Set("Content-Type", "application/json") // <-- Important!
613612 for key, value := range headers {
614613 req.Header.Set(key, value)
615614 }
@@ -691,9 +690,9 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
691690 Episodes: toInt(media["episodes"]),
692691 ID: toInt(media["id"]),
693692 Title: AnimeTitle{
694 English: safeString(media["title"].(map[string]interface{})["english"]),
695 Romaji: safeString(media["title"].(map[string]interface{})["romaji"]),
696 Japanese: safeString(media["title"].(map[string]interface{})["native"]),
693 English: safeString(media["title"].(map[string]interface{})["english"]),
694 Romaji: safeString(media["title"].(map[string]interface{})["romaji"]),
695 Japanese: safeString(media["title"].(map[string]interface{})["native"]),
697696 },
698697 },
699698 Progress: toInt(entryData["progress"]),
@@ -763,78 +762,62 @@ func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error)
763762}
764763
765764// 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"
767767 query := `
768768 query ($id: Int) {
769 Media (id: $id, type: ANIME) {
769 Media(id: $id, type: ANIME) {
770770 id
771 title {
772 romaji
773 english
774 native
775 }
776771 episodes
777 duration
778772 status
773 nextAiringEpisode {
774 episode
775 }
779776 }
780 }
781 `
782
777 }`
778
783779 variables := map[string]interface{}{
784 "id": anilistID,
780 "id": id,
785781 }
786782
787 jsonValue, _ := json.Marshal(map[string]interface{}{
788 "query": query,
789 "variables": variables,
790 })
783 headers := map[string]string{
784 "Authorization": "Bearer " + token,
785 "Content-Type": "application/json",
786 }
791787
792 req, err := http.NewRequest("POST", "https://graphql.anilist.co", bytes.NewBuffer(jsonValue))
788 response, err := makePostRequest(url, query, variables, headers)
793789 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)
795791 }
796792
797 req.Header.Set("Content-Type", "application/json")
798 req.Header.Set("Authorization", "Bearer "+token)
793 data, ok := response["data"].(map[string]interface{})
794 if !ok {
795 return Anime{}, fmt.Errorf("invalid response format: data field missing")
796 }
799797
800 client := &http.Client{}
801 resp, err := client.Do(req)
802 if err != nil {
803 return Anime{}, fmt.Errorf("error sending request: %v", err)
798 media, ok := data["Media"].(map[string]interface{})
799 if !ok {
800 return Anime{}, fmt.Errorf("invalid response format: Media field missing")
804801 }
805 defer resp.Body.Close()
806802
807 body, err := ioutil.ReadAll(resp.Body)
808 if err != nil {
809 return Anime{}, fmt.Errorf("error reading response: %v", err)
803 anime := Anime{
804 AnilistId: id,
805 IsAiring: false,
810806 }
811807
812 var result struct {
813 Data struct {
814 Media struct {
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"`
808 // Safely handle episodes field which might be nil for currently airing shows
809 if episodes, ok := media["episodes"].(float64); ok {
810 anime.TotalEpisodes = int(episodes)
827811 }
828812
829 if err := json.Unmarshal(body, &result); err != nil {
830 return Anime{}, fmt.Errorf("error unmarshaling JSON: %v", err)
813 // Check status
814 if status, ok := media["status"].(string); ok {
815 anime.IsAiring = status == "RELEASING"
831816 }
832817
833 anime := Anime{
834 AnilistId: result.Data.Media.ID,
835 Title: result.Data.Media.Title,
836 TotalEpisodes: result.Data.Media.Episodes,
837 CoverImage: result.Data.Media.CoverImage.Large,
818 // Double check with nextAiringEpisode
819 if nextEp, ok := media["nextAiringEpisode"].(map[string]interface{}); ok && nextEp != nil {
820 anime.IsAiring = true
838821 }
839822
840823 return anime, nil
internal/structs.go +13 −12
@@ -7,15 +7,16 @@ type AnimeTitle struct {
77}
88
99type Anime struct {
10 Title AnimeTitle `json:"title"`
11 Ep Episode `json:"ep"`
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
14 MalId int `json:"mal_id"`
15 AnilistId int `json:"anilist_id"` // Assuming you have an Anilist ID in your struct
16 Rewatching bool
17 AllanimeId string // Can be populated as necessary
18 FillerEpisodes []int
10 Title AnimeTitle `json:"title"`
11 Ep Episode `json:"ep"`
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
14 MalId int `json:"mal_id"`
15 AnilistId int `json:"anilist_id"` // Assuming you have an Anilist ID in your struct
16 Rewatching bool
17 AllanimeId string // Can be populated as necessary
18 FillerEpisodes []int
19 IsAiring bool
1920}
2021
2122type Skip struct {
@@ -37,7 +38,7 @@ type Episode struct {
3738 Started bool `json:"started"`
3839 Duration int `json:"duration"`
3940 Links []string `json:"links"`
40 NextEpisode NextEpisode `json:"next_episode"`
41 NextEpisode NextEpisode `json:"next_episode"`
4142 IsFiller bool `json:"filler"`
4243 IsRecap bool `json:"recap"`
4344 Aired string `json:"aired"`
@@ -48,8 +49,8 @@ type Episode struct {
4849}
4950
5051type NextEpisode struct {
51 Number int
52 Links []string
52 Number int
53 Links []string
5354}
5455
5556type playingVideo struct {