internal/anilist.go

545 lines · 14382 bytes

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