internal/myanimelist.go

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