internal/myanimelist.go

1286 lines · 37444 bytes

65 symbols in this file
   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	CurdOut("MyAnimeList sign-in required. Opening browser...")
 458	Log(fmt.Sprintf("Starting MyAnimeList browser authentication after %s", reason))
 459	clearStoredTokenFile(tokenPath)
 460
 461	accessToken, authErr := authenticateMyAnimeList(config, tokenPath)
 462	if authErr != nil {
 463		return "", authErr
 464	}
 465	if user := GetGlobalUser(); user != nil {
 466		user.Token = accessToken
 467	}
 468	return accessToken, nil
 469}
 470
 471func GetMyAnimeListAccessToken(config *CurdConfig) (string, error) {
 472	tokenPath := myAnimeListTokenPath(config)
 473	token, err := loadToken(tokenPath)
 474	if err != nil {
 475		Log(fmt.Sprintf("Failed to load MyAnimeList token, starting login: %v", err))
 476		return renewMyAnimeListAccessToken(config, tokenPath, nil, "token load failure")
 477	}
 478	if isTokenValid(token) {
 479		if user := GetGlobalUser(); user != nil {
 480			user.Token = token.AccessToken
 481		}
 482		return token.AccessToken, nil
 483	}
 484	if token.RefreshToken == "" {
 485		Log("MyAnimeList token is expired and has no refresh token, starting login")
 486		return renewMyAnimeListAccessToken(config, tokenPath, token, "expired token")
 487	}
 488	return renewMyAnimeListAccessToken(config, tokenPath, token, "expired token")
 489}
 490
 491func ChangeMyAnimeListToken(config *CurdConfig, user *User) error {
 492	tokenPath := myAnimeListTokenPath(config)
 493	accessToken, err := authenticateMyAnimeList(config, tokenPath)
 494	if err != nil {
 495		return err
 496	}
 497	user.Token = accessToken
 498	return nil
 499}
 500
 501func myAnimeListRequest(config *CurdConfig, method, requestURL string, form url.Values, out interface{}) error {
 502	token, err := GetMyAnimeListAccessToken(config)
 503	if err != nil {
 504		return err
 505	}
 506
 507	buildRequest := func(accessToken string) (*http.Request, error) {
 508		urlString := requestURL
 509		var body io.Reader
 510		if !strings.HasPrefix(urlString, "http://") && !strings.HasPrefix(urlString, "https://") {
 511			urlString = myAnimeListAPIBaseURL + requestURL
 512		}
 513
 514		if method == http.MethodGet && form != nil && len(form) > 0 {
 515			separator := "?"
 516			if strings.Contains(urlString, "?") {
 517				separator = "&"
 518			}
 519			urlString += separator + form.Encode()
 520		}
 521
 522		if method != http.MethodGet && form != nil {
 523			body = strings.NewReader(form.Encode())
 524		}
 525
 526		req, reqErr := http.NewRequest(method, urlString, body)
 527		if reqErr != nil {
 528			return nil, reqErr
 529		}
 530		req.Header.Set("Authorization", "Bearer "+accessToken)
 531		if method != http.MethodGet && form != nil {
 532			req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
 533		}
 534		return req, nil
 535	}
 536
 537	for attempt := 0; attempt < 2; attempt++ {
 538		req, err := buildRequest(token)
 539		if err != nil {
 540			return err
 541		}
 542
 543		resp, err := sharedHTTPClient.Do(req)
 544		if err != nil {
 545			return err
 546		}
 547
 548		body, readErr := io.ReadAll(resp.Body)
 549		resp.Body.Close()
 550		if readErr != nil {
 551			return readErr
 552		}
 553
 554		if resp.StatusCode == http.StatusUnauthorized || isInvalidTokenResponse(resp.StatusCode, body) {
 555			if attempt == 0 {
 556				tokenPath := myAnimeListTokenPath(config)
 557				storedToken, tokenErr := loadToken(tokenPath)
 558				if tokenErr != nil {
 559					Log(fmt.Sprintf("Failed to load MyAnimeList token after unauthorized response, starting login: %v", tokenErr))
 560					accessToken, authErr := renewMyAnimeListAccessToken(config, tokenPath, nil, "unauthorized API response")
 561					if authErr != nil {
 562						return authErr
 563					}
 564					token = accessToken
 565					continue
 566				}
 567				accessToken, renewErr := renewMyAnimeListAccessToken(config, tokenPath, storedToken, "unauthorized API response")
 568				if renewErr != nil {
 569					return renewErr
 570				}
 571				token = accessToken
 572				continue
 573			}
 574		}
 575
 576		if resp.StatusCode < 200 || resp.StatusCode >= 300 {
 577			return fmt.Errorf("MyAnimeList API %s %s failed: %s", method, requestURL, strings.TrimSpace(string(body)))
 578		}
 579
 580		if out != nil {
 581			if err := json.Unmarshal(body, out); err != nil {
 582				return err
 583			}
 584		}
 585		return nil
 586	}
 587
 588	return fmt.Errorf("MyAnimeList API request failed after retry")
 589}
 590
 591func parseMyAnimeListDate(value string) FuzzyDate {
 592	if value == "" {
 593		return FuzzyDate{}
 594	}
 595	parts := strings.Split(value, "-")
 596	if len(parts) != 3 {
 597		return FuzzyDate{}
 598	}
 599
 600	year, yearErr := strconv.Atoi(parts[0])
 601	month, monthErr := strconv.Atoi(parts[1])
 602	day, dayErr := strconv.Atoi(parts[2])
 603	if yearErr != nil || monthErr != nil || dayErr != nil || year <= 0 || month < 1 || month > 12 || day < 1 || day > 31 {
 604		return FuzzyDate{}
 605	}
 606	return FuzzyDate{Year: year, Month: month, Day: day}
 607}
 608
 609func parseMyAnimeListTimestamp(value string) time.Time {
 610	value = strings.TrimSpace(value)
 611	if value == "" {
 612		return time.Time{}
 613	}
 614
 615	formats := []string{time.RFC3339Nano, time.RFC3339}
 616	for _, format := range formats {
 617		if parsed, err := time.Parse(format, value); err == nil {
 618			return parsed.UTC()
 619		}
 620	}
 621	return time.Time{}
 622}
 623
 624func formatMyAnimeListDate(value FuzzyDate) string {
 625	if value.Year == 0 || value.Month == 0 || value.Day == 0 {
 626		return ""
 627	}
 628	return fmt.Sprintf("%04d-%02d-%02d", value.Year, value.Month, value.Day)
 629}
 630
 631func myAnimeListStatusToAniListStatus(status string, isRewatching bool) string {
 632	if isRewatching {
 633		return "REPEATING"
 634	}
 635	switch strings.ToLower(status) {
 636	case "watching":
 637		return "CURRENT"
 638	case "completed":
 639		return "COMPLETED"
 640	case "on_hold":
 641		return "PAUSED"
 642	case "dropped":
 643		return "DROPPED"
 644	case "plan_to_watch":
 645		return "PLANNING"
 646	default:
 647		return "CURRENT"
 648	}
 649}
 650
 651func aniListStatusToMyAnimeListStatus(status string) string {
 652	switch strings.ToUpper(strings.TrimSpace(status)) {
 653	case "CURRENT":
 654		return "watching"
 655	case "COMPLETED":
 656		return "completed"
 657	case "PAUSED":
 658		return "on_hold"
 659	case "DROPPED":
 660		return "dropped"
 661	case "PLANNING":
 662		return "plan_to_watch"
 663	case "REPEATING":
 664		return "watching"
 665	default:
 666		return "watching"
 667	}
 668}
 669
 670func myAnimeListMediaStatusToAniListStatus(status string) string {
 671	switch strings.ToLower(status) {
 672	case "currently_airing":
 673		return "RELEASING"
 674	case "not_yet_aired":
 675		return "NOT_YET_RELEASED"
 676	default:
 677		return "FINISHED"
 678	}
 679}
 680
 681func loadTrackingIDCache(storagePath string) (trackingIDCachePayload, error) {
 682	data, err := os.ReadFile(trackingIDCachePath(storagePath))
 683	if err != nil {
 684		return trackingIDCachePayload{}, err
 685	}
 686
 687	var payload trackingIDCachePayload
 688	if err := json.Unmarshal(data, &payload); err != nil {
 689		return trackingIDCachePayload{}, err
 690	}
 691	if payload.MalToAniList == nil {
 692		payload.MalToAniList = map[string]int{}
 693	}
 694	return payload, nil
 695}
 696
 697func saveTrackingIDCache(storagePath string, payload trackingIDCachePayload) error {
 698	storagePath = os.ExpandEnv(storagePath)
 699	if err := os.MkdirAll(storagePath, 0o755); err != nil {
 700		return err
 701	}
 702
 703	if payload.MalToAniList == nil {
 704		payload.MalToAniList = map[string]int{}
 705	}
 706
 707	data, err := json.MarshalIndent(payload, "", "  ")
 708	if err != nil {
 709		return err
 710	}
 711
 712	cachePath := trackingIDCachePath(storagePath)
 713	tempPath := cachePath + ".tmp"
 714	if err := os.WriteFile(tempPath, data, 0o644); err != nil {
 715		return err
 716	}
 717	if err := os.Rename(tempPath, cachePath); err != nil {
 718		_ = os.Remove(tempPath)
 719		return err
 720	}
 721	return nil
 722}
 723
 724func lookupAniListMediaByMalID(malID int) (Media, string, error) {
 725	query := `
 726	query ($idMal: Int) {
 727		Media(idMal: $idMal, type: ANIME) {
 728			id
 729			idMal
 730			episodes
 731			duration
 732			status
 733			format
 734			title {
 735				romaji
 736				english
 737				native
 738			}
 739			coverImage {
 740				large
 741			}
 742		}
 743	}`
 744
 745	response, err := makePostRequest("https://graphql.anilist.co", query, map[string]interface{}{"idMal": malID}, map[string]string{"Content-Type": "application/json"})
 746	if err != nil {
 747		return Media{}, "", err
 748	}
 749
 750	data, ok := response["data"].(map[string]interface{})
 751	if !ok {
 752		return Media{}, "", fmt.Errorf("invalid AniList response")
 753	}
 754	mediaData, ok := data["Media"].(map[string]interface{})
 755	if !ok || mediaData == nil {
 756		return Media{}, "", fmt.Errorf("AniList media not found for MAL ID %d", malID)
 757	}
 758
 759	aniListID, ok := mediaData["id"].(float64)
 760	if !ok || aniListID == 0 {
 761		return Media{}, "", fmt.Errorf("AniList media response for MAL ID %d is missing id", malID)
 762	}
 763
 764	media := Media{
 765		ID:       int(aniListID),
 766		MalID:    malID,
 767		Episodes: 0,
 768		Duration: 0,
 769		Status:   safeAniListString(mediaData["status"]),
 770		Format:   safeAniListString(mediaData["format"]),
 771		Title: AnimeTitle{
 772			Romaji:   safeAniListTitle(mediaData, "romaji"),
 773			English:  safeAniListTitle(mediaData, "english"),
 774			Japanese: safeAniListTitle(mediaData, "native"),
 775		},
 776	}
 777
 778	if episodes, ok := mediaData["episodes"].(float64); ok {
 779		media.Episodes = int(episodes)
 780	}
 781	if duration, ok := mediaData["duration"].(float64); ok {
 782		media.Duration = int(duration)
 783	}
 784
 785	cover := ""
 786	if coverImage, ok := mediaData["coverImage"].(map[string]interface{}); ok {
 787		if large, ok := coverImage["large"].(string); ok {
 788			cover = large
 789		}
 790	}
 791
 792	return media, cover, nil
 793}
 794
 795func safeAniListString(value interface{}) string {
 796	if str, ok := value.(string); ok {
 797		return str
 798	}
 799	return ""
 800}
 801
 802func safeAniListTitle(mediaData map[string]interface{}, key string) string {
 803	titleMap, ok := mediaData["title"].(map[string]interface{})
 804	if !ok {
 805		return ""
 806	}
 807	return safeAniListString(titleMap[key])
 808}
 809
 810type aniListMediaLookupResult struct {
 811	Media Media
 812	Cover string
 813}
 814
 815func buildMediaFromMyAnimeListNode(node myAnimeListAnimeNode, aniListID int) aniListMediaLookupResult {
 816	media := Media{
 817		ID:    aniListID,
 818		MalID: node.ID,
 819		Title: AnimeTitle{
 820			English:  node.AlternativeTitles.En,
 821			Romaji:   node.Title,
 822			Japanese: node.AlternativeTitles.Ja,
 823		},
 824		Episodes: node.NumEpisodes,
 825		Status:   myAnimeListMediaStatusToAniListStatus(node.Status),
 826	}
 827	if node.AverageEpisodeDuration > 0 {
 828		media.Duration = node.AverageEpisodeDuration / 60
 829	}
 830	return aniListMediaLookupResult{
 831		Media: media,
 832		Cover: node.MainPicture.Large,
 833	}
 834}
 835
 836func lookupAniListMediaByMalIDs(malIDs []int) (map[int]aniListMediaLookupResult, error) {
 837	if len(malIDs) == 0 {
 838		return map[int]aniListMediaLookupResult{}, nil
 839	}
 840
 841	var query strings.Builder
 842	query.WriteString("query {")
 843	for idx, malID := range malIDs {
 844		fmt.Fprintf(&query, " m%d: Media(idMal: %d, type: ANIME) { id idMal episodes duration status format title { romaji english native } coverImage { large } }", idx, malID)
 845	}
 846	query.WriteString(" }")
 847
 848	headers := map[string]string{"Content-Type": "application/json"}
 849	var response map[string]interface{}
 850	var err error
 851	for attempt := 0; attempt < 3; attempt++ {
 852		response, err = makePostRequest("https://graphql.anilist.co", query.String(), nil, headers)
 853		if err == nil {
 854			break
 855		}
 856		if !strings.Contains(err.Error(), "429") {
 857			return nil, err
 858		}
 859		time.Sleep(time.Duration(attempt+1) * 750 * time.Millisecond)
 860	}
 861	if err != nil {
 862		return nil, err
 863	}
 864
 865	data, ok := response["data"].(map[string]interface{})
 866	if !ok {
 867		return nil, fmt.Errorf("invalid AniList batch response")
 868	}
 869
 870	results := make(map[int]aniListMediaLookupResult, len(malIDs))
 871	for idx, malID := range malIDs {
 872		alias := fmt.Sprintf("m%d", idx)
 873		rawMedia, ok := data[alias].(map[string]interface{})
 874		if !ok || rawMedia == nil {
 875			continue
 876		}
 877		aniListID, ok := rawMedia["id"].(float64)
 878		if !ok || aniListID == 0 {
 879			continue
 880		}
 881		media := Media{
 882			ID:       int(aniListID),
 883			MalID:    malID,
 884			Episodes: 0,
 885			Duration: 0,
 886			Status:   safeAniListString(rawMedia["status"]),
 887			Format:   safeAniListString(rawMedia["format"]),
 888			Title: AnimeTitle{
 889				Romaji:   safeAniListTitle(rawMedia, "romaji"),
 890				English:  safeAniListTitle(rawMedia, "english"),
 891				Japanese: safeAniListTitle(rawMedia, "native"),
 892			},
 893		}
 894		if episodes, ok := rawMedia["episodes"].(float64); ok {
 895			media.Episodes = int(episodes)
 896		}
 897		if duration, ok := rawMedia["duration"].(float64); ok {
 898			media.Duration = int(duration)
 899		}
 900		cover := ""
 901		if coverImage, ok := rawMedia["coverImage"].(map[string]interface{}); ok {
 902			cover = safeAniListString(coverImage["large"])
 903		}
 904		results[malID] = aniListMediaLookupResult{Media: media, Cover: cover}
 905	}
 906
 907	return results, nil
 908}
 909
 910func resolveAniListMediaForMyAnimeList(config *CurdConfig, malID int, fallbackTitle string) (Media, string, error) {
 911	cachePayload, err := loadTrackingIDCache(config.StoragePath)
 912	if err != nil && !os.IsNotExist(err) {
 913		Log(fmt.Sprintf("Failed to load MAL tracking ID cache: %v", err))
 914	}
 915	if cachePayload.MalToAniList == nil {
 916		cachePayload.MalToAniList = map[string]int{}
 917	}
 918
 919	cacheKey := strconv.Itoa(malID)
 920	if cachedID := cachePayload.MalToAniList[cacheKey]; cachedID != 0 {
 921		media, cover, err := lookupAniListMediaByMalID(malID)
 922		if err == nil {
 923			media.ID = cachedID
 924			return media, cover, nil
 925		}
 926	}
 927
 928	media, cover, err := lookupAniListMediaByMalID(malID)
 929	if err != nil {
 930		return Media{}, "", fmt.Errorf("failed to resolve AniList metadata for MAL %d (%s): %w", malID, fallbackTitle, err)
 931	}
 932
 933	cachePayload.MalToAniList[cacheKey] = media.ID
 934	if saveErr := saveTrackingIDCache(config.StoragePath, cachePayload); saveErr != nil {
 935		Log(fmt.Sprintf("Failed to save MAL tracking ID cache: %v", saveErr))
 936	}
 937
 938	return media, cover, nil
 939}
 940
 941func loadMyAnimeListCache(storagePath string, userID int) (animeListCachePayload, error) {
 942	cacheFilePath := myAnimeListCachePath(storagePath)
 943	data, err := os.ReadFile(cacheFilePath)
 944	if err != nil {
 945		return animeListCachePayload{}, err
 946	}
 947
 948	var payload animeListCachePayload
 949	if err := json.Unmarshal(data, &payload); err != nil {
 950		return animeListCachePayload{}, err
 951	}
 952	if payload.UserID != 0 && userID != 0 && payload.UserID != userID {
 953		return animeListCachePayload{}, fmt.Errorf("anime list cache belongs to a different MyAnimeList user")
 954	}
 955	return payload, nil
 956}
 957
 958func saveMyAnimeListCache(storagePath string, userID int, list AnimeList) error {
 959	storagePath = os.ExpandEnv(storagePath)
 960	if err := os.MkdirAll(storagePath, 0o755); err != nil {
 961		return err
 962	}
 963
 964	payload := animeListCachePayload{
 965		AnimeList: list,
 966		UpdatedAt: time.Now(),
 967		UserID:    userID,
 968	}
 969	data, err := json.MarshalIndent(payload, "", "  ")
 970	if err != nil {
 971		return err
 972	}
 973
 974	cacheFilePath := myAnimeListCachePath(storagePath)
 975	tempFilePath := cacheFilePath + ".tmp"
 976	if err := os.WriteFile(tempFilePath, data, 0o644); err != nil {
 977		return err
 978	}
 979	if err := os.Rename(tempFilePath, cacheFilePath); err != nil {
 980		_ = os.Remove(tempFilePath)
 981		return err
 982	}
 983	return nil
 984}
 985
 986func FetchLatestMyAnimeList(config *CurdConfig, user *User) (AnimeList, error) {
 987	var result AnimeList
 988	nextURL := "/users/@me/animelist"
 989	queryValues := url.Values{
 990		"limit":  {"1000"},
 991		"fields": {"list_status,num_episodes,average_episode_duration,alternative_titles,main_picture,status"},
 992		"sort":   {"list_updated_at"},
 993	}
 994
 995	cachePayload, err := loadTrackingIDCache(config.StoragePath)
 996	if err != nil && !os.IsNotExist(err) {
 997		Log(fmt.Sprintf("Failed to load MAL tracking ID cache: %v", err))
 998	}
 999	if cachePayload.MalToAniList == nil {
1000		cachePayload.MalToAniList = map[string]int{}
1001	}
1002
1003	for {
1004		var response myAnimeListListResponse
1005		if err := myAnimeListRequest(config, http.MethodGet, nextURL, queryValues, &response); err != nil {
1006			return AnimeList{}, err
1007		}
1008		queryValues = nil
1009
1010		resolvedMedia := make(map[int]aniListMediaLookupResult, len(response.Data))
1011		unresolvedIDs := make([]int, 0)
1012		for _, item := range response.Data {
1013			cacheKey := strconv.Itoa(item.Node.ID)
1014			if cachedID := cachePayload.MalToAniList[cacheKey]; cachedID != 0 {
1015				resolvedMedia[item.Node.ID] = buildMediaFromMyAnimeListNode(item.Node, cachedID)
1016				continue
1017			}
1018			unresolvedIDs = append(unresolvedIDs, item.Node.ID)
1019		}
1020
1021		for start := 0; start < len(unresolvedIDs); start += 25 {
1022			end := start + 25
1023			if end > len(unresolvedIDs) {
1024				end = len(unresolvedIDs)
1025			}
1026			batchResults, err := lookupAniListMediaByMalIDs(unresolvedIDs[start:end])
1027			if err != nil {
1028				Log(fmt.Sprintf("AniList batch lookup failed for MAL IDs %v: %v", unresolvedIDs[start:end], err))
1029				continue
1030			}
1031			for _, malID := range unresolvedIDs[start:end] {
1032				if lookup, ok := batchResults[malID]; ok {
1033					resolvedMedia[malID] = lookup
1034					cachePayload.MalToAniList[strconv.Itoa(malID)] = lookup.Media.ID
1035				}
1036			}
1037		}
1038
1039		for _, item := range response.Data {
1040			lookup, ok := resolvedMedia[item.Node.ID]
1041			if !ok {
1042				Log(fmt.Sprintf("Skipping MAL anime %d because AniList mapping failed after batch lookup", item.Node.ID))
1043				continue
1044			}
1045			media := lookup.Media
1046			cover := lookup.Cover
1047
1048			if media.Title.English == "" && item.Node.AlternativeTitles.En != "" {
1049				media.Title.English = item.Node.AlternativeTitles.En
1050			}
1051			if media.Title.Romaji == "" {
1052				media.Title.Romaji = item.Node.Title
1053			}
1054			if media.Title.Japanese == "" && item.Node.AlternativeTitles.Ja != "" {
1055				media.Title.Japanese = item.Node.AlternativeTitles.Ja
1056			}
1057			if media.Episodes == 0 {
1058				media.Episodes = item.Node.NumEpisodes
1059			}
1060			if media.Duration == 0 && item.Node.AverageEpisodeDuration > 0 {
1061				media.Duration = item.Node.AverageEpisodeDuration / 60
1062			}
1063			if media.Status == "" {
1064				media.Status = myAnimeListMediaStatusToAniListStatus(item.Node.Status)
1065			}
1066
1067			entry := Entry{
1068				Media:       media,
1069				Progress:    item.ListStatus.NumEpisodesWatched,
1070				Repeat:      item.ListStatus.NumTimesRewatched,
1071				Score:       float64(item.ListStatus.Score),
1072				Status:      myAnimeListStatusToAniListStatus(item.ListStatus.Status, item.ListStatus.IsRewatching),
1073				StartedAt:   parseMyAnimeListDate(item.ListStatus.StartDate),
1074				CompletedAt: parseMyAnimeListDate(item.ListStatus.FinishDate),
1075				CoverImage:  cover,
1076				UpdatedAt:   parseMyAnimeListTimestamp(item.ListStatus.UpdatedAt),
1077			}
1078			if entry.CoverImage == "" {
1079				entry.CoverImage = item.Node.MainPicture.Large
1080			}
1081
1082			switch entry.Status {
1083			case "CURRENT":
1084				result.Watching = append(result.Watching, entry)
1085			case "COMPLETED":
1086				result.Completed = append(result.Completed, entry)
1087			case "PAUSED":
1088				result.Paused = append(result.Paused, entry)
1089			case "DROPPED":
1090				result.Dropped = append(result.Dropped, entry)
1091			case "PLANNING":
1092				result.Planning = append(result.Planning, entry)
1093			case "REPEATING":
1094				result.Rewatching = append(result.Rewatching, entry)
1095			}
1096		}
1097		if saveErr := saveTrackingIDCache(config.StoragePath, cachePayload); saveErr != nil {
1098			Log(fmt.Sprintf("Failed to save MAL tracking ID cache: %v", saveErr))
1099		}
1100
1101		if response.Paging.Next == "" {
1102			break
1103		}
1104		nextURL = response.Paging.Next
1105	}
1106
1107	if user != nil {
1108		var me myAnimeListUser
1109		if err := myAnimeListRequest(config, http.MethodGet, "/users/@me", url.Values{"fields": {"id,name"}}, &me); err == nil {
1110			user.Id = me.ID
1111			user.Username = me.Name
1112		}
1113	}
1114
1115	return result, nil
1116}
1117
1118func refreshMyAnimeListInBackground(config *CurdConfig, user *User) {
1119	if user == nil || user.ListSync == nil {
1120		return
1121	}
1122
1123	go func() {
1124		defer user.ListSync.MarkRefreshDone()
1125
1126		latestList, err := FetchLatestMyAnimeList(config, user)
1127		if err != nil {
1128			Log(fmt.Sprintf("Failed to refresh MyAnimeList anime list in background: %v", err))
1129			return
1130		}
1131		if err := saveMyAnimeListCache(config.StoragePath, user.Id, latestList); err != nil {
1132			Log(fmt.Sprintf("Failed to save MyAnimeList cache: %v", err))
1133		}
1134		user.ListSync.Replace(latestList, true)
1135	}()
1136}
1137
1138func InitializeMyAnimeListUserAnimeList(config *CurdConfig, user *User) error {
1139	cachedPayload, err := loadMyAnimeListCache(config.StoragePath, user.Id)
1140	if err == nil {
1141		if user.Id == 0 && cachedPayload.UserID != 0 {
1142			user.Id = cachedPayload.UserID
1143		}
1144		user.AnimeList = cachedPayload.AnimeList
1145		user.ListSync = NewAnimeListSync(cachedPayload.AnimeList)
1146		refreshMyAnimeListInBackground(config, user)
1147		return nil
1148	}
1149
1150	latestList, err := FetchLatestMyAnimeList(config, user)
1151	if err != nil {
1152		return err
1153	}
1154	user.AnimeList = latestList
1155	user.ListSync = NewAnimeListSync(latestList)
1156	user.ListSync.MarkRefreshDone()
1157	if err := saveMyAnimeListCache(config.StoragePath, user.Id, latestList); err != nil {
1158		Log(fmt.Sprintf("Failed to save MyAnimeList anime list cache: %v", err))
1159	}
1160	return nil
1161}
1162
1163func RefreshMyAnimeListUserAnimeList(config *CurdConfig, user *User) error {
1164	latestList, err := FetchLatestMyAnimeList(config, user)
1165	if err != nil {
1166		return err
1167	}
1168	user.AnimeList = latestList
1169	if user.ListSync == nil {
1170		user.ListSync = NewAnimeListSync(latestList)
1171		user.ListSync.MarkRefreshDone()
1172	} else {
1173		user.ListSync.Replace(latestList, true)
1174	}
1175	if err := saveMyAnimeListCache(config.StoragePath, user.Id, latestList); err != nil {
1176		Log(fmt.Sprintf("Failed to save MyAnimeList anime list cache: %v", err))
1177	}
1178	return nil
1179}
1180
1181func updateMyAnimeListListStatus(config *CurdConfig, malID int, payload map[string]string) error {
1182	form := url.Values{}
1183	for key, value := range payload {
1184		if strings.TrimSpace(value) == "" && key != "start_date" && key != "finish_date" {
1185			continue
1186		}
1187		form.Set(key, value)
1188	}
1189
1190	var response myAnimeListListStatus
1191	return myAnimeListRequest(config, http.MethodPut, fmt.Sprintf("/anime/%d/my_list_status", malID), form, &response)
1192}
1193
1194func updateMyAnimeListProgress(config *CurdConfig, malID int, progress int) error {
1195	if err := updateMyAnimeListListStatus(config, malID, map[string]string{
1196		"num_watched_episodes": strconv.Itoa(progress),
1197	}); err != nil {
1198		return err
1199	}
1200	CurdOut(fmt.Sprint("Anime progress updated! Latest watched episode: ", progress))
1201	return nil
1202}
1203
1204func updateMyAnimeListStatus(config *CurdConfig, malID int, status string) error {
1205	payload := map[string]string{
1206		"status":        aniListStatusToMyAnimeListStatus(status),
1207		"is_rewatching": "false",
1208	}
1209	if strings.EqualFold(status, "REPEATING") {
1210		payload["status"] = "watching"
1211		payload["is_rewatching"] = "true"
1212	}
1213	if err := updateMyAnimeListListStatus(config, malID, payload); err != nil {
1214		return err
1215	}
1216	CurdOut(fmt.Sprintf("Anime status updated to: %s", status))
1217	return nil
1218}
1219
1220func rateMyAnimeListAnime(config *CurdConfig, malID int) error {
1221	score, err := promptAnimeScoreValue()
1222	if err != nil {
1223		return err
1224	}
1225	return rateMyAnimeListAnimeWithScore(config, malID, int(score+0.5))
1226}
1227
1228func rateMyAnimeListAnimeWithScore(config *CurdConfig, malID int, score int) error {
1229	if err := updateMyAnimeListListStatus(config, malID, map[string]string{
1230		"score": strconv.Itoa(score),
1231	}); err != nil {
1232		return err
1233	}
1234
1235	CurdOut(fmt.Sprintf("Successfully rated anime (malId: %d) with score: %d", malID, score))
1236	return nil
1237}
1238
1239func addMyAnimeListAnimeToList(config *CurdConfig, malID int, status string) error {
1240	payload := map[string]string{
1241		"status":        aniListStatusToMyAnimeListStatus(status),
1242		"is_rewatching": "false",
1243	}
1244	if strings.EqualFold(status, "REPEATING") {
1245		payload["status"] = "watching"
1246		payload["is_rewatching"] = "true"
1247	}
1248	if err := updateMyAnimeListListStatus(config, malID, payload); err != nil {
1249		return err
1250	}
1251	CurdOut(fmt.Sprintf("Anime added to: %s", status))
1252	return nil
1253}
1254
1255func completeMyAnimeListRewatch(config *CurdConfig, malID int, anime Anime) error {
1256	completedAt := currentFuzzyDate()
1257	startedAt := anime.StartedAt
1258	if startedAt == (FuzzyDate{}) {
1259		startedAt = completedAt
1260	}
1261	payload := map[string]string{
1262		"status":               "completed",
1263		"is_rewatching":        "false",
1264		"num_watched_episodes": strconv.Itoa(anime.Ep.Number),
1265		"start_date":           formatMyAnimeListDate(startedAt),
1266		"finish_date":          formatMyAnimeListDate(completedAt),
1267	}
1268	if err := updateMyAnimeListListStatus(config, malID, payload); err != nil {
1269		return err
1270	}
1271	return updateMyAnimeListListStatus(config, malID, map[string]string{
1272		"num_times_rewatched": strconv.Itoa(anime.Repeat + 1),
1273	})
1274}
1275
1276func deleteMyAnimeListEntry(config *CurdConfig, malID int) error {
1277	return myAnimeListRequest(config, http.MethodDelete, fmt.Sprintf("/anime/%d/my_list_status", malID), nil, nil)
1278}
1279
1280func maybeMarshalMALResponse(v interface{}) string {
1281	body, err := json.Marshal(v)
1282	if err != nil {
1283		return ""
1284	}
1285	return string(bytes.TrimSpace(body))
1286}