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