internal/myanimelist.go
1277 lines · 37070 bytes
1package internal
2
3import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "encoding/json"
8 "fmt"
9 "io"
10 "net/http"
11 "net/url"
12 "os"
13 "path/filepath"
14 "strconv"
15 "strings"
16 "time"
17
18 "github.com/pkg/browser"
19)
20
21type OAuthToken = AnilistToken
22
23const (
24 myAnimeListAuthorizeURL = "https://myanimelist.net/v1/oauth2/authorize"
25 myAnimeListTokenURL = "https://myanimelist.net/v1/oauth2/token"
26 myAnimeListAPIBaseURL = "https://api.myanimelist.net/v2"
27 myAnimeListRedirectURI = "http://localhost:8123/oauth/callback"
28 myAnimeListServerPort = 8123
29 myAnimeListListCacheFileName = "myanimelist_list_cache.json"
30 trackingIDCacheFileName = "tracking_id_cache.json"
31 myAnimeListPendingAuthFile = "myanimelist_oauth_pending.json"
32)
33
34type myAnimeListUser struct {
35 ID int `json:"id"`
36 Name string `json:"name"`
37}
38
39type myAnimeListPicture struct {
40 Medium string `json:"medium"`
41 Large string `json:"large"`
42}
43
44type myAnimeListAlternativeTitles struct {
45 En string `json:"en"`
46 Ja string `json:"ja"`
47}
48
49type myAnimeListAnimeNode struct {
50 ID int `json:"id"`
51 Title string `json:"title"`
52 MainPicture myAnimeListPicture `json:"main_picture"`
53 AlternativeTitles myAnimeListAlternativeTitles `json:"alternative_titles"`
54 NumEpisodes int `json:"num_episodes"`
55 AverageEpisodeDuration int `json:"average_episode_duration"`
56 Status string `json:"status"`
57}
58
59type myAnimeListListStatus struct {
60 Status string `json:"status"`
61 Score int `json:"score"`
62 NumEpisodesWatched int `json:"num_episodes_watched"`
63 IsRewatching bool `json:"is_rewatching"`
64 NumTimesRewatched int `json:"num_times_rewatched"`
65 StartDate string `json:"start_date"`
66 FinishDate string `json:"finish_date"`
67 UpdatedAt string `json:"updated_at"`
68}
69
70type myAnimeListListResponse struct {
71 Data []struct {
72 Node myAnimeListAnimeNode `json:"node"`
73 ListStatus myAnimeListListStatus `json:"list_status"`
74 } `json:"data"`
75 Paging struct {
76 Next string `json:"next"`
77 } `json:"paging"`
78}
79
80type trackingIDCachePayload struct {
81 MalToAniList map[string]int `json:"mal_to_anilist"`
82}
83
84type pendingMyAnimeListAuth struct {
85 CodeVerifier string `json:"code_verifier"`
86 State string `json:"state"`
87 CreatedAt time.Time `json:"created_at"`
88}
89
90func myAnimeListTokenPath(config *CurdConfig) string {
91 return filepath.Join(os.ExpandEnv(config.StoragePath), "myanimelist_token.json")
92}
93
94func myAnimeListCachePath(storagePath string) string {
95 return filepath.Join(os.ExpandEnv(storagePath), myAnimeListListCacheFileName)
96}
97
98func trackingIDCachePath(storagePath string) string {
99 return filepath.Join(os.ExpandEnv(storagePath), trackingIDCacheFileName)
100}
101
102func myAnimeListPendingAuthPath(config *CurdConfig) string {
103 return filepath.Join(os.ExpandEnv(config.StoragePath), myAnimeListPendingAuthFile)
104}
105
106func savePendingMyAnimeListAuth(config *CurdConfig, pending pendingMyAnimeListAuth) error {
107 storagePath := os.ExpandEnv(config.StoragePath)
108 if err := os.MkdirAll(storagePath, 0o755); err != nil {
109 return err
110 }
111 data, err := json.MarshalIndent(pending, "", " ")
112 if err != nil {
113 return err
114 }
115 return os.WriteFile(myAnimeListPendingAuthPath(config), data, 0o600)
116}
117
118func loadPendingMyAnimeListAuth(config *CurdConfig) (*pendingMyAnimeListAuth, error) {
119 data, err := os.ReadFile(myAnimeListPendingAuthPath(config))
120 if err != nil {
121 return nil, err
122 }
123 var pending pendingMyAnimeListAuth
124 if err := json.Unmarshal(data, &pending); err != nil {
125 return nil, err
126 }
127 return &pending, nil
128}
129
130func clearPendingMyAnimeListAuth(config *CurdConfig) {
131 _ = os.Remove(myAnimeListPendingAuthPath(config))
132}
133
134func extractOAuthCodeFromInput(input string, expectedState string) (string, error) {
135 input = strings.TrimSpace(input)
136 if input == "" {
137 return "", fmt.Errorf("empty callback input")
138 }
139
140 if strings.Contains(input, "://") || strings.Contains(input, "code=") {
141 if strings.Contains(input, "://") {
142 parsed, err := url.Parse(input)
143 if err != nil {
144 return "", err
145 }
146 query := parsed.Query()
147 if expectedState != "" {
148 if state := query.Get("state"); state != "" && state != expectedState {
149 return "", fmt.Errorf("callback state does not match the pending login")
150 }
151 }
152 if code := query.Get("code"); code != "" {
153 return code, nil
154 }
155 return "", fmt.Errorf("callback URL does not include an authorization code")
156 }
157
158 query, err := url.ParseQuery(strings.TrimPrefix(input, "?"))
159 if err != nil {
160 return "", err
161 }
162 if expectedState != "" {
163 if state := query.Get("state"); state != "" && state != expectedState {
164 return "", fmt.Errorf("callback state does not match the pending login")
165 }
166 }
167 if code := query.Get("code"); code != "" {
168 return code, nil
169 }
170 }
171
172 return input, nil
173}
174
175func exchangeMyAnimeListAuthorizationCode(config *CurdConfig, tokenPath string, codeVerifier string, code string) (string, error) {
176 clientID, clientSecret := myAnimeListClientCredentials(config)
177 form := url.Values{
178 "client_id": {clientID},
179 "grant_type": {"authorization_code"},
180 "code": {code},
181 "redirect_uri": {myAnimeListRedirectURI},
182 "code_verifier": {codeVerifier},
183 }
184 if clientSecret != "" {
185 form.Set("client_secret", clientSecret)
186 }
187
188 req, err := http.NewRequest("POST", myAnimeListTokenURL, strings.NewReader(form.Encode()))
189 if err != nil {
190 return "", err
191 }
192 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
193
194 resp, err := sharedHTTPClient.Do(req)
195 if err != nil {
196 return "", err
197 }
198 defer resp.Body.Close()
199
200 body, err := io.ReadAll(resp.Body)
201 if err != nil {
202 return "", err
203 }
204 if resp.StatusCode != http.StatusOK {
205 return "", fmt.Errorf("MyAnimeList token exchange failed: %s", strings.TrimSpace(string(body)))
206 }
207
208 var token OAuthToken
209 if err := json.Unmarshal(body, &token); err != nil {
210 return "", err
211 }
212 if strings.TrimSpace(token.AccessToken) == "" {
213 return "", fmt.Errorf("MyAnimeList token response did not include an access token")
214 }
215 token.ExpiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second)
216 if err := saveToken(tokenPath, &token); err != nil {
217 return "", err
218 }
219 clearPendingMyAnimeListAuth(config)
220 return token.AccessToken, nil
221}
222
223func myAnimeListClientCredentials(config *CurdConfig) (string, string) {
224 if config == nil {
225 return "", ""
226 }
227
228 clientID := strings.TrimSpace(config.MyAnimeListClientID)
229 if clientID == "" {
230 clientID = strings.TrimSpace(os.Getenv("CURD_MAL_CLIENT_ID"))
231 }
232 if clientID == "" {
233 clientID = strings.TrimSpace(os.Getenv("MYANIMELIST_CLIENT_ID"))
234 }
235
236 clientSecret := strings.TrimSpace(config.MyAnimeListClientSecret)
237 if clientSecret == "" {
238 clientSecret = strings.TrimSpace(os.Getenv("CURD_MAL_CLIENT_SECRET"))
239 }
240 if clientSecret == "" {
241 clientSecret = strings.TrimSpace(os.Getenv("MYANIMELIST_CLIENT_SECRET"))
242 }
243
244 return clientID, clientSecret
245}
246
247func randomOAuthString(length int) (string, error) {
248 const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"
249 if length < 43 {
250 length = 43
251 }
252 buf := make([]byte, length)
253 if _, err := rand.Read(buf); err != nil {
254 return "", err
255 }
256
257 for i := range buf {
258 buf[i] = chars[int(buf[i])%len(chars)]
259 }
260 return string(buf), nil
261}
262
263func authenticateMyAnimeListWithBrowser(config *CurdConfig, tokenPath string) (string, error) {
264 clientID, _ := myAnimeListClientCredentials(config)
265 if clientID == "" {
266 return "", fmt.Errorf("MyAnimeList client ID is not configured")
267 }
268
269 if token, err := loadToken(tokenPath); err == nil {
270 if isTokenValid(token) {
271 return token.AccessToken, nil
272 }
273 if token.RefreshToken != "" {
274 refreshed, refreshErr := refreshMyAnimeListToken(config, tokenPath, token.RefreshToken)
275 if refreshErr == nil {
276 return refreshed.AccessToken, nil
277 }
278 }
279 }
280
281 if pending, err := loadPendingMyAnimeListAuth(config); err == nil {
282 CurdOut("Found an unfinished MyAnimeList login.")
283 callbackInput, inputErr := promptTrackingInput("Paste the full MyAnimeList callback URL (or just the code), or press Enter to start over", true)
284 if inputErr != nil {
285 return "", inputErr
286 }
287 if strings.TrimSpace(callbackInput) != "" {
288 code, parseErr := extractOAuthCodeFromInput(callbackInput, pending.State)
289 if parseErr != nil {
290 return "", parseErr
291 }
292 return exchangeMyAnimeListAuthorizationCode(config, tokenPath, pending.CodeVerifier, code)
293 }
294 clearPendingMyAnimeListAuth(config)
295 }
296
297 codeVerifier, err := randomOAuthString(64)
298 if err != nil {
299 return "", err
300 }
301 state, err := randomOAuthString(32)
302 if err != nil {
303 return "", err
304 }
305 if err := savePendingMyAnimeListAuth(config, pendingMyAnimeListAuth{
306 CodeVerifier: codeVerifier,
307 State: state,
308 CreatedAt: time.Now(),
309 }); err != nil {
310 return "", err
311 }
312
313 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
314 defer cancel()
315
316 callbackCh := make(chan string, 1)
317 errCh := make(chan error, 1)
318 mux := http.NewServeMux()
319 srv := &http.Server{
320 Addr: fmt.Sprintf(":%d", myAnimeListServerPort),
321 Handler: mux,
322 }
323
324 mux.HandleFunc("/oauth/callback", func(w http.ResponseWriter, r *http.Request) {
325 code := r.URL.Query().Get("code")
326 returnedState := r.URL.Query().Get("state")
327 if returnedState != state {
328 http.Error(w, "invalid state", http.StatusBadRequest)
329 errCh <- fmt.Errorf("invalid state returned from MyAnimeList")
330 return
331 }
332 if code == "" {
333 http.Error(w, "missing authorization code", http.StatusBadRequest)
334 errCh <- fmt.Errorf("missing authorization code")
335 return
336 }
337
338 fmt.Fprint(w, "<html><body><p>Authentication complete. You can close this window.</p></body></html>")
339 callbackCh <- code
340 })
341
342 go func() {
343 if serveErr := srv.ListenAndServe(); serveErr != nil && serveErr != http.ErrServerClosed {
344 errCh <- serveErr
345 }
346 }()
347 defer srv.Shutdown(ctx)
348
349 time.Sleep(100 * time.Millisecond)
350
351 authURL := fmt.Sprintf(
352 "%s?response_type=code&client_id=%s&state=%s&redirect_uri=%s&code_challenge=%s&code_challenge_method=plain",
353 myAnimeListAuthorizeURL,
354 url.QueryEscape(clientID),
355 url.QueryEscape(state),
356 url.QueryEscape(myAnimeListRedirectURI),
357 url.QueryEscape(codeVerifier),
358 )
359
360 fmt.Println("Opening browser for MyAnimeList authentication...")
361 fmt.Printf("If the browser doesn't open automatically, visit: %s\n", authURL)
362 if err := browser.OpenURL(authURL); err != nil {
363 fmt.Printf("Failed to open browser automatically: %v\n", err)
364 }
365 fmt.Println("If curd does not continue after the browser reaches localhost, rerun the command and paste the full callback URL when prompted.")
366
367 var code string
368 select {
369 case code = <-callbackCh:
370 case err := <-errCh:
371 return "", fmt.Errorf("%w. rerun the command and paste the callback URL to finish login", err)
372 case <-ctx.Done():
373 callbackInput, inputErr := promptTrackingInput("Paste the full MyAnimeList callback URL or just the code", false)
374 if inputErr != nil {
375 return "", fmt.Errorf("MyAnimeList authentication timed out; rerun the command and paste the callback URL to finish login")
376 }
377 code, err = extractOAuthCodeFromInput(callbackInput, state)
378 if err != nil {
379 return "", err
380 }
381 }
382
383 return exchangeMyAnimeListAuthorizationCode(config, tokenPath, codeVerifier, code)
384}
385
386var authenticateMyAnimeList = authenticateMyAnimeListWithBrowser
387
388func refreshMyAnimeListToken(config *CurdConfig, tokenPath string, refreshToken string) (*OAuthToken, error) {
389 clientID, clientSecret := myAnimeListClientCredentials(config)
390 if clientID == "" {
391 return nil, fmt.Errorf("MyAnimeList client ID is not configured")
392 }
393 if refreshToken == "" {
394 return nil, fmt.Errorf("MyAnimeList refresh token is missing")
395 }
396
397 form := url.Values{
398 "grant_type": {"refresh_token"},
399 "refresh_token": {refreshToken},
400 "client_id": {clientID},
401 }
402 if clientSecret != "" {
403 form.Set("client_secret", clientSecret)
404 }
405
406 req, err := http.NewRequest("POST", myAnimeListTokenURL, strings.NewReader(form.Encode()))
407 if err != nil {
408 return nil, err
409 }
410 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
411
412 resp, err := sharedHTTPClient.Do(req)
413 if err != nil {
414 return nil, err
415 }
416 defer resp.Body.Close()
417
418 body, err := io.ReadAll(resp.Body)
419 if err != nil {
420 return nil, err
421 }
422 if resp.StatusCode != http.StatusOK {
423 return nil, fmt.Errorf("failed refreshing MyAnimeList token: %s", strings.TrimSpace(string(body)))
424 }
425
426 var token OAuthToken
427 if err := json.Unmarshal(body, &token); err != nil {
428 return nil, err
429 }
430 if strings.TrimSpace(token.AccessToken) == "" {
431 return nil, fmt.Errorf("MyAnimeList refresh response did not include an access token")
432 }
433 if strings.TrimSpace(token.RefreshToken) == "" {
434 token.RefreshToken = refreshToken
435 }
436 token.ExpiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second)
437 if err := saveToken(tokenPath, &token); err != nil {
438 return nil, err
439 }
440
441 if user := GetGlobalUser(); user != nil {
442 user.Token = token.AccessToken
443 }
444
445 return &token, nil
446}
447
448func renewMyAnimeListAccessToken(config *CurdConfig, tokenPath string, token *OAuthToken, reason string) (string, error) {
449 if token != nil && strings.TrimSpace(token.RefreshToken) != "" {
450 refreshed, refreshErr := refreshMyAnimeListToken(config, tokenPath, token.RefreshToken)
451 if refreshErr == nil {
452 return refreshed.AccessToken, nil
453 }
454 Log(fmt.Sprintf("Failed to refresh MyAnimeList token after %s: %v", reason, refreshErr))
455 }
456
457 accessToken, authErr := authenticateMyAnimeList(config, tokenPath)
458 if authErr != nil {
459 return "", authErr
460 }
461 if user := GetGlobalUser(); user != nil {
462 user.Token = accessToken
463 }
464 return accessToken, nil
465}
466
467func GetMyAnimeListAccessToken(config *CurdConfig) (string, error) {
468 tokenPath := myAnimeListTokenPath(config)
469 token, err := loadToken(tokenPath)
470 if err != nil {
471 Log(fmt.Sprintf("Failed to load MyAnimeList token, starting login: %v", err))
472 return renewMyAnimeListAccessToken(config, tokenPath, nil, "token load failure")
473 }
474 if isTokenValid(token) {
475 if user := GetGlobalUser(); user != nil {
476 user.Token = token.AccessToken
477 }
478 return token.AccessToken, nil
479 }
480 if token.RefreshToken == "" {
481 Log("MyAnimeList token is expired and has no refresh token, starting login")
482 return renewMyAnimeListAccessToken(config, tokenPath, token, "expired token")
483 }
484 return renewMyAnimeListAccessToken(config, tokenPath, token, "expired token")
485}
486
487func ChangeMyAnimeListToken(config *CurdConfig, user *User) error {
488 tokenPath := myAnimeListTokenPath(config)
489 accessToken, err := authenticateMyAnimeList(config, tokenPath)
490 if err != nil {
491 return err
492 }
493 user.Token = accessToken
494 return nil
495}
496
497func myAnimeListRequest(config *CurdConfig, method, requestURL string, form url.Values, out interface{}) error {
498 token, err := GetMyAnimeListAccessToken(config)
499 if err != nil {
500 return err
501 }
502
503 buildRequest := func(accessToken string) (*http.Request, error) {
504 urlString := requestURL
505 var body io.Reader
506 if !strings.HasPrefix(urlString, "http://") && !strings.HasPrefix(urlString, "https://") {
507 urlString = myAnimeListAPIBaseURL + requestURL
508 }
509
510 if method == http.MethodGet && form != nil && len(form) > 0 {
511 separator := "?"
512 if strings.Contains(urlString, "?") {
513 separator = "&"
514 }
515 urlString += separator + form.Encode()
516 }
517
518 if method != http.MethodGet && form != nil {
519 body = strings.NewReader(form.Encode())
520 }
521
522 req, reqErr := http.NewRequest(method, urlString, body)
523 if reqErr != nil {
524 return nil, reqErr
525 }
526 req.Header.Set("Authorization", "Bearer "+accessToken)
527 if method != http.MethodGet && form != nil {
528 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
529 }
530 return req, nil
531 }
532
533 for attempt := 0; attempt < 2; attempt++ {
534 req, err := buildRequest(token)
535 if err != nil {
536 return err
537 }
538
539 resp, err := sharedHTTPClient.Do(req)
540 if err != nil {
541 return err
542 }
543
544 body, readErr := io.ReadAll(resp.Body)
545 resp.Body.Close()
546 if readErr != nil {
547 return readErr
548 }
549
550 if resp.StatusCode == http.StatusUnauthorized && attempt == 0 {
551 tokenPath := myAnimeListTokenPath(config)
552 storedToken, tokenErr := loadToken(tokenPath)
553 if tokenErr != nil {
554 Log(fmt.Sprintf("Failed to load MyAnimeList token after unauthorized response, starting login: %v", tokenErr))
555 accessToken, authErr := renewMyAnimeListAccessToken(config, tokenPath, nil, "unauthorized API response")
556 if authErr != nil {
557 return authErr
558 }
559 token = accessToken
560 continue
561 }
562 accessToken, renewErr := renewMyAnimeListAccessToken(config, tokenPath, storedToken, "unauthorized API response")
563 if renewErr != nil {
564 return renewErr
565 }
566 token = accessToken
567 continue
568 }
569
570 if resp.StatusCode < 200 || resp.StatusCode >= 300 {
571 return fmt.Errorf("MyAnimeList API %s %s failed: %s", method, requestURL, strings.TrimSpace(string(body)))
572 }
573
574 if out != nil {
575 if err := json.Unmarshal(body, out); err != nil {
576 return err
577 }
578 }
579 return nil
580 }
581
582 return fmt.Errorf("MyAnimeList API request failed after retry")
583}
584
585func parseMyAnimeListDate(value string) FuzzyDate {
586 if value == "" {
587 return FuzzyDate{}
588 }
589 parts := strings.Split(value, "-")
590 if len(parts) != 3 {
591 return FuzzyDate{}
592 }
593
594 year, yearErr := strconv.Atoi(parts[0])
595 month, monthErr := strconv.Atoi(parts[1])
596 day, dayErr := strconv.Atoi(parts[2])
597 if yearErr != nil || monthErr != nil || dayErr != nil || year <= 0 || month < 1 || month > 12 || day < 1 || day > 31 {
598 return FuzzyDate{}
599 }
600 return FuzzyDate{Year: year, Month: month, Day: day}
601}
602
603func parseMyAnimeListTimestamp(value string) time.Time {
604 value = strings.TrimSpace(value)
605 if value == "" {
606 return time.Time{}
607 }
608
609 formats := []string{time.RFC3339Nano, time.RFC3339}
610 for _, format := range formats {
611 if parsed, err := time.Parse(format, value); err == nil {
612 return parsed.UTC()
613 }
614 }
615 return time.Time{}
616}
617
618func formatMyAnimeListDate(value FuzzyDate) string {
619 if value.Year == 0 || value.Month == 0 || value.Day == 0 {
620 return ""
621 }
622 return fmt.Sprintf("%04d-%02d-%02d", value.Year, value.Month, value.Day)
623}
624
625func myAnimeListStatusToAniListStatus(status string, isRewatching bool) string {
626 if isRewatching {
627 return "REPEATING"
628 }
629 switch strings.ToLower(status) {
630 case "watching":
631 return "CURRENT"
632 case "completed":
633 return "COMPLETED"
634 case "on_hold":
635 return "PAUSED"
636 case "dropped":
637 return "DROPPED"
638 case "plan_to_watch":
639 return "PLANNING"
640 default:
641 return "CURRENT"
642 }
643}
644
645func aniListStatusToMyAnimeListStatus(status string) string {
646 switch strings.ToUpper(strings.TrimSpace(status)) {
647 case "CURRENT":
648 return "watching"
649 case "COMPLETED":
650 return "completed"
651 case "PAUSED":
652 return "on_hold"
653 case "DROPPED":
654 return "dropped"
655 case "PLANNING":
656 return "plan_to_watch"
657 case "REPEATING":
658 return "watching"
659 default:
660 return "watching"
661 }
662}
663
664func myAnimeListMediaStatusToAniListStatus(status string) string {
665 switch strings.ToLower(status) {
666 case "currently_airing":
667 return "RELEASING"
668 case "not_yet_aired":
669 return "NOT_YET_RELEASED"
670 default:
671 return "FINISHED"
672 }
673}
674
675func loadTrackingIDCache(storagePath string) (trackingIDCachePayload, error) {
676 data, err := os.ReadFile(trackingIDCachePath(storagePath))
677 if err != nil {
678 return trackingIDCachePayload{}, err
679 }
680
681 var payload trackingIDCachePayload
682 if err := json.Unmarshal(data, &payload); err != nil {
683 return trackingIDCachePayload{}, err
684 }
685 if payload.MalToAniList == nil {
686 payload.MalToAniList = map[string]int{}
687 }
688 return payload, nil
689}
690
691func saveTrackingIDCache(storagePath string, payload trackingIDCachePayload) error {
692 storagePath = os.ExpandEnv(storagePath)
693 if err := os.MkdirAll(storagePath, 0o755); err != nil {
694 return err
695 }
696
697 if payload.MalToAniList == nil {
698 payload.MalToAniList = map[string]int{}
699 }
700
701 data, err := json.MarshalIndent(payload, "", " ")
702 if err != nil {
703 return err
704 }
705
706 cachePath := trackingIDCachePath(storagePath)
707 tempPath := cachePath + ".tmp"
708 if err := os.WriteFile(tempPath, data, 0o644); err != nil {
709 return err
710 }
711 if err := os.Rename(tempPath, cachePath); err != nil {
712 _ = os.Remove(tempPath)
713 return err
714 }
715 return nil
716}
717
718func lookupAniListMediaByMalID(malID int) (Media, string, error) {
719 query := `
720 query ($idMal: Int) {
721 Media(idMal: $idMal, type: ANIME) {
722 id
723 idMal
724 episodes
725 duration
726 status
727 title {
728 romaji
729 english
730 native
731 }
732 coverImage {
733 large
734 }
735 }
736 }`
737
738 response, err := makePostRequest("https://graphql.anilist.co", query, map[string]interface{}{"idMal": malID}, map[string]string{"Content-Type": "application/json"})
739 if err != nil {
740 return Media{}, "", err
741 }
742
743 data, ok := response["data"].(map[string]interface{})
744 if !ok {
745 return Media{}, "", fmt.Errorf("invalid AniList response")
746 }
747 mediaData, ok := data["Media"].(map[string]interface{})
748 if !ok || mediaData == nil {
749 return Media{}, "", fmt.Errorf("AniList media not found for MAL ID %d", malID)
750 }
751
752 aniListID, ok := mediaData["id"].(float64)
753 if !ok || aniListID == 0 {
754 return Media{}, "", fmt.Errorf("AniList media response for MAL ID %d is missing id", malID)
755 }
756
757 media := Media{
758 ID: int(aniListID),
759 MalID: malID,
760 Episodes: 0,
761 Duration: 0,
762 Status: safeAniListString(mediaData["status"]),
763 Title: AnimeTitle{
764 Romaji: safeAniListTitle(mediaData, "romaji"),
765 English: safeAniListTitle(mediaData, "english"),
766 Japanese: safeAniListTitle(mediaData, "native"),
767 },
768 }
769
770 if episodes, ok := mediaData["episodes"].(float64); ok {
771 media.Episodes = int(episodes)
772 }
773 if duration, ok := mediaData["duration"].(float64); ok {
774 media.Duration = int(duration)
775 }
776
777 cover := ""
778 if coverImage, ok := mediaData["coverImage"].(map[string]interface{}); ok {
779 if large, ok := coverImage["large"].(string); ok {
780 cover = large
781 }
782 }
783
784 return media, cover, nil
785}
786
787func safeAniListString(value interface{}) string {
788 if str, ok := value.(string); ok {
789 return str
790 }
791 return ""
792}
793
794func safeAniListTitle(mediaData map[string]interface{}, key string) string {
795 titleMap, ok := mediaData["title"].(map[string]interface{})
796 if !ok {
797 return ""
798 }
799 return safeAniListString(titleMap[key])
800}
801
802type aniListMediaLookupResult struct {
803 Media Media
804 Cover string
805}
806
807func buildMediaFromMyAnimeListNode(node myAnimeListAnimeNode, aniListID int) aniListMediaLookupResult {
808 media := Media{
809 ID: aniListID,
810 MalID: node.ID,
811 Title: AnimeTitle{
812 English: node.AlternativeTitles.En,
813 Romaji: node.Title,
814 Japanese: node.AlternativeTitles.Ja,
815 },
816 Episodes: node.NumEpisodes,
817 Status: myAnimeListMediaStatusToAniListStatus(node.Status),
818 }
819 if node.AverageEpisodeDuration > 0 {
820 media.Duration = node.AverageEpisodeDuration / 60
821 }
822 return aniListMediaLookupResult{
823 Media: media,
824 Cover: node.MainPicture.Large,
825 }
826}
827
828func lookupAniListMediaByMalIDs(malIDs []int) (map[int]aniListMediaLookupResult, error) {
829 if len(malIDs) == 0 {
830 return map[int]aniListMediaLookupResult{}, nil
831 }
832
833 var query strings.Builder
834 query.WriteString("query {")
835 for idx, malID := range malIDs {
836 fmt.Fprintf(&query, " m%d: Media(idMal: %d, type: ANIME) { id idMal episodes duration status title { romaji english native } coverImage { large } }", idx, malID)
837 }
838 query.WriteString(" }")
839
840 headers := map[string]string{"Content-Type": "application/json"}
841 var response map[string]interface{}
842 var err error
843 for attempt := 0; attempt < 3; attempt++ {
844 response, err = makePostRequest("https://graphql.anilist.co", query.String(), nil, headers)
845 if err == nil {
846 break
847 }
848 if !strings.Contains(err.Error(), "429") {
849 return nil, err
850 }
851 time.Sleep(time.Duration(attempt+1) * 750 * time.Millisecond)
852 }
853 if err != nil {
854 return nil, err
855 }
856
857 data, ok := response["data"].(map[string]interface{})
858 if !ok {
859 return nil, fmt.Errorf("invalid AniList batch response")
860 }
861
862 results := make(map[int]aniListMediaLookupResult, len(malIDs))
863 for idx, malID := range malIDs {
864 alias := fmt.Sprintf("m%d", idx)
865 rawMedia, ok := data[alias].(map[string]interface{})
866 if !ok || rawMedia == nil {
867 continue
868 }
869 aniListID, ok := rawMedia["id"].(float64)
870 if !ok || aniListID == 0 {
871 continue
872 }
873 media := Media{
874 ID: int(aniListID),
875 MalID: malID,
876 Episodes: 0,
877 Duration: 0,
878 Status: safeAniListString(rawMedia["status"]),
879 Title: AnimeTitle{
880 Romaji: safeAniListTitle(rawMedia, "romaji"),
881 English: safeAniListTitle(rawMedia, "english"),
882 Japanese: safeAniListTitle(rawMedia, "native"),
883 },
884 }
885 if episodes, ok := rawMedia["episodes"].(float64); ok {
886 media.Episodes = int(episodes)
887 }
888 if duration, ok := rawMedia["duration"].(float64); ok {
889 media.Duration = int(duration)
890 }
891 cover := ""
892 if coverImage, ok := rawMedia["coverImage"].(map[string]interface{}); ok {
893 cover = safeAniListString(coverImage["large"])
894 }
895 results[malID] = aniListMediaLookupResult{Media: media, Cover: cover}
896 }
897
898 return results, nil
899}
900
901func resolveAniListMediaForMyAnimeList(config *CurdConfig, malID int, fallbackTitle string) (Media, string, error) {
902 cachePayload, err := loadTrackingIDCache(config.StoragePath)
903 if err != nil && !os.IsNotExist(err) {
904 Log(fmt.Sprintf("Failed to load MAL tracking ID cache: %v", err))
905 }
906 if cachePayload.MalToAniList == nil {
907 cachePayload.MalToAniList = map[string]int{}
908 }
909
910 cacheKey := strconv.Itoa(malID)
911 if cachedID := cachePayload.MalToAniList[cacheKey]; cachedID != 0 {
912 media, cover, err := lookupAniListMediaByMalID(malID)
913 if err == nil {
914 media.ID = cachedID
915 return media, cover, nil
916 }
917 }
918
919 media, cover, err := lookupAniListMediaByMalID(malID)
920 if err != nil {
921 return Media{}, "", fmt.Errorf("failed to resolve AniList metadata for MAL %d (%s): %w", malID, fallbackTitle, err)
922 }
923
924 cachePayload.MalToAniList[cacheKey] = media.ID
925 if saveErr := saveTrackingIDCache(config.StoragePath, cachePayload); saveErr != nil {
926 Log(fmt.Sprintf("Failed to save MAL tracking ID cache: %v", saveErr))
927 }
928
929 return media, cover, nil
930}
931
932func loadMyAnimeListCache(storagePath string, userID int) (animeListCachePayload, error) {
933 cacheFilePath := myAnimeListCachePath(storagePath)
934 data, err := os.ReadFile(cacheFilePath)
935 if err != nil {
936 return animeListCachePayload{}, err
937 }
938
939 var payload animeListCachePayload
940 if err := json.Unmarshal(data, &payload); err != nil {
941 return animeListCachePayload{}, err
942 }
943 if payload.UserID != 0 && userID != 0 && payload.UserID != userID {
944 return animeListCachePayload{}, fmt.Errorf("anime list cache belongs to a different MyAnimeList user")
945 }
946 return payload, nil
947}
948
949func saveMyAnimeListCache(storagePath string, userID int, list AnimeList) error {
950 storagePath = os.ExpandEnv(storagePath)
951 if err := os.MkdirAll(storagePath, 0o755); err != nil {
952 return err
953 }
954
955 payload := animeListCachePayload{
956 AnimeList: list,
957 UpdatedAt: time.Now(),
958 UserID: userID,
959 }
960 data, err := json.MarshalIndent(payload, "", " ")
961 if err != nil {
962 return err
963 }
964
965 cacheFilePath := myAnimeListCachePath(storagePath)
966 tempFilePath := cacheFilePath + ".tmp"
967 if err := os.WriteFile(tempFilePath, data, 0o644); err != nil {
968 return err
969 }
970 if err := os.Rename(tempFilePath, cacheFilePath); err != nil {
971 _ = os.Remove(tempFilePath)
972 return err
973 }
974 return nil
975}
976
977func FetchLatestMyAnimeList(config *CurdConfig, user *User) (AnimeList, error) {
978 var result AnimeList
979 nextURL := "/users/@me/animelist"
980 queryValues := url.Values{
981 "limit": {"1000"},
982 "fields": {"list_status,num_episodes,average_episode_duration,alternative_titles,main_picture,status"},
983 "sort": {"list_updated_at"},
984 }
985
986 cachePayload, err := loadTrackingIDCache(config.StoragePath)
987 if err != nil && !os.IsNotExist(err) {
988 Log(fmt.Sprintf("Failed to load MAL tracking ID cache: %v", err))
989 }
990 if cachePayload.MalToAniList == nil {
991 cachePayload.MalToAniList = map[string]int{}
992 }
993
994 for {
995 var response myAnimeListListResponse
996 if err := myAnimeListRequest(config, http.MethodGet, nextURL, queryValues, &response); err != nil {
997 return AnimeList{}, err
998 }
999 queryValues = nil
1000
1001 resolvedMedia := make(map[int]aniListMediaLookupResult, len(response.Data))
1002 unresolvedIDs := make([]int, 0)
1003 for _, item := range response.Data {
1004 cacheKey := strconv.Itoa(item.Node.ID)
1005 if cachedID := cachePayload.MalToAniList[cacheKey]; cachedID != 0 {
1006 resolvedMedia[item.Node.ID] = buildMediaFromMyAnimeListNode(item.Node, cachedID)
1007 continue
1008 }
1009 unresolvedIDs = append(unresolvedIDs, item.Node.ID)
1010 }
1011
1012 for start := 0; start < len(unresolvedIDs); start += 25 {
1013 end := start + 25
1014 if end > len(unresolvedIDs) {
1015 end = len(unresolvedIDs)
1016 }
1017 batchResults, err := lookupAniListMediaByMalIDs(unresolvedIDs[start:end])
1018 if err != nil {
1019 Log(fmt.Sprintf("AniList batch lookup failed for MAL IDs %v: %v", unresolvedIDs[start:end], err))
1020 continue
1021 }
1022 for _, malID := range unresolvedIDs[start:end] {
1023 if lookup, ok := batchResults[malID]; ok {
1024 resolvedMedia[malID] = lookup
1025 cachePayload.MalToAniList[strconv.Itoa(malID)] = lookup.Media.ID
1026 }
1027 }
1028 }
1029
1030 for _, item := range response.Data {
1031 lookup, ok := resolvedMedia[item.Node.ID]
1032 if !ok {
1033 Log(fmt.Sprintf("Skipping MAL anime %d because AniList mapping failed after batch lookup", item.Node.ID))
1034 continue
1035 }
1036 media := lookup.Media
1037 cover := lookup.Cover
1038
1039 if media.Title.English == "" && item.Node.AlternativeTitles.En != "" {
1040 media.Title.English = item.Node.AlternativeTitles.En
1041 }
1042 if media.Title.Romaji == "" {
1043 media.Title.Romaji = item.Node.Title
1044 }
1045 if media.Title.Japanese == "" && item.Node.AlternativeTitles.Ja != "" {
1046 media.Title.Japanese = item.Node.AlternativeTitles.Ja
1047 }
1048 if media.Episodes == 0 {
1049 media.Episodes = item.Node.NumEpisodes
1050 }
1051 if media.Duration == 0 && item.Node.AverageEpisodeDuration > 0 {
1052 media.Duration = item.Node.AverageEpisodeDuration / 60
1053 }
1054 if media.Status == "" {
1055 media.Status = myAnimeListMediaStatusToAniListStatus(item.Node.Status)
1056 }
1057
1058 entry := Entry{
1059 Media: media,
1060 Progress: item.ListStatus.NumEpisodesWatched,
1061 Repeat: item.ListStatus.NumTimesRewatched,
1062 Score: float64(item.ListStatus.Score),
1063 Status: myAnimeListStatusToAniListStatus(item.ListStatus.Status, item.ListStatus.IsRewatching),
1064 StartedAt: parseMyAnimeListDate(item.ListStatus.StartDate),
1065 CompletedAt: parseMyAnimeListDate(item.ListStatus.FinishDate),
1066 CoverImage: cover,
1067 UpdatedAt: parseMyAnimeListTimestamp(item.ListStatus.UpdatedAt),
1068 }
1069 if entry.CoverImage == "" {
1070 entry.CoverImage = item.Node.MainPicture.Large
1071 }
1072
1073 switch entry.Status {
1074 case "CURRENT":
1075 result.Watching = append(result.Watching, entry)
1076 case "COMPLETED":
1077 result.Completed = append(result.Completed, entry)
1078 case "PAUSED":
1079 result.Paused = append(result.Paused, entry)
1080 case "DROPPED":
1081 result.Dropped = append(result.Dropped, entry)
1082 case "PLANNING":
1083 result.Planning = append(result.Planning, entry)
1084 case "REPEATING":
1085 result.Rewatching = append(result.Rewatching, entry)
1086 }
1087 }
1088 if saveErr := saveTrackingIDCache(config.StoragePath, cachePayload); saveErr != nil {
1089 Log(fmt.Sprintf("Failed to save MAL tracking ID cache: %v", saveErr))
1090 }
1091
1092 if response.Paging.Next == "" {
1093 break
1094 }
1095 nextURL = response.Paging.Next
1096 }
1097
1098 if user != nil {
1099 var me myAnimeListUser
1100 if err := myAnimeListRequest(config, http.MethodGet, "/users/@me", url.Values{"fields": {"id,name"}}, &me); err == nil {
1101 user.Id = me.ID
1102 user.Username = me.Name
1103 }
1104 }
1105
1106 return result, nil
1107}
1108
1109func refreshMyAnimeListInBackground(config *CurdConfig, user *User) {
1110 if user == nil || user.ListSync == nil {
1111 return
1112 }
1113
1114 go func() {
1115 defer user.ListSync.MarkRefreshDone()
1116
1117 latestList, err := FetchLatestMyAnimeList(config, user)
1118 if err != nil {
1119 Log(fmt.Sprintf("Failed to refresh MyAnimeList anime list in background: %v", err))
1120 return
1121 }
1122 if err := saveMyAnimeListCache(config.StoragePath, user.Id, latestList); err != nil {
1123 Log(fmt.Sprintf("Failed to save MyAnimeList cache: %v", err))
1124 }
1125 user.ListSync.Replace(latestList, true)
1126 }()
1127}
1128
1129func InitializeMyAnimeListUserAnimeList(config *CurdConfig, user *User) error {
1130 cachedPayload, err := loadMyAnimeListCache(config.StoragePath, user.Id)
1131 if err == nil {
1132 if user.Id == 0 && cachedPayload.UserID != 0 {
1133 user.Id = cachedPayload.UserID
1134 }
1135 user.AnimeList = cachedPayload.AnimeList
1136 user.ListSync = NewAnimeListSync(cachedPayload.AnimeList)
1137 refreshMyAnimeListInBackground(config, user)
1138 return nil
1139 }
1140
1141 latestList, err := FetchLatestMyAnimeList(config, user)
1142 if err != nil {
1143 return err
1144 }
1145 user.AnimeList = latestList
1146 user.ListSync = NewAnimeListSync(latestList)
1147 user.ListSync.MarkRefreshDone()
1148 if err := saveMyAnimeListCache(config.StoragePath, user.Id, latestList); err != nil {
1149 Log(fmt.Sprintf("Failed to save MyAnimeList anime list cache: %v", err))
1150 }
1151 return nil
1152}
1153
1154func RefreshMyAnimeListUserAnimeList(config *CurdConfig, user *User) error {
1155 latestList, err := FetchLatestMyAnimeList(config, user)
1156 if err != nil {
1157 return err
1158 }
1159 user.AnimeList = latestList
1160 if user.ListSync == nil {
1161 user.ListSync = NewAnimeListSync(latestList)
1162 user.ListSync.MarkRefreshDone()
1163 } else {
1164 user.ListSync.Replace(latestList, true)
1165 }
1166 if err := saveMyAnimeListCache(config.StoragePath, user.Id, latestList); err != nil {
1167 Log(fmt.Sprintf("Failed to save MyAnimeList anime list cache: %v", err))
1168 }
1169 return nil
1170}
1171
1172func updateMyAnimeListListStatus(config *CurdConfig, malID int, payload map[string]string) error {
1173 form := url.Values{}
1174 for key, value := range payload {
1175 if strings.TrimSpace(value) == "" && key != "start_date" && key != "finish_date" {
1176 continue
1177 }
1178 form.Set(key, value)
1179 }
1180
1181 var response myAnimeListListStatus
1182 return myAnimeListRequest(config, http.MethodPut, fmt.Sprintf("/anime/%d/my_list_status", malID), form, &response)
1183}
1184
1185func updateMyAnimeListProgress(config *CurdConfig, malID int, progress int) error {
1186 if err := updateMyAnimeListListStatus(config, malID, map[string]string{
1187 "num_watched_episodes": strconv.Itoa(progress),
1188 }); err != nil {
1189 return err
1190 }
1191 CurdOut(fmt.Sprint("Anime progress updated! Latest watched episode: ", progress))
1192 return nil
1193}
1194
1195func updateMyAnimeListStatus(config *CurdConfig, malID int, status string) error {
1196 payload := map[string]string{
1197 "status": aniListStatusToMyAnimeListStatus(status),
1198 "is_rewatching": "false",
1199 }
1200 if strings.EqualFold(status, "REPEATING") {
1201 payload["status"] = "watching"
1202 payload["is_rewatching"] = "true"
1203 }
1204 if err := updateMyAnimeListListStatus(config, malID, payload); err != nil {
1205 return err
1206 }
1207 CurdOut(fmt.Sprintf("Anime status updated to: %s", status))
1208 return nil
1209}
1210
1211func rateMyAnimeListAnime(config *CurdConfig, malID int) error {
1212 score, err := promptAnimeScoreValue()
1213 if err != nil {
1214 return err
1215 }
1216 return rateMyAnimeListAnimeWithScore(config, malID, int(score+0.5))
1217}
1218
1219func rateMyAnimeListAnimeWithScore(config *CurdConfig, malID int, score int) error {
1220 if err := updateMyAnimeListListStatus(config, malID, map[string]string{
1221 "score": strconv.Itoa(score),
1222 }); err != nil {
1223 return err
1224 }
1225
1226 CurdOut(fmt.Sprintf("Successfully rated anime (malId: %d) with score: %d", malID, score))
1227 return nil
1228}
1229
1230func addMyAnimeListAnimeToList(config *CurdConfig, malID int, status string) error {
1231 payload := map[string]string{
1232 "status": aniListStatusToMyAnimeListStatus(status),
1233 "is_rewatching": "false",
1234 }
1235 if strings.EqualFold(status, "REPEATING") {
1236 payload["status"] = "watching"
1237 payload["is_rewatching"] = "true"
1238 }
1239 if err := updateMyAnimeListListStatus(config, malID, payload); err != nil {
1240 return err
1241 }
1242 CurdOut(fmt.Sprintf("Anime added to: %s", status))
1243 return nil
1244}
1245
1246func completeMyAnimeListRewatch(config *CurdConfig, malID int, anime Anime) error {
1247 completedAt := currentFuzzyDate()
1248 startedAt := anime.StartedAt
1249 if startedAt == (FuzzyDate{}) {
1250 startedAt = completedAt
1251 }
1252 payload := map[string]string{
1253 "status": "completed",
1254 "is_rewatching": "false",
1255 "num_watched_episodes": strconv.Itoa(anime.Ep.Number),
1256 "start_date": formatMyAnimeListDate(startedAt),
1257 "finish_date": formatMyAnimeListDate(completedAt),
1258 }
1259 if err := updateMyAnimeListListStatus(config, malID, payload); err != nil {
1260 return err
1261 }
1262 return updateMyAnimeListListStatus(config, malID, map[string]string{
1263 "num_times_rewatched": strconv.Itoa(anime.Repeat + 1),
1264 })
1265}
1266
1267func deleteMyAnimeListEntry(config *CurdConfig, malID int) error {
1268 return myAnimeListRequest(config, http.MethodDelete, fmt.Sprintf("/anime/%d/my_list_status", malID), nil, nil)
1269}
1270
1271func maybeMarshalMALResponse(v interface{}) string {
1272 body, err := json.Marshal(v)
1273 if err != nil {
1274 return ""
1275 }
1276 return string(bytes.TrimSpace(body))
1277}