internal/anilist.go

416 lines · 10159 bytes

  1package internal
  2
  3import (
  4	"bytes"
  5	"encoding/json"
  6	"fmt"
  7	"io/ioutil"
  8	"net/http"
  9	"strconv"
 10	"strings"
 11)
 12
 13// AnimeTitle represents the title in different languages
 14type AnimeTitle struct {
 15	Romanji_title   string
 16	English_title   string
 17	Japanese_title  string
 18}
 19
 20// AniListAnime is the struct for the API response
 21type AniListAnime struct {
 22	ID    int `json:"id"`
 23	Title struct {
 24		Romaji  string `json:"romaji"`
 25		English string `json:"english"`
 26		Native  string `json:"native"`
 27	} `json:"title"`
 28}
 29
 30// Page represents the page in AniList response
 31type Page struct {
 32	Media []AniListAnime `json:"media"`
 33}
 34
 35// ResponseData represents the full response structure
 36type ResponseData struct {
 37	Page Page `json:"Page"`
 38}
 39
 40// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
 41func SearchAnimeAnilist(query, token string) (map[string]string, error) {
 42	url := "https://graphql.anilist.co"
 43
 44	queryString := `
 45	query ($search: String) {
 46		Page(page: 1, perPage: 10) {
 47			media(search: $search, type: ANIME) {
 48				id
 49				title {
 50					romaji
 51					english
 52					native
 53				}
 54			}
 55		}
 56	}`
 57
 58	variables := map[string]string{"search": query}
 59	requestBody, err := json.Marshal(map[string]interface{}{
 60		"query":     queryString,
 61		"variables": variables,
 62	})
 63	if err != nil {
 64		return nil, fmt.Errorf("failed to marshal request body: %w", err)
 65	}
 66
 67	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
 68	if err != nil {
 69		return nil, fmt.Errorf("failed to create new request: %w", err)
 70	}
 71
 72	req.Header.Set("Authorization", "Bearer "+token)
 73	req.Header.Set("Content-Type", "application/json")
 74
 75	client := &http.Client{}
 76	resp, err := client.Do(req)
 77	if err != nil {
 78		return nil, fmt.Errorf("failed to make request: %w", err)
 79	}
 80	defer resp.Body.Close()
 81
 82	if resp.StatusCode != http.StatusOK {
 83		body, _ := ioutil.ReadAll(resp.Body)
 84		return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body))
 85	}
 86
 87	body, err := ioutil.ReadAll(resp.Body)
 88	if err != nil {
 89		return nil, fmt.Errorf("failed to read response body: %w", err)
 90	}
 91
 92	var responseData map[string]ResponseData
 93	err = json.Unmarshal(body, &responseData)
 94	if err != nil {
 95		return nil, fmt.Errorf("failed to unmarshal response: %w", err)
 96	}
 97
 98	animeList := responseData["data"].Page.Media
 99	animeDict := make(map[string]string)
