internal/anilist.go

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