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