internal/anilist.go

800 lines · 20680 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
503// Function to rate an anime on AniList
504func RateAnime(token string, mediaID int) error {
505	var score float64
506	var err error
507
508	userCurdConfig := GetGlobalConfig()
509	if userCurdConfig == nil {
510		return fmt.Errorf("failed to get curd config")
511	}
512
513	if userCurdConfig.RofiSelection {
514		userInput, err := GetUserInputFromRofi("Enter a score for the anime (0-10):")
515		if err != nil {
516			return err
517		}
518		score, err = strconv.ParseFloat(userInput, 64)
519		if err != nil {
520			return err
521		}
522	} else {
523		fmt.Println("Rate this anime: ")
524		fmt.Scanln(&score)
525	}
526
527	url := "https://graphql.anilist.co"
528	query := `
529	mutation($mediaId: Int, $score: Float) {
530		SaveMediaListEntry(mediaId: $mediaId, score: $score) {
531			id
532			mediaId
533			score
534		}
535	}`
536
537	variables := map[string]interface{}{
538		"mediaId": mediaID,
539		"score":   score,
540	}
541
542	headers := map[string]string{
543		"Authorization": "Bearer " + token,
544		"Content-Type":  "application/json",
545	}
546
547	_, err = makePostRequest(url, query, variables, headers)
548	if err != nil {
549		return err
550	}
551
552	CurdOut(fmt.Sprintf("Successfully rated anime (mediaId: %d) with score: %.2f", mediaID, score))
553	return nil
554}
555
556// Helper function to make POST requests
557func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) {
558	requestBody, err := json.Marshal(map[string]interface{}{
559		"query":     query,
560		"variables": variables,
561	})
562	if err != nil {
563		return nil, fmt.Errorf("failed to marshal request body: %w", err)
564	}
565
566	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
567	if err != nil {
568		return nil, fmt.Errorf("failed to create request: %w", err)
569	}
570
571	req.Header.Set("Content-Type", "application/json")  // <-- Important!
572	for key, value := range headers {
573		req.Header.Set(key, value)
574	}
575
576	client := &http.Client{}
577	resp, err := client.Do(req)
578	if err != nil {
579		return nil, fmt.Errorf("failed to send request: %w", err)
580	}
581	defer resp.Body.Close()
582
583	body, err := io.ReadAll(resp.Body)
584	if err != nil {
585		return nil, fmt.Errorf("failed to read response body: %w", err)
586	}
587
588	if resp.StatusCode != http.StatusOK {
589		return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
590	}
591
592	var responseData map[string]interface{}
593	// Unmarshal the response into a map
594	err = json.Unmarshal(body, &responseData)
595	if err != nil {
596		return nil, fmt.Errorf("failed to unmarshal response: %w", err)
597	}
598
599	return responseData, nil
600}
601
602func ParseAnimeList(input map[string]interface{}) AnimeList {
603	var animeList AnimeList
604	userCurdConfig := GetGlobalConfig()
605
606	toInt := func(value interface{}) int {
607		switch v := value.(type) {
608		case int:
609			return v
610		case float64:
611			return int(v) // You could also use int(math.Round(v)) to round
612		default:
613			return 0 // Default value for unexpected types
614		}
615	}
616
617	safeString := func(value interface{}) string {
618		if value == nil {
619			return ""
620		}
621
622		// Attempt to assert the value as a string
623		if str, ok := value.(string); ok {
624			return str
625		}
626
627		// If it's not a string, return an empty string or handle it as needed
628		return ""
629	}
630
631	// Access the list entries in the input map
632	if input["data"] == nil {
633		Log("Anilist request failed", logFile)
634		CurdOut("Anilist request failed")
635		ExitCurd(fmt.Errorf("Anilist request failed"))
636		return animeList
637	}
638	data := input["data"].(map[string]interface{})
639	mediaList := data["MediaListCollection"].(map[string]interface{})["lists"].([]interface{})
640
641	for _, list := range mediaList {
642		entries := list.(map[string]interface{})["entries"].([]interface{})
643
644		for _, entry := range entries {
645			entryData := entry.(map[string]interface{})
646			media := entryData["media"].(map[string]interface{})
647			animeEntry := Entry{
648				Media: Media{
649					Duration: toInt(media["duration"]),
650					Episodes: toInt(media["episodes"]),
651					ID:       toInt(media["id"]),
652					Title: AnimeTitle{
653						English: safeString(media["title"].(map[string]interface{})["english"]),
654						Romaji:  safeString(media["title"].(map[string]interface{})["romaji"]),
655						Japanese:  safeString(media["title"].(map[string]interface{})["native"]),
656					},
657				},
658				Progress: toInt(entryData["progress"]),
659				Score:    entryData["score"].(float64),
660				Status:   safeString(entryData["status"]), // Ensure status is fetched safely
661			}
662
663			if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
664				animeEntry.CoverImage = safeString(media["coverImage"].(map[string]interface{})["large"])
665			}
666
667			// Append entries based on their status
668			switch animeEntry.Status {
669			case "CURRENT":
670				animeList.Watching = append(animeList.Watching, animeEntry)
671			case "COMPLETED":
672				animeList.Completed = append(animeList.Completed, animeEntry) // Fix: Ensure Completed list is used
673			case "PAUSED":
674				animeList.Paused = append(animeList.Paused, animeEntry) // Fix: Append to Paused list
675			case "DROPPED":
676				animeList.Dropped = append(animeList.Dropped, animeEntry) // Fix: Append to Dropped list
677			case "PLANNING":
678				animeList.Planning = append(animeList.Planning, animeEntry) // Fix: Append to Planning list
679			}
680		}
681	}
682
683	return animeList
684}
685
686// FindAnimeByID searches for an anime by its ID in the AnimeList
687func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
688	id, err := strconv.Atoi(idStr)
689	if err != nil {
690		return nil, fmt.Errorf("invalid ID format: %s", idStr)
691	}
692
693	// Define a slice of pointers to hold categories
694	categories := [][]Entry{
695		list.Watching,
696		list.Completed,
697		list.Paused,
698		list.Dropped,
699		list.Planning,
700	}
701
702	// Iterate through each category
703	for _, category := range categories {
704		for _, entry := range category {
705			if entry.Media.ID == id {
706				return &entry, nil // Return a pointer to the found entry
707			}
708		}
709	}
710
711	return nil, fmt.Errorf("anime with ID %d not found", id) // Return an error if not found
712}
713
714// FindAnimeByAnilistIDInAnimes searches for an anime by its AniList ID in a slice of Anime
715func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error) {
716	for i := range animes {
717		if animes[i].AnilistId == anilistID {
718			return &animes[i], nil
719		}
720	}
721	return nil, fmt.Errorf("anime with ID %d not found", anilistID)
722}
723
724// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token
725func GetAnimeDataByID(anilistID int, token string) (Anime, error) {
726	query := `
727	query ($id: Int) {
728		Media (id: $id, type: ANIME) {
729			id
730			title {
731				romaji
732				english
733				native
734			}
735			episodes
736			duration
737			status
738		}
739	}
740	`
741	
742	variables := map[string]interface{}{
743		"id": anilistID,
744	}
745
746	jsonValue, _ := json.Marshal(map[string]interface{}{
747		"query":     query,
748		"variables": variables,
749	})
750
751	req, err := http.NewRequest("POST", "https://graphql.anilist.co", bytes.NewBuffer(jsonValue))
752	if err != nil {
753		return Anime{}, fmt.Errorf("error creating request: %v", err)
754	}
755
756	req.Header.Set("Content-Type", "application/json")
757	req.Header.Set("Authorization", "Bearer "+token)
758
759	client := &http.Client{}
760	resp, err := client.Do(req)
761	if err != nil {
762		return Anime{}, fmt.Errorf("error sending request: %v", err)
763	}
764	defer resp.Body.Close()
765
766	body, err := ioutil.ReadAll(resp.Body)
767	if err != nil {
768		return Anime{}, fmt.Errorf("error reading response: %v", err)
769	}
770
771	var result struct {
772		Data struct {
773			Media struct {
774				ID          int    `json:"id"`
775				Title       AnimeTitle  `json:"title"`
776				Episodes    int    `json:"episodes"`
777				Duration    int    `json:"duration"`
778				Status      string `json:"status"`
779				CoverImage  struct {
780					Large string `json:"large"`
781				} `json:"coverImage"`
782				Genres       []string `json:"genres"`
783				AverageScore int      `json:"averageScore"`
784			} `json:"Media"`
785		} `json:"data"`
786	}
787
788	if err := json.Unmarshal(body, &result); err != nil {
789		return Anime{}, fmt.Errorf("error unmarshaling JSON: %v", err)
790	}
791
792	anime := Anime{
793		AnilistId:     result.Data.Media.ID,
794		Title:         result.Data.Media.Title,
795		TotalEpisodes: result.Data.Media.Episodes,
796		CoverImage:    result.Data.Media.CoverImage.Large,
797	}
798
799	return anime, nil
800}