internal/anilist.go
546 lines · 14383 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 if searchTitle == "1P" {
293 searchTitle = "ONE PIECE"
294 }
295
296 lists := jsonData["data"].(map[string]interface{})["MediaListCollection"].(map[string]interface{})["lists"].([]interface{})
297 for _, list := range lists {
298 entries := list.(map[string]interface{})["entries"].([]interface{})
299 for _, entry := range entries {
300 media := entry.(map[string]interface{})["media"].(map[string]interface{})
301 romajiTitle := media["title"].(map[string]interface{})["romaji"].(string)
302 englishTitle := media["title"].(map[string]interface{})["english"].(string)
303 episodes := int(media["episodes"].(float64))
304 duration := int(media["duration"].(float64))
305
306 if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) {
307 result := map[string]interface{}{
308 "id": media["id"],
309 "progress": entry.(map[string]interface{})["progress"],
310 "romaji_title": romajiTitle,
311 "english_title": englishTitle,
312 "episodes": episodes,
313 "duration": duration,
314 }
315 results = append(results, result)
316 }
317 }
318 }
319
320 return results
321}
322
323// Function to update anime progress
324func UpdateAnimeProgress(token string, mediaID, progress int) error {
325 url := "https://graphql.anilist.co"
326 query := `
327 mutation($mediaId: Int, $progress: Int) {
328 SaveMediaListEntry(mediaId: $mediaId, progress: $progress) {
329 id
330 progress
331 }
332 }`
333
334 variables := map[string]interface{}{
335 "mediaId": mediaID,
336 "progress": progress,
337 }
338
339 headers := map[string]string{
340 "Authorization": "Bearer " + token,
341 "Content-Type": "application/json",
342 }
343
344 _, err := makePostRequest(url, query, variables, headers)
345 if err != nil {
346 return err
347 }
348
349 fmt.Println("Anime progress updated! Latest watched episode:", progress)
350 return nil
351}
352
353// Function to rate an anime on AniList
354func RateAnime(token string, mediaID int, score float64) error {
355 url := "https://graphql.anilist.co"
356 query := `
357 mutation($mediaId: Int, $score: Float) {
358 SaveMediaListEntry(mediaId: $mediaId, score: $score) {
359 id
360 mediaId
361 score
362 }
363 }`
364
365 variables := map[string]interface{}{
366 "mediaId": mediaID,
367 "score": score,
368 }
369
370 headers := map[string]string{
371 "Authorization": "Bearer " + token,
372 "Content-Type": "application/json",
373 }
374
375 _, err := makePostRequest(url, query, variables, headers)
376 if err != nil {
377 return err
378 }
379
380 fmt.Printf("Successfully rated anime (mediaId: %d) with score: %.2f\n", mediaID, score)
381 return nil
382}
383
384// Helper function to make POST requests
385func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) {
386 requestBody, err := json.Marshal(map[string]interface{}{
387 "query": query,
388 "variables": variables,
389 })
390 if err != nil {
391 return nil, fmt.Errorf("failed to marshal request body: %w", err)
392 }
393
394 req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
395 if err != nil {
396 return nil, fmt.Errorf("failed to create request: %w", err)
397 }
398
399 req.Header.Set("Content-Type", "application/json") // <-- Important!
400 for key, value := range headers {
401 req.Header.Set(key, value)
402 }
403
404 client := &http.Client{}
405 resp, err := client.Do(req)
406 if err != nil {
407 return nil, fmt.Errorf("failed to send request: %w", err)
408 }
409 defer resp.Body.Close()
410
411 body, err := io.ReadAll(resp.Body)
412 if err != nil {
413 return nil, fmt.Errorf("failed to read response body: %w", err)
414 }
415
416 if resp.StatusCode != http.StatusOK {
417 return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
418 }
419
420 var responseData map[string]interface{}
421 // Unmarshal the response into a map
422 err = json.Unmarshal(body, &responseData)
423 if err != nil {
424 return nil, fmt.Errorf("failed to unmarshal response: %w", err)
425 }
426
427 return responseData, nil
428}
429
430func ParseAnimeList(input map[string]interface{}) AnimeList {
431 var animeList AnimeList
432
433 toInt := func(value interface{}) int {
434 switch v := value.(type) {
435 case int:
436 return v
437 case float64:
438 return int(v) // You could also use int(math.Round(v)) to round
439 default:
440 return 0 // Default value for unexpected types
441 }
442 }
443
444 safeString := func(value interface{}) string {
445 if value == nil {
446 return ""
447 }
448
449 // Attempt to assert the value as a string
450 if str, ok := value.(string); ok {
451 return str
452 }
453
454 // If it's not a string, return an empty string or handle it as needed
455 return ""
456 }
457
458 // Access the list entries in the input map
459 if input["data"] == nil {
460 Log("Anilist request failed", logFile)
461 fmt.Println("Anilist request failed")
462 ExitCurd()
463 return animeList
464 }
465 data := input["data"].(map[string]interface{})
466 mediaList := data["MediaListCollection"].(map[string]interface{})["lists"].([]interface{})
467
468 for _, list := range mediaList {
469 entries := list.(map[string]interface{})["entries"].([]interface{})
470
471 for _, entry := range entries {
472 entryData := entry.(map[string]interface{})
473 media := entryData["media"].(map[string]interface{})
474
475 animeEntry := Entry{
476 Media: Media{
477 Duration: toInt(media["duration"]),
478 Episodes: toInt(media["episodes"]),
479 ID: toInt(media["id"]),
480 Title: AnimeTitle{
481 English: safeString(media["title"].(map[string]interface{})["english"]),
482 Romaji: safeString(media["title"].(map[string]interface{})["romaji"]),
483 Japanese: safeString(media["title"].(map[string]interface{})["native"]),
484 },
485 },
486 Progress: toInt(entryData["progress"]),
487 Score: entryData["score"].(float64),
488 Status: safeString(entryData["status"]), // Ensure status is fetched safely
489 }
490
491 // Append entries based on their status
492 switch animeEntry.Status {
493 case "CURRENT":
494 animeList.Watching = append(animeList.Watching, animeEntry)
495 case "COMPLETED":
496 animeList.Completed = append(animeList.Completed, animeEntry) // Fix: Ensure Completed list is used
497 case "PAUSED":
498 animeList.Paused = append(animeList.Paused, animeEntry) // Fix: Append to Paused list
499 case "DROPPED":
500 animeList.Dropped = append(animeList.Dropped, animeEntry) // Fix: Append to Dropped list
501 case "PLANNING":
502 animeList.Planning = append(animeList.Planning, animeEntry) // Fix: Append to Planning list
503 }
504 }
505 }
506
507 return animeList
508}
509
510// FindAnimeByID searches for an anime by its ID in the AnimeList
511func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
512 id, err := strconv.Atoi(idStr)
513 if err != nil {
514 return nil, fmt.Errorf("invalid ID format: %s", idStr)
515 }
516
517 // Define a slice of pointers to hold categories
518 categories := [][]Entry{
519 list.Watching,
520 list.Completed,
521 list.Paused,
522 list.Dropped,
523 list.Planning,
524 }
525
526 // Iterate through each category
527 for _, category := range categories {
528 for _, entry := range category {
529 if entry.Media.ID == id {
530 return &entry, nil // Return a pointer to the found entry
531 }
532 }
533 }
534
535 return nil, fmt.Errorf("anime with ID %d not found", id) // Return an error if not found
536}
537
538// FindAnimeByAnilistIDInAnimes searches for an anime by its AniList ID in a slice of Anime
539func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error) {
540 for i := range animes {
541 if animes[i].AnilistId == anilistID {
542 return &animes[i], nil
543 }
544 }
545 return nil, fmt.Errorf("anime with ID %d not found", anilistID)
546}