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