internal/anilist.go

622 lines · 16319 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, score float64) error {
353	url := "https://graphql.anilist.co"
354	query := `
355	mutation($mediaId: Int, $score: Float) {
356		SaveMediaListEntry(mediaId: $mediaId, score: $score) {
357			id
358			mediaId
359			score
360		}
361	}`
362
363	variables := map[string]interface{}{
364		"mediaId": mediaID,
365		"score":   score,
366	}
367
368	headers := map[string]string{
369		"Authorization": "Bearer " + token,
370		"Content-Type":  "application/json",
371	}
372
373	_, err := makePostRequest(url, query, variables, headers)
374	if err != nil {
375		return err
376	}
377
378	CurdOut(fmt.Sprintf("Successfully rated anime (mediaId: %d) with score: %.2f", mediaID, score))
379	return nil
380}
381
382// Helper function to make POST requests
383func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) {
384	requestBody, err := json.Marshal(map[string]interface{}{
385		"query":     query,
386		"variables": variables,
387	})
388	if err != nil {
389		return nil, fmt.Errorf("failed to marshal request body: %w", err)
390	}
391
392	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
393	if err != nil {
394		return nil, fmt.Errorf("failed to create request: %w", err)
395	}
396
397	req.Header.Set("Content-Type", "application/json")  // <-- Important!
398	for key, value := range headers {
399		req.Header.Set(key, value)
400	}
401
402	client := &http.Client{}
403	resp, err := client.Do(req)
404	if err != nil {
405		return nil, fmt.Errorf("failed to send request: %w", err)
406	}
407	defer resp.Body.Close()
408
409	body, err := io.ReadAll(resp.Body)
410	if err != nil {
411		return nil, fmt.Errorf("failed to read response body: %w", err)
412	}
413
414	if resp.StatusCode != http.StatusOK {
415		return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
416	}
417
418	var responseData map[string]interface{}
419	// Unmarshal the response into a map
420	err = json.Unmarshal(body, &responseData)
421	if err != nil {
422		return nil, fmt.Errorf("failed to unmarshal response: %w", err)
423	}
424
425	return responseData, nil
426}
427
428func ParseAnimeList(input map[string]interface{}) AnimeList {
429	var animeList AnimeList
430
431	toInt := func(value interface{}) int {
432		switch v := value.(type) {
433		case int:
434			return v
435		case float64:
436			return int(v) // You could also use int(math.Round(v)) to round
437		default:
438			return 0 // Default value for unexpected types
439		}
440	}
441
442	safeString := func(value interface{}) string {
443		if value == nil {
444			return ""
445		}
446
447		// Attempt to assert the value as a string
448		if str, ok := value.(string); ok {
449			return str
450		}
451
452		// If it's not a string, return an empty string or handle it as needed
453		return ""
454	}
455
456	// Access the list entries in the input map
457	if input["data"] == nil {
458		Log("Anilist request failed", logFile)
459		CurdOut("Anilist request failed")
460		ExitCurd(fmt.Errorf("Anilist request failed"))
461		return animeList
462	}
463	data := input["data"].(map[string]interface{})
464	mediaList := data["MediaListCollection"].(map[string]interface{})["lists"].([]interface{})
465
466	for _, list := range mediaList {
467		entries := list.(map[string]interface{})["entries"].([]interface{})
468
469		for _, entry := range entries {
470			entryData := entry.(map[string]interface{})
471			media := entryData["media"].(map[string]interface{})
472
473			animeEntry := Entry{
474				Media: Media{
475					Duration: toInt(media["duration"]),
476					Episodes: toInt(media["episodes"]),
477					ID:       toInt(media["id"]),
478					Title: AnimeTitle{
479						English: safeString(media["title"].(map[string]interface{})["english"]),
480						Romaji:  safeString(media["title"].(map[string]interface{})["romaji"]),
481						Japanese:  safeString(media["title"].(map[string]interface{})["native"]),
482					},
483				},
484				Progress: toInt(entryData["progress"]),
485				Score:    entryData["score"].(float64),
486				Status:   safeString(entryData["status"]), // Ensure status is fetched safely
487			}
488
489			// Append entries based on their status
490			switch animeEntry.Status {
491			case "CURRENT":
492				animeList.Watching = append(animeList.Watching, animeEntry)
493			case "COMPLETED":
494				animeList.Completed = append(animeList.Completed, animeEntry) // Fix: Ensure Completed list is used
495			case "PAUSED":
496				animeList.Paused = append(animeList.Paused, animeEntry) // Fix: Append to Paused list
497			case "DROPPED":
498				animeList.Dropped = append(animeList.Dropped, animeEntry) // Fix: Append to Dropped list
499			case "PLANNING":
500				animeList.Planning = append(animeList.Planning, animeEntry) // Fix: Append to Planning list
501			}
502		}
503	}
504
505	return animeList
506}
507
508// FindAnimeByID searches for an anime by its ID in the AnimeList
509func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
510	id, err := strconv.Atoi(idStr)
511	if err != nil {
512		return nil, fmt.Errorf("invalid ID format: %s", idStr)
513	}
514
515	// Define a slice of pointers to hold categories
516	categories := [][]Entry{
517		list.Watching,
518		list.Completed,
519		list.Paused,
520		list.Dropped,
521		list.Planning,
522	}
523
524	// Iterate through each category
525	for _, category := range categories {
526		for _, entry := range category {
527			if entry.Media.ID == id {
528				return &entry, nil // Return a pointer to the found entry
529			}
530		}
531	}
532
533	return nil, fmt.Errorf("anime with ID %d not found", id) // Return an error if not found
534}
535
536// FindAnimeByAnilistIDInAnimes searches for an anime by its AniList ID in a slice of Anime
537func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error) {
538	for i := range animes {
539		if animes[i].AnilistId == anilistID {
540			return &animes[i], nil
541		}
542	}
543	return nil, fmt.Errorf("anime with ID %d not found", anilistID)
544}
545
546// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token
547func GetAnimeDataByID(anilistID int, token string) (Anime, error) {
548	query := `
549	query ($id: Int) {
550		Media (id: $id, type: ANIME) {
551			id
552			title {
553				romaji
554				english
555				native
556			}
557			episodes
558			duration
559			status
560		}
561	}
562	`
563	
564	variables := map[string]interface{}{
565		"id": anilistID,
566	}
567
568	jsonValue, _ := json.Marshal(map[string]interface{}{
569		"query":     query,
570		"variables": variables,
571	})
572
573	req, err := http.NewRequest("POST", "https://graphql.anilist.co", bytes.NewBuffer(jsonValue))
574	if err != nil {
575		return Anime{}, fmt.Errorf("error creating request: %v", err)
576	}
577
578	req.Header.Set("Content-Type", "application/json")
579	req.Header.Set("Authorization", "Bearer "+token)
580
581	client := &http.Client{}
582	resp, err := client.Do(req)
583	if err != nil {
584		return Anime{}, fmt.Errorf("error sending request: %v", err)
585	}
586	defer resp.Body.Close()
587
588	body, err := ioutil.ReadAll(resp.Body)
589	if err != nil {
590		return Anime{}, fmt.Errorf("error reading response: %v", err)
591	}
592
593	var result struct {
594		Data struct {
595			Media struct {
596				ID          int    `json:"id"`
597				Title       AnimeTitle  `json:"title"`
598				Episodes    int    `json:"episodes"`
599				Duration    int    `json:"duration"`
600				Status      string `json:"status"`
601				CoverImage  struct {
602					Large string `json:"large"`
603				} `json:"coverImage"`
604				Genres       []string `json:"genres"`
605				AverageScore int      `json:"averageScore"`
606			} `json:"Media"`
607		} `json:"data"`
608	}
609
610	if err := json.Unmarshal(body, &result); err != nil {
611		return Anime{}, fmt.Errorf("error unmarshaling JSON: %v", err)
612	}
613
614	anime := Anime{
615		AnilistId:     result.Data.Media.ID,
616		Title:         result.Data.Media.Title,
617		TotalEpisodes: result.Data.Media.Episodes,
618		CoverImage:    result.Data.Media.CoverImage.Large,
619	}
620
621	return anime, nil
622}