100
101	// Map titles to their IDs as strings
102	for _, anime := range animeList {
103		idStr := strconv.Itoa(anime.ID) // Convert ID to string
104		if anime.Title.English != "" {
105			animeDict[idStr] = anime.Title.English
106		} else {
107			animeDict[idStr] = anime.Title.Romaji
108		}
109	}
110
111	return animeDict, nil
112}
113
114// Function to get AniList user ID and username
115func GetAnilistUserID(token string) (int, string, error) {
116	url := "https://graphql.anilist.co"
117	query := `
118	query {
119		Viewer {
120			id
121			name
122		}
123	}`
124
125	headers := map[string]string{
126		"Authorization": "Bearer " + token,
127		"Content-Type":  "application/json",
128		"Accept":        "application/json",
129	}
130
131	response, err := makePostRequest(url, query, nil, headers)
132	if err != nil {
133		return 0, "", err
134	}
135
136	data := response["data"].(map[string]interface{})["Viewer"].(map[string]interface{})
137	userID := int(data["id"].(float64))
138	userName := data["name"].(string)
139
140	return userID, userName, nil
141}
142
143// Function to add an anime to the watching list
144func AddAnimeToWatchingList(animeID int, token string) error {
145	url := "https://graphql.anilist.co"
146	mutation := `
147	mutation ($mediaId: Int) {
148		SaveMediaListEntry (mediaId: $mediaId, status: CURRENT) {
149			id
150			status
151		}
152	}`
153
154	variables := map[string]interface{}{
155		"mediaId": animeID,
156	}
157
158	headers := map[string]string{
159		"Authorization": "Bearer " + token,
160		"Content-Type":  "application/json",
161	}
162
163	_, err := makePostRequest(url, mutation, variables, headers)
164	if err != nil {
165		return fmt.Errorf("failed to add anime: %w", err)
166	}
167
168	fmt.Printf("Anime with ID %d has been added to your watching list.\n", animeID)
169	return nil
170}
171
172// Function to get MAL ID using AniList media ID
173func GetAnimeMalID(anilistMediaID int) (int, error) {
174	url := "https://graphql.anilist.co"
175	query := `
176	query ($id: Int) {
177		Media(id: $id) {
178			idMal
179		}
180	}`
181
182	variables := map[string]interface{}{
183		"id": anilistMediaID,
184	}
185
186	response, err := makePostRequest(url, query, variables, nil)
187	if err != nil {
188		return 0, err
189	}
190
191	malID := int(response["data"].(map[string]interface{})["Media"].(map[string]interface{})["idMal"].(float64))
192	return malID, nil
193}
194
195// Function to get AniList media ID and image
196func GetAnimeIDAndImage(anilistMediaID int) (int, string, error) {
197	url := "https://graphql.anilist.co"
198	query := `
199	query ($id: Int) {
200		Media(id: $id) {
201			coverImage {
202				large
203			}
204			idMal
205		}
206	}`
207
208	variables := map[string]interface{}{
209		"id": anilistMediaID,
210	}
211
212	response, err := makePostRequest(url, query, variables, nil)
213	if err != nil {
214		return 0, "", err
215	}
216
217	data := response["data"].(map[string]interface{})["Media"].(map[string]interface{})
218	malID := int(data["idMal"].(float64))
219	imageURL := data["coverImage"].(map[string]interface{})["large"].(string)
220
221	return malID, imageURL, nil
222}
223
224// Function to get user data from AniList
225func GetUserData(token string, userID int) (map[string]interface{}, error) {
226	query := fmt.Sprintf(`
227	{
228		MediaListCollection(userId: %d, type: ANIME) {
229			lists {
230				entries {
231					media {
232						id
233						episodes
234						duration
235						title {
236							romaji
237							english
238						}
239					}
240					status
241					score
242					progress
243				}
244			}
245		}
246	}`, userID)
247
248	headers := map[string]string{
249		"Authorization": "Bearer " + token,
250		"Content-Type":  "application/json",
251	}
252
253	response, err := makePostRequest("https://graphql.anilist.co", query, nil, headers)
254	if err != nil {
255		return nil, err
256	}
257
258	return response, nil
259}
260
261// Function to load a JSON file
262func LoadJSONFile(filePath string) (map[string]interface{}, error) {
263	data, err := ioutil.ReadFile(filePath)
264	if err != nil {
265		return nil, fmt.Errorf("failed to read file: %w", err)
266	}
267
268	var jsonData map[string]interface{}
269	err = json.Unmarshal(data, &jsonData)
270	if err != nil {
271		return nil, fmt.Errorf("failed to parse JSON: %w", err)
272	}
273
274	return jsonData, nil
275}
276
277// Function to search for an anime by title in user data
278func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []map[string]interface{} {
279	results := []map[string]interface{}{}
280
281	if searchTitle == "1P" {
282		searchTitle = "ONE PIECE"
283	}
284
285	lists := jsonData["data"].(map[string]interface{})["MediaListCollection"].(map[string]interface{})["lists"].([]interface{})
286	for _, list := range lists {
287		entries := list.(map[string]interface{})["entries"].([]interface{})
288		for _, entry := range entries {
289			media := entry.(map[string]interface{})["media"].(map[string]interface{})
290			romajiTitle := media["title"].(map[string]interface{})["romaji"].(string)
291			englishTitle := media["title"].(map[string]interface{})["english"].(string)
292			episodes := int(media["episodes"].(float64))
293			duration := int(media["duration"].(float64))
294
295			if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) {
296				result := map[string]interface{}{
297					"id":           media["id"],
298					"progress":     entry.(map[string]interface{})["progress"],
299					"romaji_title": romajiTitle,
300					"english_title": englishTitle,
301					"episodes":      episodes,
302					"duration":      duration,
303				}
304				results = append(results, result)
305			}
306		}
307	}
308
309	return results
310}
311
312// Function to update anime progress
313func UpdateAnimeProgress(token string, mediaID, progress int) error {
314	url := "https://graphql.anilist.co"
315	query := `
316	mutation($mediaId: Int, $progress: Int) {
317		SaveMediaListEntry(mediaId: $mediaId, progress: $progress) {
318			id
319			progress
320		}
321	}`
322
323	variables := map[string]interface{}{
324		"mediaId":  mediaID,
325		"progress": progress,
326	}
327
328	headers := map[string]string{
329		"Authorization": "Bearer " + token,
330		"Content-Type":  "application/json",
331	}
332
333	_, err := makePostRequest(url, query, variables, headers)
334	if err != nil {
335		return err
336	}
337
338	fmt.Println("Anime progress updated! Latest watched episode:", progress)
339	return nil
340}
341
342// Function to rate an anime on AniList
343func RateAnime(token string, mediaID int, score float64) error {
344	url := "https://graphql.anilist.co"
345	query := `
346	mutation($mediaId: Int, $score: Float) {
347		SaveMediaListEntry(mediaId: $mediaId, score: $score) {
348			id
349			mediaId
350			score
351		}
352	}`
353
354	variables := map[string]interface{}{
355		"mediaId": mediaID,
356		"score":   score,
357	}
358
359	headers := map[string]string{
360		"Authorization": "Bearer " + token,
361		"Content-Type":  "application/json",
362	}
363
364	_, err := makePostRequest(url, query, variables, headers)
365	if err != nil {
366		return err
367	}
368
369	fmt.Printf("Successfully rated anime (mediaId: %d) with score: %.2f\n", mediaID, score)
370	return nil
371}
372
373// Helper function to make POST requests
374func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) {
375	requestBody, err := json.Marshal(map[string]interface{}{
376		"query":     query,
377		"variables": variables,
378	})
379	if err != nil {
380		return nil, fmt.Errorf("failed to marshal request body: %w", err)
381	}
382
383	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
384	if err != nil {
385		return nil, fmt.Errorf("failed to create request: %w", err)
386	}
387
388	for key, value := range headers {
389		req.Header.Set(key, value)
390	}
391
392	client := &http.Client{}
393	resp, err := client.Do(req)
394	if err != nil {
395		return nil, fmt.Errorf("failed to send request: %w", err)
396	}
397	defer resp.Body.Close()
398
399	body, err := ioutil.ReadAll(resp.Body)
400	if err != nil {
401		return nil, fmt.Errorf("failed to read response body: %w", err)
402	}
403
404	if resp.StatusCode != http.StatusOK {
405		return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
406	}
407
408	var responseData map[string]interface{}
409	// Unmarshal the response into a map
410	err = json.Unmarshal(body, &responseData)
411	if err != nil {
412		return nil, fmt.Errorf("failed to unmarshal response: %w", err)
413	}
414
415	return responseData, nil
416}