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