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