internal/anilist.go

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