internal/anilist.go
824 lines · 21382 bytes
1package internal
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "os"
10 "path/filepath"
11 "strconv"
12 "strings"
13)
14
15// FindKeyByValue searches for a key associated with a given value in a map[string]string
16func FindKeyByValue(m map[string]string, value string) (string, error) {
17 for key, val := range m {
18 if val == value {
19 return key, nil // Return the key and true if the value is found
20 }
21 }
22 return "", fmt.Errorf("no key with value %v", value) // Return empty string and false if the value is not found
23}
24
25// GetAnimeMap takes an AnimeList and returns a map with media.id as key and media.title.english as value.
26func GetAnimeMap(animeList AnimeList) map[string]string {
27 animeMap := make(map[string]string)
28 userCurdConfig := GetGlobalConfig()
29
30 // Helper function to populate the map from a slice of entries
31 populateMap := func(entries []Entry) {
32 for _, entry := range entries {
33 // Only include entries with a non-empty English title
34
35 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
36 animeMap[strconv.Itoa(entry.Media.ID)] = entry.Media.Title.English
37 } else {
38 animeMap[strconv.Itoa(entry.Media.ID)] = entry.Media.Title.Romaji
39 }
40 }
41 }
42
43 // Populate the map for each category
44 populateMap(animeList.Watching)
45 populateMap(animeList.Completed)
46 populateMap(animeList.Paused)
47 populateMap(animeList.Dropped)
48 populateMap(animeList.Planning)
49
50 return animeMap
51}
52
53// GetAnimeMapPreview takes an AnimeList and returns a map with media.id as key and media.title.english as value.
54func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
55 userCurdConfig := GetGlobalConfig()
56 animeMap := make(map[string]RofiSelectPreview)
57
58 // Helper function to populate the map from a slice of entries
59 populateMap := func(entries []Entry) {
60 for _, entry := range entries {
61 // Only include entries with a non-empty English title
62 Log(fmt.Errorf("AnimeNameLanguage: %v", userCurdConfig.AnimeNameLanguage))
63 if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
64 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
65 Title: entry.Media.Title.English,
66 CoverImage: entry.CoverImage,
67 }
68 } else {
69 animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
70 Title: entry.Media.Title.Romaji,
71 CoverImage: entry.CoverImage,
72 }
73 }
74 }
75 }
76
77 // Populate the map for each category
78 populateMap(animeList.Watching)
79 populateMap(animeList.Completed)
80 populateMap(animeList.Paused)
81 populateMap(animeList.Dropped)
82 populateMap(animeList.Planning)
83
84 return animeMap
85}
86
87// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
88func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPreview, error) {
89 url := "https://graphql.anilist.co"
90
91 queryString := `
92 query ($search: String) {
93 Page(page: 1, perPage: 10) {
94 media(search: $search, type: ANIME) {
95 id
96 title {
97 romaji
98 english
99 native
100 }
101 coverImage {
102 large
103 }
104 }
105 }
106 }`
107
108 variables := map[string]string{"search": query}
109 requestBody, err := json.Marshal(map[string]interface{}{
110 "query": queryString,
111 "variables": variables,
112 })
113 if err != nil {
114 return nil, fmt.Errorf("failed to marshal request body: %w", err)
115 }
116
117 req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
118 if err != nil {
119 return nil, fmt.Errorf("failed to create new request: %w", err)
120 }
121
122 req.Header.Set("Authorization", "Bearer "+token)
123 req.Header.Set("Content-Type", "application/json")
124
125 client := &http.Client{}
126 resp, err := client.Do(req)
127 if err != nil {
128 return nil, fmt.Errorf("failed to make request: %w", err)
129 }
130 defer resp.Body.Close()
131
132 if resp.StatusCode != http.StatusOK {
133 body, _ := io.ReadAll(resp.Body)
134 return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body))
135 }
136
137 body, err := io.ReadAll(resp.Body)
138 if err != nil {
139 return nil, fmt.Errorf("failed to read response body: %w", err)
140 }
141
142 var responseData map[string]ResponseData
143 err = json.Unmarshal(body, &responseData)
144 if err != nil {
145 return nil, fmt.Errorf("failed to unmarshal response: %w", err)
146 }
147
148 animeList := responseData["data"].Page.Media
149 animeDict := make(map[string]RofiSelectPreview)
150
151 // Map titles and cover images to their IDs
152 for _, anime := range animeList {
153 idStr := strconv.Itoa(anime.ID)
154 title := anime.Title.English
155 if title == "" {
156 title = anime.Title.Romaji
157 }
158 animeDict[idStr] = RofiSelectPreview{
159 Title: title,
160 CoverImage: anime.CoverImage.Large,
161 }
162 }
163
164 return animeDict, nil
165}
166
167// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
168func SearchAnimeAnilist(query, token string) (map[string]string, error) {
169 url := "https://graphql.anilist.co"
170
171 queryString := `
172 query ($search: String) {
173 Page(page: 1, perPage: 10) {
174 media(search: $search, type: ANIME) {
175 id
176 title {
177 romaji
178 english
179 native
180 }
181 }
182 }
183 }`
184
185 variables := map[string]string{"search": query}
186 requestBody, err := json.Marshal(map[string]interface{}{
187 "query": queryString,
188 "variables": variables,
189 })
190 if err != nil {
191 return nil, fmt.Errorf("failed to marshal request body: %w", err)
192 }
193
194 req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
195 if err != nil {
196 return nil, fmt.Errorf("failed to create new request: %w", err)
197 }
198
199 req.Header.Set("Authorization", "Bearer "+token)
200 req.Header.Set("Content-Type", "application/json")
201
202 client := &http.Client{}
203 resp, err := client.Do(req)
204 if err != nil {
205 return nil, fmt.Errorf("failed to make request: %w", err)
206 }
207 defer resp.Body.Close()
208
209 if resp.StatusCode != http.StatusOK {
210 body, _ := io.ReadAll(resp.Body)
211 return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body))
212 }
213
214 body, err := io.ReadAll(resp.Body)
215 if err != nil {
216 return nil, fmt.Errorf("failed to read response body: %w", err)
217 }
218
219 var responseData map[string]ResponseData
220 err = json.Unmarshal(body, &responseData)
221 if err != nil {
222 return nil, fmt.Errorf("failed to unmarshal response: %w", err)
223 }
224
225 animeList := responseData["data"].Page.Media
226 animeDict := make(map[string]string)
227
228 // Map titles to their IDs as strings
229 for _, anime := range animeList {
230 idStr := strconv.Itoa(anime.ID) // Convert ID to string
231 if anime.Title.English != "" {
232 animeDict[idStr] = anime.Title.English
233 } else {
234 animeDict[idStr] = anime.Title.Romaji
235 }
236 }
237
238 return animeDict, nil
239}
240
241// Function to get AniList user ID and username
242func GetAnilistUserID(token string) (int, string, error) {
243 url := "https://graphql.anilist.co"
244 query := `
245 query {
246 Viewer {
247 id
248 name
249 }
250 }`
251
252 headers := map[string]string{
253 "Authorization": "Bearer " + token,
254 "Content-Type": "application/json",
255 "Accept": "application/json",
256 }
257
258 response, err := makePostRequest(url, query, nil, headers)
259 if err != nil {
260 return 0, "", err
261 }
262
263 data := response["data"].(map[string]interface{})["Viewer"].(map[string]interface{})
264 userID := int(data["id"].(float64))
265 userName := data["name"].(string)
266
267 return userID, userName, nil
268}
269
270// Function to add an anime to the watching list
271func AddAnimeToWatchingList(animeID int, token string) error {
272 url := "https://graphql.anilist.co"
273 mutation := `
274 mutation ($mediaId: Int) {
275 SaveMediaListEntry (mediaId: $mediaId, status: CURRENT) {
276 id
277 status
278 }
279 }`
280
281 variables := map[string]interface{}{
282 "mediaId": animeID,
283 }
284
285 headers := map[string]string{
286 "Authorization": "Bearer " + token,
287 "Content-Type": "application/json",
288 }
289
290 _, err := makePostRequest(url, mutation, variables, headers)
291 if err != nil {
292 return fmt.Errorf("failed to add anime: %w", err)
293 }
294
295 CurdOut(fmt.Sprintf("Anime with ID %d has been added to your watching list.", animeID))
296 return nil
297}
298
299// Function to get MAL ID using AniList media ID
300func GetAnimeMalID(anilistMediaID int) (int, error) {
301 url := "https://graphql.anilist.co"
302 query := `
303 query ($id: Int) {
304 Media(id: $id) {
305 idMal
306 }
307 }`
308
309 variables := map[string]interface{}{
310 "id": anilistMediaID,
311 }
312
313 response, err := makePostRequest(url, query, variables, nil)
314 if err != nil {
315 return 0, err
316 }
317
318 malID := int(response["data"].(map[string]interface{})["Media"].(map[string]interface{})["idMal"].(float64))
319 return malID, nil
320}
321
322// This function retrieves the MAL ID and cover image URL for an anime from AniList
323func GetAnimeIDAndImage(anilistMediaID int) (int, string, error) {
324 url := "https://graphql.anilist.co"
325 query := `
326 query ($id: Int) {
327 Media(id: $id) {
328 coverImage {
329 large
330 }
331 idMal
332 }
333 }`
334
335 variables := map[string]interface{}{
336 "id": anilistMediaID,
337 }
338
339 response, err := makePostRequest(url, query, variables, nil)
340 if err != nil {
341 return 0, "", err
342 }
343
344 data := response["data"].(map[string]interface{})["Media"].(map[string]interface{})
345 malID := int(data["idMal"].(float64))
346 imageURL := data["coverImage"].(map[string]interface{})["large"].(string)
347
348 return malID, imageURL, nil
349}
350
351// Function to get user data from AniList
352func GetUserData(token string, userID int) (map[string]interface{}, error) {
353 query := fmt.Sprintf(`
354 {
355 MediaListCollection(userId: %d, type: ANIME) {
356 lists {
357 entries {
358 media {
359 id
360 episodes
361 duration
362 title {
363 romaji
364 english
365 native
366 }
367 }
368 status
369 score
370 progress
371 }
372 }
373 }
374 }`, userID)
375
376 headers := map[string]string{
377 "Authorization": "Bearer " + token,
378 "Content-Type": "application/json",
379 }
380
381 response, err := makePostRequest("https://graphql.anilist.co", query, nil, headers)
382 if err != nil {
383 return nil, err
384 }
385
386 return response, nil
387}
388
389func GetUserDataPreview(token string, userID int) (map[string]interface{}, error) {
390 query := fmt.Sprintf(`
391 {
392 MediaListCollection(userId: %d, type: ANIME) {
393 lists {
394 entries {
395 media {
396 id
397 episodes
398 duration
399 coverImage {
400 large
401 }
402 title {
403 romaji
404 english
405 native
406 }
407 }
408 status
409 score
410 progress
411 }
412 }
413 }
414 }`, userID)
415
416 headers := map[string]string{
417 "Authorization": "Bearer " + token,
418 "Content-Type": "application/json",
419 }
420
421 response, err := makePostRequest("https://graphql.anilist.co", query, nil, headers)
422 if err != nil {
423 return nil, err
424 }
425
426 return response, nil
427}
428
429// Function to load a JSON file
430func LoadJSONFile(filePath string) (map[string]interface{}, error) {
431 data, err := os.ReadFile(filepath.Clean(filePath))
432 if err != nil {
433 return nil, fmt.Errorf("failed to read file: %w", err)
434 }
435
436 var jsonData map[string]interface{}
437 err = json.Unmarshal(data, &jsonData)
438 if err != nil {
439 return nil, fmt.Errorf("failed to parse JSON: %w", err)
440 }
441
442 return jsonData, nil
443}
444
445// Function to search for an anime by title in user data
446func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []map[string]interface{} {
447 results := []map[string]interface{}{}
448
449 lists := jsonData["data"].(map[string]interface{})["MediaListCollection"].(map[string]interface{})["lists"].([]interface{})
450 for _, list := range lists {
451 entries := list.(map[string]interface{})["entries"].([]interface{})
452 for _, entry := range entries {
453 media := entry.(map[string]interface{})["media"].(map[string]interface{})
454 romajiTitle := media["title"].(map[string]interface{})["romaji"].(string)
455 englishTitle := media["title"].(map[string]interface{})["english"].(string)
456 episodes := int(media["episodes"].(float64))
457 duration := int(media["duration"].(float64))
458
459 if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) {
460 result := map[string]interface{}{
461 "id": media["id"],
462 "progress": entry.(map[string]interface{})["progress"],
463 "romaji_title": romajiTitle,
464 "english_title": englishTitle,
465 "episodes": episodes,
466 "duration": duration,
467 }
468 results = append(results, result)
469 }
470 }
471 }
472
473 return results
474}
475
476// Function to update anime progress
477func UpdateAnimeProgress(token string, mediaID, progress int) error {
478 url := "https://graphql.anilist.co"
479 query := `
480 mutation($mediaId: Int, $progress: Int) {
481 SaveMediaListEntry(mediaId: $mediaId, progress: $progress) {
482 id
483 progress
484 }
485 }`
486
487 variables := map[string]interface{}{
488 "mediaId": mediaID,
489 "progress": progress,
490 }
491
492 headers := map[string]string{
493 "Authorization": "Bearer " + token,
494 "Content-Type": "application/json",
495 }
496
497 _, err := makePostRequest(url, query, variables, headers)
498 if err != nil {
499 return err
500 }
501
502 CurdOut(fmt.Sprint("Anime progress updated! Latest watched episode: ", progress))
503 return nil
504}
505
506func UpdateAnimeStatus(token string, mediaID int, status string) error {
507 url := "https://graphql.anilist.co"
508 query := `
509 mutation($mediaId: Int, $status: MediaListStatus) {
510 SaveMediaListEntry(mediaId: $mediaId, status: $status) {
511 id
512 status
513 }
514 }`
515
516 variables := map[string]interface{}{
517 "mediaId": mediaID,
518 "status": status,
519 }
520
521 headers := map[string]string{
522 "Authorization": "Bearer " + token,
523 "Content-Type": "application/json",
524 }
525
526 _, err := makePostRequest(url, query, variables, headers)
527 if err != nil {
528 return fmt.Errorf("failed to update anime status: %w", err)
529 }
530
531 statusMap := map[string]string{
532 "CURRENT": "Currently Watching",
533 "COMPLETED": "Completed",
534 "PAUSED": "On Hold",
535 "DROPPED": "Dropped",
536 "PLANNING": "Plan to Watch",
537 }
538
539 CurdOut(fmt.Sprintf("Anime status updated to: %s", statusMap[status]))
540 return nil
541}
542
543// Function to rate an anime on AniList
544func RateAnime(token string, mediaID int) error {
545 var score float64
546 var err error
547
548 userCurdConfig := GetGlobalConfig()
549 if userCurdConfig == nil {
550 return fmt.Errorf("failed to get curd config")
551 }
552
553 if userCurdConfig.RofiSelection {
554 userInput, err := GetUserInputFromRofi("Enter a score for the anime (0-10)")
555 if err != nil {
556 return err
557 }
558 score, err = strconv.ParseFloat(userInput, 64)
559 if err != nil {
560 return err
561 }
562 } else {
563 fmt.Println("Rate this anime: ")
564 fmt.Scanln(&score)
565 }
566
567 url := "https://graphql.anilist.co"
568 query := `
569 mutation($mediaId: Int, $score: Float) {
570 SaveMediaListEntry(mediaId: $mediaId, score: $score) {
571 id
572 mediaId
573 score
574 }
575 }`
576
577 variables := map[string]interface{}{
578 "mediaId": mediaID,
579 "score": score,
580 }
581
582 headers := map[string]string{
583 "Authorization": "Bearer " + token,
584 "Content-Type": "application/json",
585 }
586
587 _, err = makePostRequest(url, query, variables, headers)
588 if err != nil {
589 return err
590 }
591
592 CurdOut(fmt.Sprintf("Successfully rated anime (mediaId: %d) with score: %.2f", mediaID, score))
593 return nil
594}
595
596// Helper function to make POST requests
597func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) {
598 requestBody, err := json.Marshal(map[string]interface{}{
599 "query": query,
600 "variables": variables,
601 })
602 if err != nil {
603 return nil, fmt.Errorf("failed to marshal request body: %w", err)
604 }
605
606 req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
607 if err != nil {
608 return nil, fmt.Errorf("failed to create request: %w", err)
609 }
610
611 req.Header.Set("Content-Type", "application/json") // <-- Important!
612 for key, value := range headers {
613 req.Header.Set(key, value)
614 }
615
616 client := &http.Client{}
617 resp, err := client.Do(req)
618 if err != nil {
619 return nil, fmt.Errorf("failed to send request: %w", err)
620 }
621 defer resp.Body.Close()
622
623 body, err := io.ReadAll(resp.Body)
624 if err != nil {
625 return nil, fmt.Errorf("failed to read response body: %w", err)
626 }
627
628 if resp.StatusCode != http.StatusOK {
629 return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
630 }
631
632 var responseData map[string]interface{}
633 // Unmarshal the response into a map
634 err = json.Unmarshal(body, &responseData)
635 if err != nil {
636 return nil, fmt.Errorf("failed to unmarshal response: %w", err)
637 }
638
639 return responseData, nil
640}
641
642func ParseAnimeList(input map[string]interface{}) AnimeList {
643 var animeList AnimeList
644 userCurdConfig := GetGlobalConfig()
645
646 toInt := func(value interface{}) int {
647 switch v := value.(type) {
648 case int:
649 return v
650 case float64:
651 return int(v) // You could also use int(math.Round(v)) to round
652 default:
653 return 0 // Default value for unexpected types
654 }
655 }
656
657 safeString := func(value interface{}) string {
658 if value == nil {
659 return ""
660 }
661
662 // Attempt to assert the value as a string
663 if str, ok := value.(string); ok {
664 return str
665 }
666
667 // If it's not a string, return an empty string or handle it as needed
668 return ""
669 }
670
671 // Access the list entries in the input map
672 if input["data"] == nil {
673 Log("Anilist request failed")
674 CurdOut("Anilist request failed")
675 ExitCurd(fmt.Errorf("Anilist request failed"))
676 return animeList
677 }
678 data := input["data"].(map[string]interface{})
679 mediaList := data["MediaListCollection"].(map[string]interface{})["lists"].([]interface{})
680
681 for _, list := range mediaList {
682 entries := list.(map[string]interface{})["entries"].([]interface{})
683
684 for _, entry := range entries {
685 entryData := entry.(map[string]interface{})
686 media := entryData["media"].(map[string]interface{})
687 animeEntry := Entry{
688 Media: Media{
689 Duration: toInt(media["duration"]),
690 Episodes: toInt(media["episodes"]),
691 ID: toInt(media["id"]),
692 Title: AnimeTitle{
693 English: safeString(media["title"].(map[string]interface{})["english"]),
694 Romaji: safeString(media["title"].(map[string]interface{})["romaji"]),
695 Japanese: safeString(media["title"].(map[string]interface{})["native"]),
696 },
697 },
698 Progress: toInt(entryData["progress"]),
699 Score: entryData["score"].(float64),
700 Status: safeString(entryData["status"]), // Ensure status is fetched safely
701 }
702
703 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
704 animeEntry.CoverImage = safeString(media["coverImage"].(map[string]interface{})["large"])
705 }
706
707 // Append entries based on their status
708 switch animeEntry.Status {
709 case "CURRENT":
710 animeList.Watching = append(animeList.Watching, animeEntry)
711 case "COMPLETED":
712 animeList.Completed = append(animeList.Completed, animeEntry) // Fix: Ensure Completed list is used
713 case "PAUSED":
714 animeList.Paused = append(animeList.Paused, animeEntry) // Fix: Append to Paused list
715 case "DROPPED":
716 animeList.Dropped = append(animeList.Dropped, animeEntry) // Fix: Append to Dropped list
717 case "PLANNING":
718 animeList.Planning = append(animeList.Planning, animeEntry) // Fix: Append to Planning list
719 }
720 }
721 }
722
723 return animeList
724}
725
726// FindAnimeByID searches for an anime by its ID in the AnimeList
727func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
728 id, err := strconv.Atoi(idStr)
729 if err != nil {
730 return nil, fmt.Errorf("invalid ID format: %s", idStr)
731 }
732
733 // Define a slice of pointers to hold categories
734 categories := [][]Entry{
735 list.Watching,
736 list.Completed,
737 list.Paused,
738 list.Dropped,
739 list.Planning,
740 }
741
742 // Iterate through each category
743 for _, category := range categories {
744 for _, entry := range category {
745 if entry.Media.ID == id {
746 return &entry, nil // Return a pointer to the found entry
747 }
748 }
749 }
750
751 return nil, fmt.Errorf("anime with ID %d not found", id) // Return an error if not found
752}
753
754// FindAnimeByAnilistIDInAnimes searches for an anime by its AniList ID in a slice of Anime
755func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error) {
756 for i := range animes {
757 if animes[i].AnilistId == anilistID {
758 return &animes[i], nil
759 }
760 }
761 return nil, fmt.Errorf("anime with ID %d not found", anilistID)
762}
763
764// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token
765func GetAnimeDataByID(id int, token string) (Anime, error) {
766 url := "https://graphql.anilist.co"
767 query := `
768 query ($id: Int) {
769 Media(id: $id, type: ANIME) {
770 id
771 episodes
772 status
773 nextAiringEpisode {
774 episode
775 }
776 }
777 }`
778
779 variables := map[string]interface{}{
780 "id": id,
781 }
782
783 headers := map[string]string{
784 "Authorization": "Bearer " + token,
785 "Content-Type": "application/json",
786 }
787
788 response, err := makePostRequest(url, query, variables, headers)
789 if err != nil {
790 return Anime{}, fmt.Errorf("failed to get anime data: %w", err)
791 }
792
793 data, ok := response["data"].(map[string]interface{})
794 if !ok {
795 return Anime{}, fmt.Errorf("invalid response format: data field missing")
796 }
797
798 media, ok := data["Media"].(map[string]interface{})
799 if !ok {
800 return Anime{}, fmt.Errorf("invalid response format: Media field missing")
801 }
802
803 anime := Anime{
804 AnilistId: id,
805 IsAiring: false,
806 }
807
808 // Safely handle episodes field which might be nil for currently airing shows
809 if episodes, ok := media["episodes"].(float64); ok {
810 anime.TotalEpisodes = int(episodes)
811 }
812
813 // Check status
814 if status, ok := media["status"].(string); ok {
815 anime.IsAiring = status == "RELEASING"
816 }
817
818 // Double check with nextAiringEpisode
819 if nextEp, ok := media["nextAiringEpisode"].(map[string]interface{}); ok && nextEp != nil {
820 anime.IsAiring = true
821 }
822
823 return anime, nil
824}