internal/anilist.go
1564 lines · 38603 bytes · executable
1package internal
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "os"
10 "path/filepath"
11 "sort"
12 "strconv"
13 "strings"
14 "time"
15)
16
17// FindKeyByValue searches for a key associated with a given value in a map[string]string
18func FindKeyByValue(m map[string]string, value string) (string, error) {
19 for key, val := range m {
20 if val == value {
21 return key, nil // Return the key and true if the value is found
22 }
23 }
24 return "", fmt.Errorf("no key with value %v", value) // Return empty string and false if the value is not found
25}
26
27func 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
46// GetAnimeMap takes an AnimeList and returns a map with media.id as key and media.title.english as value.
47func GetAnimeMap(animeList AnimeList) map[string]string {
48 animeMap := make(map[string]string)
49 userCurdConfig := GetGlobalConfig()
50
51 // Helper function to populate the map from a slice of entries
52 populateMap := func(entries []Entry) {
53 for _, entry := range entries {
54 animeMap[strconv.Itoa(entry.Media.ID)] = mediaDisplayTitle(entry.Media, userCurdConfig)
55 }
56 }
57
58 // Populate the map for each category
59 populateMap(animeList.Watching)
60 populateMap(animeList.Completed)
61 populateMap(animeList.Paused)
62 populateMap(animeList.Dropped)
63 populateMap(animeList.Planning)
64 populateMap(animeList.Rewatching) // Add Rewatching list
65
66 return animeMap
67}
68
69// GetAnimeMapPreview takes an AnimeList and returns a map with media.id as key and media.title.english as value.
70func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
71 userCurdConfig := GetGlobalConfig()
72 animeMap := make(map[string]RofiSelectPreview)
73
74 // Helper function to populate the map from a slice of entries
75 populateMap := func(entries []Entry) {
76 for _, entry := range entries {
77 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
78 Title: mediaDisplayTitle(entry.Media, userCurdConfig),
79 CoverImage: entry.CoverImage,
80 }
81 }
82 }
83
84 // Populate the map for each category
85 populateMap(animeList.Watching)
86 populateMap(animeList.Completed)
87 populateMap(animeList.Paused)
88 populateMap(animeList.Dropped)
89 populateMap(animeList.Planning)
90 populateMap(animeList.Rewatching) // Add Rewatching list
91
92 return animeMap
93}
94
95// fuzzy matching w/ Levenshtein distance
96func levenshtein(a, b string) int {
97 a = strings.ToLower(a)
98 b = strings.ToLower(b)
99 ar, br := []rune(a), []rune(b)
100 alen, blen := len(ar), len(br)
101 if alen == 0 {
102 return blen
103 }
104 if blen == 0 {
105 return alen
106 }
107 matrix := make([][]int, alen+1)
108 for i := range matrix {
109 matrix[i] = make([]int, blen+1)
110 }
111 for i := 0; i <= alen; i++ {
112 matrix[i][0] = i
113 }
114 for j := 0; j <= blen; j++ {
115 matrix[0][j] = j
116 }
117 for i := 1; i <= alen; i++ {
118 for j := 1; j <= blen; j++ {
119 cost := 0
120 if ar[i-1] != br[j-1] {
121 cost = 1
122 }
123 matrix[i][j] = min3(
124 matrix[i-1][j]+1,
125 matrix[i][j-1]+1,
126 matrix[i-1][j-1]+cost,
127 )
128 }
129 }
130 return matrix[alen][blen]
131}
132
133func min3(a, b, c int) int {
134 if a < b && a < c {
135 return a
136 }
137 if b < c {
138 return b
139 }
140 return c
141}
142
143func doAniListSearchRequest(url string, requestBody []byte, token string) ([]byte, error) {
144 token = anilistTokenForAPI(nil, token)
145 for authAttempt := 0; authAttempt < 2; authAttempt++ {
146 body, err := doAniListSearchRequestAttempt(url, requestBody, token)
147 if err == nil {
148 return body, nil
149 }
150 if authAttempt == 0 && isInvalidTokenError(err) {
151 newToken, renewed, renewErr := tryRenewAniListTokenForAPI(token, "invalid token")
152 if renewErr != nil {
153 return nil, renewErr
154 }
155 if renewed {
156 token = newToken
157 continue
158 }
159 }
160 return nil, err
161 }
162
163 return nil, fmt.Errorf("AniList search failed after token renewal")
164}
165
166func doAniListSearchRequestAttempt(url string, requestBody []byte, token string) ([]byte, error) {
167 client := sharedHTTPClient
168 if client == nil {
169 client = &http.Client{Timeout: 15 * time.Second}
170 }
171 for attempt := 0; attempt < 5; attempt++ {
172 req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
173 if err != nil {
174 return nil, fmt.Errorf("failed to create new request: %w", err)
175 }
176 if token != "" {
177 req.Header.Set("Authorization", "Bearer "+token)
178 }
179 req.Header.Set("Content-Type", "application/json")
180
181 resp, err := client.Do(req)
182 if err != nil {
183 return nil, fmt.Errorf("failed to make request: %w", err)
184 }
185
186 body, readErr := io.ReadAll(resp.Body)
187 resp.Body.Close()
188 if readErr != nil {
189 return nil, fmt.Errorf("failed to read response body: %w", readErr)
190 }
191 if resp.StatusCode == http.StatusTooManyRequests {
192 if attempt == 4 {
193 return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body))
194 }
195 time.Sleep(aniListRetryDelay(resp, attempt))
196 continue
197 }
198 if resp.StatusCode != http.StatusOK {
199 return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body))
200 }
201 var envelope map[string]interface{}
202 if err := json.Unmarshal(body, &envelope); err == nil {
203 if rawErrors, exists := envelope["errors"]; exists {
204 errorBody, _ := json.Marshal(rawErrors)
205 return nil, fmt.Errorf("graphql errors: %s", strings.TrimSpace(string(errorBody)))
206 }
207 }
208 return body, nil
209 }
210
211 return nil, fmt.Errorf("AniList search failed after retries")
212}
213
214// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
215func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPreview, error) {
216 url := "https://graphql.anilist.co"
217
218 queryString := `
219 query ($search: String) {
220 Page(page: 1, perPage: 50) {
221 media(search: $search, type: ANIME) {
222 id
223 episodes
224 title {
225 romaji
226 english
227 native
228 }
229 coverImage {
230 large
231 }
232 }
233 }
234 }`
235
236 variables := map[string]string{"search": query}
237 requestBody, err := json.Marshal(map[string]interface{}{
238 "query": queryString,
239 "variables": variables,
240 })
241 if err != nil {
242 return nil, fmt.Errorf("failed to marshal request body: %w", err)
243 }
244
245 body, err := doAniListSearchRequest(url, requestBody, token)
246 if err != nil {
247 return nil, err
248 }
249
250 var responseData map[string]ResponseData
251 err = json.Unmarshal(body, &responseData)
252 if err != nil {
253 return nil, fmt.Errorf("failed to unmarshal response: %w", err)
254 }
255
256 animeList := responseData["data"].Page.Media
257 animeDict := make(map[string]RofiSelectPreview)
258
259 type scoredAnime struct {
260 id string
261 title string
262 cover string
263 episodes int
264 score int
265 }
266 var scored []scoredAnime
267 for _, anime := range animeList {
268 idStr := strconv.Itoa(anime.ID)
269 title := anime.Title.English
270 if title == "" {
271 title = anime.Title.Romaji
272 }
273 cover := anime.CoverImage.Large
274 score := levenshtein(title, query)
275 scored = append(scored, scoredAnime{idStr, title, cover, anime.Episodes, score})
276 }
277 sort.Slice(scored, func(i, j int) bool {
278 return scored[i].score < scored[j].score
279 })
280 for i, s := range scored {
281 if i >= 10 {
282 break
283 }
284 animeDict[s.id] = RofiSelectPreview{
285 Title: FormatAnimeSearchLabel(s.title, s.episodes),
286 CoverImage: s.cover,
287 }
288 }
289 return animeDict, nil
290}
291
292// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
293func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
294 url := "https://graphql.anilist.co"
295
296 queryString := `
297 query ($search: String) {
298 Page(page: 1, perPage: 50) {
299 media(search: $search, type: ANIME) {
300 id
301 episodes
302 title {
303 romaji
304 english
305 native
306 }
307 }
308 }
309 }`
310
311 variables := map[string]string{"search": query}
312 requestBody, err := json.Marshal(map[string]interface{}{
313 "query": queryString,
314 "variables": variables,
315 })
316 if err != nil {
317 return nil, fmt.Errorf("failed to marshal request body: %w", err)
318 }
319
320 body, err := doAniListSearchRequest(url, requestBody, token)
321 if err != nil {
322 return nil, err
323 }
324
325 var responseData map[string]ResponseData
326 err = json.Unmarshal(body, &responseData)
327 if err != nil {
328 return nil, fmt.Errorf("failed to unmarshal response: %w", err)
329 }
330
331 animeList := responseData["data"].Page.Media
332 var results []SelectionOption
333
334 type scoredAnime struct {
335 id string
336 title string
337 episodes int
338 score int
339 }
340 var scored []scoredAnime
341 for _, anime := range animeList {
342 idStr := strconv.Itoa(anime.ID)
343 title := anime.Title.English
344 if title == "" {
345 title = anime.Title.Romaji
346 }
347 score := levenshtein(title, query)
348 scored = append(scored, scoredAnime{idStr, title, anime.Episodes, score})
349 }
350 sort.Slice(scored, func(i, j int) bool {
351 return scored[i].score < scored[j].score
352 })
353 for i, s := range scored {
354 if i >= 10 {
355 break
356 }
357 results = append(results, SelectionOption{
358 Key: s.id,
359 Label: FormatAnimeSearchLabel(s.title, s.episodes),
360 Title: s.title,
361 })
362 }
363 return results, nil
364}
365
366// Function to get AniList user ID and username
367func GetAnilistUserID(token string) (int, string, error) {
368 url := "https://graphql.anilist.co"
369 query := `
370 query {
371 Viewer {
372 id
373 name
374 }
375 }`
376
377 headers := map[string]string{
378 "Content-Type": "application/json",
379 "Accept": "application/json",
380 }
381 if token != "" {
382 headers["Authorization"] = "Bearer " + token
383 }
384
385 response, err := makePostRequest(url, query, nil, headers)
386 if err != nil {
387 return 0, "", err
388 }
389
390 data, ok := response["data"].(map[string]interface{})
391 if !ok {
392 return 0, "", fmt.Errorf("invalid AniList viewer response: data field missing")
393 }
394 viewer, ok := data["Viewer"].(map[string]interface{})
395 if !ok || viewer == nil {
396 return 0, "", fmt.Errorf("invalid AniList viewer response: Viewer field missing")
397 }
398 userIDFloat, ok := viewer["id"].(float64)
399 if !ok {
400 return 0, "", fmt.Errorf("invalid AniList viewer response: id field missing")
401 }
402 userName, _ := viewer["name"].(string)
403 if userName == "" {
404 return 0, "", fmt.Errorf("invalid AniList viewer response: name field missing")
405 }
406
407 return int(userIDFloat), userName, nil
408}
409
410// Function to add an anime to the watching list
411func AddAniListAnimeToWatchingList(animeID int, token string) error {
412 url := "https://graphql.anilist.co"
413 mutation := `
414 mutation ($mediaId: Int) {
415 SaveMediaListEntry (mediaId: $mediaId, status: CURRENT) {
416 id
417 status
418 }
419 }`
420
421 variables := map[string]interface{}{
422 "mediaId": animeID,
423 }
424
425 headers := map[string]string{"Content-Type": "application/json"}
426 if token != "" {
427 headers["Authorization"] = "Bearer " + token
428 }
429
430 _, err := makePostRequest(url, mutation, variables, headers)
431 if err != nil {
432 return fmt.Errorf("failed to add anime: %w", err)
433 }
434
435 CurdOut(fmt.Sprintf("Anime with ID %d has been added to your watching list.", animeID))
436 return nil
437}
438
439// Function to get MAL ID using AniList media ID
440func GetAnimeMalID(anilistMediaID int) (int, error) {
441 url := "https://graphql.anilist.co"
442 query := `
443 query ($id: Int) {
444 Media(id: $id) {
445 idMal
446 }
447 }`
448
449 variables := map[string]interface{}{
450 "id": anilistMediaID,
451 }
452
453 response, err := makePostRequest(url, query, variables, nil)
454 if err != nil {
455 return 0, err
456 }
457
458 data, ok := response["data"].(map[string]interface{})
459 if !ok {
460 return 0, fmt.Errorf("invalid AniList media response: data field missing")
461 }
462 media, ok := data["Media"].(map[string]interface{})
463 if !ok || media == nil {
464 return 0, fmt.Errorf("AniList media %d not found", anilistMediaID)
465 }
466 malID, ok := media["idMal"].(float64)
467 if !ok || malID == 0 {
468 return 0, fmt.Errorf("AniList media %d has no MyAnimeList ID", anilistMediaID)
469 }
470 return int(malID), nil
471}
472
473// This function retrieves the MAL ID and cover image URL for an anime from AniList
474func GetAnimeIDAndImage(anilistMediaID int) (int, string, error) {
475 url := "https://graphql.anilist.co"
476 query := `
477 query ($id: Int) {
478 Media(id: $id) {
479 coverImage {
480 large
481 }
482 idMal
483 }
484 }`
485
486 variables := map[string]interface{}{
487 "id": anilistMediaID,
488 }
489
490 response, err := makePostRequest(url, query, variables, nil)
491 if err != nil {
492 return 0, "", err
493 }
494
495 data, ok := response["data"].(map[string]interface{})
496 if !ok {
497 return 0, "", fmt.Errorf("invalid AniList media response: data field missing")
498 }
499 media, ok := data["Media"].(map[string]interface{})
500 if !ok || media == nil {
501 return 0, "", fmt.Errorf("AniList media %d not found", anilistMediaID)
502 }
503 malID := 0
504 if value, ok := media["idMal"].(float64); ok {
505 malID = int(value)
506 }
507 imageURL := ""
508 if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
509 imageURL = safeAniListString(coverImage["large"])
510 }
511
512 return malID, imageURL, nil
513}
514
515// Function to get user data from AniList
516func GetUserData(token string, userID int) (map[string]interface{}, error) {
517 query := `
518 query ($userId: Int, $type: MediaType) {
519 MediaListCollection(userId: $userId, type: $type) {
520 lists {
521 name
522 isCustomList
523 entries {
524 id
525 media {
526 id
527 idMal
528 episodes
529 duration
530 format
531 title {
532 romaji
533 english
534 native
535 }
536 status
537 }
538 status
539 score
540 progress
541 repeat
542 updatedAt
543 startedAt {
544 year
545 month
546 day
547 }
548 completedAt {
549 year
550 month
551 day
552 }
553 }
554 }
555 }
556 }`
557
558 variables := map[string]interface{}{
559 "userId": userID,
560 "type": "ANIME",
561 }
562
563 headers := map[string]string{"Content-Type": "application/json"}
564 if token != "" {
565 headers["Authorization"] = "Bearer " + token
566 }
567
568 response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers)
569 if err != nil {
570 return nil, err
571 }
572
573 return response, nil
574}
575
576func GetUserDataPreview(token string, userID int) (map[string]interface{}, error) {
577 query := `
578 query ($userId: Int, $type: MediaType) {
579 MediaListCollection(userId: $userId, type: $type) {
580 lists {
581 name
582 isCustomList
583 entries {
584 id
585 media {
586 id
587 idMal
588 episodes
589 duration
590 format
591 coverImage {
592 large
593 }
594 title {
595 romaji
596 english
597 native
598 }
599 status
600 }
601 status
602 score
603 progress
604 repeat
605 updatedAt
606 startedAt {
607 year
608 month
609 day
610 }
611 completedAt {
612 year
613 month
614 day
615 }
616 }
617 }
618 }
619 }`
620
621 variables := map[string]interface{}{
622 "userId": userID,
623 "type": "ANIME",
624 }
625
626 headers := map[string]string{"Content-Type": "application/json"}
627 if token != "" {
628 headers["Authorization"] = "Bearer " + token
629 }
630
631 response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers)
632 if err != nil {
633 return nil, err
634 }
635
636 return response, nil
637}
638
639// Function to load a JSON file
640func LoadJSONFile(filePath string) (map[string]interface{}, error) {
641 data, err := os.ReadFile(filepath.Clean(filePath))
642 if err != nil {
643 return nil, fmt.Errorf("failed to read file: %w", err)
644 }
645
646 var jsonData map[string]interface{}
647 err = json.Unmarshal(data, &jsonData)
648 if err != nil {
649 return nil, fmt.Errorf("failed to parse JSON: %w", err)
650 }
651
652 return jsonData, nil
653}
654
655// Function to search for an anime by title in user data
656func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []map[string]interface{} {
657 results := []map[string]interface{}{}
658
659 data, ok := jsonData["data"].(map[string]interface{})
660 if !ok {
661 return results
662 }
663 collection, ok := data["MediaListCollection"].(map[string]interface{})
664 if !ok {
665 return results
666 }
667 lists, ok := collection["lists"].([]interface{})
668 if !ok {
669 return results
670 }
671 seenMediaIDs := make(map[int]struct{})
672 for _, list := range lists {
673 listMap, ok := list.(map[string]interface{})
674 if !ok {
675 continue
676 }
677 // Custom lists re-export status-list entries and would create search hits twice.
678 if isAniListCustomList(listMap) {
679 continue
680 }
681 entries, ok := listMap["entries"].([]interface{})
682 if !ok {
683 continue
684 }
685 for _, entry := range entries {
686 entryMap, ok := entry.(map[string]interface{})
687 if !ok {
688 continue
689 }
690 media, ok := entryMap["media"].(map[string]interface{})
691 if !ok {
692 continue
693 }
694 title, _ := media["title"].(map[string]interface{})
695 romajiTitle := safeAniListString(title["romaji"])
696 englishTitle := safeAniListString(title["english"])
697 episodes := 0
698 if value, ok := media["episodes"].(float64); ok {
699 episodes = int(value)
700 }
701 duration := 0
702 if value, ok := media["duration"].(float64); ok {
703 duration = int(value)
704 }
705 mediaID := 0
706 switch id := media["id"].(type) {
707 case float64:
708 mediaID = int(id)
709 case int:
710 mediaID = id
711 }
712
713 if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) {
714 if mediaID != 0 {
715 if _, seen := seenMediaIDs[mediaID]; seen {
716 continue
717 }
718 seenMediaIDs[mediaID] = struct{}{}
719 }
720 result := map[string]interface{}{
721 "id": media["id"],
722 "progress": entryMap["progress"],
723 "romaji_title": romajiTitle,
724 "english_title": englishTitle,
725 "episodes": episodes,
726 "duration": duration,
727 }
728 results = append(results, result)
729 }
730 }
731 }
732
733 return results
734}
735
736// Function to update anime progress
737func UpdateAniListAnimeProgress(token string, mediaID, progress int) error {
738 err := SaveAniListAnimeListEntry(token, mediaID, nil, &progress, nil, nil, nil, nil)
739 if err != nil {
740 return err
741 }
742
743 CurdOut(fmt.Sprint("Anime progress updated! Latest watched episode: ", progress))
744 return nil
745}
746
747func UpdateAniListAnimeStatus(token string, mediaID int, status string) error {
748 err := SaveAniListAnimeListEntry(token, mediaID, &status, nil, nil, nil, nil, nil)
749 if err != nil {
750 return fmt.Errorf("failed to update anime status: %w", err)
751 }
752
753 statusMap := map[string]string{
754 "CURRENT": "Currently Watching",
755 "COMPLETED": "Completed",
756 "PAUSED": "On Hold",
757 "DROPPED": "Dropped",
758 "PLANNING": "Plan to Watch",
759 "REPEATING": "Rewatching",
760 }
761
762 CurdOut(fmt.Sprintf("Anime status updated to: %s", statusMap[status]))
763 return nil
764}
765
766func SaveAniListAnimeListEntry(token string, mediaID int, status *string, progress *int, repeat *int, score *float64, startedAt *FuzzyDate, completedAt *FuzzyDate) error {
767 url := "https://graphql.anilist.co"
768 query := `
769 mutation(
770 $mediaId: Int
771 $status: MediaListStatus
772 $progress: Int
773 $repeat: Int
774 $score: Float
775 $startedAt: FuzzyDateInput
776 $completedAt: FuzzyDateInput
777 ) {
778 SaveMediaListEntry(
779 mediaId: $mediaId
780 status: $status
781 progress: $progress
782 repeat: $repeat
783 score: $score
784 startedAt: $startedAt
785 completedAt: $completedAt
786 ) {
787 id
788 status
789 progress
790 repeat
791 startedAt {
792 year
793 month
794 day
795 }
796 completedAt {
797 year
798 month
799 day
800 }
801 }
802 }`
803
804 variables := map[string]interface{}{
805 "mediaId": mediaID,
806 }
807 if status != nil {
808 variables["status"] = *status
809 }
810 if progress != nil {
811 variables["progress"] = *progress
812 }
813 if repeat != nil {
814 variables["repeat"] = *repeat
815 }
816 if score != nil {
817 variables["score"] = *score
818 }
819 if startedAt != nil {
820 if startedAt.Year == 0 && startedAt.Month == 0 && startedAt.Day == 0 {
821 variables["startedAt"] = nil
822 } else {
823 variables["startedAt"] = map[string]int{
824 "year": startedAt.Year,
825 "month": startedAt.Month,
826 "day": startedAt.Day,
827 }
828 }
829 }
830 if completedAt != nil {
831 if completedAt.Year == 0 && completedAt.Month == 0 && completedAt.Day == 0 {
832 variables["completedAt"] = nil
833 } else {
834 variables["completedAt"] = map[string]int{
835 "year": completedAt.Year,
836 "month": completedAt.Month,
837 "day": completedAt.Day,
838 }
839 }
840 }
841
842 headers := map[string]string{
843 "Authorization": "Bearer " + token,
844 "Content-Type": "application/json",
845 }
846
847 _, err := makePostRequest(url, query, variables, headers)
848 if err != nil {
849 return err
850 }
851 return nil
852}
853
854func CompleteAniListAnimeRewatch(token string, anime Anime) error {
855 status := "COMPLETED"
856 progress := anime.Ep.Number
857 repeat := anime.Repeat + 1
858 completedAt := currentFuzzyDate()
859 startedAt := anime.StartedAt
860 if startedAt == (FuzzyDate{}) {
861 startedAt = completedAt
862 }
863 return SaveAniListAnimeListEntry(token, anime.AnilistId, &status, &progress, &repeat, nil, &startedAt, &completedAt)
864}
865
866// Function to rate an anime on AniList
867func RateAniListAnime(token string, mediaID int) error {
868 score, err := promptAnimeScoreValue()
869 if err != nil {
870 return err
871 }
872 return saveAniListAnimeScore(token, mediaID, score)
873}
874
875func saveAniListAnimeScore(token string, mediaID int, score float64) error {
876 url := "https://graphql.anilist.co"
877 query := `
878 mutation($mediaId: Int, $score: Float) {
879 SaveMediaListEntry(mediaId: $mediaId, score: $score) {
880 id
881 mediaId
882 score
883 }
884 }`
885
886 variables := map[string]interface{}{
887 "mediaId": mediaID,
888 "score": score,
889 }
890
891 headers := map[string]string{
892 "Authorization": "Bearer " + token,
893 "Content-Type": "application/json",
894 }
895
896 _, err := makePostRequest(url, query, variables, headers)
897 if err != nil {
898 return err
899 }
900
901 CurdOut(fmt.Sprintf("Successfully rated anime (mediaId: %d) with score: %.2f", mediaID, score))
902 return nil
903}
904
905func aniListRetryDelay(resp *http.Response, attempt int) time.Duration {
906 if resp != nil {
907 if retryAfter := strings.TrimSpace(resp.Header.Get("Retry-After")); retryAfter != "" {
908 if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds > 0 {
909 return time.Duration(seconds) * time.Second
910 }
911 }
912 }
913
914 return time.Duration(attempt+1) * 2 * time.Second
915}
916
917// Helper function to make POST requests
918func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) {
919 requestBody, err := json.Marshal(map[string]interface{}{
920 "query": query,
921 "variables": variables,
922 })
923 if err != nil {
924 return nil, fmt.Errorf("failed to marshal request body: %w", err)
925 }
926
927 token := ""
928 if headers != nil {
929 if authHeader := headers["Authorization"]; strings.HasPrefix(authHeader, "Bearer ") {
930 token = strings.TrimPrefix(authHeader, "Bearer ")
931 }
932 }
933 token = anilistTokenForAPI(nil, token)
934 if headers == nil && token != "" {
935 headers = map[string]string{"Authorization": "Bearer " + token}
936 } else if headers != nil && token != "" {
937 headers["Authorization"] = "Bearer " + token
938 }
939
940 for authAttempt := 0; authAttempt < 2; authAttempt++ {
941 response, err := makePostRequestAttempt(url, requestBody, headers)
942 if err == nil {
943 return response, nil
944 }
945 if authAttempt == 0 && isInvalidTokenError(err) && token != "" {
946 newToken, renewed, renewErr := tryRenewAniListTokenForAPI(token, "invalid token")
947 if renewErr != nil {
948 return nil, renewErr
949 }
950 if renewed {
951 token = newToken
952 if headers == nil {
953 headers = map[string]string{}
954 }
955 headers["Authorization"] = "Bearer " + newToken
956 continue
957 }
958 }
959 return nil, err
960 }
961
962 return nil, fmt.Errorf("AniList request failed after token renewal")
963}
964
965func makePostRequestAttempt(url string, requestBody []byte, headers map[string]string) (map[string]interface{}, error) {
966 client := sharedHTTPClient
967 if client == nil {
968 client = &http.Client{Timeout: 15 * time.Second}
969 }
970 for attempt := 0; attempt < 5; attempt++ {
971 req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
972 if err != nil {
973 return nil, fmt.Errorf("failed to create request: %w", err)
974 }
975
976 req.Header.Set("Content-Type", "application/json")
977 for key, value := range headers {
978 req.Header.Set(key, value)
979 }
980
981 resp, err := client.Do(req)
982 if err != nil {
983 return nil, fmt.Errorf("failed to send request: %w", err)
984 }
985
986 body, readErr := io.ReadAll(resp.Body)
987 resp.Body.Close()
988 if readErr != nil {
989 return nil, fmt.Errorf("failed to read response body: %w", readErr)
990 }
991
992 if resp.StatusCode == http.StatusTooManyRequests {
993 if attempt == 4 {
994 return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
995 }
996 time.Sleep(aniListRetryDelay(resp, attempt))
997 continue
998 }
999 if resp.StatusCode != http.StatusOK {
1000 return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
1001 }
1002
1003 var responseData map[string]interface{}
1004 if err := json.Unmarshal(body, &responseData); err != nil {
1005 return nil, fmt.Errorf("failed to unmarshal response: %w", err)
1006 }
1007 if rawErrors, exists := responseData["errors"]; exists {
1008 errorBody, _ := json.Marshal(rawErrors)
1009 return nil, fmt.Errorf("graphql errors: %s", strings.TrimSpace(string(errorBody)))
1010 }
1011
1012 return responseData, nil
1013 }
1014
1015 return nil, fmt.Errorf("AniList request failed after retries")
1016}
1017
1018// isAniListCustomList reports whether a MediaListCollection list is a user custom
1019// list. Custom lists re-export entries that already appear under status lists, so
1020// including them double-counts the same media in Show All / CURRENT.
1021func isAniListCustomList(listData map[string]interface{}) bool {
1022 if listData == nil {
1023 return false
1024 }
1025 if isCustom, ok := listData["isCustomList"].(bool); ok {
1026 return isCustom
1027 }
1028 return false
1029}
1030
1031// dedupeEntriesByMediaID keeps the first occurrence of each non-zero Media.ID.
1032func dedupeEntriesByMediaID(entries []Entry) []Entry {
1033 if len(entries) < 2 {
1034 return entries
1035 }
1036 seen := make(map[int]struct{}, len(entries))
1037 out := make([]Entry, 0, len(entries))
1038 for _, entry := range entries {
1039 id := entry.Media.ID
1040 if id != 0 {
1041 if _, exists := seen[id]; exists {
1042 continue
1043 }
1044 seen[id] = struct{}{}
1045 }
1046 out = append(out, entry)
1047 }
1048 return out
1049}
1050
1051func ParseAnimeList(input map[string]interface{}) AnimeList {
1052 var animeList AnimeList
1053
1054 toInt := func(value interface{}) int {
1055 switch v := value.(type) {
1056 case int:
1057 return v
1058 case float64:
1059 return int(v) // You could also use int(math.Round(v)) to round
1060 default:
1061 return 0 // Default value for unexpected types
1062 }
1063 }
1064
1065 safeString := func(value interface{}) string {
1066 if value == nil {
1067 return ""
1068 }
1069
1070 // Attempt to assert the value as a string
1071 if str, ok := value.(string); ok {
1072 return str
1073 }
1074
1075 // If it's not a string, return an empty string or handle it as needed
1076 return ""
1077 }
1078
1079 parseFuzzyDate := func(value interface{}) FuzzyDate {
1080 dateMap, ok := value.(map[string]interface{})
1081 if !ok || dateMap == nil {
1082 return FuzzyDate{}
1083 }
1084
1085 return FuzzyDate{
1086 Year: toInt(dateMap["year"]),
1087 Month: toInt(dateMap["month"]),
1088 Day: toInt(dateMap["day"]),
1089 }
1090 }
1091
1092 if input == nil {
1093 Log("AniList response is nil")
1094 return animeList
1095 }
1096
1097 // Access the list entries in the input map
1098 if input["data"] == nil {
1099 Log("Anilist request failed")
1100 return animeList
1101 }
1102 data, ok := input["data"].(map[string]interface{})
1103 if !ok {
1104 Log("AniList response data field is invalid")
1105 return animeList
1106 }
1107 collection, ok := data["MediaListCollection"].(map[string]interface{})
1108 if !ok {
1109 Log("AniList response MediaListCollection field is invalid")
1110 return animeList
1111 }
1112 mediaList, ok := collection["lists"].([]interface{})
1113 if !ok {
1114 Log("AniList response lists field is invalid")
1115 return animeList
1116 }
1117
1118 // Prefer status lists; custom lists re-export the same MediaList entries.
1119 seenMediaIDs := make(map[int]struct{})
1120
1121 for _, list := range mediaList {
1122 listData, ok := list.(map[string]interface{})
1123 if !ok {
1124 continue
1125 }
1126 if isAniListCustomList(listData) {
1127 continue
1128 }
1129 entries, ok := listData["entries"].([]interface{})
1130 if !ok {
1131 continue
1132 }
1133
1134 for _, entry := range entries {
1135 entryData, ok := entry.(map[string]interface{})
1136 if !ok {
1137 continue
1138 }
1139 media, ok := entryData["media"].(map[string]interface{})
1140 if !ok {
1141 continue
1142 }
1143 title, _ := media["title"].(map[string]interface{})
1144 animeEntry := Entry{
1145 ListID: toInt(entryData["id"]),
1146 Media: Media{
1147 Duration: toInt(media["duration"]),
1148 Episodes: toInt(media["episodes"]),
1149 Format: safeString(media["format"]),
1150 ID: toInt(media["id"]),
1151 MalID: toInt(media["idMal"]),
1152 Title: AnimeTitle{
1153 English: safeString(title["english"]),
1154 Romaji: safeString(title["romaji"]),
1155 Japanese: safeString(title["native"]),
1156 },
1157 Status: safeString(media["status"]),
1158 },
1159 Progress: toInt(entryData["progress"]),
1160 Repeat: toInt(entryData["repeat"]),
1161 Status: safeString(entryData["status"]), // Ensure status is fetched safely
1162 StartedAt: parseFuzzyDate(entryData["startedAt"]),
1163 CompletedAt: parseFuzzyDate(entryData["completedAt"]),
1164 UpdatedAt: time.Unix(int64(toInt(entryData["updatedAt"])), 0).UTC(),
1165 }
1166 if score, ok := entryData["score"].(float64); ok {
1167 animeEntry.Score = score
1168 }
1169
1170 if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
1171 animeEntry.CoverImage = safeString(coverImage["large"])
1172 }
1173
1174 // Defense in depth: never insert the same media twice even if AniList
1175 // returns the entry under multiple non-custom lists.
1176 if animeEntry.Media.ID != 0 {
1177 if _, exists := seenMediaIDs[animeEntry.Media.ID]; exists {
1178 continue
1179 }
1180 seenMediaIDs[animeEntry.Media.ID] = struct{}{}
1181 }
1182
1183 // Append entries based on their status
1184 switch animeEntry.Status {
1185 case "CURRENT":
1186 animeList.Watching = append(animeList.Watching, animeEntry)
1187 case "COMPLETED":
1188 animeList.Completed = append(animeList.Completed, animeEntry)
1189 case "PAUSED":
1190 animeList.Paused = append(animeList.Paused, animeEntry)
1191 case "DROPPED":
1192 animeList.Dropped = append(animeList.Dropped, animeEntry)
1193 case "PLANNING":
1194 animeList.Planning = append(animeList.Planning, animeEntry)
1195 case "REPEATING": // Anilist uses REPEATING for rewatching
1196 animeList.Rewatching = append(animeList.Rewatching, animeEntry)
1197 }
1198 }
1199 }
1200
1201 return animeList
1202}
1203
1204// FindAnimeByID searches for an anime by its ID in the AnimeList
1205func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
1206 id, err := strconv.Atoi(idStr)
1207 if err != nil {
1208 return nil, fmt.Errorf("invalid ID format: %s", idStr)
1209 }
1210
1211 // Define a slice of pointers to hold categories
1212 categories := [][]Entry{
1213 list.Watching,
1214 list.Completed,
1215 list.Paused,
1216 list.Dropped,
1217 list.Planning,
1218 list.Rewatching, // Add Rewatching list
1219 }
1220
1221 // Iterate through each category
1222 for _, category := range categories {
1223 for _, entry := range category {
1224 if entry.Media.ID == id {
1225 return &entry, nil // Return a pointer to the found entry
1226 }
1227 }
1228 }
1229
1230 return nil, fmt.Errorf("anime with ID %d not found", id) // Return an error if not found
1231}
1232
1233// FindAnimeByAnilistIDInAnimes searches for an anime by its AniList ID in a slice of Anime
1234func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error) {
1235 for i := range animes {
1236 if animes[i].AnilistId == anilistID {
1237 return &animes[i], nil
1238 }
1239 }
1240 return nil, fmt.Errorf("anime with ID %d not found", anilistID)
1241}
1242
1243// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token
1244func GetAnimeDataByID(id int, token string) (Anime, error) {
1245 url := "https://graphql.anilist.co"
1246 query := `
1247 query ($id: Int) {
1248 Media(id: $id, type: ANIME) {
1249 id
1250 idMal
1251 episodes
1252 duration
1253 status
1254 title {
1255 romaji
1256 english
1257 native
1258 }
1259 coverImage {
1260 large
1261 }
1262 nextAiringEpisode {
1263 episode
1264 }
1265 }
1266 }`
1267
1268 variables := map[string]interface{}{
1269 "id": id,
1270 }
1271
1272 headers := map[string]string{"Content-Type": "application/json"}
1273 if token != "" {
1274 headers["Authorization"] = "Bearer " + token
1275 }
1276
1277 response, err := makePostRequest(url, query, variables, headers)
1278 if err != nil {
1279 return Anime{}, fmt.Errorf("failed to get anime data: %w", err)
1280 }
1281
1282 data, ok := response["data"].(map[string]interface{})
1283 if !ok {
1284 return Anime{}, fmt.Errorf("invalid response format: data field missing")
1285 }
1286
1287 media, ok := data["Media"].(map[string]interface{})
1288 if !ok {
1289 return Anime{}, fmt.Errorf("invalid response format: Media field missing")
1290 }
1291
1292 anime := Anime{
1293 AnilistId: id,
1294 IsAiring: false,
1295 }
1296
1297 if malID, ok := media["idMal"].(float64); ok {
1298 anime.MalId = int(malID)
1299 }
1300
1301 // Safely handle episodes field which might be nil for currently airing shows
1302 if episodes, ok := media["episodes"].(float64); ok {
1303 anime.TotalEpisodes = int(episodes)
1304 }
1305 if duration, ok := media["duration"].(float64); ok {
1306 anime.Ep.Duration = int(duration) * 60
1307 }
1308 if title, ok := media["title"].(map[string]interface{}); ok {
1309 anime.Title = AnimeTitle{
1310 Romaji: safeAniListString(title["romaji"]),
1311 English: safeAniListString(title["english"]),
1312 Japanese: safeAniListString(title["native"]),
1313 }
1314 }
1315 if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
1316 anime.CoverImage = safeAniListString(coverImage["large"])
1317 }
1318
1319 // Check status
1320 if status, ok := media["status"].(string); ok {
1321 anime.IsAiring = status == "RELEASING"
1322 }
1323
1324 // Double check with nextAiringEpisode
1325 if nextEp, ok := media["nextAiringEpisode"].(map[string]interface{}); ok && nextEp != nil {
1326 anime.IsAiring = true
1327 }
1328
1329 return anime, nil
1330}
1331
1332// SequelInfo holds information about a sequel anime
1333type SequelInfo struct {
1334 ID int
1335 Title AnimeTitle
1336 CoverImage string
1337 Episodes int
1338 Status string // "FINISHED", "RELEASING", "NOT_YET_RELEASED"
1339 SiteURL string
1340}
1341
1342// GetAnimeSequel fetches sequel information for a given anime from AniList
1343// GetAnimeSequel fetches sequel information for a given anime from AniList
1344func GetAnimeSequel(animeID int, token string) ([]SequelInfo, error) {
1345 url := "https://graphql.anilist.co"
1346 query := `
1347 query ($id: Int) {
1348 Media(id: $id, type: ANIME) {
1349 relations {
1350 edges {
1351 relationType
1352 node {
1353 id
1354 title {
1355 romaji
1356 english
1357 }
1358 coverImage {
1359 large
1360 }
1361 episodes
1362 status
1363 siteUrl
1364 }
1365 }
1366 }
1367 }
1368 }`
1369
1370 variables := map[string]interface{}{
1371 "id": animeID,
1372 }
1373
1374 headers := map[string]string{"Content-Type": "application/json"}
1375 if token != "" {
1376 headers["Authorization"] = "Bearer " + token
1377 }
1378
1379 response, err := makePostRequest(url, query, variables, headers)
1380 if err != nil {
1381 return nil, fmt.Errorf("failed to get anime relations: %w", err)
1382 }
1383
1384 data, ok := response["data"].(map[string]interface{})
1385 if !ok {
1386 return nil, fmt.Errorf("invalid response format: data field missing")
1387 }
1388
1389 media, ok := data["Media"].(map[string]interface{})
1390 if !ok {
1391 return nil, fmt.Errorf("invalid response format: Media field missing")
1392 }
1393
1394 relations, ok := media["relations"].(map[string]interface{})
1395 if !ok {
1396 return nil, nil // No relations found
1397 }
1398
1399 edges, ok := relations["edges"].([]interface{})
1400 if !ok || len(edges) == 0 {
1401 return nil, nil // No edges found
1402 }
1403
1404 var sequels []SequelInfo
1405
1406 // Look for a SEQUEL relation
1407 for _, edge := range edges {
1408 edgeData, ok := edge.(map[string]interface{})
1409 if !ok {
1410 continue
1411 }
1412
1413 relationType, ok := edgeData["relationType"].(string)
1414 if !ok || relationType != "SEQUEL" {
1415 continue
1416 }
1417
1418 node, ok := edgeData["node"].(map[string]interface{})
1419 if !ok {
1420 continue
1421 }
1422
1423 var sequel SequelInfo
1424
1425 // Parse ID
1426 if id, ok := node["id"].(float64); ok {
1427 sequel.ID = int(id)
1428 }
1429
1430 // Parse title
1431 if title, ok := node["title"].(map[string]interface{}); ok {
1432 if romaji, ok := title["romaji"].(string); ok {
1433 sequel.Title.Romaji = romaji
1434 }
1435 if english, ok := title["english"].(string); ok {
1436 sequel.Title.English = english
1437 }
1438 }
1439
1440 // Parse cover image
1441 if coverImage, ok := node["coverImage"].(map[string]interface{}); ok {
1442 if large, ok := coverImage["large"].(string); ok {
1443 sequel.CoverImage = large
1444 }
1445 }
1446
1447 // Parse episodes
1448 if episodes, ok := node["episodes"].(float64); ok {
1449 sequel.Episodes = int(episodes)
1450 }
1451
1452 // Parse status
1453 if status, ok := node["status"].(string); ok {
1454 sequel.Status = status
1455 }
1456
1457 // Parse siteUrl
1458 if siteUrl, ok := node["siteUrl"].(string); ok {
1459 sequel.SiteURL = siteUrl
1460 }
1461
1462 sequels = append(sequels, sequel)
1463 }
1464
1465 if len(sequels) == 0 {
1466 return nil, nil // No sequel found
1467 }
1468
1469 return sequels, nil
1470}
1471
1472// AddAnimeToList adds an anime to a specified list (CURRENT, PLANNING, PAUSED, DROPPED)
1473func AddAniListAnimeToList(animeID int, status string, token string) error {
1474 url := "https://graphql.anilist.co"
1475 mutation := `
1476 mutation ($mediaId: Int, $status: MediaListStatus) {
1477 SaveMediaListEntry (mediaId: $mediaId, status: $status) {
1478 id
1479 status
1480 }
1481 }`
1482
1483 variables := map[string]interface{}{
1484 "mediaId": animeID,
1485 "status": status,
1486 }
1487
1488 headers := map[string]string{
1489 "Authorization": "Bearer " + token,
1490 "Content-Type": "application/json",
1491 }
1492
1493 _, err := makePostRequest(url, mutation, variables, headers)
1494 if err != nil {
1495 return fmt.Errorf("failed to add anime to list: %w", err)
1496 }
1497
1498 statusMap := map[string]string{
1499 "CURRENT": "Currently Watching",
1500 "COMPLETED": "Completed",
1501 "PAUSED": "On Hold",
1502 "DROPPED": "Dropped",
1503 "PLANNING": "Plan to Watch",
1504 "REPEATING": "Rewatching",
1505 }
1506
1507 CurdOut(fmt.Sprintf("Anime added to: %s", statusMap[status]))
1508 return nil
1509}
1510
1511func DeleteAniListListEntry(token string, listID int) error {
1512 url := "https://graphql.anilist.co"
1513 query := `
1514 mutation ($id: Int) {
1515 DeleteMediaListEntry(id: $id) {
1516 deleted
1517 }
1518 }`
1519
1520 headers := map[string]string{"Content-Type": "application/json"}
1521 if token != "" {
1522 headers["Authorization"] = "Bearer " + token
1523 }
1524
1525 _, err := makePostRequest(url, query, map[string]interface{}{"id": listID}, headers)
1526 return err
1527}
1528
1529// FindSequelInAnimeList searches for a sequel in the user's anime list and returns its status
1530func FindSequelInAnimeList(list AnimeList, sequelID int) (string, bool) {
1531 // Check all categories
1532 for _, entry := range list.Watching {
1533 if entry.Media.ID == sequelID {
1534 return "CURRENT", true
1535 }
1536 }
1537 for _, entry := range list.Planning {
1538 if entry.Media.ID == sequelID {
1539 return "PLANNING", true
1540 }
1541 }
1542 for _, entry := range list.Completed {
1543 if entry.Media.ID == sequelID {
1544 return "COMPLETED", true
1545 }
1546 }
1547 for _, entry := range list.Paused {
1548 if entry.Media.ID == sequelID {
1549 return "PAUSED", true
1550 }
1551 }
1552 for _, entry := range list.Dropped {
1553 if entry.Media.ID == sequelID {
1554 return "DROPPED", true
1555 }
1556 }
1557 for _, entry := range list.Rewatching {
1558 if entry.Media.ID == sequelID {
1559 return "REWATCHING", true
1560 }
1561 }
1562
1563 return "", false
1564}