internal/anilist.go

621 lines · 16229 bytes

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