internal/anilist.go

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