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