internal/anilist.go
1579 lines · 39023 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 nextAiringEpisode {
538 episode
539 timeUntilAiring
540 }
541 }
542 status
543 score
544 progress
545 repeat
546 updatedAt
547 startedAt {
548 year
549 month
550 day
551 }
552 completedAt {
553 year
554 month
555 day
556 }
557 }
558 }
559 }
560 }`
561
562 variables := map[string]interface{}{
563 "userId": userID,
564 "type": "ANIME",
565 }
566
567 headers := map[string]string{"Content-Type": "application/json"}
568 if token != "" {
569 headers["Authorization"] = "Bearer " + token
570 }
571
572 response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers)
573 if err != nil {
574 return nil, err
575 }
576
577 return response, nil
578}
579
580func GetUserDataPreview(token string, userID int) (map[string]interface{}, error) {
581 query := `
582 query ($userId: Int, $type: MediaType) {
583 MediaListCollection(userId: $userId, type: $type) {
584 lists {
585 name
586 isCustomList
587 entries {
588 id
589 media {
590 id
591 idMal
592 episodes
593 duration
594 format
595 coverImage {
596 large
597 }
598 title {
599 romaji
600 english
601 native
602 }
603 status
604 nextAiringEpisode {
605 episode
606 timeUntilAiring
607 }
608 }
609 status
610 score
611 progress
612 repeat
613 updatedAt
614 startedAt {
615 year
616 month
617 day
618 }
619 completedAt {
620 year
621 month
622 day
623 }
624 }
625 }
626 }
627 }`
628
629 variables := map[string]interface{}{
630 "userId": userID,
631 "type": "ANIME",
632 }
633
634 headers := map[string]string{"Content-Type": "application/json"}
635 if token != "" {
636 headers["Authorization"] = "Bearer " + token
637 }
638
639 response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers)
640 if err != nil {
641 return nil, err
642 }
643
644 return response, nil
645}
646
647// Function to load a JSON file
648func LoadJSONFile(filePath string) (map[string]interface{}, error) {
649 data, err := os.ReadFile(filepath.Clean(filePath))
650 if err != nil {
651 return nil, fmt.Errorf("failed to read file: %w", err)
652 }
653
654 var jsonData map[string]interface{}
655 err = json.Unmarshal(data, &jsonData)
656 if err != nil {
657 return nil, fmt.Errorf("failed to parse JSON: %w", err)
658 }
659
660 return jsonData, nil
661}
662
663// Function to search for an anime by title in user data
664func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []map[string]interface{} {
665 results := []map[string]interface{}{}
666
667 data, ok := jsonData["data"].(map[string]interface{})
668 if !ok {
669 return results
670 }
671 collection, ok := data["MediaListCollection"].(map[string]interface{})
672 if !ok {
673 return results
674 }
675 lists, ok := collection["lists"].([]interface{})
676 if !ok {
677 return results
678 }
679 seenMediaIDs := make(map[int]struct{})
680 for _, list := range lists {
681 listMap, ok := list.(map[string]interface{})
682 if !ok {
683 continue
684 }
685 // Custom lists re-export status-list entries and would create search hits twice.
686 if isAniListCustomList(listMap) {
687 continue
688 }
689 entries, ok := listMap["entries"].([]interface{})
690 if !ok {
691 continue
692 }
693 for _, entry := range entries {
694 entryMap, ok := entry.(map[string]interface{})
695 if !ok {
696 continue
697 }
698 media, ok := entryMap["media"].(map[string]interface{})
699 if !ok {
700 continue
701 }
702 title, _ := media["title"].(map[string]interface{})
703 romajiTitle := safeAniListString(title["romaji"])
704 englishTitle := safeAniListString(title["english"])
705 episodes := 0
706 if value, ok := media["episodes"].(float64); ok {
707 episodes = int(value)
708 }
709 duration := 0
710 if value, ok := media["duration"].(float64); ok {
711 duration = int(value)
712 }
713 mediaID := 0
714 switch id := media["id"].(type) {
715 case float64:
716 mediaID = int(id)
717 case int:
718 mediaID = id
719 }
720
721 if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) {
722 if mediaID != 0 {
723 if _, seen := seenMediaIDs[mediaID]; seen {
724 continue
725 }
726 seenMediaIDs[mediaID] = struct{}{}
727 }
728 result := map[string]interface{}{
729 "id": media["id"],
730 "progress": entryMap["progress"],
731 "romaji_title": romajiTitle,
732 "english_title": englishTitle,
733 "episodes": episodes,
734 "duration": duration,
735 }
736 results = append(results, result)
737 }
738 }
739 }
740
741 return results
742}
743
744// Function to update anime progress
745func UpdateAniListAnimeProgress(token string, mediaID, progress int) error {
746 err := SaveAniListAnimeListEntry(token, mediaID, nil, &progress, nil, nil, nil, nil)
747 if err != nil {
748 return err
749 }
750
751 CurdOut(fmt.Sprint("Anime progress updated! Latest watched episode: ", progress))
752 return nil
753}
754
755func UpdateAniListAnimeStatus(token string, mediaID int, status string) error {
756 err := SaveAniListAnimeListEntry(token, mediaID, &status, nil, nil, nil, nil, nil)
757 if err != nil {
758 return fmt.Errorf("failed to update anime status: %w", err)
759 }
760
761 statusMap := map[string]string{
762 "CURRENT": "Currently Watching",
763 "COMPLETED": "Completed",
764 "PAUSED": "On Hold",
765 "DROPPED": "Dropped",
766 "PLANNING": "Plan to Watch",
767 "REPEATING": "Rewatching",
768 }
769
770 CurdOut(fmt.Sprintf("Anime status updated to: %s", statusMap[status]))
771 return nil
772}
773
774func SaveAniListAnimeListEntry(token string, mediaID int, status *string, progress *int, repeat *int, score *float64, startedAt *FuzzyDate, completedAt *FuzzyDate) error {
775 url := "https://graphql.anilist.co"
776 query := `
777 mutation(
778 $mediaId: Int
779 $status: MediaListStatus
780 $progress: Int
781 $repeat: Int
782 $score: Float
783 $startedAt: FuzzyDateInput
784 $completedAt: FuzzyDateInput
785 ) {
786 SaveMediaListEntry(
787 mediaId: $mediaId
788 status: $status
789 progress: $progress
790 repeat: $repeat
791 score: $score
792 startedAt: $startedAt
793 completedAt: $completedAt
794 ) {
795 id
796 status
797 progress
798 repeat
799 startedAt {
800 year
801 month
802 day
803 }
804 completedAt {
805 year
806 month
807 day
808 }
809 }
810 }`
811
812 variables := map[string]interface{}{
813 "mediaId": mediaID,
814 }
815 if status != nil {
816 variables["status"] = *status
817 }
818 if progress != nil {
819 variables["progress"] = *progress
820 }
821 if repeat != nil {
822 variables["repeat"] = *repeat
823 }
824 if score != nil {
825 variables["score"] = *score
826 }
827 if startedAt != nil {
828 if startedAt.Year == 0 && startedAt.Month == 0 && startedAt.Day == 0 {
829 variables["startedAt"] = nil
830 } else {
831 variables["startedAt"] = map[string]int{
832 "year": startedAt.Year,
833 "month": startedAt.Month,
834 "day": startedAt.Day,
835 }
836 }
837 }
838 if completedAt != nil {
839 if completedAt.Year == 0 && completedAt.Month == 0 && completedAt.Day == 0 {
840 variables["completedAt"] = nil
841 } else {
842 variables["completedAt"] = map[string]int{
843 "year": completedAt.Year,
844 "month": completedAt.Month,
845 "day": completedAt.Day,
846 }
847 }
848 }
849
850 headers := map[string]string{
851 "Authorization": "Bearer " + token,
852 "Content-Type": "application/json",
853 }
854
855 _, err := makePostRequest(url, query, variables, headers)
856 if err != nil {
857 return err
858 }
859 return nil
860}
861
862func CompleteAniListAnimeRewatch(token string, anime Anime) error {
863 status := "COMPLETED"
864 progress := anime.Ep.Number
865 repeat := anime.Repeat + 1
866 completedAt := currentFuzzyDate()
867 startedAt := anime.StartedAt
868 if startedAt == (FuzzyDate{}) {
869 startedAt = completedAt
870 }
871 return SaveAniListAnimeListEntry(token, anime.AnilistId, &status, &progress, &repeat, nil, &startedAt, &completedAt)
872}
873
874// Function to rate an anime on AniList
875func RateAniListAnime(token string, mediaID int) error {
876 score, err := promptAnimeScoreValue()
877 if err != nil {
878 return err
879 }
880 return saveAniListAnimeScore(token, mediaID, score)
881}
882
883func saveAniListAnimeScore(token string, mediaID int, score float64) error {
884 url := "https://graphql.anilist.co"
885 query := `
886 mutation($mediaId: Int, $score: Float) {
887 SaveMediaListEntry(mediaId: $mediaId, score: $score) {
888 id
889 mediaId
890 score
891 }
892 }`
893
894 variables := map[string]interface{}{
895 "mediaId": mediaID,
896 "score": score,
897 }
898
899 headers := map[string]string{
900 "Authorization": "Bearer " + token,
901 "Content-Type": "application/json",
902 }
903
904 _, err := makePostRequest(url, query, variables, headers)
905 if err != nil {
906 return err
907 }
908
909 CurdOut(fmt.Sprintf("Successfully rated anime (mediaId: %d) with score: %.2f", mediaID, score))
910 return nil
911}
912
913func aniListRetryDelay(resp *http.Response, attempt int) time.Duration {
914 if resp != nil {
915 if retryAfter := strings.TrimSpace(resp.Header.Get("Retry-After")); retryAfter != "" {
916 if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds > 0 {
917 return time.Duration(seconds) * time.Second
918 }
919 }
920 }
921
922 return time.Duration(attempt+1) * 2 * time.Second
923}
924
925// Helper function to make POST requests
926func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) {
927 requestBody, err := json.Marshal(map[string]interface{}{
928 "query": query,
929 "variables": variables,
930 })
931 if err != nil {
932 return nil, fmt.Errorf("failed to marshal request body: %w", err)
933 }
934
935 token := ""
936 if headers != nil {
937 if authHeader := headers["Authorization"]; strings.HasPrefix(authHeader, "Bearer ") {
938 token = strings.TrimPrefix(authHeader, "Bearer ")
939 }
940 }
941 token = anilistTokenForAPI(nil, token)
942 if headers == nil && token != "" {
943 headers = map[string]string{"Authorization": "Bearer " + token}
944 } else if headers != nil && token != "" {
945 headers["Authorization"] = "Bearer " + token
946 }
947
948 for authAttempt := 0; authAttempt < 2; authAttempt++ {
949 response, err := makePostRequestAttempt(url, requestBody, headers)
950 if err == nil {
951 return response, nil
952 }
953 if authAttempt == 0 && isInvalidTokenError(err) && token != "" {
954 newToken, renewed, renewErr := tryRenewAniListTokenForAPI(token, "invalid token")
955 if renewErr != nil {
956 return nil, renewErr
957 }
958 if renewed {
959 token = newToken
960 if headers == nil {
961 headers = map[string]string{}
962 }
963 headers["Authorization"] = "Bearer " + newToken
964 continue
965 }
966 }
967 return nil, err
968 }
969
970 return nil, fmt.Errorf("AniList request failed after token renewal")
971}
972
973func makePostRequestAttempt(url string, requestBody []byte, headers map[string]string) (map[string]interface{}, error) {
974 client := sharedHTTPClient
975 if client == nil {
976 client = &http.Client{Timeout: 15 * time.Second}
977 }
978 for attempt := 0; attempt < 5; attempt++ {
979 req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
980 if err != nil {
981 return nil, fmt.Errorf("failed to create request: %w", err)
982 }
983
984 req.Header.Set("Content-Type", "application/json")
985 for key, value := range headers {
986 req.Header.Set(key, value)
987 }
988
989 resp, err := client.Do(req)
990 if err != nil {
991 return nil, fmt.Errorf("failed to send request: %w", err)
992 }
993
994 body, readErr := io.ReadAll(resp.Body)
995 resp.Body.Close()
996 if readErr != nil {
997 return nil, fmt.Errorf("failed to read response body: %w", readErr)
998 }
999
1000 if resp.StatusCode == http.StatusTooManyRequests {
1001 if attempt == 4 {
1002 return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
1003 }
1004 time.Sleep(aniListRetryDelay(resp, attempt))
1005 continue
1006 }
1007 if resp.StatusCode != http.StatusOK {
1008 return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
1009 }
1010
1011 var responseData map[string]interface{}
1012 if err := json.Unmarshal(body, &responseData); err != nil {
1013 return nil, fmt.Errorf("failed to unmarshal response: %w", err)
1014 }
1015 if rawErrors, exists := responseData["errors"]; exists {
1016 errorBody, _ := json.Marshal(rawErrors)
1017 return nil, fmt.Errorf("graphql errors: %s", strings.TrimSpace(string(errorBody)))
1018 }
1019
1020 return responseData, nil
1021 }
1022
1023 return nil, fmt.Errorf("AniList request failed after retries")
1024}
1025
1026// isAniListCustomList reports whether a MediaListCollection list is a user custom
1027// list. Custom lists re-export entries that already appear under status lists, so
1028// including them double-counts the same media in Show All / CURRENT.
1029func isAniListCustomList(listData map[string]interface{}) bool {
1030 if listData == nil {
1031 return false
1032 }
1033 if isCustom, ok := listData["isCustomList"].(bool); ok {
1034 return isCustom
1035 }
1036 return false
1037}
1038
1039// dedupeEntriesByMediaID keeps the first occurrence of each non-zero Media.ID.
1040func dedupeEntriesByMediaID(entries []Entry) []Entry {
1041 if len(entries) < 2 {
1042 return entries
1043 }
1044 seen := make(map[int]struct{}, len(entries))
1045 out := make([]Entry, 0, len(entries))
1046 for _, entry := range entries {
1047 id := entry.Media.ID
1048 if id != 0 {
1049 if _, exists := seen[id]; exists {
1050 continue
1051 }
1052 seen[id] = struct{}{}
1053 }
1054 out = append(out, entry)
1055 }
1056 return out
1057}
1058
1059func ParseAnimeList(input map[string]interface{}) AnimeList {
1060 var animeList AnimeList
1061
1062 toInt := func(value interface{}) int {
1063 switch v := value.(type) {
1064 case int:
1065 return v
1066 case float64:
1067 return int(v) // You could also use int(math.Round(v)) to round
1068 default:
1069 return 0 // Default value for unexpected types
1070 }
1071 }
1072
1073 safeString := func(value interface{}) string {
1074 if value == nil {
1075 return ""
1076 }
1077
1078 // Attempt to assert the value as a string
1079 if str, ok := value.(string); ok {
1080 return str
1081 }
1082
1083 // If it's not a string, return an empty string or handle it as needed
1084 return ""
1085 }
1086
1087 parseFuzzyDate := func(value interface{}) FuzzyDate {
1088 dateMap, ok := value.(map[string]interface{})
1089 if !ok || dateMap == nil {
1090 return FuzzyDate{}
1091 }
1092
1093 return FuzzyDate{
1094 Year: toInt(dateMap["year"]),
1095 Month: toInt(dateMap["month"]),
1096 Day: toInt(dateMap["day"]),
1097 }
1098 }
1099
1100 if input == nil {
1101 Log("AniList response is nil")
1102 return animeList
1103 }
1104
1105 // Access the list entries in the input map
1106 if input["data"] == nil {
1107 Log("Anilist request failed")
1108 return animeList
1109 }
1110 data, ok := input["data"].(map[string]interface{})
1111 if !ok {
1112 Log("AniList response data field is invalid")
1113 return animeList
1114 }
1115 collection, ok := data["MediaListCollection"].(map[string]interface{})
1116 if !ok {
1117 Log("AniList response MediaListCollection field is invalid")
1118 return animeList
1119 }
1120 mediaList, ok := collection["lists"].([]interface{})
1121 if !ok {
1122 Log("AniList response lists field is invalid")
1123 return animeList
1124 }
1125
1126 // Prefer status lists; custom lists re-export the same MediaList entries.
1127 seenMediaIDs := make(map[int]struct{})
1128
1129 for _, list := range mediaList {
1130 listData, ok := list.(map[string]interface{})
1131 if !ok {
1132 continue
1133 }
1134 if isAniListCustomList(listData) {
1135 continue
1136 }
1137 entries, ok := listData["entries"].([]interface{})
1138 if !ok {
1139 continue
1140 }
1141
1142 for _, entry := range entries {
1143 entryData, ok := entry.(map[string]interface{})
1144 if !ok {
1145 continue
1146 }
1147 media, ok := entryData["media"].(map[string]interface{})
1148 if !ok {
1149 continue
1150 }
1151 title, _ := media["title"].(map[string]interface{})
1152 animeEntry := Entry{
1153 ListID: toInt(entryData["id"]),
1154 Media: Media{
1155 Duration: toInt(media["duration"]),
1156 Episodes: toInt(media["episodes"]),
1157 Format: safeString(media["format"]),
1158 ID: toInt(media["id"]),
1159 MalID: toInt(media["idMal"]),
1160 Title: AnimeTitle{
1161 English: safeString(title["english"]),
1162 Romaji: safeString(title["romaji"]),
1163 Japanese: safeString(title["native"]),
1164 },
1165 Status: safeString(media["status"]),
1166 },
1167 Progress: toInt(entryData["progress"]),
1168 Repeat: toInt(entryData["repeat"]),
1169 Status: safeString(entryData["status"]), // Ensure status is fetched safely
1170 StartedAt: parseFuzzyDate(entryData["startedAt"]),
1171 CompletedAt: parseFuzzyDate(entryData["completedAt"]),
1172 UpdatedAt: time.Unix(int64(toInt(entryData["updatedAt"])), 0).UTC(),
1173 }
1174 if score, ok := entryData["score"].(float64); ok {
1175 animeEntry.Score = score
1176 }
1177
1178 if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
1179 animeEntry.CoverImage = safeString(coverImage["large"])
1180 }
1181
1182 if nextEp, ok := media["nextAiringEpisode"].(map[string]interface{}); ok && nextEp != nil {
1183 animeEntry.Media.NextAiringEpisode = &NextAiringEpisodeInfo{
1184 Episode: toInt(nextEp["episode"]),
1185 TimeUntilAiring: toInt(nextEp["timeUntilAiring"]),
1186 }
1187 }
1188
1189 // Defense in depth: never insert the same media twice even if AniList
1190 // returns the entry under multiple non-custom lists.
1191 if animeEntry.Media.ID != 0 {
1192 if _, exists := seenMediaIDs[animeEntry.Media.ID]; exists {
1193 continue
1194 }
1195 seenMediaIDs[animeEntry.Media.ID] = struct{}{}
1196 }
1197
1198 // Append entries based on their status
1199 switch animeEntry.Status {
1200 case "CURRENT":
1201 animeList.Watching = append(animeList.Watching, animeEntry)
1202 case "COMPLETED":
1203 animeList.Completed = append(animeList.Completed, animeEntry)
1204 case "PAUSED":
1205 animeList.Paused = append(animeList.Paused, animeEntry)
1206 case "DROPPED":
1207 animeList.Dropped = append(animeList.Dropped, animeEntry)
1208 case "PLANNING":
1209 animeList.Planning = append(animeList.Planning, animeEntry)
1210 case "REPEATING": // Anilist uses REPEATING for rewatching
1211 animeList.Rewatching = append(animeList.Rewatching, animeEntry)
1212 }
1213 }
1214 }
1215
1216 return animeList
1217}
1218
1219// FindAnimeByID searches for an anime by its ID in the AnimeList
1220func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
1221 id, err := strconv.Atoi(idStr)
1222 if err != nil {
1223 return nil, fmt.Errorf("invalid ID format: %s", idStr)
1224 }
1225
1226 // Define a slice of pointers to hold categories
1227 categories := [][]Entry{
1228 list.Watching,
1229 list.Completed,
1230 list.Paused,
1231 list.Dropped,
1232 list.Planning,
1233 list.Rewatching, // Add Rewatching list
1234 }
1235
1236 // Iterate through each category
1237 for _, category := range categories {
1238 for _, entry := range category {
1239 if entry.Media.ID == id {
1240 return &entry, nil // Return a pointer to the found entry
1241 }
1242 }
1243 }
1244
1245 return nil, fmt.Errorf("anime with ID %d not found", id) // Return an error if not found
1246}
1247
1248// FindAnimeByAnilistIDInAnimes searches for an anime by its AniList ID in a slice of Anime
1249func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error) {
1250 for i := range animes {
1251 if animes[i].AnilistId == anilistID {
1252 return &animes[i], nil
1253 }
1254 }
1255 return nil, fmt.Errorf("anime with ID %d not found", anilistID)
1256}
1257
1258// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token
1259func GetAnimeDataByID(id int, token string) (Anime, error) {
1260 url := "https://graphql.anilist.co"
1261 query := `
1262 query ($id: Int) {
1263 Media(id: $id, type: ANIME) {
1264 id
1265 idMal
1266 episodes
1267 duration
1268 status
1269 title {
1270 romaji
1271 english
1272 native
1273 }
1274 coverImage {
1275 large
1276 }
1277 nextAiringEpisode {
1278 episode
1279 }
1280 }
1281 }`
1282
1283 variables := map[string]interface{}{
1284 "id": id,
1285 }
1286
1287 headers := map[string]string{"Content-Type": "application/json"}
1288 if token != "" {
1289 headers["Authorization"] = "Bearer " + token
1290 }
1291
1292 response, err := makePostRequest(url, query, variables, headers)
1293 if err != nil {
1294 return Anime{}, fmt.Errorf("failed to get anime data: %w", err)
1295 }
1296
1297 data, ok := response["data"].(map[string]interface{})
1298 if !ok {
1299 return Anime{}, fmt.Errorf("invalid response format: data field missing")
1300 }
1301
1302 media, ok := data["Media"].(map[string]interface{})
1303 if !ok {
1304 return Anime{}, fmt.Errorf("invalid response format: Media field missing")
1305 }
1306
1307 anime := Anime{
1308 AnilistId: id,
1309 IsAiring: false,
1310 }
1311
1312 if malID, ok := media["idMal"].(float64); ok {
1313 anime.MalId = int(malID)
1314 }
1315
1316 // Safely handle episodes field which might be nil for currently airing shows
1317 if episodes, ok := media["episodes"].(float64); ok {
1318 anime.TotalEpisodes = int(episodes)
1319 }
1320 if duration, ok := media["duration"].(float64); ok {
1321 anime.Ep.Duration = int(duration) * 60
1322 }
1323 if title, ok := media["title"].(map[string]interface{}); ok {
1324 anime.Title = AnimeTitle{
1325 Romaji: safeAniListString(title["romaji"]),
1326 English: safeAniListString(title["english"]),
1327 Japanese: safeAniListString(title["native"]),
1328 }
1329 }
1330 if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
1331 anime.CoverImage = safeAniListString(coverImage["large"])
1332 }
1333
1334 // Check status
1335 if status, ok := media["status"].(string); ok {
1336 anime.IsAiring = status == "RELEASING"
1337 }
1338
1339 // Double check with nextAiringEpisode
1340 if nextEp, ok := media["nextAiringEpisode"].(map[string]interface{}); ok && nextEp != nil {
1341 anime.IsAiring = true
1342 }
1343
1344 return anime, nil
1345}
1346
1347// SequelInfo holds information about a sequel anime
1348type SequelInfo struct {
1349 ID int
1350 Title AnimeTitle
1351 CoverImage string
1352 Episodes int
1353 Status string // "FINISHED", "RELEASING", "NOT_YET_RELEASED"
1354 SiteURL string
1355}
1356
1357// GetAnimeSequel fetches sequel information for a given anime from AniList
1358// GetAnimeSequel fetches sequel information for a given anime from AniList
1359func GetAnimeSequel(animeID int, token string) ([]SequelInfo, error) {
1360 url := "https://graphql.anilist.co"
1361 query := `
1362 query ($id: Int) {
1363 Media(id: $id, type: ANIME) {
1364 relations {
1365 edges {
1366 relationType
1367 node {
1368 id
1369 title {
1370 romaji
1371 english
1372 }
1373 coverImage {
1374 large
1375 }
1376 episodes
1377 status
1378 siteUrl
1379 }
1380 }
1381 }
1382 }
1383 }`
1384
1385 variables := map[string]interface{}{
1386 "id": animeID,
1387 }
1388
1389 headers := map[string]string{"Content-Type": "application/json"}
1390 if token != "" {
1391 headers["Authorization"] = "Bearer " + token
1392 }
1393
1394 response, err := makePostRequest(url, query, variables, headers)
1395 if err != nil {
1396 return nil, fmt.Errorf("failed to get anime relations: %w", err)
1397 }
1398
1399 data, ok := response["data"].(map[string]interface{})
1400 if !ok {
1401 return nil, fmt.Errorf("invalid response format: data field missing")
1402 }
1403
1404 media, ok := data["Media"].(map[string]interface{})
1405 if !ok {
1406 return nil, fmt.Errorf("invalid response format: Media field missing")
1407 }
1408
1409 relations, ok := media["relations"].(map[string]interface{})
1410 if !ok {
1411 return nil, nil // No relations found
1412 }
1413
1414 edges, ok := relations["edges"].([]interface{})
1415 if !ok || len(edges) == 0 {
1416 return nil, nil // No edges found
1417 }
1418
1419 var sequels []SequelInfo
1420
1421 // Look for a SEQUEL relation
1422 for _, edge := range edges {
1423 edgeData, ok := edge.(map[string]interface{})
1424 if !ok {
1425 continue
1426 }
1427
1428 relationType, ok := edgeData["relationType"].(string)
1429 if !ok || relationType != "SEQUEL" {
1430 continue
1431 }
1432
1433 node, ok := edgeData["node"].(map[string]interface{})
1434 if !ok {
1435 continue
1436 }
1437
1438 var sequel SequelInfo
1439
1440 // Parse ID
1441 if id, ok := node["id"].(float64); ok {
1442 sequel.ID = int(id)
1443 }
1444
1445 // Parse title
1446 if title, ok := node["title"].(map[string]interface{}); ok {
1447 if romaji, ok := title["romaji"].(string); ok {
1448 sequel.Title.Romaji = romaji
1449 }
1450 if english, ok := title["english"].(string); ok {
1451 sequel.Title.English = english
1452 }
1453 }
1454
1455 // Parse cover image
1456 if coverImage, ok := node["coverImage"].(map[string]interface{}); ok {
1457 if large, ok := coverImage["large"].(string); ok {
1458 sequel.CoverImage = large
1459 }
1460 }
1461
1462 // Parse episodes
1463 if episodes, ok := node["episodes"].(float64); ok {
1464 sequel.Episodes = int(episodes)
1465 }
1466
1467 // Parse status
1468 if status, ok := node["status"].(string); ok {
1469 sequel.Status = status
1470 }
1471
1472 // Parse siteUrl
1473 if siteUrl, ok := node["siteUrl"].(string); ok {
1474 sequel.SiteURL = siteUrl
1475 }
1476
1477 sequels = append(sequels, sequel)
1478 }
1479
1480 if len(sequels) == 0 {
1481 return nil, nil // No sequel found
1482 }
1483
1484 return sequels, nil
1485}
1486
1487// AddAnimeToList adds an anime to a specified list (CURRENT, PLANNING, PAUSED, DROPPED)
1488func AddAniListAnimeToList(animeID int, status string, token string) error {
1489 url := "https://graphql.anilist.co"
1490 mutation := `
1491 mutation ($mediaId: Int, $status: MediaListStatus) {
1492 SaveMediaListEntry (mediaId: $mediaId, status: $status) {
1493 id
1494 status
1495 }
1496 }`
1497
1498 variables := map[string]interface{}{
1499 "mediaId": animeID,
1500 "status": status,
1501 }
1502
1503 headers := map[string]string{
1504 "Authorization": "Bearer " + token,
1505 "Content-Type": "application/json",
1506 }
1507
1508 _, err := makePostRequest(url, mutation, variables, headers)
1509 if err != nil {
1510 return fmt.Errorf("failed to add anime to list: %w", err)
1511 }
1512
1513 statusMap := map[string]string{
1514 "CURRENT": "Currently Watching",
1515 "COMPLETED": "Completed",
1516 "PAUSED": "On Hold",
1517 "DROPPED": "Dropped",
1518 "PLANNING": "Plan to Watch",
1519 "REPEATING": "Rewatching",
1520 }
1521
1522 CurdOut(fmt.Sprintf("Anime added to: %s", statusMap[status]))
1523 return nil
1524}
1525
1526func DeleteAniListListEntry(token string, listID int) error {
1527 url := "https://graphql.anilist.co"
1528 query := `
1529 mutation ($id: Int) {
1530 DeleteMediaListEntry(id: $id) {
1531 deleted
1532 }
1533 }`
1534
1535 headers := map[string]string{"Content-Type": "application/json"}
1536 if token != "" {
1537 headers["Authorization"] = "Bearer " + token
1538 }
1539
1540 _, err := makePostRequest(url, query, map[string]interface{}{"id": listID}, headers)
1541 return err
1542}
1543
1544// FindSequelInAnimeList searches for a sequel in the user's anime list and returns its status
1545func FindSequelInAnimeList(list AnimeList, sequelID int) (string, bool) {
1546 // Check all categories
1547 for _, entry := range list.Watching {
1548 if entry.Media.ID == sequelID {
1549 return "CURRENT", true
1550 }
1551 }
1552 for _, entry := range list.Planning {
1553 if entry.Media.ID == sequelID {
1554 return "PLANNING", true
1555 }
1556 }
1557 for _, entry := range list.Completed {
1558 if entry.Media.ID == sequelID {
1559 return "COMPLETED", true
1560 }
1561 }
1562 for _, entry := range list.Paused {
1563 if entry.Media.ID == sequelID {
1564 return "PAUSED", true
1565 }
1566 }
1567 for _, entry := range list.Dropped {
1568 if entry.Media.ID == sequelID {
1569 return "DROPPED", true
1570 }
1571 }
1572 for _, entry := range list.Rewatching {
1573 if entry.Media.ID == sequelID {
1574 return "REWATCHING", true
1575 }
1576 }
1577
1578 return "", false
1579}