Commit f8e2ee8393
Unsigned
Layout: unified · split
README.md +28 −2
| @@ -27,7 +27,8 @@ https://github.com/user-attachments/assets/cbf799bc-9fdd-4402-ab61-b4e31f1e264d | |||
| 27 | - Multiple Content Providers (AllAnime and Animepahe) with up to 1080p support | 27 | - Multiple Content Providers (AllAnime and Animepahe) with up to 1080p support |
| 28 | - Built-in headless browser to bypass Cloudflare/DDoS-Guard protections | 28 | - Built-in headless browser to bypass Cloudflare/DDoS-Guard protections |
| 29 | - Stream anime online | 29 | - Stream anime online |
| 30 | - Update anime in Anilist after completion | 30 | - Track anime locally, on AniList, or on MyAnimeList |
| 31 | - Browser-based AniList and MyAnimeList login flows | ||
| 31 | - Skip anime Intro and Outro | 32 | - Skip anime Intro and Outro |
| 32 | - Skip Filler and Recap episodes | 33 | - Skip Filler and Recap episodes |
| 33 | - Discord RPC about the anime | 34 | - Discord RPC about the anime |
| @@ -351,6 +352,24 @@ You can quit it anytime and the resume time would be saved in the history file | |||
| 351 | more settings can be found at config file. | 352 | more settings can be found at config file. |
| 352 | config file is located at ```~/.config/curd/curd.conf``` | 353 | config file is located at ```~/.config/curd/curd.conf``` |
| 353 | 354 | ||
| 355 | On first start, curd asks which tracking mode you want to use: | ||
| 356 | |||
| 357 | - local | ||
| 358 | - anilist | ||
| 359 | - myanimelist | ||
| 360 | - anilist + myanimelist | ||
| 361 | |||
| 362 | Local history stays enabled in all modes. `anilist` means local history + AniList sync, `myanimelist` means local history + MyAnimeList sync, and `anilist + myanimelist` updates both platforms. In dual-sync mode, curd compares the latest remote update time for each anime and pushes the newest status/progress/category back to the older tracker so both sides converge automatically. Legacy installs are migrated to `anilist` automatically. If you switch trackers later, curd exposes a **Change Tracker** menu entry and can either merge both lists, replace MyAnimeList with AniList, or replace AniList with MyAnimeList. | ||
| 363 | |||
| 364 | MyAnimeList OAuth requires your own MAL application credentials. You can set them in the config file or with environment variables: | ||
| 365 | |||
| 366 | ```bash | ||
| 367 | CURD_MAL_CLIENT_ID=your_client_id | ||
| 368 | CURD_MAL_CLIENT_SECRET=your_client_secret | ||
| 369 | ``` | ||
| 370 | |||
| 371 | If the browser reaches the localhost callback page but curd does not continue automatically, rerun the command and paste the full callback URL when prompted. Curd now keeps the pending MyAnimeList PKCE state so the login can be completed manually. | ||
| 372 | |||
| 354 | | **Option** | **Type** | **Valid Values** | **Description** | | 373 | | **Option** | **Type** | **Valid Values** | **Description** | |
| 355 | |---------------------------|------------|-------------------------------------------|---------------------------------------------------------------------------------------------------| | 374 | |---------------------------|------------|-------------------------------------------|---------------------------------------------------------------------------------------------------| |
| 356 | | `DiscordPresence` | Boolean | `true`, `false` | Enables or disables Discord Rich Presence integration. | | 375 | | `DiscordPresence` | Boolean | `true`, `false` | Enables or disables Discord Rich Presence integration. | |
| @@ -372,8 +391,14 @@ config file is located at ```~/.config/curd/curd.conf``` | |||
| 372 | | `Player` | String | any mpv-compatible binary (e.g. `mpv`, `iina`) | Player binary used for playback. If not found, Curd falls back to `mpv`. | | 391 | | `Player` | String | any mpv-compatible binary (e.g. `mpv`, `iina`) | Player binary used for playback. If not found, Curd falls back to `mpv`. | |
| 373 | | `SaveMpvSpeed` | Boolean | `true`, `false` | Retains the playback speed set in MPV for next episode. | | 392 | | `SaveMpvSpeed` | Boolean | `true`, `false` | Retains the playback speed set in MPV for next episode. | |
| 374 | | `SkipFiller` | Boolean | `true`, `false` | Skips filler episodes when supported. | | 393 | | `SkipFiller` | Boolean | `true`, `false` | Skips filler episodes when supported. | |
| 375 | | `MenuOrder` | String | Comma-separated list | Controls which menu items appear and their order. Available options: `CURRENT`, `ALL`, `UNTRACKED`, `UPDATE`, `CONTINUE_LAST`, `PLANNING`, `COMPLETED`, `PAUSED`, `DROPPED`, `REWATCHING`, `PROVIDER`. Only listed items will be shown. Default: `CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,PROVIDER` | | 394 | | `MenuOrder` | String | Comma-separated list | Controls which menu items appear and their order. Available options: `CURRENT`, `ALL`, `UNTRACKED`, `UPDATE`, `CONTINUE_LAST`, `PLANNING`, `COMPLETED`, `PAUSED`, `DROPPED`, `REWATCHING`, `TRACKER`, `PROVIDER`. Only listed items will be shown. Default: `CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,TRACKER,PROVIDER` | |
| 376 | | `Provider` | Enum | `allanime`, `animepahe` | Sets the content provider for anime streams. `animepahe` requires chromium to bypass DDoS-Guard. Default: `allanime` | | 395 | | `Provider` | Enum | `allanime`, `animepahe` | Sets the content provider for anime streams. `animepahe` requires chromium to bypass DDoS-Guard. Default: `allanime` | |
| 396 | | `TrackingLocal` | Boolean | `true` | Legacy compatibility flag. Local playback history is always enabled. | | ||
| 397 | | `TrackingRemote` | Enum | `none`, `anilist`, `myanimelist`, `anilist+myanimelist` | Selects which remote tracker curd syncs with. | | ||
| 398 | | `TrackingConfigured` | Boolean | `true`, `false` | Internal flag used to remember that the startup tracking prompt has already been completed. | | ||
| 399 | | `MyAnimeListClientID` | String | MAL OAuth client ID | Client ID used for MyAnimeList browser login. | | ||
| 400 | | `MyAnimeListClientSecret` | String | MAL OAuth client secret | Optional secret used for MyAnimeList browser login and token refresh. | | ||
| 401 | | `MyAnimeListImported` | Boolean | `true`, `false` | Tracks whether the one-time AniList-to-MyAnimeList import prompt has already been handled. | | ||
| 377 | 402 | ||
| 378 | ## Todo (fix) | 403 | ## Todo (fix) |
| 379 | - Use Powershell for windows token input instead of notepad or cmd | 404 | - Use Powershell for windows token input instead of notepad or cmd |
| @@ -388,6 +413,7 @@ config file is located at ```~/.config/curd/curd.conf``` | |||
| 388 | 413 | ||
| 389 | ## API Used | 414 | ## API Used |
| 390 | - [Anilist API](https://anilist.gitbook.io/anilist-apiv2-docs) - Update user data and download user data | 415 | - [Anilist API](https://anilist.gitbook.io/anilist-apiv2-docs) - Update user data and download user data |
| 416 | - [MyAnimeList API](https://myanimelist.net/apiconfig/references/api/v2) - MyAnimeList OAuth and tracking sync | ||
| 391 | - [AniSkip API](https://api.aniskip.com/api-docs) - Get anime intro and outro timings | 417 | - [AniSkip API](https://api.aniskip.com/api-docs) - Get anime intro and outro timings |
| 392 | - [AllAnime Content](https://allanime.to/) - Fetch anime url | 418 | - [AllAnime Content](https://allanime.to/) - Fetch anime url |
| 393 | - [Animepahe Content](https://animepahe.pw/) - Alternative provider for 1080p streams | 419 | - [Animepahe Content](https://animepahe.pw/) - Alternative provider for 1080p streams |
cmd/curd/main.go +32 −28
| @@ -28,6 +28,7 @@ func main() { | |||
| 28 | var user internal.User | 28 | var user internal.User |
| 29 | 29 | ||
| 30 | internal.SetGlobalAnime(&anime) | 30 | internal.SetGlobalAnime(&anime) |
| 31 | internal.SetGlobalUser(&user) | ||
| 31 | 32 | ||
| 32 | configDir, err := os.UserConfigDir() | 33 | configDir, err := os.UserConfigDir() |
| 33 | if err != nil { | 34 | if err != nil { |
| @@ -121,15 +122,6 @@ func main() { | |||
| 121 | } | 122 | } |
| 122 | } | 123 | } |
| 123 | 124 | ||
| 124 | if *changeToken { | ||
| 125 | internal.ChangeToken(&userCurdConfig, &user) | ||
| 126 | return | ||
| 127 | } | ||
| 128 | |||
| 129 | // Setup screen for interactive mode (only if not changing token) | ||
| 130 | internal.ClearScreen() | ||
| 131 | defer internal.RestoreScreen() | ||
| 132 | |||
| 133 | if *currentCategory { | 125 | if *currentCategory { |
| 134 | userCurdConfig.CurrentCategory = true | 126 | userCurdConfig.CurrentCategory = true |
| 135 | } | 127 | } |
| @@ -155,31 +147,13 @@ func main() { | |||
| 155 | return | 147 | return |
| 156 | } | 148 | } |
| 157 | 149 | ||
| 158 | // Set SubOrDub based on the flags | ||
| 159 | if *subFlag { | ||
| 160 | userCurdConfig.SubOrDub = "sub" | ||
| 161 | } else if *dubFlag { | ||
| 162 | userCurdConfig.SubOrDub = "dub" | ||
| 163 | } | ||
| 164 | |||
| 165 | // Get the token from the token file | ||
| 166 | user.Token, err = internal.GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "anilist_token.json")) | ||
| 167 | if err != nil { | ||
| 168 | internal.Log("Error reading token") | ||
| 169 | } | ||
| 170 | if user.Token == "" { | ||
| 171 | internal.ChangeToken(&userCurdConfig, &user) | ||
| 172 | } | ||
| 173 | |||
| 174 | if userCurdConfig.RofiSelection { | 150 | if userCurdConfig.RofiSelection { |
| 175 | // Define a slice of file names to check and download | ||
| 176 | filesToCheck := []string{ | 151 | filesToCheck := []string{ |
| 177 | "selectanimepreview.rasi", | 152 | "selectanimepreview.rasi", |
| 178 | "selectanime.rasi", | 153 | "selectanime.rasi", |
| 179 | "userinput.rasi", | 154 | "userinput.rasi", |
| 180 | } | 155 | } |
| 181 | 156 | ||
| 182 | // Call the function to check and download files | ||
| 183 | err := internal.CheckAndDownloadFiles(os.ExpandEnv(userCurdConfig.StoragePath), filesToCheck) | 157 | err := internal.CheckAndDownloadFiles(os.ExpandEnv(userCurdConfig.StoragePath), filesToCheck) |
| 184 | if err != nil { | 158 | if err != nil { |
| 185 | internal.Log(fmt.Sprintf("Error checking and downloading files: %v\n", err)) | 159 | internal.Log(fmt.Sprintf("Error checking and downloading files: %v\n", err)) |
| @@ -188,6 +162,36 @@ func main() { | |||
| 188 | } | 162 | } |
| 189 | } | 163 | } |
| 190 | 164 | ||
| 165 | if err := internal.EnsureTrackingConfigured(&userCurdConfig); err != nil { | ||
| 166 | fmt.Println("Error configuring tracking:", err) | ||
| 167 | return | ||
| 168 | } | ||
| 169 | internal.SetGlobalConfig(&userCurdConfig) | ||
| 170 | |||
| 171 | if *changeToken { | ||
| 172 | internal.ChangeTrackingToken(&userCurdConfig, &user) | ||
| 173 | return | ||
| 174 | } | ||
| 175 | |||
| 176 | // Setup screen for interactive mode (only if not changing token) | ||
| 177 | internal.ClearScreen() | ||
| 178 | defer internal.RestoreScreen() | ||
| 179 | |||
| 180 | // Set SubOrDub based on the flags | ||
| 181 | if *subFlag { | ||
| 182 | userCurdConfig.SubOrDub = "sub" | ||
| 183 | } else if *dubFlag { | ||
| 184 | userCurdConfig.SubOrDub = "dub" | ||
| 185 | } | ||
| 186 | |||
| 187 | // Get the token from the token file for the configured remote tracker. | ||
| 188 | if internal.UsesRemoteTracking(&userCurdConfig) { | ||
| 189 | if err := internal.EnsureConfiguredTrackersReady(&userCurdConfig, &user); err != nil { | ||
| 190 | internal.Log("Error preparing trackers: " + err.Error()) | ||
| 191 | internal.ExitCurd(err) | ||
| 192 | } | ||
| 193 | } | ||
| 194 | |||
| 191 | // Load animes in database | 195 | // Load animes in database |
| 192 | databaseFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_history.txt") | 196 | databaseFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_history.txt") |
| 193 | databaseAnimes := internal.LocalGetAllAnime(databaseFile) | 197 | databaseAnimes := internal.LocalGetAllAnime(databaseFile) |
| @@ -204,7 +208,7 @@ func main() { | |||
| 204 | internal.Log("Error finding anime by Anilist ID: " + err.Error()) | 208 | internal.Log("Error finding anime by Anilist ID: " + err.Error()) |
| 205 | } | 209 | } |
| 206 | 210 | ||
| 207 | if anime.TotalEpisodes == temp_anime.Progress && temp_anime.Status != "CURRENT" { | 211 | if err == nil && temp_anime != nil && anime.TotalEpisodes == temp_anime.Progress && temp_anime.Status != "CURRENT" { |
| 208 | internal.Log(temp_anime.Progress) | 212 | internal.Log(temp_anime.Progress) |
| 209 | internal.Log(anime.TotalEpisodes) | 213 | internal.Log(anime.TotalEpisodes) |
| 210 | internal.Log(user.AnimeList) | 214 | internal.Log(user.AnimeList) |
internal/anilist.go +211 −130
| @@ -11,6 +11,7 @@ import ( | |||
| 11 | "sort" | 11 | "sort" |
| 12 | "strconv" | 12 | "strconv" |
| 13 | "strings" | 13 | "strings" |
| 14 | "time" | ||
| 14 | ) | 15 | ) |
| 15 | 16 | ||
| 16 | // FindKeyByValue searches for a key associated with a given value in a map[string]string | 17 | // FindKeyByValue searches for a key associated with a given value in a map[string]string |
| @@ -136,6 +137,44 @@ func min3(a, b, c int) int { | |||
| 136 | return c | 137 | return c |
| 137 | } | 138 | } |
| 138 | 139 | ||
| 140 | func doAniListSearchRequest(url string, requestBody []byte, token string) ([]byte, error) { | ||
| 141 | client := &http.Client{} | ||
| 142 | for attempt := 0; attempt < 5; attempt++ { | ||
| 143 | req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) | ||
| 144 | if err != nil { | ||
| 145 | return nil, fmt.Errorf("failed to create new request: %w", err) | ||
| 146 | } | ||
| 147 | if token != "" { | ||
| 148 | req.Header.Set("Authorization", "Bearer "+token) | ||
| 149 | } | ||
| 150 | req.Header.Set("Content-Type", "application/json") | ||
| 151 | |||
| 152 | resp, err := client.Do(req) | ||
| 153 | if err != nil { | ||
| 154 | return nil, fmt.Errorf("failed to make request: %w", err) | ||
| 155 | } | ||
| 156 | |||
| 157 | body, readErr := io.ReadAll(resp.Body) | ||
| 158 | resp.Body.Close() | ||
| 159 | if readErr != nil { | ||
| 160 | return nil, fmt.Errorf("failed to read response body: %w", readErr) | ||
| 161 | } | ||
| 162 | if resp.StatusCode == http.StatusTooManyRequests { | ||
| 163 | if attempt == 4 { | ||
| 164 | return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body)) | ||
| 165 | } | ||
| 166 | time.Sleep(aniListRetryDelay(resp, attempt)) | ||
| 167 | continue | ||
| 168 | } | ||
| 169 | if resp.StatusCode != http.StatusOK { | ||
| 170 | return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body)) | ||
| 171 | } | ||
| 172 | return body, nil | ||
| 173 | } | ||
| 174 | |||
| 175 | return nil, fmt.Errorf("AniList search failed after retries") | ||
| 176 | } | ||
| 177 | |||
| 139 | // SearchAnimeAnilist sends the query to AniList and returns a map of title to ID | 178 | // SearchAnimeAnilist sends the query to AniList and returns a map of title to ID |
| 140 | func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPreview, error) { | 179 | func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPreview, error) { |
| 141 | url := "https://graphql.anilist.co" | 180 | url := "https://graphql.anilist.co" |
| @@ -166,29 +205,9 @@ func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPrevie | |||
| 166 | return nil, fmt.Errorf("failed to marshal request body: %w", err) | 205 | return nil, fmt.Errorf("failed to marshal request body: %w", err) |
| 167 | } | 206 | } |
| 168 | 207 | ||
| 169 | req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) | 208 | body, err := doAniListSearchRequest(url, requestBody, token) |
| 170 | if err != nil { | ||
| 171 | return nil, fmt.Errorf("failed to create new request: %w", err) | ||
| 172 | } | ||
| 173 | |||
| 174 | req.Header.Set("Authorization", "Bearer "+token) | ||
| 175 | req.Header.Set("Content-Type", "application/json") | ||
| 176 | |||
| 177 | client := &http.Client{} | ||
| 178 | resp, err := client.Do(req) | ||
| 179 | if err != nil { | 209 | if err != nil { |
| 180 | return nil, fmt.Errorf("failed to make request: %w", err) | 210 | return nil, err |
| 181 | } | ||
| 182 | defer resp.Body.Close() | ||
| 183 | |||
| 184 | if resp.StatusCode != http.StatusOK { | ||
| 185 | body, _ := io.ReadAll(resp.Body) | ||
| 186 | return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body)) | ||
| 187 | } | ||
| 188 | |||
| 189 | body, err := io.ReadAll(resp.Body) | ||
| 190 | if err != nil { | ||
| 191 | return nil, fmt.Errorf("failed to read response body: %w", err) | ||
| 192 | } | 211 | } |
| 193 | 212 | ||
| 194 | var responseData map[string]ResponseData | 213 | var responseData map[string]ResponseData |
| @@ -259,29 +278,9 @@ func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) { | |||
| 259 | return nil, fmt.Errorf("failed to marshal request body: %w", err) | 278 | return nil, fmt.Errorf("failed to marshal request body: %w", err) |
| 260 | } | 279 | } |
| 261 | 280 | ||
| 262 | req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) | 281 | body, err := doAniListSearchRequest(url, requestBody, token) |
| 263 | if err != nil { | ||
| 264 | return nil, fmt.Errorf("failed to create new request: %w", err) | ||
| 265 | } | ||
| 266 | |||
| 267 | req.Header.Set("Authorization", "Bearer "+token) | ||
| 268 | req.Header.Set("Content-Type", "application/json") | ||
| 269 | |||
| 270 | client := &http.Client{} | ||
| 271 | resp, err := client.Do(req) | ||
| 272 | if err != nil { | ||
| 273 | return nil, fmt.Errorf("failed to make request: %w", err) | ||
| 274 | } | ||
| 275 | defer resp.Body.Close() | ||
| 276 | |||
| 277 | if resp.StatusCode != http.StatusOK { | ||
| 278 | body, _ := io.ReadAll(resp.Body) | ||
| 279 | return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body)) | ||
| 280 | } | ||
| 281 | |||
| 282 | body, err := io.ReadAll(resp.Body) | ||
| 283 | if err != nil { | 282 | if err != nil { |
| 284 | return nil, fmt.Errorf("failed to read response body: %w", err) | 283 | return nil, err |
| 285 | } | 284 | } |
| 286 | 285 | ||
| 287 | var responseData map[string]ResponseData | 286 | var responseData map[string]ResponseData |
| @@ -335,9 +334,11 @@ func GetAnilistUserID(token string) (int, string, error) { | |||
| 335 | }` | 334 | }` |
| 336 | 335 | ||
| 337 | headers := map[string]string{ | 336 | headers := map[string]string{ |
| 338 | "Authorization": "Bearer " + token, | 337 | "Content-Type": "application/json", |
| 339 | "Content-Type": "application/json", | 338 | "Accept": "application/json", |
| 340 | "Accept": "application/json", | 339 | } |
| 340 | if token != "" { | ||
| 341 | headers["Authorization"] = "Bearer " + token | ||
| 341 | } | 342 | } |
| 342 | 343 | ||
| 343 | response, err := makePostRequest(url, query, nil, headers) | 344 | response, err := makePostRequest(url, query, nil, headers) |
| @@ -353,7 +354,7 @@ func GetAnilistUserID(token string) (int, string, error) { | |||
| 353 | } | 354 | } |
| 354 | 355 | ||
| 355 | // Function to add an anime to the watching list | 356 | // Function to add an anime to the watching list |
| 356 | func AddAnimeToWatchingList(animeID int, token string) error { | 357 | func AddAniListAnimeToWatchingList(animeID int, token string) error { |
| 357 | url := "https://graphql.anilist.co" | 358 | url := "https://graphql.anilist.co" |
| 358 | mutation := ` | 359 | mutation := ` |
| 359 | mutation ($mediaId: Int) { | 360 | mutation ($mediaId: Int) { |
| @@ -367,9 +368,9 @@ func AddAnimeToWatchingList(animeID int, token string) error { | |||
| 367 | "mediaId": animeID, | 368 | "mediaId": animeID, |
| 368 | } | 369 | } |
| 369 | 370 | ||
| 370 | headers := map[string]string{ | 371 | headers := map[string]string{"Content-Type": "application/json"} |
| 371 | "Authorization": "Bearer " + token, | 372 | if token != "" { |
| 372 | "Content-Type": "application/json", | 373 | headers["Authorization"] = "Bearer " + token |
| 373 | } | 374 | } |
| 374 | 375 | ||
| 375 | _, err := makePostRequest(url, mutation, variables, headers) | 376 | _, err := makePostRequest(url, mutation, variables, headers) |
| @@ -440,8 +441,10 @@ func GetUserData(token string, userID int) (map[string]interface{}, error) { | |||
| 440 | MediaListCollection(userId: $userId, type: $type) { | 441 | MediaListCollection(userId: $userId, type: $type) { |
| 441 | lists { | 442 | lists { |
| 442 | entries { | 443 | entries { |
| 444 | id | ||
| 443 | media { | 445 | media { |
| 444 | id | 446 | id |
| 447 | idMal | ||
| 445 | episodes | 448 | episodes |
| 446 | duration | 449 | duration |
| 447 | title { | 450 | title { |
| @@ -455,6 +458,7 @@ func GetUserData(token string, userID int) (map[string]interface{}, error) { | |||
| 455 | score | 458 | score |
| 456 | progress | 459 | progress |
| 457 | repeat | 460 | repeat |
| 461 | updatedAt | ||
| 458 | startedAt { | 462 | startedAt { |
| 459 | year | 463 | year |
| 460 | month | 464 | month |
| @@ -475,9 +479,9 @@ func GetUserData(token string, userID int) (map[string]interface{}, error) { | |||
| 475 | "type": "ANIME", | 479 | "type": "ANIME", |
| 476 | } | 480 | } |
| 477 | 481 | ||
| 478 | headers := map[string]string{ | 482 | headers := map[string]string{"Content-Type": "application/json"} |
| 479 | "Authorization": "Bearer " + token, | 483 | if token != "" { |
| 480 | "Content-Type": "application/json", | 484 | headers["Authorization"] = "Bearer " + token |
| 481 | } | 485 | } |
| 482 | 486 | ||
| 483 | response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers) | 487 | response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers) |
| @@ -494,8 +498,10 @@ func GetUserDataPreview(token string, userID int) (map[string]interface{}, error | |||
| 494 | MediaListCollection(userId: $userId, type: $type) { | 498 | MediaListCollection(userId: $userId, type: $type) { |
| 495 | lists { | 499 | lists { |
| 496 | entries { | 500 | entries { |
| 501 | id | ||
| 497 | media { | 502 | media { |
| 498 | id | 503 | id |
| 504 | idMal | ||
| 499 | episodes | 505 | episodes |
| 500 | duration | 506 | duration |
| 501 | coverImage { | 507 | coverImage { |
| @@ -512,6 +518,7 @@ func GetUserDataPreview(token string, userID int) (map[string]interface{}, error | |||
| 512 | score | 518 | score |
| 513 | progress | 519 | progress |
| 514 | repeat | 520 | repeat |
| 521 | updatedAt | ||
| 515 | startedAt { | 522 | startedAt { |
| 516 | year | 523 | year |
| 517 | month | 524 | month |
| @@ -532,9 +539,9 @@ func GetUserDataPreview(token string, userID int) (map[string]interface{}, error | |||
| 532 | "type": "ANIME", | 539 | "type": "ANIME", |
| 533 | } | 540 | } |
| 534 | 541 | ||
| 535 | headers := map[string]string{ | 542 | headers := map[string]string{"Content-Type": "application/json"} |
| 536 | "Authorization": "Bearer " + token, | 543 | if token != "" { |
| 537 | "Content-Type": "application/json", | 544 | headers["Authorization"] = "Bearer " + token |
| 538 | } | 545 | } |
| 539 | 546 | ||
| 540 | response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers) | 547 | response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers) |
| @@ -593,8 +600,8 @@ func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []m | |||
| 593 | } | 600 | } |
| 594 | 601 | ||
| 595 | // Function to update anime progress | 602 | // Function to update anime progress |
| 596 | func UpdateAnimeProgress(token string, mediaID, progress int) error { | 603 | func UpdateAniListAnimeProgress(token string, mediaID, progress int) error { |
| 597 | err := SaveAnimeListEntry(token, mediaID, nil, &progress, nil, nil, nil) | 604 | err := SaveAniListAnimeListEntry(token, mediaID, nil, &progress, nil, nil, nil, nil) |
| 598 | if err != nil { | 605 | if err != nil { |
| 599 | return err | 606 | return err |
| 600 | } | 607 | } |
| @@ -603,8 +610,8 @@ func UpdateAnimeProgress(token string, mediaID, progress int) error { | |||
| 603 | return nil | 610 | return nil |
| 604 | } | 611 | } |
| 605 | 612 | ||
| 606 | func UpdateAnimeStatus(token string, mediaID int, status string) error { | 613 | func UpdateAniListAnimeStatus(token string, mediaID int, status string) error { |
| 607 | err := SaveAnimeListEntry(token, mediaID, &status, nil, nil, nil, nil) | 614 | err := SaveAniListAnimeListEntry(token, mediaID, &status, nil, nil, nil, nil, nil) |
| 608 | if err != nil { | 615 | if err != nil { |
| 609 | return fmt.Errorf("failed to update anime status: %w", err) | 616 | return fmt.Errorf("failed to update anime status: %w", err) |
| 610 | } | 617 | } |
| @@ -622,7 +629,7 @@ func UpdateAnimeStatus(token string, mediaID int, status string) error { | |||
| 622 | return nil | 629 | return nil |
| 623 | } | 630 | } |
| 624 | 631 | ||
| 625 | func SaveAnimeListEntry(token string, mediaID int, status *string, progress *int, repeat *int, startedAt *FuzzyDate, completedAt *FuzzyDate) error { | 632 | func SaveAniListAnimeListEntry(token string, mediaID int, status *string, progress *int, repeat *int, score *float64, startedAt *FuzzyDate, completedAt *FuzzyDate) error { |
| 626 | url := "https://graphql.anilist.co" | 633 | url := "https://graphql.anilist.co" |
| 627 | query := ` | 634 | query := ` |
| 628 | mutation( | 635 | mutation( |
| @@ -630,6 +637,7 @@ func SaveAnimeListEntry(token string, mediaID int, status *string, progress *int | |||
| 630 | $status: MediaListStatus | 637 | $status: MediaListStatus |
| 631 | $progress: Int | 638 | $progress: Int |
| 632 | $repeat: Int | 639 | $repeat: Int |
| 640 | $score: Float | ||
| 633 | $startedAt: FuzzyDateInput | 641 | $startedAt: FuzzyDateInput |
| 634 | $completedAt: FuzzyDateInput | 642 | $completedAt: FuzzyDateInput |
| 635 | ) { | 643 | ) { |
| @@ -638,6 +646,7 @@ func SaveAnimeListEntry(token string, mediaID int, status *string, progress *int | |||
| 638 | status: $status | 646 | status: $status |
| 639 | progress: $progress | 647 | progress: $progress |
| 640 | repeat: $repeat | 648 | repeat: $repeat |
| 649 | score: $score | ||
| 641 | startedAt: $startedAt | 650 | startedAt: $startedAt |
| 642 | completedAt: $completedAt | 651 | completedAt: $completedAt |
| 643 | ) { | 652 | ) { |
| @@ -670,18 +679,29 @@ func SaveAnimeListEntry(token string, mediaID int, status *string, progress *int | |||
| 670 | if repeat != nil { | 679 | if repeat != nil { |
| 671 | variables["repeat"] = *repeat | 680 | variables["repeat"] = *repeat |
| 672 | } | 681 | } |
| 673 | if startedAt != nil && (startedAt.Year != 0 || startedAt.Month != 0 || startedAt.Day != 0) { | 682 | if score != nil { |
| 674 | variables["startedAt"] = map[string]int{ | 683 | variables["score"] = *score |
| 675 | "year": startedAt.Year, | 684 | } |
| 676 | "month": startedAt.Month, | 685 | if startedAt != nil { |
| 677 | "day": startedAt.Day, | 686 | if startedAt.Year == 0 && startedAt.Month == 0 && startedAt.Day == 0 { |
| 687 | variables["startedAt"] = nil | ||
| 688 | } else { | ||
| 689 | variables["startedAt"] = map[string]int{ | ||
| 690 | "year": startedAt.Year, | ||
| 691 | "month": startedAt.Month, | ||
| 692 | "day": startedAt.Day, | ||
| 693 | } | ||
| 678 | } | 694 | } |
| 679 | } | 695 | } |
| 680 | if completedAt != nil && (completedAt.Year != 0 || completedAt.Month != 0 || completedAt.Day != 0) { | 696 | if completedAt != nil { |
| 681 | variables["completedAt"] = map[string]int{ | 697 | if completedAt.Year == 0 && completedAt.Month == 0 && completedAt.Day == 0 { |
| 682 | "year": completedAt.Year, | 698 | variables["completedAt"] = nil |
| 683 | "month": completedAt.Month, | 699 | } else { |
| 684 | "day": completedAt.Day, | 700 | variables["completedAt"] = map[string]int{ |
| 701 | "year": completedAt.Year, | ||
| 702 | "month": completedAt.Month, | ||
| 703 | "day": completedAt.Day, | ||
| 704 | } | ||
| 685 | } | 705 | } |
| 686 | } | 706 | } |
| 687 | 707 | ||
| @@ -697,36 +717,28 @@ func SaveAnimeListEntry(token string, mediaID int, status *string, progress *int | |||
| 697 | return nil | 717 | return nil |
| 698 | } | 718 | } |
| 699 | 719 | ||
| 700 | func CompleteAnimeRewatch(token string, anime Anime) error { | 720 | func CompleteAniListAnimeRewatch(token string, anime Anime) error { |
| 701 | status := "COMPLETED" | 721 | status := "COMPLETED" |
| 722 | progress := anime.Ep.Number | ||
| 702 | repeat := anime.Repeat + 1 | 723 | repeat := anime.Repeat + 1 |
| 703 | return SaveAnimeListEntry(token, anime.AnilistId, &status, nil, &repeat, &anime.StartedAt, &anime.CompletedAt) | 724 | completedAt := currentFuzzyDate() |
| 725 | startedAt := anime.StartedAt | ||
| 726 | if startedAt == (FuzzyDate{}) { | ||
| 727 | startedAt = completedAt | ||
| 728 | } | ||
| 729 | return SaveAniListAnimeListEntry(token, anime.AnilistId, &status, &progress, &repeat, nil, &startedAt, &completedAt) | ||
| 704 | } | 730 | } |
| 705 | 731 | ||
| 706 | // Function to rate an anime on AniList | 732 | // Function to rate an anime on AniList |
| 707 | func RateAnime(token string, mediaID int) error { | 733 | func RateAniListAnime(token string, mediaID int) error { |
| 708 | var score float64 | 734 | score, err := promptAnimeScoreValue() |
| 709 | var err error | 735 | if err != nil { |
| 710 | 736 | return err | |
| 711 | userCurdConfig := GetGlobalConfig() | ||
| 712 | if userCurdConfig == nil { | ||
| 713 | return fmt.Errorf("failed to get curd config") | ||
| 714 | } | ||
| 715 | |||
| 716 | if userCurdConfig.RofiSelection { | ||
| 717 | userInput, err := GetUserInputFromRofi("Enter a score for the anime (0-10)") | ||
| 718 | if err != nil { | ||
| 719 | return err | ||
| 720 | } | ||
| 721 | score, err = strconv.ParseFloat(userInput, 64) | ||
| 722 | if err != nil { | ||
| 723 | return err | ||
| 724 | } | ||
| 725 | } else { | ||
| 726 | fmt.Println("Rate this anime: ") | ||
| 727 | fmt.Scanln(&score) | ||
| 728 | } | 737 | } |
| 738 | return saveAniListAnimeScore(token, mediaID, score) | ||
| 739 | } | ||
| 729 | 740 | ||
| 741 | func saveAniListAnimeScore(token string, mediaID int, score float64) error { | ||
| 730 | url := "https://graphql.anilist.co" | 742 | url := "https://graphql.anilist.co" |
| 731 | query := ` | 743 | query := ` |
| 732 | mutation($mediaId: Int, $score: Float) { | 744 | mutation($mediaId: Int, $score: Float) { |
| @@ -747,7 +759,7 @@ func RateAnime(token string, mediaID int) error { | |||
| 747 | "Content-Type": "application/json", | 759 | "Content-Type": "application/json", |
| 748 | } | 760 | } |
| 749 | 761 | ||
| 750 | _, err = makePostRequest(url, query, variables, headers) | 762 | _, err := makePostRequest(url, query, variables, headers) |
| 751 | if err != nil { | 763 | if err != nil { |
| 752 | return err | 764 | return err |
| 753 | } | 765 | } |
| @@ -756,6 +768,18 @@ func RateAnime(token string, mediaID int) error { | |||
| 756 | return nil | 768 | return nil |
| 757 | } | 769 | } |
| 758 | 770 | ||
| 771 | func aniListRetryDelay(resp *http.Response, attempt int) time.Duration { | ||
| 772 | if resp != nil { | ||
| 773 | if retryAfter := strings.TrimSpace(resp.Header.Get("Retry-After")); retryAfter != "" { | ||
| 774 | if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds > 0 { | ||
| 775 | return time.Duration(seconds) * time.Second | ||
| 776 | } | ||
| 777 | } | ||
| 778 | } | ||
| 779 | |||
| 780 | return time.Duration(attempt+1) * 2 * time.Second | ||
| 781 | } | ||
| 782 | |||
| 759 | // Helper function to make POST requests | 783 | // Helper function to make POST requests |
| 760 | func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) { | 784 | func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) { |
| 761 | requestBody, err := json.Marshal(map[string]interface{}{ | 785 | requestBody, err := json.Marshal(map[string]interface{}{ |
| @@ -766,40 +790,49 @@ func makePostRequest(url, query string, variables map[string]interface{}, header | |||
| 766 | return nil, fmt.Errorf("failed to marshal request body: %w", err) | 790 | return nil, fmt.Errorf("failed to marshal request body: %w", err) |
| 767 | } | 791 | } |
| 768 | 792 | ||
| 769 | req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) | 793 | client := &http.Client{} |
| 770 | if err != nil { | 794 | for attempt := 0; attempt < 5; attempt++ { |
| 771 | return nil, fmt.Errorf("failed to create request: %w", err) | 795 | req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) |
| 772 | } | 796 | if err != nil { |
| 797 | return nil, fmt.Errorf("failed to create request: %w", err) | ||
| 798 | } | ||
| 773 | 799 | ||
| 774 | req.Header.Set("Content-Type", "application/json") // <-- Important! | 800 | req.Header.Set("Content-Type", "application/json") |
| 775 | for key, value := range headers { | 801 | for key, value := range headers { |
| 776 | req.Header.Set(key, value) | 802 | req.Header.Set(key, value) |
| 777 | } | 803 | } |
| 778 | 804 | ||
| 779 | client := &http.Client{} | 805 | resp, err := client.Do(req) |
| 780 | resp, err := client.Do(req) | 806 | if err != nil { |
| 781 | if err != nil { | 807 | return nil, fmt.Errorf("failed to send request: %w", err) |
| 782 | return nil, fmt.Errorf("failed to send request: %w", err) | 808 | } |
| 783 | } | ||
| 784 | defer resp.Body.Close() | ||
| 785 | 809 | ||
| 786 | body, err := io.ReadAll(resp.Body) | 810 | body, readErr := io.ReadAll(resp.Body) |
| 787 | if err != nil { | 811 | resp.Body.Close() |
| 788 | return nil, fmt.Errorf("failed to read response body: %w", err) | 812 | if readErr != nil { |
| 789 | } | 813 | return nil, fmt.Errorf("failed to read response body: %w", readErr) |
| 814 | } | ||
| 790 | 815 | ||
| 791 | if resp.StatusCode != http.StatusOK { | 816 | if resp.StatusCode == http.StatusTooManyRequests { |
| 792 | return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body) | 817 | if attempt == 4 { |
| 793 | } | 818 | return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body) |
| 819 | } | ||
| 820 | time.Sleep(aniListRetryDelay(resp, attempt)) | ||
| 821 | continue | ||
| 822 | } | ||
| 823 | if resp.StatusCode != http.StatusOK { | ||
| 824 | return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body) | ||
| 825 | } | ||
| 794 | 826 | ||
| 795 | var responseData map[string]interface{} | 827 | var responseData map[string]interface{} |
| 796 | // Unmarshal the response into a map | 828 | if err := json.Unmarshal(body, &responseData); err != nil { |
| 797 | err = json.Unmarshal(body, &responseData) | 829 | return nil, fmt.Errorf("failed to unmarshal response: %w", err) |
| 798 | if err != nil { | 830 | } |
| 799 | return nil, fmt.Errorf("failed to unmarshal response: %w", err) | 831 | |
| 832 | return responseData, nil | ||
| 800 | } | 833 | } |
| 801 | 834 | ||
| 802 | return responseData, nil | 835 | return nil, fmt.Errorf("AniList request failed after retries") |
| 803 | } | 836 | } |
| 804 | 837 | ||
| 805 | func ParseAnimeList(input map[string]interface{}) AnimeList { | 838 | func ParseAnimeList(input map[string]interface{}) AnimeList { |
| @@ -860,10 +893,12 @@ func ParseAnimeList(input map[string]interface{}) AnimeList { | |||
| 860 | entryData := entry.(map[string]interface{}) | 893 | entryData := entry.(map[string]interface{}) |
| 861 | media := entryData["media"].(map[string]interface{}) | 894 | media := entryData["media"].(map[string]interface{}) |
| 862 | animeEntry := Entry{ | 895 | animeEntry := Entry{ |
| 896 | ListID: toInt(entryData["id"]), | ||
| 863 | Media: Media{ | 897 | Media: Media{ |
| 864 | Duration: toInt(media["duration"]), | 898 | Duration: toInt(media["duration"]), |
| 865 | Episodes: toInt(media["episodes"]), | 899 | Episodes: toInt(media["episodes"]), |
| 866 | ID: toInt(media["id"]), | 900 | ID: toInt(media["id"]), |
| 901 | MalID: toInt(media["idMal"]), | ||
| 867 | Title: AnimeTitle{ | 902 | Title: AnimeTitle{ |
| 868 | English: safeString(media["title"].(map[string]interface{})["english"]), | 903 | English: safeString(media["title"].(map[string]interface{})["english"]), |
| 869 | Romaji: safeString(media["title"].(map[string]interface{})["romaji"]), | 904 | Romaji: safeString(media["title"].(map[string]interface{})["romaji"]), |
| @@ -877,6 +912,7 @@ func ParseAnimeList(input map[string]interface{}) AnimeList { | |||
| 877 | Status: safeString(entryData["status"]), // Ensure status is fetched safely | 912 | Status: safeString(entryData["status"]), // Ensure status is fetched safely |
| 878 | StartedAt: parseFuzzyDate(entryData["startedAt"]), | 913 | StartedAt: parseFuzzyDate(entryData["startedAt"]), |
| 879 | CompletedAt: parseFuzzyDate(entryData["completedAt"]), | 914 | CompletedAt: parseFuzzyDate(entryData["completedAt"]), |
| 915 | UpdatedAt: time.Unix(int64(toInt(entryData["updatedAt"])), 0).UTC(), | ||
| 880 | } | 916 | } |
| 881 | 917 | ||
| 882 | if coverImage, ok := media["coverImage"].(map[string]interface{}); ok { | 918 | if coverImage, ok := media["coverImage"].(map[string]interface{}); ok { |
| @@ -950,8 +986,18 @@ func GetAnimeDataByID(id int, token string) (Anime, error) { | |||
| 950 | query ($id: Int) { | 986 | query ($id: Int) { |
| 951 | Media(id: $id, type: ANIME) { | 987 | Media(id: $id, type: ANIME) { |
| 952 | id | 988 | id |
| 989 | idMal | ||
| 953 | episodes | 990 | episodes |
| 991 | duration | ||
| 954 | status | 992 | status |
| 993 | title { | ||
| 994 | romaji | ||
| 995 | english | ||
| 996 | native | ||
| 997 | } | ||
| 998 | coverImage { | ||
| 999 | large | ||
| 1000 | } | ||
| 955 | nextAiringEpisode { | 1001 | nextAiringEpisode { |
| 956 | episode | 1002 | episode |
| 957 | } | 1003 | } |
| @@ -962,9 +1008,9 @@ func GetAnimeDataByID(id int, token string) (Anime, error) { | |||
| 962 | "id": id, | 1008 | "id": id, |
| 963 | } | 1009 | } |
| 964 | 1010 | ||
| 965 | headers := map[string]string{ | 1011 | headers := map[string]string{"Content-Type": "application/json"} |
| 966 | "Authorization": "Bearer " + token, | 1012 | if token != "" { |
| 967 | "Content-Type": "application/json", | 1013 | headers["Authorization"] = "Bearer " + token |
| 968 | } | 1014 | } |
| 969 | 1015 | ||
| 970 | response, err := makePostRequest(url, query, variables, headers) | 1016 | response, err := makePostRequest(url, query, variables, headers) |
| @@ -987,10 +1033,27 @@ func GetAnimeDataByID(id int, token string) (Anime, error) { | |||
| 987 | IsAiring: false, | 1033 | IsAiring: false, |
| 988 | } | 1034 | } |
| 989 | 1035 | ||
| 1036 | if malID, ok := media["idMal"].(float64); ok { | ||
| 1037 | anime.MalId = int(malID) | ||
| 1038 | } | ||
| 1039 | |||
| 990 | // Safely handle episodes field which might be nil for currently airing shows | 1040 | // Safely handle episodes field which might be nil for currently airing shows |
| 991 | if episodes, ok := media["episodes"].(float64); ok { | 1041 | if episodes, ok := media["episodes"].(float64); ok { |
| 992 | anime.TotalEpisodes = int(episodes) | 1042 | anime.TotalEpisodes = int(episodes) |
| 993 | } | 1043 | } |
| 1044 | if duration, ok := media["duration"].(float64); ok { | ||
| 1045 | anime.Ep.Duration = int(duration) * 60 | ||
| 1046 | } | ||
| 1047 | if title, ok := media["title"].(map[string]interface{}); ok { | ||
| 1048 | anime.Title = AnimeTitle{ | ||
| 1049 | Romaji: safeAniListString(title["romaji"]), | ||
| 1050 | English: safeAniListString(title["english"]), | ||
| 1051 | Japanese: safeAniListString(title["native"]), | ||
| 1052 | } | ||
| 1053 | } | ||
| 1054 | if coverImage, ok := media["coverImage"].(map[string]interface{}); ok { | ||
| 1055 | anime.CoverImage = safeAniListString(coverImage["large"]) | ||
| 1056 | } | ||
| 994 | 1057 | ||
| 995 | // Check status | 1058 | // Check status |
| 996 | if status, ok := media["status"].(string); ok { | 1059 | if status, ok := media["status"].(string); ok { |
| @@ -1047,9 +1110,9 @@ func GetAnimeSequel(animeID int, token string) ([]SequelInfo, error) { | |||
| 1047 | "id": animeID, | 1110 | "id": animeID, |
| 1048 | } | 1111 | } |
| 1049 | 1112 | ||
| 1050 | headers := map[string]string{ | 1113 | headers := map[string]string{"Content-Type": "application/json"} |
| 1051 | "Authorization": "Bearer " + token, | 1114 | if token != "" { |
| 1052 | "Content-Type": "application/json", | 1115 | headers["Authorization"] = "Bearer " + token |
| 1053 | } | 1116 | } |
| 1054 | 1117 | ||
| 1055 | response, err := makePostRequest(url, query, variables, headers) | 1118 | response, err := makePostRequest(url, query, variables, headers) |
| @@ -1146,7 +1209,7 @@ func GetAnimeSequel(animeID int, token string) ([]SequelInfo, error) { | |||
| 1146 | } | 1209 | } |
| 1147 | 1210 | ||
| 1148 | // AddAnimeToList adds an anime to a specified list (CURRENT, PLANNING, PAUSED, DROPPED) | 1211 | // AddAnimeToList adds an anime to a specified list (CURRENT, PLANNING, PAUSED, DROPPED) |
| 1149 | func AddAnimeToList(animeID int, status string, token string) error { | 1212 | func AddAniListAnimeToList(animeID int, status string, token string) error { |
| 1150 | url := "https://graphql.anilist.co" | 1213 | url := "https://graphql.anilist.co" |
| 1151 | mutation := ` | 1214 | mutation := ` |
| 1152 | mutation ($mediaId: Int, $status: MediaListStatus) { | 1215 | mutation ($mediaId: Int, $status: MediaListStatus) { |
| @@ -1184,6 +1247,24 @@ func AddAnimeToList(animeID int, status string, token string) error { | |||
| 1184 | return nil | 1247 | return nil |
| 1185 | } | 1248 | } |
| 1186 | 1249 | ||
| 1250 | func DeleteAniListListEntry(token string, listID int) error { | ||
| 1251 | url := "https://graphql.anilist.co" | ||
| 1252 | query := ` | ||
| 1253 | mutation ($id: Int) { | ||
| 1254 | DeleteMediaListEntry(id: $id) { | ||
| 1255 | deleted | ||
| 1256 | } | ||
| 1257 | }` | ||
| 1258 | |||
| 1259 | headers := map[string]string{"Content-Type": "application/json"} | ||
| 1260 | if token != "" { | ||
| 1261 | headers["Authorization"] = "Bearer " + token | ||
| 1262 | } | ||
| 1263 | |||
| 1264 | _, err := makePostRequest(url, query, map[string]interface{}{"id": listID}, headers) | ||
| 1265 | return err | ||
| 1266 | } | ||
| 1267 | |||
| 1187 | // FindSequelInAnimeList searches for a sequel in the user's anime list and returns its status | 1268 | // FindSequelInAnimeList searches for a sequel in the user's anime list and returns its status |
| 1188 | func FindSequelInAnimeList(list AnimeList, sequelID int) (string, bool) { | 1269 | func FindSequelInAnimeList(list AnimeList, sequelID int) (string, bool) { |
| 1189 | // Check all categories | 1270 | // Check all categories |
internal/anilist_cache.go +19 −19
| @@ -10,7 +10,7 @@ import ( | |||
| 10 | "time" | 10 | "time" |
| 11 | ) | 11 | ) |
| 12 | 12 | ||
| 13 | const animeListCacheFileName = "anilist_list_cache.json" | 13 | const anilistAnimeListCacheFileName = "anilist_list_cache.json" |
| 14 | 14 | ||
| 15 | type animeListCachePayload struct { | 15 | type animeListCachePayload struct { |
| 16 | AnimeList AnimeList `json:"anime_list"` | 16 | AnimeList AnimeList `json:"anime_list"` |
| @@ -75,12 +75,12 @@ func (s *AnimeListSync) Updates() <-chan AnimeList { | |||
| 75 | return s.updates | 75 | return s.updates |
| 76 | } | 76 | } |
| 77 | 77 | ||
| 78 | func animeListCachePath(storagePath string) string { | 78 | func aniListCachePath(storagePath string) string { |
| 79 | return filepath.Join(os.ExpandEnv(storagePath), animeListCacheFileName) | 79 | return filepath.Join(os.ExpandEnv(storagePath), anilistAnimeListCacheFileName) |
| 80 | } | 80 | } |
| 81 | 81 | ||
| 82 | func loadAnimeListCache(storagePath string, userID int) (animeListCachePayload, error) { | 82 | func loadAniListAnimeListCache(storagePath string, userID int) (animeListCachePayload, error) { |
| 83 | cacheFilePath := animeListCachePath(storagePath) | 83 | cacheFilePath := aniListCachePath(storagePath) |
| 84 | data, err := os.ReadFile(cacheFilePath) | 84 | data, err := os.ReadFile(cacheFilePath) |
| 85 | if err != nil { | 85 | if err != nil { |
| 86 | return animeListCachePayload{}, err | 86 | return animeListCachePayload{}, err |
| @@ -98,7 +98,7 @@ func loadAnimeListCache(storagePath string, userID int) (animeListCachePayload, | |||
| 98 | return payload, nil | 98 | return payload, nil |
| 99 | } | 99 | } |
| 100 | 100 | ||
| 101 | func saveAnimeListCache(storagePath string, userID int, list AnimeList) error { | 101 | func saveAniListAnimeListCache(storagePath string, userID int, list AnimeList) error { |
| 102 | storagePath = os.ExpandEnv(storagePath) | 102 | storagePath = os.ExpandEnv(storagePath) |
| 103 | if err := os.MkdirAll(storagePath, 0o755); err != nil { | 103 | if err := os.MkdirAll(storagePath, 0o755); err != nil { |
| 104 | return fmt.Errorf("failed to create storage directory: %w", err) | 104 | return fmt.Errorf("failed to create storage directory: %w", err) |
| @@ -115,7 +115,7 @@ func saveAnimeListCache(storagePath string, userID int, list AnimeList) error { | |||
| 115 | return fmt.Errorf("failed to marshal anime list cache: %w", err) | 115 | return fmt.Errorf("failed to marshal anime list cache: %w", err) |
| 116 | } | 116 | } |
| 117 | 117 | ||
| 118 | cacheFilePath := animeListCachePath(storagePath) | 118 | cacheFilePath := aniListCachePath(storagePath) |
| 119 | tempFilePath := cacheFilePath + ".tmp" | 119 | tempFilePath := cacheFilePath + ".tmp" |
| 120 | if err := os.WriteFile(tempFilePath, data, 0o644); err != nil { | 120 | if err := os.WriteFile(tempFilePath, data, 0o644); err != nil { |
| 121 | return fmt.Errorf("failed to write anime list cache: %w", err) | 121 | return fmt.Errorf("failed to write anime list cache: %w", err) |
| @@ -141,7 +141,7 @@ func animeListEqual(a, b AnimeList) bool { | |||
| 141 | return string(left) == string(right) | 141 | return string(left) == string(right) |
| 142 | } | 142 | } |
| 143 | 143 | ||
| 144 | func FetchLatestAnimeList(token string, userID int) (AnimeList, error) { | 144 | func FetchLatestAniListAnimeList(token string, userID int) (AnimeList, error) { |
| 145 | userData, err := GetUserDataPreview(token, userID) | 145 | userData, err := GetUserDataPreview(token, userID) |
| 146 | if err != nil { | 146 | if err != nil { |
| 147 | return AnimeList{}, err | 147 | return AnimeList{}, err |
| @@ -150,7 +150,7 @@ func FetchLatestAnimeList(token string, userID int) (AnimeList, error) { | |||
| 150 | return ParseAnimeList(userData), nil | 150 | return ParseAnimeList(userData), nil |
| 151 | } | 151 | } |
| 152 | 152 | ||
| 153 | func refreshAnimeListInBackground(userCurdConfig *CurdConfig, user *User) { | 153 | func refreshAniListAnimeListInBackground(userCurdConfig *CurdConfig, user *User) { |
| 154 | if user == nil || user.ListSync == nil { | 154 | if user == nil || user.ListSync == nil { |
| 155 | return | 155 | return |
| 156 | } | 156 | } |
| @@ -173,13 +173,13 @@ func refreshAnimeListInBackground(userCurdConfig *CurdConfig, user *User) { | |||
| 173 | } | 173 | } |
| 174 | } | 174 | } |
| 175 | 175 | ||
| 176 | latestList, err := FetchLatestAnimeList(user.Token, user.Id) | 176 | latestList, err := FetchLatestAniListAnimeList(user.Token, user.Id) |
| 177 | if err != nil { | 177 | if err != nil { |
| 178 | Log(fmt.Sprintf("Failed to refresh anime list in background: %v", err)) | 178 | Log(fmt.Sprintf("Failed to refresh anime list in background: %v", err)) |
| 179 | return | 179 | return |
| 180 | } | 180 | } |
| 181 | 181 | ||
| 182 | if err := saveAnimeListCache(userCurdConfig.StoragePath, user.Id, latestList); err != nil { | 182 | if err := saveAniListAnimeListCache(userCurdConfig.StoragePath, user.Id, latestList); err != nil { |
| 183 | Log(fmt.Sprintf("Failed to save refreshed anime list cache: %v", err)) | 183 | Log(fmt.Sprintf("Failed to save refreshed anime list cache: %v", err)) |
| 184 | } | 184 | } |
| 185 | 185 | ||
| @@ -187,8 +187,8 @@ func refreshAnimeListInBackground(userCurdConfig *CurdConfig, user *User) { | |||
| 187 | }() | 187 | }() |
| 188 | } | 188 | } |
| 189 | 189 | ||
| 190 | func InitializeUserAnimeList(userCurdConfig *CurdConfig, user *User) error { | 190 | func InitializeAniListUserAnimeList(userCurdConfig *CurdConfig, user *User) error { |
| 191 | cachedPayload, err := loadAnimeListCache(userCurdConfig.StoragePath, user.Id) | 191 | cachedPayload, err := loadAniListAnimeListCache(userCurdConfig.StoragePath, user.Id) |
| 192 | if err == nil { | 192 | if err == nil { |
| 193 | // Seed user ID from cache so we skip the blocking GetAnilistUserID network call. | 193 | // Seed user ID from cache so we skip the blocking GetAnilistUserID network call. |
| 194 | if user.Id == 0 && cachedPayload.UserID != 0 { | 194 | if user.Id == 0 && cachedPayload.UserID != 0 { |
| @@ -197,7 +197,7 @@ func InitializeUserAnimeList(userCurdConfig *CurdConfig, user *User) error { | |||
| 197 | user.AnimeList = cachedPayload.AnimeList | 197 | user.AnimeList = cachedPayload.AnimeList |
| 198 | user.ListSync = NewAnimeListSync(cachedPayload.AnimeList) | 198 | user.ListSync = NewAnimeListSync(cachedPayload.AnimeList) |
| 199 | // Refresh user ID + anime list in the background (non-blocking). | 199 | // Refresh user ID + anime list in the background (non-blocking). |
| 200 | refreshAnimeListInBackground(userCurdConfig, user) | 200 | refreshAniListAnimeListInBackground(userCurdConfig, user) |
| 201 | return nil | 201 | return nil |
| 202 | } | 202 | } |
| 203 | 203 | ||
| @@ -215,7 +215,7 @@ func InitializeUserAnimeList(userCurdConfig *CurdConfig, user *User) error { | |||
| 215 | user.Username = username | 215 | user.Username = username |
| 216 | } | 216 | } |
| 217 | 217 | ||
| 218 | latestList, err := FetchLatestAnimeList(user.Token, user.Id) | 218 | latestList, err := FetchLatestAniListAnimeList(user.Token, user.Id) |
| 219 | if err != nil { | 219 | if err != nil { |
| 220 | return err | 220 | return err |
| 221 | } | 221 | } |
| @@ -224,14 +224,14 @@ func InitializeUserAnimeList(userCurdConfig *CurdConfig, user *User) error { | |||
| 224 | user.ListSync = NewAnimeListSync(latestList) | 224 | user.ListSync = NewAnimeListSync(latestList) |
| 225 | // Blocking fetch already has the freshest data — mark done immediately. | 225 | // Blocking fetch already has the freshest data — mark done immediately. |
| 226 | user.ListSync.MarkRefreshDone() | 226 | user.ListSync.MarkRefreshDone() |
| 227 | if err := saveAnimeListCache(userCurdConfig.StoragePath, user.Id, latestList); err != nil { | 227 | if err := saveAniListAnimeListCache(userCurdConfig.StoragePath, user.Id, latestList); err != nil { |
| 228 | Log(fmt.Sprintf("Failed to save anime list cache: %v", err)) | 228 | Log(fmt.Sprintf("Failed to save anime list cache: %v", err)) |
| 229 | } | 229 | } |
| 230 | 230 | ||
| 231 | return nil | 231 | return nil |
| 232 | } | 232 | } |
| 233 | 233 | ||
| 234 | func RefreshUserAnimeList(userCurdConfig *CurdConfig, user *User) error { | 234 | func RefreshAniListUserAnimeList(userCurdConfig *CurdConfig, user *User) error { |
| 235 | if user.Id == 0 { | 235 | if user.Id == 0 { |
| 236 | userID, username, err := GetAnilistUserID(user.Token) | 236 | userID, username, err := GetAnilistUserID(user.Token) |
| 237 | if err != nil { | 237 | if err != nil { |
| @@ -243,7 +243,7 @@ func RefreshUserAnimeList(userCurdConfig *CurdConfig, user *User) error { | |||
| 243 | } | 243 | } |
| 244 | } | 244 | } |
| 245 | 245 | ||
| 246 | latestList, err := FetchLatestAnimeList(user.Token, user.Id) | 246 | latestList, err := FetchLatestAniListAnimeList(user.Token, user.Id) |
| 247 | if err != nil { | 247 | if err != nil { |
| 248 | return err | 248 | return err |
| 249 | } | 249 | } |
| @@ -255,7 +255,7 @@ func RefreshUserAnimeList(userCurdConfig *CurdConfig, user *User) error { | |||
| 255 | user.ListSync.Replace(latestList, true) | 255 | user.ListSync.Replace(latestList, true) |
| 256 | } | 256 | } |
| 257 | 257 | ||
| 258 | if err := saveAnimeListCache(userCurdConfig.StoragePath, user.Id, latestList); err != nil { | 258 | if err := saveAniListAnimeListCache(userCurdConfig.StoragePath, user.Id, latestList); err != nil { |
| 259 | Log(fmt.Sprintf("Failed to save anime list cache: %v", err)) | 259 | Log(fmt.Sprintf("Failed to save anime list cache: %v", err)) |
| 260 | } | 260 | } |
| 261 | 261 | ||
internal/config.go +64 −2
| @@ -61,6 +61,12 @@ type CurdConfig struct { | |||
| 61 | DiscordPresence bool `config:"DiscordPresence"` | 61 | DiscordPresence bool `config:"DiscordPresence"` |
| 62 | DiscordClientId string `config:"DiscordClientId"` | 62 | DiscordClientId string `config:"DiscordClientId"` |
| 63 | Provider string `config:"Provider"` | 63 | Provider string `config:"Provider"` |
| 64 | TrackingLocal bool `config:"TrackingLocal"` | ||
| 65 | TrackingRemote string `config:"TrackingRemote"` | ||
| 66 | TrackingConfigured bool `config:"TrackingConfigured"` | ||
| 67 | MyAnimeListClientID string `config:"MyAnimeListClientID"` | ||
| 68 | MyAnimeListClientSecret string `config:"MyAnimeListClientSecret"` | ||
| 69 | MyAnimeListImported bool `config:"MyAnimeListImported"` | ||
| 64 | } | 70 | } |
| 65 | 71 | ||
| 66 | func GetStoragePath() string { | 72 | func GetStoragePath() string { |
| @@ -78,7 +84,7 @@ func defaultConfigMap() map[string]string { | |||
| 78 | "StoragePath": "$HOME/.local/share/curd", | 84 | "StoragePath": "$HOME/.local/share/curd", |
| 79 | "AnimeNameLanguage": "english", | 85 | "AnimeNameLanguage": "english", |
| 80 | "SubsLanguage": "english", | 86 | "SubsLanguage": "english", |
| 81 | "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,PROVIDER", | 87 | "MenuOrder": "CURRENT,ALL,UNTRACKED,UPDATE,CONTINUE_LAST,TRACKER,PROVIDER", |
| 82 | "SubOrDub": "sub", | 88 | "SubOrDub": "sub", |
| 83 | "PercentageToMarkComplete": "85", | 89 | "PercentageToMarkComplete": "85", |
| 84 | "NextEpisodePrompt": "false", | 90 | "NextEpisodePrompt": "false", |
| @@ -95,6 +101,12 @@ func defaultConfigMap() map[string]string { | |||
| 95 | "DiscordPresence": "true", | 101 | "DiscordPresence": "true", |
| 96 | "DiscordClientId": "1287457464148820089", | 102 | "DiscordClientId": "1287457464148820089", |
| 97 | "Provider": "allanime", | 103 | "Provider": "allanime", |
| 104 | "TrackingLocal": "true", | ||
| 105 | "TrackingRemote": "anilist", | ||
| 106 | "TrackingConfigured": "false", | ||
| 107 | "MyAnimeListClientID": "f76d4c827152327b60654285d221222c", | ||
| 108 | "MyAnimeListClientSecret": "", | ||
| 109 | "MyAnimeListImported": "false", | ||
| 98 | } | 110 | } |
| 99 | } | 111 | } |
| 100 | 112 | ||
| @@ -137,6 +149,7 @@ var GlobalConfigPath string | |||
| 137 | func LoadConfig(configPath string) (CurdConfig, error) { | 149 | func LoadConfig(configPath string) (CurdConfig, error) { |
| 138 | configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME | 150 | configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME |
| 139 | GlobalConfigPath = configPath | 151 | GlobalConfigPath = configPath |
| 152 | createdConfig := false | ||
| 140 | 153 | ||
| 141 | // Check if config file exists | 154 | // Check if config file exists |
| 142 | if _, err := os.Stat(configPath); os.IsNotExist(err) { | 155 | if _, err := os.Stat(configPath); os.IsNotExist(err) { |
| @@ -145,6 +158,7 @@ func LoadConfig(configPath string) (CurdConfig, error) { | |||
| 145 | if err := createDefaultConfig(configPath); err != nil { | 158 | if err := createDefaultConfig(configPath); err != nil { |
| 146 | return CurdConfig{}, fmt.Errorf("error creating default config file: %v", err) | 159 | return CurdConfig{}, fmt.Errorf("error creating default config file: %v", err) |
| 147 | } | 160 | } |
| 161 | createdConfig = true | ||
| 148 | } | 162 | } |
| 149 | 163 | ||
| 150 | // Load the config from file | 164 | // Load the config from file |
| @@ -159,6 +173,10 @@ func LoadConfig(configPath string) (CurdConfig, error) { | |||
| 159 | addMissing, _ = strconv.ParseBool(val) | 173 | addMissing, _ = strconv.ParseBool(val) |
| 160 | } | 174 | } |
| 161 | 175 | ||
| 176 | _, hadTrackingRemote := configMap["TrackingRemote"] | ||
| 177 | _, hadTrackingConfigured := configMap["TrackingConfigured"] | ||
| 178 | legacyConfig := !createdConfig && !hadTrackingRemote && !hadTrackingConfigured | ||
| 179 | |||
| 162 | // Add missing fields to the config map | 180 | // Add missing fields to the config map |
| 163 | updated := false | 181 | updated := false |
| 164 | defaultConfigMap := defaultConfigMap() | 182 | defaultConfigMap := defaultConfigMap() |
| @@ -168,6 +186,12 @@ func LoadConfig(configPath string) (CurdConfig, error) { | |||
| 168 | updated = true | 186 | updated = true |
| 169 | } | 187 | } |
| 170 | } | 188 | } |
| 189 | if legacyConfig { | ||
| 190 | configMap["TrackingLocal"] = "true" | ||
| 191 | configMap["TrackingRemote"] = TrackingRemoteAniList | ||
| 192 | configMap["TrackingConfigured"] = "true" | ||
| 193 | updated = true | ||
| 194 | } | ||
| 171 | 195 | ||
| 172 | // Write updated config back to file only if AddMissingOptions is true | 196 | // Write updated config back to file only if AddMissingOptions is true |
| 173 | if addMissing && updated { | 197 | if addMissing && updated { |
| @@ -183,6 +207,7 @@ func LoadConfig(configPath string) (CurdConfig, error) { | |||
| 183 | 207 | ||
| 184 | // Populate the CurdConfig struct from the config map | 208 | // Populate the CurdConfig struct from the config map |
| 185 | config := PopulateConfig(configMap) | 209 | config := PopulateConfig(configMap) |
| 210 | normalizeTrackingConfig(&config) | ||
| 186 | 211 | ||
| 187 | return config, nil | 212 | return config, nil |
| 188 | } | 213 | } |
| @@ -592,9 +617,39 @@ func PopulateConfig(configMap map[string]string) CurdConfig { | |||
| 592 | return config | 617 | return config |
| 593 | } | 618 | } |
| 594 | 619 | ||
| 620 | func normalizeRemoteTracker(value string) string { | ||
| 621 | switch strings.ToLower(strings.TrimSpace(value)) { | ||
| 622 | case "", "none", "disabled", "off", "local": | ||
| 623 | return TrackingRemoteNone | ||
| 624 | case "anilist", "ani-list": | ||
| 625 | return TrackingRemoteAniList | ||
| 626 | case "myanimelist", "my_anime_list", "my-anime-list", "mal": | ||
| 627 | return TrackingRemoteMyAnimeList | ||
| 628 | case "anilist+myanimelist", "anilist,myanimelist", "myanimelist+anilist", "myanimelist,anilist", "both", "dual": | ||
| 629 | return TrackingRemoteBoth | ||
| 630 | default: | ||
| 631 | return "" | ||
| 632 | } | ||
| 633 | } | ||
| 634 | |||
| 635 | func normalizeTrackingConfig(config *CurdConfig) { | ||
| 636 | if config == nil { | ||
| 637 | return | ||
| 638 | } | ||
| 639 | |||
| 640 | remote := normalizeRemoteTracker(config.TrackingRemote) | ||
| 641 | if remote == "" { | ||
| 642 | config.TrackingConfigured = false | ||
| 643 | remote = TrackingRemoteAniList | ||
| 644 | } | ||
| 645 | |||
| 646 | config.TrackingRemote = remote | ||
| 647 | config.TrackingLocal = true | ||
| 648 | } | ||
| 649 | |||
| 595 | func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption { | 650 | func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption { |
| 596 | // Define the default categories and all available labels | 651 | // Define the default categories and all available labels |
| 597 | defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "CONTINUE_LAST", "PROVIDER"} | 652 | defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "CONTINUE_LAST", "TRACKER", "PROVIDER"} |
| 598 | availableLabels := map[string]string{ | 653 | availableLabels := map[string]string{ |
| 599 | "CURRENT": "Currently Watching", | 654 | "CURRENT": "Currently Watching", |
| 600 | "ALL": "Show All", | 655 | "ALL": "Show All", |
| @@ -606,6 +661,7 @@ func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption { | |||
| 606 | "PAUSED": "Paused", | 661 | "PAUSED": "Paused", |
| 607 | "DROPPED": "Dropped", | 662 | "DROPPED": "Dropped", |
| 608 | "REWATCHING": "Rewatching", | 663 | "REWATCHING": "Rewatching", |
| 664 | "TRACKER": "Change Tracker", | ||
| 609 | "PROVIDER": "Change Provider", | 665 | "PROVIDER": "Change Provider", |
| 610 | } | 666 | } |
| 611 | 667 | ||
| @@ -629,8 +685,14 @@ func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption { | |||
| 629 | } | 685 | } |
| 630 | 686 | ||
| 631 | // Create the final ordered slice of SelectionOptions | 687 | // Create the final ordered slice of SelectionOptions |
| 688 | if !seen["TRACKER"] { | ||
| 689 | finalOrder = append(finalOrder, "TRACKER") | ||
| 690 | } | ||
| 632 | orderedCategories := make([]SelectionOption, 0, len(finalOrder)) | 691 | orderedCategories := make([]SelectionOption, 0, len(finalOrder)) |
| 633 | for _, key := range finalOrder { | 692 | for _, key := range finalOrder { |
| 693 | if !trackingCategoryEnabled(userCurdConfig, key) { | ||
| 694 | continue | ||
| 695 | } | ||
| 634 | orderedCategories = append(orderedCategories, SelectionOption{ | 696 | orderedCategories = append(orderedCategories, SelectionOption{ |
| 635 | Key: key, | 697 | Key: key, |
| 636 | Label: availableLabels[key], | 698 | Label: availableLabels[key], |
internal/curd.go +77 −44
| @@ -217,6 +217,11 @@ func CurdOut(data interface{}) { | |||
| 217 | } | 217 | } |
| 218 | 218 | ||
| 219 | func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) { | 219 | func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) { |
| 220 | if !UsesRemoteTracking(userCurdConfig) { | ||
| 221 | CurdOut("Remote tracking is disabled in your config.") | ||
| 222 | return | ||
| 223 | } | ||
| 224 | |||
| 220 | // Create update options | 225 | // Create update options |
| 221 | updateOptions := []SelectionOption{ | 226 | updateOptions := []SelectionOption{ |
| 222 | {Key: "CATEGORY", Label: "Change Anime Category"}, | 227 | {Key: "CATEGORY", Label: "Change Anime Category"}, |
| @@ -305,8 +310,8 @@ updateOptionLoop: | |||
| 305 | // After getting animeID, get the current anime entry | 310 | // After getting animeID, get the current anime entry |
| 306 | selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key) | 311 | selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key) |
| 307 | if err != nil { | 312 | if err != nil { |
| 308 | Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err)) | 313 | Log(fmt.Sprintf("Can not find the anime in tracked anime list: %v", err)) |
| 309 | ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist")) | 314 | ExitCurd(fmt.Errorf("Can not find the anime in tracked anime list")) |
| 310 | } | 315 | } |
| 311 | ClearScreen() | 316 | ClearScreen() |
| 312 | 317 | ||
| @@ -574,6 +579,10 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA | |||
| 574 | ExitCurd(fmt.Errorf("Failed to convert anime ID to integer")) | 579 | ExitCurd(fmt.Errorf("Failed to convert anime ID to integer")) |
| 575 | } | 580 | } |
| 576 | 581 | ||
| 582 | if !UsesRemoteTracking(userCurdConfig) { | ||
| 583 | return anilistSelectedOption | ||
| 584 | } | ||
| 585 | |||
| 577 | // Add category selection before adding to list | 586 | // Add category selection before adding to list |
| 578 | categories := []SelectionOption{ | 587 | categories := []SelectionOption{ |
| 579 | {Key: "CURRENT", Label: "Currently Watching"}, | 588 | {Key: "CURRENT", Label: "Currently Watching"}, |
| @@ -712,6 +721,11 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | |||
| 712 | ChangeProvider(userCurdConfig) | 721 | ChangeProvider(userCurdConfig) |
| 713 | ClearScreen() | 722 | ClearScreen() |
| 714 | continue categorySelectionLoop | 723 | continue categorySelectionLoop |
| 724 | } else if categorySelection.Key == "TRACKER" { | ||
| 725 | ClearScreen() | ||
| 726 | ChangeTracker(userCurdConfig, user) | ||
| 727 | ClearScreen() | ||
| 728 | continue categorySelectionLoop | ||
| 715 | } else if categorySelection.Key == "UPDATE" { | 729 | } else if categorySelection.Key == "UPDATE" { |
| 716 | ClearScreen() | 730 | ClearScreen() |
| 717 | UpdateAnimeEntry(userCurdConfig, user) | 731 | UpdateAnimeEntry(userCurdConfig, user) |
| @@ -857,8 +871,29 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | |||
| 857 | // Get anime entry | 871 | // Get anime entry |
| 858 | selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key) | 872 | selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key) |
| 859 | if err != nil { | 873 | if err != nil { |
| 860 | Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err)) | 874 | if UsesRemoteTracking(userCurdConfig) { |
| 861 | ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist")) | 875 | Log(fmt.Sprintf("Can not find the anime in tracked anime list: %v", err)) |
| 876 | ExitCurd(fmt.Errorf("Can not find the anime in tracked anime list")) | ||
| 877 | } | ||
| 878 | |||
| 879 | fallbackAnime, fallbackErr := GetAnimeDataByID(anime.AnilistId, "") | ||
| 880 | if fallbackErr != nil { | ||
| 881 | Log(fmt.Sprintf("Failed to fetch fallback anime data: %v", fallbackErr)) | ||
| 882 | ExitCurd(fmt.Errorf("Failed to get anime data")) | ||
| 883 | } | ||
| 884 | |||
| 885 | selectedAnilistAnime = &Entry{ | ||
| 886 | Media: Media{ | ||
| 887 | ID: fallbackAnime.AnilistId, | ||
| 888 | MalID: fallbackAnime.MalId, | ||
| 889 | Episodes: fallbackAnime.TotalEpisodes, | ||
| 890 | Title: fallbackAnime.Title, | ||
| 891 | Status: "FINISHED", | ||
| 892 | }, | ||
| 893 | Progress: 0, | ||
| 894 | Status: "CURRENT", | ||
| 895 | CoverImage: fallbackAnime.CoverImage, | ||
| 896 | } | ||
| 862 | } | 897 | } |
| 863 | 898 | ||
| 864 | if selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED" { | 899 | if selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED" { |
| @@ -873,6 +908,9 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | |||
| 873 | anime.Title = selectedAnilistAnime.Media.Title | 908 | anime.Title = selectedAnilistAnime.Media.Title |
| 874 | anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes | 909 | anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes |
| 875 | anime.CoverImage = selectedAnilistAnime.CoverImage | 910 | anime.CoverImage = selectedAnilistAnime.CoverImage |
| 911 | if selectedAnilistAnime.Media.MalID != 0 { | ||
| 912 | anime.MalId = selectedAnilistAnime.Media.MalID | ||
| 913 | } | ||
| 876 | if anime.MalId == 0 { | 914 | if anime.MalId == 0 { |
| 877 | anime.MalId, _ = GetAnimeMalID(anime.AnilistId) | 915 | anime.MalId, _ = GetAnimeMalID(anime.AnilistId) |
| 878 | } | 916 | } |
| @@ -886,9 +924,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | |||
| 886 | userQuery = anime.Title.Romaji | 924 | userQuery = anime.Title.Romaji |
| 887 | 925 | ||
| 888 | if selectedAnilistAnime.Status == "COMPLETED" { | 926 | if selectedAnilistAnime.Status == "COMPLETED" { |
| 889 | status := "REPEATING" | 927 | err = StartAnimeRewatch(user.Token, *anime) |
| 890 | progress := 0 | ||
| 891 | err = SaveAnimeListEntry(user.Token, anime.AnilistId, &status, &progress, nil, &anime.StartedAt, &anime.CompletedAt) | ||
| 892 | if err != nil { | 928 | if err != nil { |
| 893 | Log(fmt.Sprintf("Error starting anime rewatch: %v", err)) | 929 | Log(fmt.Sprintf("Error starting anime rewatch: %v", err)) |
| 894 | ExitCurd(fmt.Errorf("Failed to move anime to rewatching")) | 930 | ExitCurd(fmt.Errorf("Failed to move anime to rewatching")) |
| @@ -1184,29 +1220,30 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | |||
| 1184 | // If local history episode is ahead of AniList upstream, prompt user | 1220 | // If local history episode is ahead of AniList upstream, prompt user |
| 1185 | anilistEpisode := selectedAnilistAnime.Progress + 1 | 1221 | anilistEpisode := selectedAnilistAnime.Progress + 1 |
| 1186 | if animePointer.Ep.Number > anilistEpisode { | 1222 | if animePointer.Ep.Number > anilistEpisode { |
| 1187 | Log(fmt.Sprintf("Local history episode (%d) is ahead of AniList episode (%d), prompting user", animePointer.Ep.Number, anilistEpisode)) | 1223 | trackerLabel := RemoteTrackingDisplayName(userCurdConfig) |
| 1224 | Log(fmt.Sprintf("Local history episode (%d) is ahead of %s episode (%d), prompting user", animePointer.Ep.Number, trackerLabel, anilistEpisode)) | ||
| 1188 | options := []SelectionOption{ | 1225 | options := []SelectionOption{ |
| 1189 | {Key: "update_upstream", Label: fmt.Sprintf("Update AniList to episode %d (local history)", animePointer.Ep.Number-1)}, | 1226 | {Key: "update_upstream", Label: fmt.Sprintf("Update %s to episode %d (local history)", trackerLabel, animePointer.Ep.Number-1)}, |
| 1190 | {Key: "use_anilist", Label: fmt.Sprintf("Use AniList episode %d", anilistEpisode)}, | 1227 | {Key: "use_anilist", Label: fmt.Sprintf("Use %s episode %d", trackerLabel, anilistEpisode)}, |
| 1191 | } | 1228 | } |
| 1192 | CurdOut(fmt.Sprintf("Local history (ep %d) is ahead of AniList (ep %d).", animePointer.Ep.Number, anilistEpisode)) | 1229 | CurdOut(fmt.Sprintf("Local history (ep %d) is ahead of %s (ep %d).", animePointer.Ep.Number, trackerLabel, anilistEpisode)) |
| 1193 | selectedOption, err := DynamicSelect(options) | 1230 | selectedOption, err := DynamicSelect(options) |
| 1194 | if err != nil { | 1231 | if err != nil { |
| 1195 | Log("Error in episode conflict selection: " + err.Error()) | 1232 | Log("Error in episode conflict selection: " + err.Error()) |
| 1196 | } else if selectedOption.Key == "-1" { | 1233 | } else if selectedOption.Key == "-1" { |
| 1197 | ExitCurd(nil) | 1234 | ExitCurd(nil) |
| 1198 | } else if selectedOption.Key == "update_upstream" { | 1235 | } else if selectedOption.Key == "update_upstream" { |
| 1199 | // Update AniList progress to match local history (progress = local ep - 1, since local ep is "next to watch") | 1236 | // Update remote progress to match local history (progress = local ep - 1, since local ep is "next to watch") |
| 1200 | progressToUpdate := animePointer.Ep.Number - 1 | 1237 | progressToUpdate := animePointer.Ep.Number - 1 |
| 1201 | if err := UpdateAnimeProgress(user.Token, anime.AnilistId, progressToUpdate); err != nil { | 1238 | if err := UpdateAnimeProgress(user.Token, anime.AnilistId, progressToUpdate); err != nil { |
| 1202 | Log(fmt.Sprintf("Error updating AniList progress to %d: %v", progressToUpdate, err)) | 1239 | Log(fmt.Sprintf("Error updating %s progress to %d: %v", trackerLabel, progressToUpdate, err)) |
| 1203 | } else { | 1240 | } else { |
| 1204 | Log(fmt.Sprintf("Updated AniList progress to %d", progressToUpdate)) | 1241 | Log(fmt.Sprintf("Updated %s progress to %d", trackerLabel, progressToUpdate)) |
| 1205 | } | 1242 | } |
| 1206 | anime.Ep.Number = animePointer.Ep.Number | 1243 | anime.Ep.Number = animePointer.Ep.Number |
| 1207 | anime.Ep.Resume = true | 1244 | anime.Ep.Resume = true |
| 1208 | } else if selectedOption.Key == "use_anilist" { | 1245 | } else if selectedOption.Key == "use_anilist" { |
| 1209 | // Use AniList episode number (already set from selectedAnilistAnime.Progress + 1) | 1246 | // Use remote episode number (already set from selectedAnilistAnime.Progress + 1) |
| 1210 | anime.Ep.Number = anilistEpisode | 1247 | anime.Ep.Number = anilistEpisode |
| 1211 | anime.Ep.Player.PlaybackTime = 0 | 1248 | anime.Ep.Player.PlaybackTime = 0 |
| 1212 | anime.Ep.Resume = false | 1249 | anime.Ep.Resume = false |
| @@ -1245,7 +1282,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | |||
| 1245 | isInWatchingList = true | 1282 | isInWatchingList = true |
| 1246 | } | 1283 | } |
| 1247 | 1284 | ||
| 1248 | if !isInWatchingList { | 1285 | if UsesRemoteTracking(userCurdConfig) && !isInWatchingList { |
| 1249 | // Create options for the prompt | 1286 | // Create options for the prompt |
| 1250 | options := []SelectionOption{ | 1287 | options := []SelectionOption{ |
| 1251 | {Key: "yes", Label: "Add to watching list"}, | 1288 | {Key: "yes", Label: "Add to watching list"}, |
| @@ -1328,7 +1365,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | |||
| 1328 | 1365 | ||
| 1329 | if anime.TotalEpisodes == 0 { | 1366 | if anime.TotalEpisodes == 0 { |
| 1330 | CurdOut("Still unable to determine total episodes.") | 1367 | CurdOut("Still unable to determine total episodes.") |
| 1331 | CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress)) | 1368 | CurdOut(fmt.Sprintf("Your %s progress: %d", RemoteTrackingDisplayName(userCurdConfig), selectedAnilistAnime.Progress)) |
| 1332 | var episodeNumber int | 1369 | var episodeNumber int |
| 1333 | if userCurdConfig.RofiSelection { | 1370 | if userCurdConfig.RofiSelection { |
| 1334 | userInput, err := GetUserInputFromRofi("Enter the episode you want to start from") | 1371 | userInput, err := GetUserInputFromRofi("Enter the episode you want to start from") |
| @@ -1679,12 +1716,14 @@ func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string | |||
| 1679 | Log("Error updating local database on quit: " + err.Error()) | 1716 | Log("Error updating local database on quit: " + err.Error()) |
| 1680 | } | 1717 | } |
| 1681 | 1718 | ||
| 1682 | go func() { | 1719 | if !(anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && anime.Rewatching) { |
| 1683 | err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number) | 1720 | go func() { |
| 1684 | if err != nil { | 1721 | err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number) |
| 1685 | Log("Error updating Anilist progress on quit: " + err.Error()) | 1722 | if err != nil { |
| 1686 | } | 1723 | Log("Error updating Anilist progress on quit: " + err.Error()) |
| 1687 | }() | 1724 | } |
| 1725 | }() | ||
| 1726 | } | ||
| 1688 | 1727 | ||
| 1689 | CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched)) | 1728 | CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched)) |
| 1690 | } else { | 1729 | } else { |
| @@ -1773,9 +1812,11 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str | |||
| 1773 | // Handle scoring and completion for the last episode | 1812 | // Handle scoring and completion for the last episode |
| 1774 | HandleLastEpisodeCompletion(userCurdConfig, anime, userToken) | 1813 | HandleLastEpisodeCompletion(userCurdConfig, anime, userToken) |
| 1775 | 1814 | ||
| 1776 | err := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode) | 1815 | if !anime.Rewatching { |
| 1777 | if err != nil { | 1816 | err := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode) |
| 1778 | Log("Error updating Anilist progress: " + err.Error()) | 1817 | if err != nil { |
| 1818 | Log("Error updating Anilist progress: " + err.Error()) | ||
| 1819 | } | ||
| 1779 | } | 1820 | } |
| 1780 | // Note: UpdateAnimeProgress already outputs a message on success | 1821 | // Note: UpdateAnimeProgress already outputs a message on success |
| 1781 | 1822 | ||
| @@ -1880,6 +1921,10 @@ func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userT | |||
| 1880 | 1921 | ||
| 1881 | // handleSequelCheck checks for sequels and prompts the user accordingly | 1922 | // handleSequelCheck checks for sequels and prompts the user accordingly |
| 1882 | func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken string) { | 1923 | func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken string) { |
| 1924 | if !UsesRemoteTracking(userCurdConfig) { | ||
| 1925 | return | ||
| 1926 | } | ||
| 1927 | |||
| 1883 | // Recover from any panics in this function to prevent crashes | 1928 | // Recover from any panics in this function to prevent crashes |
| 1884 | defer func() { | 1929 | defer func() { |
| 1885 | if r := recover(); r != nil { | 1930 | if r := recover(); r != nil { |
| @@ -1939,28 +1984,16 @@ func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken strin | |||
| 1939 | return | 1984 | return |
| 1940 | } | 1985 | } |
| 1941 | 1986 | ||
| 1942 | // Fetch user's anime list to check if sequel is already there | 1987 | currentUser := GetGlobalUser() |
| 1943 | userId, _, err := GetAnilistUserID(userToken) | 1988 | userAnimeList := AnimeList{} |
| 1944 | if err != nil { | 1989 | if currentUser != nil { |
| 1945 | Log(fmt.Sprintf("Error getting user ID: %v", err)) | 1990 | userAnimeList = currentUser.AnimeList |
| 1946 | return | ||
| 1947 | } | ||
| 1948 | |||
| 1949 | userData, err := GetUserData(userToken, userId) | ||
| 1950 | if err != nil { | ||
| 1951 | Log(fmt.Sprintf("Error getting user data: %v", err)) | ||
| 1952 | return | ||
| 1953 | } | 1991 | } |
| 1954 | 1992 | if !hasAnyEntries(userAnimeList) { | |
| 1955 | // Check if userData is valid before parsing | 1993 | Log("Tracked anime list is empty, skipping sequel list check") |
| 1956 | if userData == nil || userData["data"] == nil { | ||
| 1957 | Log("User data is nil or malformed, skipping sequel list check") | ||
| 1958 | // Still show the sequel prompt, but assume it's not in any list | ||
| 1959 | promptSequelNotInList(sequel, sequelTitle, userToken, anime) | 1994 | promptSequelNotInList(sequel, sequelTitle, userToken, anime) |
| 1960 | return | 1995 | return |
| 1961 | } | 1996 | } |
| 1962 | |||
| 1963 | userAnimeList := ParseAnimeList(userData) | ||
| 1964 | sequelStatus, isInList := FindSequelInAnimeList(userAnimeList, sequel.ID) | 1997 | sequelStatus, isInList := FindSequelInAnimeList(userAnimeList, sequel.ID) |
| 1965 | 1998 | ||
| 1966 | if !isInList { | 1999 | if !isInList { |
internal/localTracking.go +3 −3
| @@ -257,9 +257,9 @@ func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime | |||
| 257 | for i := range animeList { | 257 | for i := range animeList { |
| 258 | anime := &animeList[i] | 258 | anime := &animeList[i] |
| 259 | if anime.AnilistId == anilistID || (allanimeID != "" && anime.ProviderId == allanimeID) { | 259 | if anime.AnilistId == anilistID || (allanimeID != "" && anime.ProviderId == allanimeID) { |
| 260 | if bestMatch == nil || | 260 | if bestMatch == nil || |
| 261 | anime.Ep.Number > bestMatch.Ep.Number || | 261 | anime.Ep.Number > bestMatch.Ep.Number || |
| 262 | (anime.Ep.Number == bestMatch.Ep.Number && anime.Ep.Player.PlaybackTime > bestMatch.Ep.Player.PlaybackTime) { | 262 | (anime.Ep.Number == bestMatch.Ep.Number && anime.Ep.Player.PlaybackTime > bestMatch.Ep.Player.PlaybackTime) { |
| 263 | bestMatch = anime | 263 | bestMatch = anime |
| 264 | } | 264 | } |
| 265 | } | 265 | } |
internal/myanimelist.go added +1230
| @@ -0,0 +1,1230 @@ | |||
| 1 | package internal | ||
| 2 | |||
| 3 | import ( | ||
| 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 | |||
| 21 | type OAuthToken = AnilistToken | ||
| 22 | |||
| 23 | const ( | ||
| 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 | |||
| 34 | type myAnimeListUser struct { | ||
| 35 | ID int `json:"id"` | ||
| 36 | Name string `json:"name"` | ||
| 37 | } | ||
| 38 | |||
| 39 | type myAnimeListPicture struct { | ||
| 40 | Medium string `json:"medium"` | ||
| 41 | Large string `json:"large"` | ||
| 42 | } | ||
| 43 | |||
| 44 | type myAnimeListAlternativeTitles struct { | ||
| 45 | En string `json:"en"` | ||
| 46 | Ja string `json:"ja"` | ||
| 47 | } | ||
| 48 | |||
| 49 | type 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 | |||
| 59 | type 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 | |||
| 70 | type 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 | |||
| 80 | type trackingIDCachePayload struct { | ||
| 81 | MalToAniList map[string]int `json:"mal_to_anilist"` | ||
| 82 | } | ||
| 83 | |||
| 84 | type pendingMyAnimeListAuth struct { | ||
| 85 | CodeVerifier string `json:"code_verifier"` | ||
| 86 | State string `json:"state"` | ||
| 87 | CreatedAt time.Time `json:"created_at"` | ||
| 88 | } | ||
| 89 | |||
| 90 | func myAnimeListTokenPath(config *CurdConfig) string { | ||
| 91 | return filepath.Join(os.ExpandEnv(config.StoragePath), "myanimelist_token.json") | ||
| 92 | } | ||
| 93 | |||
| 94 | func myAnimeListCachePath(storagePath string) string { | ||
| 95 | return filepath.Join(os.ExpandEnv(storagePath), myAnimeListListCacheFileName) | ||
| 96 | } | ||
| 97 | |||
| 98 | func trackingIDCachePath(storagePath string) string { | ||
| 99 | return filepath.Join(os.ExpandEnv(storagePath), trackingIDCacheFileName) | ||
| 100 | } | ||
| 101 | |||
| 102 | func myAnimeListPendingAuthPath(config *CurdConfig) string { | ||
| 103 | return filepath.Join(os.ExpandEnv(config.StoragePath), myAnimeListPendingAuthFile) | ||
| 104 | } | ||
| 105 | |||
| 106 | func 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 | |||
| 118 | func 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 | |||
| 130 | func clearPendingMyAnimeListAuth(config *CurdConfig) { | ||
| 131 | _ = os.Remove(myAnimeListPendingAuthPath(config)) | ||
| 132 | } | ||
| 133 | |||
| 134 | func 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 | |||
| 175 | func 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 | |||
| 220 | func 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 | |||
| 244 | func 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 | |||
| 260 | func 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 | |||
| 383 | func 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 | |||
| 437 | func 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 | |||
| 459 | func 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 | |||
| 469 | func 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 | |||
| 550 | func 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 | |||
| 565 | func 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 | |||
| 580 | func 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 | |||
| 587 | func 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 | |||
| 607 | func 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 | |||
| 626 | func 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 | |||
| 637 | func 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 | |||
| 653 | func 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 | |||
| 680 | func 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 | |||
| 744 | func safeAniListString(value interface{}) string { | ||
| 745 | if str, ok := value.(string); ok { | ||
| 746 | return str | ||
| 747 | } | ||
| 748 | return "" | ||
| 749 | } | ||
| 750 | |||
| 751 | func 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 | |||
| 759 | type aniListMediaLookupResult struct { | ||
| 760 | Media Media | ||
| 761 | Cover string | ||
| 762 | } | ||
| 763 | |||
| 764 | func 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 | |||
| 785 | func 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 | |||
| 854 | func 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 | |||
| 885 | func 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 | |||
| 902 | func 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 | |||
| 930 | func 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 | |||
| 1062 | func 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 | |||
| 1082 | func 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 | |||
| 1107 | func 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 | |||
| 1125 | func 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 | |||
| 1138 | func 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 | |||
| 1148 | func 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 | |||
| 1164 | func 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 | |||
| 1172 | func 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 | |||
| 1183 | func 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 | |||
| 1199 | func 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 | |||
| 1220 | func deleteMyAnimeListEntry(config *CurdConfig, malID int) error { | ||
| 1221 | return myAnimeListRequest(config, http.MethodDelete, fmt.Sprintf("/anime/%d/my_list_status", malID), nil, nil) | ||
| 1222 | } | ||
| 1223 | |||
| 1224 | func maybeMarshalMALResponse(v interface{}) string { | ||
| 1225 | body, err := json.Marshal(v) | ||
| 1226 | if err != nil { | ||
| 1227 | return "" | ||
| 1228 | } | ||
| 1229 | return string(bytes.TrimSpace(body)) | ||
| 1230 | } | ||
internal/provider_animepahe.go +43 −42
| @@ -19,6 +19,7 @@ import ( | |||
| 19 | ) | 19 | ) |
| 20 | 20 | ||
| 21 | var animepaheCookiesBypassed bool | 21 | var animepaheCookiesBypassed bool |
| 22 | |||
| 22 | func getCookieFilePath() string { | 23 | func getCookieFilePath() string { |
| 23 | return filepath.Join(GetStoragePath(), "animepahe_cookies.json") | 24 | return filepath.Join(GetStoragePath(), "animepahe_cookies.json") |
| 24 | } | 25 | } |
| @@ -57,7 +58,7 @@ func checkCookiesValid() bool { | |||
| 57 | if resp.StatusCode != 200 { | 58 | if resp.StatusCode != 200 { |
| 58 | return false | 59 | return false |
| 59 | } | 60 | } |
| 60 | 61 | ||
| 61 | contentType := resp.Header.Get("Content-Type") | 62 | contentType := resp.Header.Get("Content-Type") |
| 62 | return strings.Contains(contentType, "application/json") | 63 | return strings.Contains(contentType, "application/json") |
| 63 | } | 64 | } |
| @@ -71,7 +72,7 @@ func (p *AnimepaheProvider) ensureBypass() error { | |||
| 71 | if len(cookies) > 0 { | 72 | if len(cookies) > 0 { |
| 72 | u, _ := url.Parse("https://animepahe.pw") | 73 | u, _ := url.Parse("https://animepahe.pw") |
| 73 | SetCookiesForAnimepahe(u, cookies) | 74 | SetCookiesForAnimepahe(u, cookies) |
| 74 | 75 | ||
| 75 | if checkCookiesValid() { | 76 | if checkCookiesValid() { |
| 76 | animepaheCookiesBypassed = true | 77 | animepaheCookiesBypassed = true |
| 77 | Log("Successfully restored Animepahe session from cache.") | 78 | Log("Successfully restored Animepahe session from cache.") |
| @@ -81,7 +82,7 @@ func (p *AnimepaheProvider) ensureBypass() error { | |||
| 81 | } | 82 | } |
| 82 | 83 | ||
| 83 | CurdOut("Solving Animepahe DDoS-Guard challenge via headless browser...") | 84 | CurdOut("Solving Animepahe DDoS-Guard challenge via headless browser...") |
| 84 | 85 | ||
| 85 | l := launcher.New().Headless(true) | 86 | l := launcher.New().Headless(true) |
| 86 | defer l.Cleanup() | 87 | defer l.Cleanup() |
| 87 | browser := rod.New().ControlURL(l.MustLaunch()).MustConnect() | 88 | browser := rod.New().ControlURL(l.MustLaunch()).MustConnect() |
| @@ -89,7 +90,7 @@ func (p *AnimepaheProvider) ensureBypass() error { | |||
| 89 | 90 | ||
| 90 | page := browser.MustPage("https://animepahe.pw/") | 91 | page := browser.MustPage("https://animepahe.pw/") |
| 91 | page.MustWaitLoad() | 92 | page.MustWaitLoad() |
| 92 | 93 | ||
| 93 | for i := 0; i < 30; i++ { | 94 | for i := 0; i < 30; i++ { |
| 94 | info, err := page.Info() | 95 | info, err := page.Info() |
| 95 | if err == nil && info.Title != "DDoS-Guard" && info.Title != "Just a moment..." && info.Title != "" { | 96 | if err == nil && info.Title != "DDoS-Guard" && info.Title != "Just a moment..." && info.Title != "" { |
| @@ -112,7 +113,7 @@ func (p *AnimepaheProvider) ensureBypass() error { | |||
| 112 | }) | 113 | }) |
| 113 | } | 114 | } |
| 114 | SetCookiesForAnimepahe(u, httpCookies) | 115 | SetCookiesForAnimepahe(u, httpCookies) |
| 115 | 116 | ||
| 116 | if !checkCookiesValid() { | 117 | if !checkCookiesValid() { |
| 117 | return fmt.Errorf("bypassed cookies are still invalid") | 118 | return fmt.Errorf("bypassed cookies are still invalid") |
| 118 | } | 119 | } |
| @@ -130,23 +131,23 @@ func (p *AnimepaheProvider) Name() string { | |||
| 130 | } | 131 | } |
| 131 | 132 | ||
| 132 | type AnimepaheSearchItem struct { | 133 | type AnimepaheSearchItem struct { |
| 133 | ID int `json:"id"` | 134 | ID int `json:"id"` |
| 134 | Title string `json:"title"` | 135 | Title string `json:"title"` |
| 135 | Type string `json:"type"` | 136 | Type string `json:"type"` |
| 136 | Episodes int `json:"episodes"` | 137 | Episodes int `json:"episodes"` |
| 137 | Status string `json:"status"` | 138 | Status string `json:"status"` |
| 138 | Season string `json:"season"` | 139 | Season string `json:"season"` |
| 139 | Year int `json:"year"` | 140 | Year int `json:"year"` |
| 140 | Score float64 `json:"score"` | 141 | Score float64 `json:"score"` |
| 141 | Poster string `json:"poster"` | 142 | Poster string `json:"poster"` |
| 142 | Session string `json:"session"` | 143 | Session string `json:"session"` |
| 143 | } | 144 | } |
| 144 | 145 | ||
| 145 | type animepaheSearchResponse struct { | 146 | type animepaheSearchResponse struct { |
| 146 | Total int `json:"total"` | 147 | Total int `json:"total"` |
| 147 | PerPage int `json:"per_page"` | 148 | PerPage int `json:"per_page"` |
| 148 | CurrentPage int `json:"current_page"` | 149 | CurrentPage int `json:"current_page"` |
| 149 | LastPage int `json:"last_page"` | 150 | LastPage int `json:"last_page"` |
| 150 | Data []AnimepaheSearchItem `json:"data"` | 151 | Data []AnimepaheSearchItem `json:"data"` |
| 151 | } | 152 | } |
| 152 | 153 | ||
| @@ -156,13 +157,13 @@ func (p *AnimepaheProvider) SearchAnime(query, mode string) ([]SelectionOption, | |||
| 156 | } | 157 | } |
| 157 | // animepahe doesn't distinguish sub/dub at the search level | 158 | // animepahe doesn't distinguish sub/dub at the search level |
| 158 | searchUrl := fmt.Sprintf("https://animepahe.pw/api?m=search&q=%s", url.QueryEscape(query)) | 159 | searchUrl := fmt.Sprintf("https://animepahe.pw/api?m=search&q=%s", url.QueryEscape(query)) |
| 159 | 160 | ||
| 160 | req, _ := http.NewRequest("GET", searchUrl, nil) | 161 | req, _ := http.NewRequest("GET", searchUrl, nil) |
| 161 | req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") | 162 | req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") |
| 162 | req.Header.Set("Referer", "https://animepahe.pw/") | 163 | req.Header.Set("Referer", "https://animepahe.pw/") |
| 163 | req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") | 164 | req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") |
| 164 | req.Header.Set("X-Requested-With", "XMLHttpRequest") | 165 | req.Header.Set("X-Requested-With", "XMLHttpRequest") |
| 165 | 166 | ||
| 166 | resp, err := sharedHTTPClient.Do(req) | 167 | resp, err := sharedHTTPClient.Do(req) |
| 167 | if err != nil { | 168 | if err != nil { |
| 168 | return nil, err | 169 | return nil, err |
| @@ -223,7 +224,7 @@ func (p *AnimepaheProvider) EpisodesList(showID, mode string) ([]string, error) | |||
| 223 | req.Header.Set("Referer", "https://animepahe.pw/") | 224 | req.Header.Set("Referer", "https://animepahe.pw/") |
| 224 | req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") | 225 | req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") |
| 225 | req.Header.Set("X-Requested-With", "XMLHttpRequest") | 226 | req.Header.Set("X-Requested-With", "XMLHttpRequest") |
| 226 | 227 | ||
| 227 | resp, err := sharedHTTPClient.Do(req) | 228 | resp, err := sharedHTTPClient.Do(req) |
| 228 | if err != nil { | 229 | if err != nil { |
| 229 | return nil, err | 230 | return nil, err |
| @@ -273,7 +274,7 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | |||
| 273 | if epNo < 1 || epNo > len(eps) { | 274 | if epNo < 1 || epNo > len(eps) { |
| 274 | return nil, fmt.Errorf("episode %d out of bounds (found %d episodes)", epNo, len(eps)) | 275 | return nil, fmt.Errorf("episode %d out of bounds (found %d episodes)", epNo, len(eps)) |
| 275 | } | 276 | } |
| 276 | 277 | ||
| 277 | mappedEpNo, err := strconv.Atoi(eps[epNo-1]) | 278 | mappedEpNo, err := strconv.Atoi(eps[epNo-1]) |
| 278 | if err != nil { | 279 | if err != nil { |
| 279 | return nil, fmt.Errorf("invalid episode number format in provider: %v", err) | 280 | return nil, fmt.Errorf("invalid episode number format in provider: %v", err) |
| @@ -289,7 +290,7 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | |||
| 289 | req.Header.Set("Referer", "https://animepahe.pw/") | 290 | req.Header.Set("Referer", "https://animepahe.pw/") |
| 290 | req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") | 291 | req.Header.Set("Accept", "application/json, text/javascript, */*; q=0.01") |
| 291 | req.Header.Set("X-Requested-With", "XMLHttpRequest") | 292 | req.Header.Set("X-Requested-With", "XMLHttpRequest") |
| 292 | 293 | ||
| 293 | resp, err := sharedHTTPClient.Do(req) | 294 | resp, err := sharedHTTPClient.Do(req) |
| 294 | if err != nil { | 295 | if err != nil { |
| 295 | return nil, err | 296 | return nil, err |
| @@ -323,7 +324,7 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | |||
| 323 | if episodeSession == "" { | 324 | if episodeSession == "" { |
| 324 | return nil, fmt.Errorf("episode %d (mapped to %d) not found", epNo, mappedEpNo) | 325 | return nil, fmt.Errorf("episode %d (mapped to %d) not found", epNo, mappedEpNo) |
| 325 | } | 326 | } |
| 326 | 327 | ||
| 327 | // player page: https://animepahe.pw/play/<anime_session>/<episode_session> | 328 | // player page: https://animepahe.pw/play/<anime_session>/<episode_session> |
| 328 | // stream links in player page: <button type=\"button\" data-src=\"https://kwik.cx/e/Jwd0hMNswksj\" | 329 | // stream links in player page: <button type=\"button\" data-src=\"https://kwik.cx/e/Jwd0hMNswksj\" |
| 329 | playerUrl := fmt.Sprintf("https://animepahe.pw/play/%s/%s", id, episodeSession) | 330 | playerUrl := fmt.Sprintf("https://animepahe.pw/play/%s/%s", id, episodeSession) |
| @@ -331,18 +332,18 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | |||
| 331 | req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") | 332 | req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") |
| 332 | req.Header.Set("Referer", "https://animepahe.pw/") | 333 | req.Header.Set("Referer", "https://animepahe.pw/") |
| 333 | req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8") | 334 | req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8") |
| 334 | 335 | ||
| 335 | resp, err := sharedHTTPClient.Do(req) | 336 | resp, err := sharedHTTPClient.Do(req) |
| 336 | if err != nil { | 337 | if err != nil { |
| 337 | return nil, err | 338 | return nil, err |
| 338 | } | 339 | } |
| 339 | defer resp.Body.Close() | 340 | defer resp.Body.Close() |
| 340 | 341 | ||
| 341 | body, err := io.ReadAll(resp.Body) | 342 | body, err := io.ReadAll(resp.Body) |
| 342 | if err != nil { | 343 | if err != nil { |
| 343 | return nil, err | 344 | return nil, err |
| 344 | } | 345 | } |
| 345 | 346 | ||
| 346 | bodyStr := string(body) | 347 | bodyStr := string(body) |
| 347 | type streamLink struct { | 348 | type streamLink struct { |
| 348 | url string | 349 | url string |
| @@ -350,7 +351,7 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | |||
| 350 | } | 351 | } |
| 351 | var subLinks []streamLink | 352 | var subLinks []streamLink |
| 352 | var dubLinks []streamLink | 353 | var dubLinks []streamLink |
| 353 | 354 | ||
| 354 | parts := strings.Split(bodyStr, "<button") | 355 | parts := strings.Split(bodyStr, "<button") |
| 355 | for i := 1; i < len(parts); i++ { | 356 | for i := 1; i < len(parts); i++ { |
| 356 | part := parts[i] | 357 | part := parts[i] |
| @@ -358,18 +359,18 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | |||
| 358 | if srcIdx == -1 { | 359 | if srcIdx == -1 { |
| 359 | continue | 360 | continue |
| 360 | } | 361 | } |
| 361 | 362 | ||
| 362 | startIdx := srcIdx + 10 | 363 | startIdx := srcIdx + 10 |
| 363 | endIdx := strings.Index(part[startIdx:], "\"") | 364 | endIdx := strings.Index(part[startIdx:], "\"") |
| 364 | if endIdx == -1 { | 365 | if endIdx == -1 { |
| 365 | continue | 366 | continue |
| 366 | } | 367 | } |
| 367 | 368 | ||
| 368 | link := part[startIdx : startIdx+endIdx] | 369 | link := part[startIdx : startIdx+endIdx] |
| 369 | if !strings.Contains(link, "kwik.cx") { | 370 | if !strings.Contains(link, "kwik.cx") { |
| 370 | continue | 371 | continue |
| 371 | } | 372 | } |
| 372 | 373 | ||
| 373 | resIdx := strings.Index(part, "data-resolution=\"") | 374 | resIdx := strings.Index(part, "data-resolution=\"") |
| 374 | res := 0 | 375 | res := 0 |
| 375 | if resIdx != -1 { | 376 | if resIdx != -1 { |
| @@ -387,7 +388,7 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | |||
| 387 | subLinks = append(subLinks, sLink) | 388 | subLinks = append(subLinks, sLink) |
| 388 | } | 389 | } |
| 389 | } | 390 | } |
| 390 | 391 | ||
| 391 | // Sort by resolution descending | 392 | // Sort by resolution descending |
| 392 | sortFunc := func(links []streamLink) { | 393 | sortFunc := func(links []streamLink) { |
| 393 | sort.Slice(links, func(i, j int) bool { | 394 | sort.Slice(links, func(i, j int) bool { |
| @@ -411,7 +412,7 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | |||
| 411 | links = append(links, l.url) | 412 | links = append(links, l.url) |
| 412 | } | 413 | } |
| 413 | } | 414 | } |
| 414 | 415 | ||
| 415 | var finalLinks []string | 416 | var finalLinks []string |
| 416 | for _, kwikLink := range links { | 417 | for _, kwikLink := range links { |
| 417 | m3u8, err := p.extractKwikM3u8(kwikLink) | 418 | m3u8, err := p.extractKwikM3u8(kwikLink) |
| @@ -419,7 +420,7 @@ func (p *AnimepaheProvider) GetEpisodeURL(config CurdConfig, id string, epNo int | |||
| 419 | finalLinks = append(finalLinks, m3u8) | 420 | finalLinks = append(finalLinks, m3u8) |
| 420 | } | 421 | } |
| 421 | } | 422 | } |
| 422 | 423 | ||
| 423 | if len(finalLinks) == 0 { | 424 | if len(finalLinks) == 0 { |
| 424 | return nil, fmt.Errorf("failed to extract any stream links from kwik") | 425 | return nil, fmt.Errorf("failed to extract any stream links from kwik") |
| 425 | } | 426 | } |
| @@ -432,31 +433,31 @@ func (p *AnimepaheProvider) extractKwikM3u8(kwikUrl string) (string, error) { | |||
| 432 | req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") | 433 | req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") |
| 433 | req.Header.Set("Referer", "https://animepahe.pw/") | 434 | req.Header.Set("Referer", "https://animepahe.pw/") |
| 434 | req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8") | 435 | req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8") |
| 435 | 436 | ||
| 436 | resp, err := sharedHTTPClient.Do(req) | 437 | resp, err := sharedHTTPClient.Do(req) |
| 437 | if err != nil { | 438 | if err != nil { |
| 438 | return "", err | 439 | return "", err |
| 439 | } | 440 | } |
| 440 | defer resp.Body.Close() | 441 | defer resp.Body.Close() |
| 441 | 442 | ||
| 442 | body, err := io.ReadAll(resp.Body) | 443 | body, err := io.ReadAll(resp.Body) |
| 443 | if err != nil { | 444 | if err != nil { |
| 444 | return "", err | 445 | return "", err |
| 445 | } | 446 | } |
| 446 | bodyStr := string(body) | 447 | bodyStr := string(body) |
| 447 | 448 | ||
| 448 | re := regexp.MustCompile(`eval\(function\(p,a,c,k,e,d\).*?\}\('(.*?)',(\d+),(\d+),'([^']+)'\.split\('\|'\).*?\)\)`) | 449 | re := regexp.MustCompile(`eval\(function\(p,a,c,k,e,d\).*?\}\('(.*?)',(\d+),(\d+),'([^']+)'\.split\('\|'\).*?\)\)`) |
| 449 | matches := re.FindAllStringSubmatch(bodyStr, -1) | 450 | matches := re.FindAllStringSubmatch(bodyStr, -1) |
| 450 | 451 | ||
| 451 | for _, match := range matches { | 452 | for _, match := range matches { |
| 452 | pStr := match[1] | 453 | pStr := match[1] |
| 453 | a, _ := strconv.Atoi(match[2]) | 454 | a, _ := strconv.Atoi(match[2]) |
| 454 | c, _ := strconv.Atoi(match[3]) | 455 | c, _ := strconv.Atoi(match[3]) |
| 455 | k := strings.Split(match[4], "|") | 456 | k := strings.Split(match[4], "|") |
| 456 | 457 | ||
| 457 | pStr = strings.ReplaceAll(pStr, "\\'", "'") | 458 | pStr = strings.ReplaceAll(pStr, "\\'", "'") |
| 458 | unpacked := unpackKwik(pStr, a, c, k) | 459 | unpacked := unpackKwik(pStr, a, c, k) |
| 459 | 460 | ||
| 460 | if strings.Contains(unpacked, "m3u8") { | 461 | if strings.Contains(unpacked, "m3u8") { |
| 461 | urlRe := regexp.MustCompile(`(https://[a-zA-Z0-9\-\.\/]+m3u8)`) | 462 | urlRe := regexp.MustCompile(`(https://[a-zA-Z0-9\-\.\/]+m3u8)`) |
| 462 | urlMatch := urlRe.FindStringSubmatch(unpacked) | 463 | urlMatch := urlRe.FindStringSubmatch(unpacked) |
| @@ -514,4 +515,4 @@ func contains(slice []string, val string) bool { | |||
| 514 | } | 515 | } |
| 515 | } | 516 | } |
| 516 | return false | 517 | return false |
| 517 | }\ No newline at end of file | 518 | } |
internal/structs.go +15
| @@ -1,5 +1,7 @@ | |||
| 1 | package internal | 1 | package internal |
| 2 | 2 | ||
| 3 | import "time" | ||
| 4 | |||
| 3 | type AnimeTitle struct { | 5 | type AnimeTitle struct { |
| 4 | Romaji string `json:"title_romanji"` | 6 | Romaji string `json:"title_romanji"` |
| 5 | English string `json:"title"` | 7 | English string `json:"title"` |
| @@ -78,6 +80,16 @@ type User struct { | |||
| 78 | ListSync *AnimeListSync | 80 | ListSync *AnimeListSync |
| 79 | } | 81 | } |
| 80 | 82 | ||
| 83 | var globalUser *User | ||
| 84 | |||
| 85 | func SetGlobalUser(user *User) { | ||
| 86 | globalUser = user | ||
| 87 | } | ||
| 88 | |||
| 89 | func GetGlobalUser() *User { | ||
| 90 | return globalUser | ||
| 91 | } | ||
| 92 | |||
| 81 | // AniListAnime is the struct for the API response | 93 | // AniListAnime is the struct for the API response |
| 82 | type AniListAnime struct { | 94 | type AniListAnime struct { |
| 83 | ID int `json:"id"` | 95 | ID int `json:"id"` |
| @@ -105,11 +117,13 @@ type Media struct { | |||
| 105 | Duration int `json:"duration"` | 117 | Duration int `json:"duration"` |
| 106 | Episodes int `json:"episodes"` | 118 | Episodes int `json:"episodes"` |
| 107 | ID int `json:"id"` | 119 | ID int `json:"id"` |
| 120 | MalID int `json:"mal_id"` | ||
| 108 | Title AnimeTitle `json:"title"` | 121 | Title AnimeTitle `json:"title"` |
| 109 | Status string `json:"status"` | 122 | Status string `json:"status"` |
| 110 | } | 123 | } |
| 111 | 124 | ||
| 112 | type Entry struct { | 125 | type Entry struct { |
| 126 | ListID int `json:"id"` | ||
| 113 | Media Media `json:"media"` | 127 | Media Media `json:"media"` |
| 114 | Progress int `json:"progress"` | 128 | Progress int `json:"progress"` |
| 115 | Repeat int `json:"repeat"` | 129 | Repeat int `json:"repeat"` |
| @@ -118,6 +132,7 @@ type Entry struct { | |||
| 118 | StartedAt FuzzyDate `json:"startedAt"` | 132 | StartedAt FuzzyDate `json:"startedAt"` |
| 119 | CompletedAt FuzzyDate `json:"completedAt"` | 133 | CompletedAt FuzzyDate `json:"completedAt"` |
| 120 | CoverImage string `json:"coverImage"` | 134 | CoverImage string `json:"coverImage"` |
| 135 | UpdatedAt time.Time `json:"updatedAt"` | ||
| 121 | } | 136 | } |
| 122 | 137 | ||
| 123 | type AnimeList struct { | 138 | type AnimeList struct { |
internal/tracking.go added +1370
| @@ -0,0 +1,1370 @@ | |||
| 1 | package internal | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "bufio" | ||
| 5 | "fmt" | ||
| 6 | "os" | ||
| 7 | "path/filepath" | ||
| 8 | "sort" | ||
| 9 | "strconv" | ||
| 10 | "strings" | ||
| 11 | "time" | ||
| 12 | ) | ||
| 13 | |||
| 14 | const ( | ||
| 15 | TrackingRemoteNone = "none" | ||
| 16 | TrackingRemoteAniList = "anilist" | ||
| 17 | TrackingRemoteMyAnimeList = "myanimelist" | ||
| 18 | TrackingRemoteBoth = "anilist+myanimelist" | ||
| 19 | ) | ||
| 20 | |||
| 21 | func UsesLocalTracking(config *CurdConfig) bool { | ||
| 22 | return true | ||
| 23 | } | ||
| 24 | |||
| 25 | func UsesRemoteTracking(config *CurdConfig) bool { | ||
| 26 | if config == nil { | ||
| 27 | return true | ||
| 28 | } | ||
| 29 | return normalizeRemoteTracker(config.TrackingRemote) != TrackingRemoteNone | ||
| 30 | } | ||
| 31 | |||
| 32 | func UsesAniListTracking(config *CurdConfig) bool { | ||
| 33 | if config == nil { | ||
| 34 | return true | ||
| 35 | } | ||
| 36 | switch normalizeRemoteTracker(config.TrackingRemote) { | ||
| 37 | case TrackingRemoteAniList, TrackingRemoteBoth: | ||
| 38 | return true | ||
| 39 | default: | ||
| 40 | return false | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 44 | func UsesMyAnimeListTracking(config *CurdConfig) bool { | ||
| 45 | if config == nil { | ||
| 46 | return false | ||
| 47 | } | ||
| 48 | switch normalizeRemoteTracker(config.TrackingRemote) { | ||
| 49 | case TrackingRemoteMyAnimeList, TrackingRemoteBoth: | ||
| 50 | return true | ||
| 51 | default: | ||
| 52 | return false | ||
| 53 | } | ||
| 54 | } | ||
| 55 | |||
| 56 | func UsesDualRemoteTracking(config *CurdConfig) bool { | ||
| 57 | if config == nil { | ||
| 58 | return false | ||
| 59 | } | ||
| 60 | return normalizeRemoteTracker(config.TrackingRemote) == TrackingRemoteBoth | ||
| 61 | } | ||
| 62 | |||
| 63 | func trackingCategoryEnabled(config *CurdConfig, key string) bool { | ||
| 64 | switch key { | ||
| 65 | case "CURRENT", "ALL", "UNTRACKED", "CONTINUE_LAST", "PROVIDER": | ||
| 66 | return true | ||
| 67 | case "UPDATE", "PLANNING", "COMPLETED", "PAUSED", "DROPPED", "REWATCHING": | ||
| 68 | return UsesRemoteTracking(config) | ||
| 69 | default: | ||
| 70 | return true | ||
| 71 | } | ||
| 72 | } | ||
| 73 | |||
| 74 | func EnsureTrackingConfigured(config *CurdConfig) error { | ||
| 75 | if config == nil { | ||
| 76 | return fmt.Errorf("missing config") | ||
| 77 | } | ||
| 78 | |||
| 79 | normalizeTrackingConfig(config) | ||
| 80 | if config.TrackingConfigured { | ||
| 81 | return persistTrackingConfig(config) | ||
| 82 | } | ||
| 83 | |||
| 84 | options := []SelectionOption{ | ||
| 85 | {Key: "local", Label: "local"}, | ||
| 86 | {Key: "anilist", Label: "anilist"}, | ||
| 87 | {Key: "myanimelist", Label: "myanimelist"}, | ||
| 88 | {Key: "anilist+myanimelist", Label: "anilist + myanimelist"}, | ||
| 89 | } | ||
| 90 | |||
| 91 | CurdOut("Choose tracking mode. Local history stays enabled in every mode.") | ||
| 92 | selected, err := DynamicSelect(options) | ||
| 93 | if err != nil { | ||
| 94 | return err | ||
| 95 | } | ||
| 96 | |||
| 97 | switch selected.Key { | ||
| 98 | case "local": | ||
| 99 | config.TrackingLocal = true | ||
| 100 | config.TrackingRemote = TrackingRemoteNone | ||
| 101 | case "anilist": | ||
| 102 | config.TrackingLocal = true | ||
| 103 | config.TrackingRemote = TrackingRemoteAniList | ||
| 104 | case "myanimelist": | ||
| 105 | config.TrackingLocal = true | ||
| 106 | config.TrackingRemote = TrackingRemoteMyAnimeList | ||
| 107 | case "anilist+myanimelist": | ||
| 108 | config.TrackingLocal = true | ||
| 109 | config.TrackingRemote = TrackingRemoteBoth | ||
| 110 | case "-1", "-2": | ||
| 111 | return fmt.Errorf("tracking setup cancelled") | ||
| 112 | default: | ||
| 113 | return fmt.Errorf("unsupported tracking selection: %s", selected.Key) | ||
| 114 | } | ||
| 115 | |||
| 116 | config.TrackingConfigured = true | ||
| 117 | normalizeTrackingConfig(config) | ||
| 118 | return persistTrackingConfig(config) | ||
| 119 | } | ||
| 120 | |||
| 121 | func persistTrackingConfig(config *CurdConfig) error { | ||
| 122 | if config == nil || GlobalConfigPath == "" { | ||
| 123 | return nil | ||
| 124 | } | ||
| 125 | |||
| 126 | configMap, err := LoadConfigFromFile(GlobalConfigPath) | ||
| 127 | if err != nil { | ||
| 128 | return err | ||
| 129 | } | ||
| 130 | |||
| 131 | configMap["TrackingLocal"] = strconv.FormatBool(config.TrackingLocal) | ||
| 132 | configMap["TrackingRemote"] = config.TrackingRemote | ||
| 133 | configMap["TrackingConfigured"] = strconv.FormatBool(config.TrackingConfigured) | ||
| 134 | configMap["MyAnimeListClientID"] = config.MyAnimeListClientID | ||
| 135 | configMap["MyAnimeListClientSecret"] = config.MyAnimeListClientSecret | ||
| 136 | configMap["MyAnimeListImported"] = strconv.FormatBool(config.MyAnimeListImported) | ||
| 137 | |||
| 138 | return SaveConfigToFile(GlobalConfigPath, configMap) | ||
| 139 | } | ||
| 140 | |||
| 141 | func promptTrackingInput(prompt string, allowEmpty bool) (string, error) { | ||
| 142 | config := GetGlobalConfig() | ||
| 143 | if config != nil && config.RofiSelection { | ||
| 144 | value, err := GetUserInputFromRofi(prompt) | ||
| 145 | if err != nil { | ||
| 146 | return "", err | ||
| 147 | } | ||
| 148 | value = strings.TrimSpace(value) | ||
| 149 | if value == "" && !allowEmpty { | ||
| 150 | return "", fmt.Errorf("input required") | ||
| 151 | } | ||
| 152 | return value, nil | ||
| 153 | } | ||
| 154 | |||
| 155 | fmt.Print(prompt + ": ") | ||
| 156 | reader := bufio.NewReader(os.Stdin) | ||
| 157 | value, err := reader.ReadString('\n') | ||
| 158 | if err != nil { | ||
| 159 | return "", err | ||
| 160 | } | ||
| 161 | value = strings.TrimSpace(value) | ||
| 162 | if value == "" && !allowEmpty { | ||
| 163 | return "", fmt.Errorf("input required") | ||
| 164 | } | ||
| 165 | return value, nil | ||
| 166 | } | ||
| 167 | |||
| 168 | func promptAnimeScoreValue() (float64, error) { | ||
| 169 | config := GetGlobalConfig() | ||
| 170 | if config != nil && config.RofiSelection { | ||
| 171 | userInput, err := GetUserInputFromRofi("Enter a score for the anime (0-10)") | ||
| 172 | if err != nil { | ||
| 173 | return 0, err | ||
| 174 | } | ||
| 175 | return strconv.ParseFloat(strings.TrimSpace(userInput), 64) | ||
| 176 | } | ||
| 177 | |||
| 178 | fmt.Println("Rate this anime: ") | ||
| 179 | var score float64 | ||
| 180 | fmt.Scanln(&score) | ||
| 181 | return score, nil | ||
| 182 | } | ||
| 183 | |||
| 184 | func ensureMyAnimeListCredentialsConfigured(config *CurdConfig) error { | ||
| 185 | clientID, _ := myAnimeListClientCredentials(config) | ||
| 186 | if clientID != "" { | ||
| 187 | return nil | ||
| 188 | } | ||
| 189 | |||
| 190 | CurdOut("MyAnimeList sync needs MAL application credentials.") | ||
| 191 | clientIDInput, err := promptTrackingInput("Enter your MyAnimeList client ID", false) | ||
| 192 | if err != nil { | ||
| 193 | return err | ||
| 194 | } | ||
| 195 | clientSecretInput, err := promptTrackingInput("Enter your MyAnimeList client secret (optional)", true) | ||
| 196 | if err != nil { | ||
| 197 | return err | ||
| 198 | } | ||
| 199 | |||
| 200 | config.MyAnimeListClientID = clientIDInput | ||
| 201 | config.MyAnimeListClientSecret = clientSecretInput | ||
| 202 | return persistTrackingConfig(config) | ||
| 203 | } | ||
| 204 | |||
| 205 | func ensureAniListTrackerReady(config *CurdConfig, user *User) error { | ||
| 206 | tokenPath := filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json") | ||
| 207 | if token, err := GetTokenFromFile(tokenPath); err == nil && strings.TrimSpace(token) != "" { | ||
| 208 | if user != nil && user.Token == "" { | ||
| 209 | user.Token = token | ||
| 210 | } | ||
| 211 | return nil | ||
| 212 | } | ||
| 213 | |||
| 214 | ChangeToken(config, user) | ||
| 215 | return nil | ||
| 216 | } | ||
| 217 | |||
| 218 | func ensureMyAnimeListTrackerReady(config *CurdConfig, user *User) error { | ||
| 219 | if err := ensureMyAnimeListCredentialsConfigured(config); err != nil { | ||
| 220 | return err | ||
| 221 | } | ||
| 222 | if token, err := GetMyAnimeListAccessToken(config); err == nil && strings.TrimSpace(token) != "" { | ||
| 223 | return nil | ||
| 224 | } | ||
| 225 | return ChangeMyAnimeListToken(config, user) | ||
| 226 | } | ||
| 227 | |||
| 228 | func EnsureConfiguredTrackersReady(config *CurdConfig, user *User) error { | ||
| 229 | if config == nil { | ||
| 230 | return fmt.Errorf("missing config") | ||
| 231 | } | ||
| 232 | |||
| 233 | if UsesAniListTracking(config) { | ||
| 234 | if err := ensureAniListTrackerReady(config, user); err != nil { | ||
| 235 | return err | ||
| 236 | } | ||
| 237 | } | ||
| 238 | if UsesMyAnimeListTracking(config) { | ||
| 239 | if err := ensureMyAnimeListTrackerReady(config, user); err != nil { | ||
| 240 | return err | ||
| 241 | } | ||
| 242 | } | ||
| 243 | |||
| 244 | return LoadTokenForConfiguredTracking(config, user) | ||
| 245 | } | ||
| 246 | |||
| 247 | func localAnimeListFromHistory(history []Anime) AnimeList { | ||
| 248 | list := AnimeList{} | ||
| 249 | for _, anime := range history { | ||
| 250 | title := anime.Title | ||
| 251 | if title.English == "" && title.Romaji == "" { | ||
| 252 | title.English = strconv.Itoa(anime.AnilistId) | ||
| 253 | title.Romaji = title.English | ||
| 254 | } | ||
| 255 | |||
| 256 | progress := 0 | ||
| 257 | if anime.Ep.Number > 0 { | ||
| 258 | progress = anime.Ep.Number - 1 | ||
| 259 | } | ||
| 260 | |||
| 261 | entry := Entry{ | ||
| 262 | Media: Media{ | ||
| 263 | ID: anime.AnilistId, | ||
| 264 | MalID: anime.MalId, | ||
| 265 | Title: title, | ||
| 266 | Episodes: anime.TotalEpisodes, | ||
| 267 | }, | ||
| 268 | Progress: progress, | ||
| 269 | Status: "CURRENT", | ||
| 270 | } | ||
| 271 | list.Watching = append(list.Watching, entry) | ||
| 272 | } | ||
| 273 | return list | ||
| 274 | } | ||
| 275 | |||
| 276 | func BuildLocalAnimeList(storagePath string) AnimeList { | ||
| 277 | historyPath := filepath.Join(os.ExpandEnv(storagePath), "curd_history.txt") | ||
| 278 | return localAnimeListFromHistory(LocalGetAllAnime(historyPath)) | ||
| 279 | } | ||
| 280 | |||
| 281 | func hasAnyEntries(list AnimeList) bool { | ||
| 282 | return len(list.Watching)+len(list.Completed)+len(list.Paused)+len(list.Dropped)+len(list.Planning)+len(list.Rewatching) > 0 | ||
| 283 | } | ||
| 284 | |||
| 285 | func currentFuzzyDate() FuzzyDate { | ||
| 286 | now := time.Now() | ||
| 287 | return FuzzyDate{ | ||
| 288 | Year: now.Year(), | ||
| 289 | Month: int(now.Month()), | ||
| 290 | Day: now.Day(), | ||
| 291 | } | ||
| 292 | } | ||
| 293 | |||
| 294 | func entryFreshnessScore(entry Entry) int { | ||
| 295 | score := entry.Progress * 100 | ||
| 296 | switch entry.Status { | ||
| 297 | case "REPEATING": | ||
| 298 | score += 60 | ||
| 299 | case "CURRENT": | ||
| 300 | score += 50 | ||
| 301 | case "COMPLETED": | ||
| 302 | score += 40 | ||
| 303 | case "PAUSED": | ||
| 304 | score += 30 | ||
| 305 | case "PLANNING": | ||
| 306 | score += 20 | ||
| 307 | case "DROPPED": | ||
| 308 | score += 10 | ||
| 309 | } | ||
| 310 | if entry.Score > 0 { | ||
| 311 | score += int(entry.Score * 10) | ||
| 312 | } | ||
| 313 | if entry.Repeat > 0 { | ||
| 314 | score += entry.Repeat | ||
| 315 | } | ||
| 316 | if entry.CoverImage != "" { | ||
| 317 | score++ | ||
| 318 | } | ||
| 319 | return score | ||
| 320 | } | ||
| 321 | |||
| 322 | func mergeEntryMetadata(preferred, fallback Entry) Entry { | ||
| 323 | if preferred.ListID == 0 { | ||
| 324 | preferred.ListID = fallback.ListID | ||
| 325 | } | ||
| 326 | if preferred.Media.ID == 0 { | ||
| 327 | preferred.Media.ID = fallback.Media.ID | ||
| 328 | } | ||
| 329 | if preferred.Media.MalID == 0 { | ||
| 330 | preferred.Media.MalID = fallback.Media.MalID | ||
| 331 | } | ||
| 332 | if preferred.Media.Duration == 0 { | ||
| 333 | preferred.Media.Duration = fallback.Media.Duration | ||
| 334 | } | ||
| 335 | if preferred.Media.Episodes == 0 { | ||
| 336 | preferred.Media.Episodes = fallback.Media.Episodes | ||
| 337 | } | ||
| 338 | if preferred.Media.Title.English == "" { | ||
| 339 | preferred.Media.Title.English = fallback.Media.Title.English | ||
| 340 | } | ||
| 341 | if preferred.Media.Title.Romaji == "" { | ||
| 342 | preferred.Media.Title.Romaji = fallback.Media.Title.Romaji | ||
| 343 | } | ||
| 344 | if preferred.Media.Title.Japanese == "" { | ||
| 345 | preferred.Media.Title.Japanese = fallback.Media.Title.Japanese | ||
| 346 | } | ||
| 347 | if preferred.Media.Status == "" { | ||
| 348 | preferred.Media.Status = fallback.Media.Status | ||
| 349 | } | ||
| 350 | if preferred.CoverImage == "" { | ||
| 351 | preferred.CoverImage = fallback.CoverImage | ||
| 352 | } | ||
| 353 | if preferred.Repeat == 0 && fallback.Repeat > 0 { | ||
| 354 | preferred.Repeat = fallback.Repeat | ||
| 355 | } | ||
| 356 | return preferred | ||
| 357 | } | ||
| 358 | |||
| 359 | func mergeAnimeEntries(existing, incoming Entry) Entry { | ||
| 360 | switch { | ||
| 361 | case existing.UpdatedAt.IsZero() && !incoming.UpdatedAt.IsZero(): | ||
| 362 | return mergeEntryMetadata(incoming, existing) | ||
| 363 | case !existing.UpdatedAt.IsZero() && incoming.UpdatedAt.IsZero(): | ||
| 364 | return mergeEntryMetadata(existing, incoming) | ||
| 365 | case existing.UpdatedAt.After(incoming.UpdatedAt): | ||
| 366 | return mergeEntryMetadata(existing, incoming) | ||
| 367 | case incoming.UpdatedAt.After(existing.UpdatedAt): | ||
| 368 | return mergeEntryMetadata(incoming, existing) | ||
| 369 | case entryFreshnessScore(incoming) > entryFreshnessScore(existing): | ||
| 370 | return mergeEntryMetadata(incoming, existing) | ||
| 371 | default: | ||
| 372 | return mergeEntryMetadata(existing, incoming) | ||
| 373 | } | ||
| 374 | } | ||
| 375 | |||
| 376 | func mergeAnimeLists(primary, secondary AnimeList) AnimeList { | ||
| 377 | merged := make(map[int]Entry) | ||
| 378 | for _, entry := range getEntriesByCategory(primary, "ALL") { | ||
| 379 | merged[entry.Media.ID] = entry | ||
| 380 | } | ||
| 381 | for _, entry := range getEntriesByCategory(secondary, "ALL") { | ||
| 382 | if existing, ok := merged[entry.Media.ID]; ok { | ||
| 383 | merged[entry.Media.ID] = mergeAnimeEntries(existing, entry) | ||
| 384 | continue | ||
| 385 | } | ||
| 386 | merged[entry.Media.ID] = entry | ||
| 387 | } | ||
| 388 | |||
| 389 | result := AnimeList{} | ||
| 390 | for _, entry := range merged { | ||
| 391 | switch entry.Status { | ||
| 392 | case "CURRENT": | ||
| 393 | result.Watching = append(result.Watching, entry) | ||
| 394 | case "COMPLETED": | ||
| 395 | result.Completed = append(result.Completed, entry) | ||
| 396 | case "PAUSED": | ||
| 397 | result.Paused = append(result.Paused, entry) | ||
| 398 | case "DROPPED": | ||
| 399 | result.Dropped = append(result.Dropped, entry) | ||
| 400 | case "PLANNING": | ||
| 401 | result.Planning = append(result.Planning, entry) | ||
| 402 | case "REPEATING": | ||
| 403 | result.Rewatching = append(result.Rewatching, entry) | ||
| 404 | } | ||
| 405 | } | ||
| 406 | return result | ||
| 407 | } | ||
| 408 | |||
| 409 | func mapEntriesByMediaID(list AnimeList) map[int]Entry { | ||
| 410 | entries := make(map[int]Entry) | ||
| 411 | for _, entry := range getEntriesByCategory(list, "ALL") { | ||
| 412 | entries[entry.Media.ID] = entry | ||
| 413 | } | ||
| 414 | return entries | ||
| 415 | } | ||
| 416 | |||
| 417 | func animeListFromEntryMap(entries map[int]Entry) AnimeList { | ||
| 418 | ids := make([]int, 0, len(entries)) | ||
| 419 | for id := range entries { | ||
| 420 | ids = append(ids, id) | ||
| 421 | } | ||
| 422 | sort.Ints(ids) | ||
| 423 | |||
| 424 | result := AnimeList{} | ||
| 425 | for _, id := range ids { | ||
| 426 | entry := entries[id] | ||
| 427 | switch entry.Status { | ||
| 428 | case "CURRENT": | ||
| 429 | result.Watching = append(result.Watching, entry) | ||
| 430 | case "COMPLETED": | ||
| 431 | result.Completed = append(result.Completed, entry) | ||
| 432 | case "PAUSED": | ||
| 433 | result.Paused = append(result.Paused, entry) | ||
| 434 | case "DROPPED": | ||
| 435 | result.Dropped = append(result.Dropped, entry) | ||
| 436 | case "PLANNING": | ||
| 437 | result.Planning = append(result.Planning, entry) | ||
| 438 | case "REPEATING": | ||
| 439 | result.Rewatching = append(result.Rewatching, entry) | ||
| 440 | } | ||
| 441 | } | ||
| 442 | return result | ||
| 443 | } | ||
| 444 | |||
| 445 | func entriesEquivalentForSync(current, desired Entry) bool { | ||
| 446 | current = mergeEntryMetadata(current, desired) | ||
| 447 | desired = mergeEntryMetadata(desired, current) | ||
| 448 | |||
| 449 | return current.Media.ID == desired.Media.ID && | ||
| 450 | current.Media.MalID == desired.Media.MalID && | ||
| 451 | current.Progress == desired.Progress && | ||
| 452 | current.Repeat == desired.Repeat && | ||
| 453 | current.Score == desired.Score && | ||
| 454 | current.Status == desired.Status && | ||
| 455 | current.StartedAt == desired.StartedAt && | ||
| 456 | current.CompletedAt == desired.CompletedAt | ||
| 457 | } | ||
| 458 | |||
| 459 | func myAnimeListEntriesEquivalentForSync(current, desired Entry) bool { | ||
| 460 | if entriesEquivalentForSync(current, desired) { | ||
| 461 | return true | ||
| 462 | } | ||
| 463 | |||
| 464 | if current.Repeat == 0 && desired.Repeat > 0 { | ||
| 465 | current.Repeat = desired.Repeat | ||
| 466 | return entriesEquivalentForSync(current, desired) | ||
| 467 | } | ||
| 468 | |||
| 469 | return false | ||
| 470 | } | ||
| 471 | |||
| 472 | type dualRemoteSyncPlan struct { | ||
| 473 | Merged AnimeList | ||
| 474 | AniListUpdates []Entry | ||
| 475 | MyAnimeListUpdates []Entry | ||
| 476 | } | ||
| 477 | |||
| 478 | func buildDualRemoteSyncPlan(aniList, myAnimeList AnimeList) dualRemoteSyncPlan { | ||
| 479 | aniMap := mapEntriesByMediaID(aniList) | ||
| 480 | malMap := mapEntriesByMediaID(myAnimeList) | ||
| 481 | unionIDs := make(map[int]struct{}, len(aniMap)+len(malMap)) | ||
| 482 | for id := range aniMap { | ||
| 483 | unionIDs[id] = struct{}{} | ||
| 484 | } | ||
| 485 | for id := range malMap { | ||
| 486 | unionIDs[id] = struct{}{} | ||
| 487 | } | ||
| 488 | |||
| 489 | orderedIDs := make([]int, 0, len(unionIDs)) | ||
| 490 | for id := range unionIDs { | ||
| 491 | orderedIDs = append(orderedIDs, id) | ||
| 492 | } | ||
| 493 | sort.Ints(orderedIDs) | ||
| 494 | |||
| 495 | mergedEntries := make(map[int]Entry, len(orderedIDs)) | ||
| 496 | plan := dualRemoteSyncPlan{} | ||
| 497 | for _, id := range orderedIDs { | ||
| 498 | aniEntry, hasAni := aniMap[id] | ||
| 499 | malEntry, hasMal := malMap[id] | ||
| 500 | |||
| 501 | switch { | ||
| 502 | case hasAni && hasMal: | ||
| 503 | winner := mergeAnimeEntries(aniEntry, malEntry) | ||
| 504 | mergedEntries[id] = winner | ||
| 505 | if !entriesEquivalentForSync(aniEntry, winner) { | ||
| 506 | plan.AniListUpdates = append(plan.AniListUpdates, winner) | ||
| 507 | } | ||
| 508 | if !myAnimeListEntriesEquivalentForSync(malEntry, winner) { | ||
| 509 | plan.MyAnimeListUpdates = append(plan.MyAnimeListUpdates, winner) | ||
| 510 | } | ||
| 511 | case hasAni: | ||
| 512 | mergedEntries[id] = aniEntry | ||
| 513 | plan.MyAnimeListUpdates = append(plan.MyAnimeListUpdates, aniEntry) | ||
| 514 | case hasMal: | ||
| 515 | mergedEntries[id] = malEntry | ||
| 516 | plan.AniListUpdates = append(plan.AniListUpdates, malEntry) | ||
| 517 | } | ||
| 518 | } | ||
| 519 | |||
| 520 | plan.Merged = animeListFromEntryMap(mergedEntries) | ||
| 521 | return plan | ||
| 522 | } | ||
| 523 | |||
| 524 | func syncDualRemoteTrackers(config *CurdConfig, aniListToken string, aniListUser, myAnimeListUser *User) (AnimeList, error) { | ||
| 525 | if config == nil { | ||
| 526 | return AnimeList{}, fmt.Errorf("missing config") | ||
| 527 | } | ||
| 528 | if aniListUser == nil || myAnimeListUser == nil { | ||
| 529 | return AnimeList{}, fmt.Errorf("missing tracker users") | ||
| 530 | } | ||
| 531 | |||
| 532 | plan := buildDualRemoteSyncPlan(aniListUser.AnimeList, myAnimeListUser.AnimeList) | ||
| 533 | for index, entry := range plan.AniListUpdates { | ||
| 534 | if index > 0 { | ||
| 535 | time.Sleep(350 * time.Millisecond) | ||
| 536 | } | ||
| 537 | if err := saveAniListTrackedEntry(aniListToken, entry); err != nil { | ||
| 538 | return AnimeList{}, err | ||
| 539 | } | ||
| 540 | } | ||
| 541 | for _, entry := range plan.MyAnimeListUpdates { | ||
| 542 | if err := saveMyAnimeListTrackedEntry(config, entry); err != nil { | ||
| 543 | return AnimeList{}, err | ||
| 544 | } | ||
| 545 | } | ||
| 546 | |||
| 547 | aniListUser.AnimeList = plan.Merged | ||
| 548 | myAnimeListUser.AnimeList = plan.Merged | ||
| 549 | if err := saveAniListAnimeListCache(config.StoragePath, aniListUser.Id, plan.Merged); err != nil { | ||
| 550 | Log(fmt.Sprintf("Failed to save AniList anime list cache after dual sync: %v", err)) | ||
| 551 | } | ||
| 552 | if err := saveMyAnimeListCache(config.StoragePath, myAnimeListUser.Id, plan.Merged); err != nil { | ||
| 553 | Log(fmt.Sprintf("Failed to save MyAnimeList anime list cache after dual sync: %v", err)) | ||
| 554 | } | ||
| 555 | return plan.Merged, nil | ||
| 556 | } | ||
| 557 | |||
| 558 | func InitializeCombinedRemoteAnimeList(config *CurdConfig, user *User) error { | ||
| 559 | aniListToken, err := GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")) | ||
| 560 | if err != nil { | ||
| 561 | return err | ||
| 562 | } | ||
| 563 | myAnimeListToken, err := GetMyAnimeListAccessToken(config) | ||
| 564 | if err != nil { | ||
| 565 | return err | ||
| 566 | } | ||
| 567 | |||
| 568 | aniListUser := &User{Token: aniListToken} | ||
| 569 | if err := InitializeAniListUserAnimeList(config, aniListUser); err != nil { | ||
| 570 | return err | ||
| 571 | } | ||
| 572 | myAnimeListUser := &User{Token: myAnimeListToken} | ||
| 573 | if err := InitializeMyAnimeListUserAnimeList(config, myAnimeListUser); err != nil { | ||
| 574 | return err | ||
| 575 | } | ||
| 576 | if err := maybeImportAniListToMyAnimeList(config, myAnimeListUser); err != nil { | ||
| 577 | return err | ||
| 578 | } | ||
| 579 | |||
| 580 | merged, err := syncDualRemoteTrackers(config, aniListToken, aniListUser, myAnimeListUser) | ||
| 581 | if err != nil { | ||
| 582 | return err | ||
| 583 | } | ||
| 584 | |||
| 585 | user.Token = aniListToken | ||
| 586 | user.AnimeList = merged | ||
| 587 | user.ListSync = NewAnimeListSync(user.AnimeList) | ||
| 588 | user.ListSync.MarkRefreshDone() | ||
| 589 | return nil | ||
| 590 | } | ||
| 591 | |||
| 592 | func RefreshCombinedRemoteAnimeList(config *CurdConfig, user *User) error { | ||
| 593 | aniListToken, err := GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")) | ||
| 594 | if err != nil { | ||
| 595 | return err | ||
| 596 | } | ||
| 597 | myAnimeListToken, err := GetMyAnimeListAccessToken(config) | ||
| 598 | if err != nil { | ||
| 599 | return err | ||
| 600 | } | ||
| 601 | |||
| 602 | aniListUser := &User{Token: aniListToken} | ||
| 603 | if err := RefreshAniListUserAnimeList(config, aniListUser); err != nil { | ||
| 604 | if err := InitializeAniListUserAnimeList(config, aniListUser); err != nil { | ||
| 605 | return err | ||
| 606 | } | ||
| 607 | } | ||
| 608 | myAnimeListUser := &User{Token: myAnimeListToken} | ||
| 609 | if err := RefreshMyAnimeListUserAnimeList(config, myAnimeListUser); err != nil { | ||
| 610 | if err := InitializeMyAnimeListUserAnimeList(config, myAnimeListUser); err != nil { | ||
| 611 | return err | ||
| 612 | } | ||
| 613 | } | ||
| 614 | |||
| 615 | merged, err := syncDualRemoteTrackers(config, aniListToken, aniListUser, myAnimeListUser) | ||
| 616 | if err != nil { | ||
| 617 | return err | ||
| 618 | } | ||
| 619 | user.Token = aniListToken | ||
| 620 | user.AnimeList = merged | ||
| 621 | if user.ListSync == nil { | ||
| 622 | user.ListSync = NewAnimeListSync(merged) | ||
| 623 | user.ListSync.MarkRefreshDone() | ||
| 624 | return nil | ||
| 625 | } | ||
| 626 | user.ListSync.Replace(merged, true) | ||
| 627 | user.ListSync.MarkRefreshDone() | ||
| 628 | return nil | ||
| 629 | } | ||
| 630 | |||
| 631 | func InitializeUserAnimeList(userCurdConfig *CurdConfig, user *User) error { | ||
| 632 | if userCurdConfig == nil || user == nil { | ||
| 633 | return fmt.Errorf("missing user or config") | ||
| 634 | } | ||
| 635 | |||
| 636 | switch normalizeRemoteTracker(userCurdConfig.TrackingRemote) { | ||
| 637 | case TrackingRemoteAniList: | ||
| 638 | return InitializeAniListUserAnimeList(userCurdConfig, user) | ||
| 639 | case TrackingRemoteMyAnimeList: | ||
| 640 | if err := InitializeMyAnimeListUserAnimeList(userCurdConfig, user); err != nil { | ||
| 641 | return err | ||
| 642 | } | ||
| 643 | return maybeImportAniListToMyAnimeList(userCurdConfig, user) | ||
| 644 | case TrackingRemoteBoth: | ||
| 645 | if err := InitializeCombinedRemoteAnimeList(userCurdConfig, user); err != nil { | ||
| 646 | return err | ||
| 647 | } | ||
| 648 | return maybeImportAniListToMyAnimeList(userCurdConfig, user) | ||
| 649 | default: | ||
| 650 | list := BuildLocalAnimeList(userCurdConfig.StoragePath) | ||
| 651 | user.AnimeList = list | ||
| 652 | user.ListSync = NewAnimeListSync(list) | ||
| 653 | user.ListSync.MarkRefreshDone() | ||
| 654 | return nil | ||
| 655 | } | ||
| 656 | } | ||
| 657 | |||
| 658 | func RefreshUserAnimeList(userCurdConfig *CurdConfig, user *User) error { | ||
| 659 | if userCurdConfig == nil || user == nil { | ||
| 660 | return fmt.Errorf("missing user or config") | ||
| 661 | } | ||
| 662 | |||
| 663 | switch normalizeRemoteTracker(userCurdConfig.TrackingRemote) { | ||
| 664 | case TrackingRemoteAniList: | ||
| 665 | return RefreshAniListUserAnimeList(userCurdConfig, user) | ||
| 666 | case TrackingRemoteMyAnimeList: | ||
| 667 | return RefreshMyAnimeListUserAnimeList(userCurdConfig, user) | ||
| 668 | case TrackingRemoteBoth: | ||
| 669 | return RefreshCombinedRemoteAnimeList(userCurdConfig, user) | ||
| 670 | default: | ||
| 671 | list := BuildLocalAnimeList(userCurdConfig.StoragePath) | ||
| 672 | user.AnimeList = list | ||
| 673 | if user.ListSync == nil { | ||
| 674 | user.ListSync = NewAnimeListSync(list) | ||
| 675 | user.ListSync.MarkRefreshDone() | ||
| 676 | return nil | ||
| 677 | } | ||
| 678 | user.ListSync.Replace(list, true) | ||
| 679 | user.ListSync.MarkRefreshDone() | ||
| 680 | return nil | ||
| 681 | } | ||
| 682 | } | ||
| 683 | |||
| 684 | func LoadTokenForConfiguredTracking(config *CurdConfig, user *User) error { | ||
| 685 | if config == nil || user == nil { | ||
| 686 | return fmt.Errorf("missing config or user") | ||
| 687 | } | ||
| 688 | |||
| 689 | switch normalizeRemoteTracker(config.TrackingRemote) { | ||
| 690 | case TrackingRemoteAniList: | ||
| 691 | token, err := GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")) | ||
| 692 | if err != nil { | ||
| 693 | return err | ||
| 694 | } | ||
| 695 | user.Token = token | ||
| 696 | case TrackingRemoteMyAnimeList: | ||
| 697 | token, err := GetMyAnimeListAccessToken(config) | ||
| 698 | if err != nil { | ||
| 699 | return err | ||
| 700 | } | ||
| 701 | user.Token = token | ||
| 702 | case TrackingRemoteBoth: | ||
| 703 | token, err := GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")) | ||
| 704 | if err == nil && strings.TrimSpace(token) != "" { | ||
| 705 | user.Token = token | ||
| 706 | return nil | ||
| 707 | } | ||
| 708 | token, err = GetMyAnimeListAccessToken(config) | ||
| 709 | if err != nil { | ||
| 710 | return err | ||
| 711 | } | ||
| 712 | user.Token = token | ||
| 713 | default: | ||
| 714 | user.Token = "" | ||
| 715 | } | ||
| 716 | |||
| 717 | return nil | ||
| 718 | } | ||
| 719 | |||
| 720 | func ChangeTrackingToken(config *CurdConfig, user *User) { | ||
| 721 | switch normalizeRemoteTracker(config.TrackingRemote) { | ||
| 722 | case TrackingRemoteAniList: | ||
| 723 | ChangeToken(config, user) | ||
| 724 | case TrackingRemoteMyAnimeList: | ||
| 725 | if err := ChangeMyAnimeListToken(config, user); err != nil { | ||
| 726 | ExitCurd(err) | ||
| 727 | } | ||
| 728 | case TrackingRemoteBoth: | ||
| 729 | if err := ensureMyAnimeListCredentialsConfigured(config); err != nil { | ||
| 730 | ExitCurd(err) | ||
| 731 | } | ||
| 732 | ChangeToken(config, user) | ||
| 733 | if err := ChangeMyAnimeListToken(config, user); err != nil { | ||
| 734 | ExitCurd(err) | ||
| 735 | } | ||
| 736 | if err := LoadTokenForConfiguredTracking(config, user); err != nil { | ||
| 737 | ExitCurd(err) | ||
| 738 | } | ||
| 739 | default: | ||
| 740 | CurdOut("Remote tracking is disabled.") | ||
| 741 | } | ||
| 742 | } | ||
| 743 | |||
| 744 | func resolveMyAnimeListID(anilistID int) (int, error) { | ||
| 745 | if anilistID == 0 { | ||
| 746 | return 0, fmt.Errorf("invalid AniList ID") | ||
| 747 | } | ||
| 748 | |||
| 749 | if user := GetGlobalUser(); user != nil { | ||
| 750 | if entry, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anilistID)); err == nil && entry.Media.MalID != 0 { | ||
| 751 | return entry.Media.MalID, nil | ||
| 752 | } | ||
| 753 | } | ||
| 754 | |||
| 755 | return GetAnimeMalID(anilistID) | ||
| 756 | } | ||
| 757 | |||
| 758 | func UpdateAnimeProgress(token string, mediaID, progress int) error { | ||
| 759 | config := GetGlobalConfig() | ||
| 760 | switch { | ||
| 761 | case !UsesRemoteTracking(config): | ||
| 762 | return nil | ||
| 763 | case UsesDualRemoteTracking(config): | ||
| 764 | var firstErr error | ||
| 765 | if err := UpdateAniListAnimeProgress(token, mediaID, progress); err != nil { | ||
| 766 | firstErr = err | ||
| 767 | } | ||
| 768 | malID, err := resolveMyAnimeListID(mediaID) | ||
| 769 | if err != nil { | ||
| 770 | if firstErr != nil { | ||
| 771 | return firstErr | ||
| 772 | } | ||
| 773 | return err | ||
| 774 | } | ||
| 775 | if err := updateMyAnimeListProgress(config, malID, progress); err != nil && firstErr == nil { | ||
| 776 | firstErr = err | ||
| 777 | } | ||
| 778 | return firstErr | ||
| 779 | case UsesAniListTracking(config): | ||
| 780 | return UpdateAniListAnimeProgress(token, mediaID, progress) | ||
| 781 | case UsesMyAnimeListTracking(config): | ||
| 782 | malID, err := resolveMyAnimeListID(mediaID) | ||
| 783 | if err != nil { | ||
| 784 | return err | ||
| 785 | } | ||
| 786 | return updateMyAnimeListProgress(config, malID, progress) | ||
| 787 | default: | ||
| 788 | return nil | ||
| 789 | } | ||
| 790 | } | ||
| 791 | |||
| 792 | func UpdateAnimeStatus(token string, mediaID int, status string) error { | ||
| 793 | config := GetGlobalConfig() | ||
| 794 | switch { | ||
| 795 | case !UsesRemoteTracking(config): | ||
| 796 | return nil | ||
| 797 | case UsesDualRemoteTracking(config): | ||
| 798 | var firstErr error | ||
| 799 | if err := UpdateAniListAnimeStatus(token, mediaID, status); err != nil { | ||
| 800 | firstErr = err | ||
| 801 | } | ||
| 802 | malID, err := resolveMyAnimeListID(mediaID) | ||
| 803 | if err != nil { | ||
| 804 | if firstErr != nil { | ||
| 805 | return firstErr | ||
| 806 | } | ||
| 807 | return err | ||
| 808 | } | ||
| 809 | if err := updateMyAnimeListStatus(config, malID, status); err != nil && firstErr == nil { | ||
| 810 | firstErr = err | ||
| 811 | } | ||
| 812 | return firstErr | ||
| 813 | case UsesAniListTracking(config): | ||
| 814 | return UpdateAniListAnimeStatus(token, mediaID, status) | ||
| 815 | case UsesMyAnimeListTracking(config): | ||
| 816 | malID, err := resolveMyAnimeListID(mediaID) | ||
| 817 | if err != nil { | ||
| 818 | return err | ||
| 819 | } | ||
| 820 | return updateMyAnimeListStatus(config, malID, status) | ||
| 821 | default: | ||
| 822 | return nil | ||
| 823 | } | ||
| 824 | } | ||
| 825 | |||
| 826 | func RateAnime(token string, mediaID int) error { | ||
| 827 | config := GetGlobalConfig() | ||
| 828 | switch { | ||
| 829 | case !UsesRemoteTracking(config): | ||
| 830 | return nil | ||
| 831 | case UsesDualRemoteTracking(config): | ||
| 832 | score, err := promptAnimeScoreValue() | ||
| 833 | if err != nil { | ||
| 834 | return err | ||
| 835 | } | ||
| 836 | var firstErr error | ||
| 837 | if err := saveAniListAnimeScore(token, mediaID, score); err != nil { | ||
| 838 | firstErr = err | ||
| 839 | } | ||
| 840 | malID, err := resolveMyAnimeListID(mediaID) | ||
| 841 | if err != nil { | ||
| 842 | if firstErr != nil { | ||
| 843 | return firstErr | ||
| 844 | } | ||
| 845 | return err | ||
| 846 | } | ||
| 847 | if err := rateMyAnimeListAnimeWithScore(config, malID, int(score+0.5)); err != nil && firstErr == nil { | ||
| 848 | firstErr = err | ||
| 849 | } | ||
| 850 | return firstErr | ||
| 851 | case UsesAniListTracking(config): | ||
| 852 | return RateAniListAnime(token, mediaID) | ||
| 853 | case UsesMyAnimeListTracking(config): | ||
| 854 | malID, err := resolveMyAnimeListID(mediaID) | ||
| 855 | if err != nil { | ||
| 856 | return err | ||
| 857 | } | ||
| 858 | return rateMyAnimeListAnime(config, malID) | ||
| 859 | default: | ||
| 860 | return nil | ||
| 861 | } | ||
| 862 | } | ||
| 863 | |||
| 864 | func AddAnimeToWatchingList(animeID int, token string) error { | ||
| 865 | config := GetGlobalConfig() | ||
| 866 | switch { | ||
| 867 | case !UsesRemoteTracking(config): | ||
| 868 | return nil | ||
| 869 | case UsesDualRemoteTracking(config): | ||
| 870 | var firstErr error | ||
| 871 | if err := AddAniListAnimeToWatchingList(animeID, token); err != nil { | ||
| 872 | firstErr = err | ||
| 873 | } | ||
| 874 | malID, err := resolveMyAnimeListID(animeID) | ||
| 875 | if err != nil { | ||
| 876 | if firstErr != nil { | ||
| 877 | return firstErr | ||
| 878 | } | ||
| 879 | return err | ||
| 880 | } | ||
| 881 | if err := addMyAnimeListAnimeToList(config, malID, "CURRENT"); err != nil && firstErr == nil { | ||
| 882 | firstErr = err | ||
| 883 | } | ||
| 884 | return firstErr | ||
| 885 | case UsesAniListTracking(config): | ||
| 886 | return AddAniListAnimeToWatchingList(animeID, token) | ||
| 887 | case UsesMyAnimeListTracking(config): | ||
| 888 | malID, err := resolveMyAnimeListID(animeID) | ||
| 889 | if err != nil { | ||
| 890 | return err | ||
| 891 | } | ||
| 892 | return addMyAnimeListAnimeToList(config, malID, "CURRENT") | ||
| 893 | default: | ||
| 894 | return nil | ||
| 895 | } | ||
| 896 | } | ||
| 897 | |||
| 898 | func CompleteAnimeRewatch(token string, anime Anime) error { | ||
| 899 | config := GetGlobalConfig() | ||
| 900 | switch { | ||
| 901 | case !UsesRemoteTracking(config): | ||
| 902 | return nil | ||
| 903 | case UsesDualRemoteTracking(config): | ||
| 904 | var firstErr error | ||
| 905 | if err := CompleteAniListAnimeRewatch(token, anime); err != nil { | ||
| 906 | firstErr = err | ||
| 907 | } | ||
| 908 | malID := anime.MalId | ||
| 909 | if malID == 0 { | ||
| 910 | var err error | ||
| 911 | malID, err = resolveMyAnimeListID(anime.AnilistId) | ||
| 912 | if err != nil { | ||
| 913 | if firstErr != nil { | ||
| 914 | return firstErr | ||
| 915 | } | ||
| 916 | return err | ||
| 917 | } | ||
| 918 | } | ||
| 919 | if err := completeMyAnimeListRewatch(config, malID, anime); err != nil && firstErr == nil { | ||
| 920 | firstErr = err | ||
| 921 | } | ||
| 922 | return firstErr | ||
| 923 | case UsesAniListTracking(config): | ||
| 924 | return CompleteAniListAnimeRewatch(token, anime) | ||
| 925 | case UsesMyAnimeListTracking(config): | ||
| 926 | malID := anime.MalId | ||
| 927 | if malID == 0 { | ||
| 928 | var err error | ||
| 929 | malID, err = resolveMyAnimeListID(anime.AnilistId) | ||
| 930 | if err != nil { | ||
| 931 | return err | ||
| 932 | } | ||
| 933 | } | ||
| 934 | return completeMyAnimeListRewatch(config, malID, anime) | ||
| 935 | default: | ||
| 936 | return nil | ||
| 937 | } | ||
| 938 | } | ||
| 939 | |||
| 940 | func StartAnimeRewatch(token string, anime Anime) error { | ||
| 941 | config := GetGlobalConfig() | ||
| 942 | startedAt := currentFuzzyDate() | ||
| 943 | completedAt := FuzzyDate{} | ||
| 944 | switch { | ||
| 945 | case !UsesRemoteTracking(config): | ||
| 946 | return nil | ||
| 947 | case UsesDualRemoteTracking(config): | ||
| 948 | var firstErr error | ||
| 949 | status := "REPEATING" | ||
| 950 | progress := 0 | ||
| 951 | if err := SaveAniListAnimeListEntry(token, anime.AnilistId, &status, &progress, nil, nil, &startedAt, &completedAt); err != nil { | ||
| 952 | firstErr = err | ||
| 953 | } | ||
| 954 | malID := anime.MalId | ||
| 955 | if malID == 0 { | ||
| 956 | var err error | ||
| 957 | malID, err = resolveMyAnimeListID(anime.AnilistId) | ||
| 958 | if err != nil { | ||
| 959 | if firstErr != nil { | ||
| 960 | return firstErr | ||
| 961 | } | ||
| 962 | return err | ||
| 963 | } | ||
| 964 | } | ||
| 965 | if err := updateMyAnimeListListStatus(config, malID, map[string]string{ | ||
| 966 | "status": "watching", | ||
| 967 | "is_rewatching": "true", | ||
| 968 | "num_watched_episodes": "0", | ||
| 969 | "start_date": formatMyAnimeListDate(startedAt), | ||
| 970 | "finish_date": "", | ||
| 971 | }); err != nil && firstErr == nil { | ||
| 972 | firstErr = err | ||
| 973 | } | ||
| 974 | return firstErr | ||
| 975 | case UsesAniListTracking(config): | ||
| 976 | status := "REPEATING" | ||
| 977 | progress := 0 | ||
| 978 | return SaveAniListAnimeListEntry(token, anime.AnilistId, &status, &progress, nil, nil, &startedAt, &completedAt) | ||
| 979 | case UsesMyAnimeListTracking(config): | ||
| 980 | malID := anime.MalId | ||
| 981 | if malID == 0 { | ||
| 982 | var err error | ||
| 983 | malID, err = resolveMyAnimeListID(anime.AnilistId) | ||
| 984 | if err != nil { | ||
| 985 | return err | ||
| 986 | } | ||
| 987 | } | ||
| 988 | return updateMyAnimeListListStatus(config, malID, map[string]string{ | ||
| 989 | "status": "watching", | ||
| 990 | "is_rewatching": "true", | ||
| 991 | "num_watched_episodes": "0", | ||
| 992 | "start_date": formatMyAnimeListDate(startedAt), | ||
| 993 | "finish_date": "", | ||
| 994 | }) | ||
| 995 | default: | ||
| 996 | return nil | ||
| 997 | } | ||
| 998 | } | ||
| 999 | |||
| 1000 | func AddAnimeToList(animeID int, status string, token string) error { | ||
| 1001 | config := GetGlobalConfig() | ||
| 1002 | switch { | ||
| 1003 | case !UsesRemoteTracking(config): | ||
| 1004 | return nil | ||
| 1005 | case UsesDualRemoteTracking(config): | ||
| 1006 | var firstErr error | ||
| 1007 | if err := AddAniListAnimeToList(animeID, status, token); err != nil { | ||
| 1008 | firstErr = err | ||
| 1009 | } | ||
| 1010 | malID, err := resolveMyAnimeListID(animeID) | ||
| 1011 | if err != nil { | ||
| 1012 | if firstErr != nil { | ||
| 1013 | return firstErr | ||
| 1014 | } | ||
| 1015 | return err | ||
| 1016 | } | ||
| 1017 | if err := addMyAnimeListAnimeToList(config, malID, status); err != nil && firstErr == nil { | ||
| 1018 | firstErr = err | ||
| 1019 | } | ||
| 1020 | return firstErr | ||
| 1021 | case UsesAniListTracking(config): | ||
| 1022 | return AddAniListAnimeToList(animeID, status, token) | ||
| 1023 | case UsesMyAnimeListTracking(config): | ||
| 1024 | malID, err := resolveMyAnimeListID(animeID) | ||
| 1025 | if err != nil { | ||
| 1026 | return err | ||
| 1027 | } | ||
| 1028 | return addMyAnimeListAnimeToList(config, malID, status) | ||
| 1029 | default: | ||
| 1030 | return nil | ||
| 1031 | } | ||
| 1032 | } | ||
| 1033 | |||
| 1034 | func maybeImportAniListToMyAnimeList(config *CurdConfig, user *User) error { | ||
| 1035 | if config == nil || user == nil || !UsesMyAnimeListTracking(config) || config.MyAnimeListImported || hasAnyEntries(user.AnimeList) { | ||
| 1036 | return nil | ||
| 1037 | } | ||
| 1038 | |||
| 1039 | legacyTokenPath := filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json") | ||
| 1040 | if _, err := os.Stat(legacyTokenPath); err != nil { | ||
| 1041 | config.MyAnimeListImported = true | ||
| 1042 | return persistTrackingConfig(config) | ||
| 1043 | } | ||
| 1044 | |||
| 1045 | options := []SelectionOption{ | ||
| 1046 | {Key: "yes", Label: "Import your existing AniList progress into MyAnimeList"}, | ||
| 1047 | {Key: "no", Label: "Start with MyAnimeList as-is"}, | ||
| 1048 | } | ||
| 1049 | |||
| 1050 | CurdOut("AniList tracking data was found.") | ||
| 1051 | selected, err := DynamicSelect(options) | ||
| 1052 | if err != nil { | ||
| 1053 | return err | ||
| 1054 | } | ||
| 1055 | |||
| 1056 | if selected.Key == "yes" { | ||
| 1057 | if err := ImportAniListTrackingToMyAnimeList(config); err != nil { | ||
| 1058 | return err | ||
| 1059 | } | ||
| 1060 | if err := RefreshMyAnimeListUserAnimeList(config, user); err != nil { | ||
| 1061 | return err | ||
| 1062 | } | ||
| 1063 | } | ||
| 1064 | |||
| 1065 | config.MyAnimeListImported = true | ||
| 1066 | return persistTrackingConfig(config) | ||
| 1067 | } | ||
| 1068 | |||
| 1069 | func ImportAniListTrackingToMyAnimeList(config *CurdConfig) error { | ||
| 1070 | aniListTokenPath := filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json") | ||
| 1071 | aniListToken, err := GetTokenFromFile(aniListTokenPath) | ||
| 1072 | if err != nil { | ||
| 1073 | return err | ||
| 1074 | } | ||
| 1075 | |||
| 1076 | userID, _, err := GetAnilistUserID(aniListToken) | ||
| 1077 | if err != nil { | ||
| 1078 | return err | ||
| 1079 | } | ||
| 1080 | |||
| 1081 | userData, err := GetUserData(aniListToken, userID) | ||
| 1082 | if err != nil { | ||
| 1083 | return err | ||
| 1084 | } | ||
| 1085 | |||
| 1086 | sourceList := ParseAnimeList(userData) | ||
| 1087 | for _, entry := range getEntriesByCategory(sourceList, "ALL") { | ||
| 1088 | if entry.Media.MalID == 0 { | ||
| 1089 | continue | ||
| 1090 | } | ||
| 1091 | |||
| 1092 | payload := map[string]string{ | ||
| 1093 | "status": aniListStatusToMyAnimeListStatus(entry.Status), | ||
| 1094 | "num_watched_episodes": strconv.Itoa(entry.Progress), | ||
| 1095 | } | ||
| 1096 | if entry.Score > 0 { | ||
| 1097 | payload["score"] = strconv.Itoa(int(entry.Score + 0.5)) | ||
| 1098 | } | ||
| 1099 | if entry.Repeat > 0 { | ||
| 1100 | payload["num_times_rewatched"] = strconv.Itoa(entry.Repeat) | ||
| 1101 | } | ||
| 1102 | if entry.Status == "REPEATING" { | ||
| 1103 | payload["is_rewatching"] = "true" | ||
| 1104 | payload["status"] = "watching" | ||
| 1105 | } | ||
| 1106 | |||
| 1107 | if err := updateMyAnimeListListStatus(config, entry.Media.MalID, payload); err != nil { | ||
| 1108 | return err | ||
| 1109 | } | ||
| 1110 | } | ||
| 1111 | |||
| 1112 | return nil | ||
| 1113 | } | ||
| 1114 | |||
| 1115 | func trackingSummary(config *CurdConfig) string { | ||
| 1116 | parts := make([]string, 0, 2) | ||
| 1117 | if UsesLocalTracking(config) { | ||
| 1118 | parts = append(parts, "local") | ||
| 1119 | } | ||
| 1120 | remote := normalizeRemoteTracker(config.TrackingRemote) | ||
| 1121 | if remote != TrackingRemoteNone { | ||
| 1122 | parts = append(parts, remote) | ||
| 1123 | } | ||
| 1124 | return strings.Join(parts, "+") | ||
| 1125 | } | ||
| 1126 | |||
| 1127 | func RemoteTrackingDisplayName(config *CurdConfig) string { | ||
| 1128 | switch normalizeRemoteTracker(config.TrackingRemote) { | ||
| 1129 | case TrackingRemoteBoth: | ||
| 1130 | return "AniList + MyAnimeList" | ||
| 1131 | case TrackingRemoteMyAnimeList: | ||
| 1132 | return "MyAnimeList" | ||
| 1133 | case TrackingRemoteAniList: | ||
| 1134 | return "AniList" | ||
| 1135 | default: | ||
| 1136 | return "remote tracking" | ||
| 1137 | } | ||
| 1138 | } | ||
| 1139 | |||
| 1140 | func fetchAniListAnimeListFromToken(token string) (AnimeList, error) { | ||
| 1141 | userID, _, err := GetAnilistUserID(token) | ||
| 1142 | if err != nil { | ||
| 1143 | return AnimeList{}, err | ||
| 1144 | } | ||
| 1145 | userData, err := GetUserData(token, userID) | ||
| 1146 | if err != nil { | ||
| 1147 | return AnimeList{}, err | ||
| 1148 | } | ||
| 1149 | return ParseAnimeList(userData), nil | ||
| 1150 | } | ||
| 1151 | |||
| 1152 | func saveAniListTrackedEntry(token string, entry Entry) error { | ||
| 1153 | status := entry.Status | ||
| 1154 | progress := entry.Progress | ||
| 1155 | repeat := entry.Repeat | ||
| 1156 | score := entry.Score | ||
| 1157 | return SaveAniListAnimeListEntry(token, entry.Media.ID, &status, &progress, &repeat, &score, &entry.StartedAt, &entry.CompletedAt) | ||
| 1158 | } | ||
| 1159 | |||
| 1160 | func saveMyAnimeListTrackedEntry(config *CurdConfig, entry Entry) error { | ||
| 1161 | malID := entry.Media.MalID | ||
| 1162 | if malID == 0 { | ||
| 1163 | var err error | ||
| 1164 | malID, err = resolveMyAnimeListID(entry.Media.ID) | ||
| 1165 | if err != nil { | ||
| 1166 | return err | ||
| 1167 | } | ||
| 1168 | } | ||
| 1169 | |||
| 1170 | payload := map[string]string{ | ||
| 1171 | "status": aniListStatusToMyAnimeListStatus(entry.Status), | ||
| 1172 | "num_watched_episodes": strconv.Itoa(entry.Progress), | ||
| 1173 | "score": strconv.Itoa(int(entry.Score + 0.5)), | ||
| 1174 | "start_date": formatMyAnimeListDate(entry.StartedAt), | ||
| 1175 | "finish_date": formatMyAnimeListDate(entry.CompletedAt), | ||
| 1176 | "is_rewatching": "false", | ||
| 1177 | } | ||
| 1178 | if entry.Status == "REPEATING" { | ||
| 1179 | payload["status"] = "watching" | ||
| 1180 | payload["is_rewatching"] = "true" | ||
| 1181 | } | ||
| 1182 | if entry.Status == "COMPLETED" && entry.Repeat > 0 { | ||
| 1183 | delete(payload, "is_rewatching") | ||
| 1184 | if err := updateMyAnimeListListStatus(config, malID, payload); err != nil { | ||
| 1185 | return err | ||
| 1186 | } | ||
| 1187 | return updateMyAnimeListListStatus(config, malID, map[string]string{ | ||
| 1188 | "num_times_rewatched": strconv.Itoa(entry.Repeat), | ||
| 1189 | }) | ||
| 1190 | } | ||
| 1191 | payload["num_times_rewatched"] = strconv.Itoa(entry.Repeat) | ||
| 1192 | return updateMyAnimeListListStatus(config, malID, payload) | ||
| 1193 | } | ||
| 1194 | |||
| 1195 | func upsertAnimeListToAniList(token string, list AnimeList) error { | ||
| 1196 | for index, entry := range getEntriesByCategory(list, "ALL") { | ||
| 1197 | if index > 0 { | ||
| 1198 | time.Sleep(350 * time.Millisecond) | ||
| 1199 | } | ||
| 1200 | if err := saveAniListTrackedEntry(token, entry); err != nil { | ||
| 1201 | return err | ||
| 1202 | } | ||
| 1203 | } | ||
| 1204 | return nil | ||
| 1205 | } | ||
| 1206 | |||
| 1207 | func upsertAnimeListToMyAnimeList(config *CurdConfig, list AnimeList) error { | ||
| 1208 | for _, entry := range getEntriesByCategory(list, "ALL") { | ||
| 1209 | if err := saveMyAnimeListTrackedEntry(config, entry); err != nil { | ||
| 1210 | return err | ||
| 1211 | } | ||
| 1212 | } | ||
| 1213 | return nil | ||
| 1214 | } | ||
| 1215 | |||
| 1216 | func wipeAniListRemote(config *CurdConfig) error { | ||
| 1217 | token, err := GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")) | ||
| 1218 | if err != nil { | ||
| 1219 | return err | ||
| 1220 | } | ||
| 1221 | list, err := fetchAniListAnimeListFromToken(token) | ||
| 1222 | if err != nil { | ||
| 1223 | return err | ||
| 1224 | } | ||
| 1225 | for index, entry := range getEntriesByCategory(list, "ALL") { | ||
| 1226 | if entry.ListID == 0 { | ||
| 1227 | continue | ||
| 1228 | } | ||
| 1229 | if index > 0 { | ||
| 1230 | time.Sleep(350 * time.Millisecond) | ||
| 1231 | } | ||
| 1232 | if err := DeleteAniListListEntry(token, entry.ListID); err != nil { | ||
| 1233 | return err | ||
| 1234 | } | ||
| 1235 | } | ||
| 1236 | return nil | ||
| 1237 | } | ||
| 1238 | |||
| 1239 | func wipeMyAnimeListRemote(config *CurdConfig) error { | ||
| 1240 | list, err := FetchLatestMyAnimeList(config, &User{}) | ||
| 1241 | if err != nil { | ||
| 1242 | return err | ||
| 1243 | } | ||
| 1244 | for _, entry := range getEntriesByCategory(list, "ALL") { | ||
| 1245 | if entry.Media.MalID == 0 { | ||
| 1246 | continue | ||
| 1247 | } | ||
| 1248 | if err := deleteMyAnimeListEntry(config, entry.Media.MalID); err != nil { | ||
| 1249 | return err | ||
| 1250 | } | ||
| 1251 | } | ||
| 1252 | return nil | ||
| 1253 | } | ||
| 1254 | |||
| 1255 | func ReplaceMyAnimeListWithAniList(config *CurdConfig) error { | ||
| 1256 | token, err := GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")) | ||
| 1257 | if err != nil { | ||
| 1258 | return err | ||
| 1259 | } | ||
| 1260 | sourceList, err := fetchAniListAnimeListFromToken(token) | ||
| 1261 | if err != nil { | ||
| 1262 | return err | ||
| 1263 | } | ||
| 1264 | if err := wipeMyAnimeListRemote(config); err != nil { | ||
| 1265 | return err | ||
| 1266 | } | ||
| 1267 | return upsertAnimeListToMyAnimeList(config, sourceList) | ||
| 1268 | } | ||
| 1269 | |||
| 1270 | func ReplaceAniListWithMyAnimeList(config *CurdConfig) error { | ||
| 1271 | token, err := GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")) | ||
| 1272 | if err != nil { | ||
| 1273 | return err | ||
| 1274 | } | ||
| 1275 | sourceList, err := FetchLatestMyAnimeList(config, &User{}) | ||
| 1276 | if err != nil { | ||
| 1277 | return err | ||
| 1278 | } | ||
| 1279 | if err := wipeAniListRemote(config); err != nil { | ||
| 1280 | return err | ||
| 1281 | } | ||
| 1282 | return upsertAnimeListToAniList(token, sourceList) | ||
| 1283 | } | ||
| 1284 | |||
| 1285 | func MergeRemoteLists(config *CurdConfig) error { | ||
| 1286 | token, err := GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")) | ||
| 1287 | if err != nil { | ||
| 1288 | return err | ||
| 1289 | } | ||
| 1290 | aniListUser := &User{} | ||
| 1291 | aniList, err := fetchAniListAnimeListFromToken(token) | ||
| 1292 | if err != nil { | ||
| 1293 | return err | ||
| 1294 | } | ||
| 1295 | aniListUser.AnimeList = aniList | ||
| 1296 | |||
| 1297 | myAnimeListUser := &User{} | ||
| 1298 | myAnimeList, err := FetchLatestMyAnimeList(config, myAnimeListUser) | ||
| 1299 | if err != nil { | ||
| 1300 | return err | ||
| 1301 | } | ||
| 1302 | myAnimeListUser.AnimeList = myAnimeList | ||
| 1303 | |||
| 1304 | _, err = syncDualRemoteTrackers(config, token, aniListUser, myAnimeListUser) | ||
| 1305 | return err | ||
| 1306 | } | ||
| 1307 | |||
| 1308 | func trackersCanCrossSync(config *CurdConfig) bool { | ||
| 1309 | if _, err := GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")); err != nil { | ||
| 1310 | return false | ||
| 1311 | } | ||
| 1312 | if _, err := GetMyAnimeListAccessToken(config); err != nil { | ||
| 1313 | return false | ||
| 1314 | } | ||
| 1315 | return true | ||
| 1316 | } | ||
| 1317 | |||
| 1318 | func ChangeTracker(config *CurdConfig, user *User) { | ||
| 1319 | options := []SelectionOption{ | ||
| 1320 | {Key: TrackingRemoteNone, Label: "local"}, | ||
| 1321 | {Key: TrackingRemoteAniList, Label: "anilist"}, | ||
| 1322 | {Key: TrackingRemoteMyAnimeList, Label: "myanimelist"}, | ||
| 1323 | {Key: TrackingRemoteBoth, Label: "anilist + myanimelist"}, | ||
| 1324 | } | ||
| 1325 | |||
| 1326 | selected, err := DynamicSelect(options) | ||
| 1327 | if err != nil || selected.Key == "-1" || selected.Key == "-2" { | ||
| 1328 | return | ||
| 1329 | } | ||
| 1330 | |||
| 1331 | config.TrackingLocal = true | ||
| 1332 | config.TrackingRemote = selected.Key | ||
| 1333 | config.TrackingConfigured = true | ||
| 1334 | normalizeTrackingConfig(config) | ||
| 1335 | if err := persistTrackingConfig(config); err != nil { | ||
| 1336 | ExitCurd(err) | ||
| 1337 | } | ||
| 1338 | if err := EnsureConfiguredTrackersReady(config, user); err != nil { | ||
| 1339 | ExitCurd(err) | ||
| 1340 | } | ||
| 1341 | |||
| 1342 | if trackersCanCrossSync(config) { | ||
| 1343 | syncOptions := []SelectionOption{ | ||
| 1344 | {Key: "skip", Label: "Keep current lists"}, | ||
| 1345 | {Key: "merge", Label: "Merge both lists and update both"}, | ||
| 1346 | {Key: "anilist_to_mal", Label: "Replace MyAnimeList with AniList"}, | ||
| 1347 | {Key: "mal_to_anilist", Label: "Replace AniList with MyAnimeList"}, | ||
| 1348 | } | ||
| 1349 | CurdOut("Optional tracker sync action:") | ||
| 1350 | syncSelection, syncErr := DynamicSelect(syncOptions) | ||
| 1351 | if syncErr == nil { | ||
| 1352 | switch syncSelection.Key { | ||
| 1353 | case "merge": | ||
| 1354 | err = MergeRemoteLists(config) | ||
| 1355 | case "anilist_to_mal": | ||
| 1356 | err = ReplaceMyAnimeListWithAniList(config) | ||
| 1357 | case "mal_to_anilist": | ||
| 1358 | err = ReplaceAniListWithMyAnimeList(config) | ||
| 1359 | } | ||
| 1360 | if err != nil { | ||
| 1361 | ExitCurd(err) | ||
| 1362 | } | ||
| 1363 | } | ||
| 1364 | } | ||
| 1365 | |||
| 1366 | if err := RefreshUserAnimeList(config, user); err != nil { | ||
| 1367 | ExitCurd(err) | ||
| 1368 | } | ||
| 1369 | CurdOut(fmt.Sprintf("Tracker changed to %s.", selected.Label)) | ||
| 1370 | } | ||
internal/tracking_live_integration_test.go added +692
| @@ -0,0 +1,692 @@ | |||
| 1 | package internal | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "fmt" | ||
| 5 | "os" | ||
| 6 | "path/filepath" | ||
| 7 | "strconv" | ||
| 8 | "sync" | ||
| 9 | "testing" | ||
| 10 | "time" | ||
| 11 | ) | ||
| 12 | |||
| 13 | type liveTestAnime struct { | ||
| 14 | Title string | ||
| 15 | AniListID int | ||
| 16 | MalID int | ||
| 17 | } | ||
| 18 | |||
| 19 | var ( | ||
| 20 | resolveLiveTestAnimeOnce sync.Once | ||
| 21 | resolvedLiveTestAnime []liveTestAnime | ||
| 22 | resolvedLiveTestAnimeErr error | ||
| 23 | ) | ||
| 24 | |||
| 25 | func TestTrackerLiveIntegration(t *testing.T) { | ||
| 26 | config, anilistToken, _, cleanup := loadLiveTrackerTestContext(t) | ||
| 27 | defer cleanup() | ||
| 28 | |||
| 29 | testAnime := resolveLiveTestAnime(t) | ||
| 30 | |||
| 31 | t.Run("dual-sync keeps latest remote update", func(t *testing.T) { | ||
| 32 | resetLiveTrackerState(t, config, anilistToken) | ||
| 33 | |||
| 34 | older := liveEntry(testAnime[0], "CURRENT", 2, 3, FuzzyDate{Year: 2026, Month: 1, Day: 2}, FuzzyDate{}) | ||
| 35 | if err := saveAniListTrackedEntry(anilistToken, older); err != nil { | ||
| 36 | t.Fatalf("seed AniList entry: %v", err) | ||
| 37 | } | ||
| 38 | |||
| 39 | waitForRemoteTimestampTick() | ||
| 40 | |||
| 41 | newer := liveEntry(testAnime[0], "PAUSED", 4, 8, FuzzyDate{Year: 2026, Month: 3, Day: 4}, FuzzyDate{}) | ||
| 42 | if err := saveMyAnimeListTrackedEntry(config, newer); err != nil { | ||
| 43 | t.Fatalf("seed MyAnimeList entry: %v", err) | ||
| 44 | } | ||
| 45 | |||
| 46 | refreshBothTrackers(t, config) | ||
| 47 | |||
| 48 | aniList, myAnimeList := fetchBothLists(t, config, anilistToken) | ||
| 49 | assertEntryState(t, aniList, newer) | ||
| 50 | assertEntryState(t, myAnimeList, newer) | ||
| 51 | }) | ||
| 52 | |||
| 53 | t.Run("dual-sync copies AniList-only entry to MyAnimeList", func(t *testing.T) { | ||
| 54 | resetLiveTrackerState(t, config, anilistToken) | ||
| 55 | |||
| 56 | entry := liveEntry(testAnime[1], "CURRENT", 5, 6, FuzzyDate{Year: 2025, Month: 12, Day: 24}, FuzzyDate{}) | ||
| 57 | if err := saveAniListTrackedEntry(anilistToken, entry); err != nil { | ||
| 58 | t.Fatalf("seed AniList entry: %v", err) | ||
| 59 | } | ||
| 60 | |||
| 61 | refreshBothTrackers(t, config) | ||
| 62 | |||
| 63 | _, myAnimeList := fetchBothLists(t, config, anilistToken) | ||
| 64 | assertEntryState(t, myAnimeList, entry) | ||
| 65 | }) | ||
| 66 | |||
| 67 | t.Run("dual-sync copies MyAnimeList-only entry to AniList", func(t *testing.T) { | ||
| 68 | resetLiveTrackerState(t, config, anilistToken) | ||
| 69 | |||
| 70 | entry := liveEntry(testAnime[2], "PLANNING", 0, 7, FuzzyDate{}, FuzzyDate{}) | ||
| 71 | if err := saveMyAnimeListTrackedEntry(config, entry); err != nil { | ||
| 72 | t.Fatalf("seed MyAnimeList entry: %v", err) | ||
| 73 | } | ||
| 74 | |||
| 75 | refreshBothTrackers(t, config) | ||
| 76 | |||
| 77 | aniList, _ := fetchBothLists(t, config, anilistToken) | ||
| 78 | assertEntryState(t, aniList, entry) | ||
| 79 | }) | ||
| 80 | |||
| 81 | t.Run("replace MyAnimeList with AniList", func(t *testing.T) { | ||
| 82 | resetLiveTrackerState(t, config, anilistToken) | ||
| 83 | |||
| 84 | sourceEntry := liveEntry(testAnime[0], "CURRENT", 3, 5, FuzzyDate{Year: 2026, Month: 2, Day: 1}, FuzzyDate{}) | ||
| 85 | targetOnlyEntry := liveEntry(testAnime[3], "PAUSED", 1, 9, FuzzyDate{}, FuzzyDate{}) | ||
| 86 | |||
| 87 | if err := saveAniListTrackedEntry(anilistToken, sourceEntry); err != nil { | ||
| 88 | t.Fatalf("seed AniList entry: %v", err) | ||
| 89 | } | ||
| 90 | if err := saveMyAnimeListTrackedEntry(config, targetOnlyEntry); err != nil { | ||
| 91 | t.Fatalf("seed MyAnimeList entry: %v", err) | ||
| 92 | } | ||
| 93 | |||
| 94 | if err := ReplaceMyAnimeListWithAniList(config); err != nil { | ||
| 95 | t.Fatalf("replace MAL with AniList: %v", err) | ||
| 96 | } | ||
| 97 | |||
| 98 | _, myAnimeList := fetchBothLists(t, config, anilistToken) | ||
| 99 | assertEntryState(t, myAnimeList, sourceEntry) | ||
| 100 | assertEntryMissing(t, myAnimeList, targetOnlyEntry.Media.ID) | ||
| 101 | }) | ||
| 102 | |||
| 103 | t.Run("replace AniList with MyAnimeList", func(t *testing.T) { | ||
| 104 | resetLiveTrackerState(t, config, anilistToken) | ||
| 105 | |||
| 106 | sourceEntry := liveEntry(testAnime[1], "PAUSED", 2, 7, FuzzyDate{Year: 2026, Month: 2, Day: 5}, FuzzyDate{}) | ||
| 107 | targetOnlyEntry := liveEntry(testAnime[4], "CURRENT", 6, 4, FuzzyDate{}, FuzzyDate{}) | ||
| 108 | |||
| 109 | if err := saveMyAnimeListTrackedEntry(config, sourceEntry); err != nil { | ||
| 110 | t.Fatalf("seed MyAnimeList entry: %v", err) | ||
| 111 | } | ||
| 112 | if err := saveAniListTrackedEntry(anilistToken, targetOnlyEntry); err != nil { | ||
| 113 | t.Fatalf("seed AniList entry: %v", err) | ||
| 114 | } | ||
| 115 | |||
| 116 | if err := ReplaceAniListWithMyAnimeList(config); err != nil { | ||
| 117 | t.Fatalf("replace AniList with MAL: %v", err) | ||
| 118 | } | ||
| 119 | |||
| 120 | aniList, _ := fetchBothLists(t, config, anilistToken) | ||
| 121 | assertEntryState(t, aniList, sourceEntry) | ||
| 122 | assertEntryMissing(t, aniList, targetOnlyEntry.Media.ID) | ||
| 123 | }) | ||
| 124 | |||
| 125 | t.Run("merge remote lists keeps union and newest conflict", func(t *testing.T) { | ||
| 126 | resetLiveTrackerState(t, config, anilistToken) | ||
| 127 | |||
| 128 | aniOnly := liveEntry(testAnime[2], "CURRENT", 2, 6, FuzzyDate{}, FuzzyDate{}) | ||
| 129 | malOnly := liveEntry(testAnime[3], "PLANNING", 0, 0, FuzzyDate{}, FuzzyDate{}) | ||
| 130 | conflictOld := liveEntry(testAnime[4], "CURRENT", 1, 5, FuzzyDate{Year: 2026, Month: 1, Day: 10}, FuzzyDate{}) | ||
| 131 | conflictNew := liveEntry(testAnime[4], "PAUSED", 4, 9, FuzzyDate{Year: 2026, Month: 4, Day: 11}, FuzzyDate{}) | ||
| 132 | |||
| 133 | if err := saveAniListTrackedEntry(anilistToken, aniOnly); err != nil { | ||
| 134 | t.Fatalf("seed AniList-only entry: %v", err) | ||
| 135 | } | ||
| 136 | if err := saveAniListTrackedEntry(anilistToken, conflictOld); err != nil { | ||
| 137 | t.Fatalf("seed older AniList conflict entry: %v", err) | ||
| 138 | } | ||
| 139 | if err := saveMyAnimeListTrackedEntry(config, malOnly); err != nil { | ||
| 140 | t.Fatalf("seed MAL-only entry: %v", err) | ||
| 141 | } | ||
| 142 | |||
| 143 | waitForRemoteTimestampTick() | ||
| 144 | |||
| 145 | if err := saveMyAnimeListTrackedEntry(config, conflictNew); err != nil { | ||
| 146 | t.Fatalf("seed newer MAL conflict entry: %v", err) | ||
| 147 | } | ||
| 148 | |||
| 149 | if err := MergeRemoteLists(config); err != nil { | ||
| 150 | t.Fatalf("merge remote lists: %v", err) | ||
| 151 | } | ||
| 152 | |||
| 153 | aniList, myAnimeList := fetchBothLists(t, config, anilistToken) | ||
| 154 | for _, list := range []AnimeList{aniList, myAnimeList} { | ||
| 155 | assertEntryState(t, list, aniOnly) | ||
| 156 | assertEntryState(t, list, malOnly) | ||
| 157 | assertEntryState(t, list, conflictNew) | ||
| 158 | } | ||
| 159 | }) | ||
| 160 | |||
| 161 | t.Run("tracker mode transitions local anilist myanimelist both", func(t *testing.T) { | ||
| 162 | resetLiveTrackerState(t, config, anilistToken) | ||
| 163 | |||
| 164 | aniEntry := liveEntry(testAnime[0], "CURRENT", 3, 6, FuzzyDate{}, FuzzyDate{}) | ||
| 165 | malEntry := liveEntry(testAnime[1], "PAUSED", 1, 8, FuzzyDate{}, FuzzyDate{}) | ||
| 166 | if err := saveAniListTrackedEntry(anilistToken, aniEntry); err != nil { | ||
| 167 | t.Fatalf("seed AniList transition entry: %v", err) | ||
| 168 | } | ||
| 169 | if err := saveMyAnimeListTrackedEntry(config, malEntry); err != nil { | ||
| 170 | t.Fatalf("seed MAL transition entry: %v", err) | ||
| 171 | } | ||
| 172 | |||
| 173 | tempStorage := t.TempDir() | ||
| 174 | copyTrackerFileForTest(t, filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json"), filepath.Join(tempStorage, "anilist_token.json")) | ||
| 175 | copyTrackerFileForTest(t, filepath.Join(os.ExpandEnv(config.StoragePath), "myanimelist_token.json"), filepath.Join(tempStorage, "myanimelist_token.json")) | ||
| 176 | |||
| 177 | localHistoryPath := filepath.Join(tempStorage, "curd_history.txt") | ||
| 178 | LocalUpdateAnime(localHistoryPath, testAnime[2].AniListID, "local-provider-id", 7, 0, 24, testAnime[2].Title, "allanime") | ||
| 179 | |||
| 180 | tempConfig := *config | ||
| 181 | tempConfig.StoragePath = tempStorage | ||
| 182 | tempConfig.MyAnimeListImported = true | ||
| 183 | |||
| 184 | localUser := &User{} | ||
| 185 | tempConfig.TrackingRemote = TrackingRemoteNone | ||
| 186 | SetGlobalConfig(&tempConfig) | ||
| 187 | SetGlobalUser(localUser) | ||
| 188 | if err := RefreshUserAnimeList(&tempConfig, localUser); err != nil { | ||
| 189 | t.Fatalf("refresh local mode: %v", err) | ||
| 190 | } | ||
| 191 | assertEntryState(t, localUser.AnimeList, Entry{ | ||
| 192 | Media: Media{ID: testAnime[2].AniListID}, | ||
| 193 | Status: "CURRENT", | ||
| 194 | Progress: 6, | ||
| 195 | }) | ||
| 196 | |||
| 197 | aniUser := &User{} | ||
| 198 | tempConfig.TrackingRemote = TrackingRemoteAniList | ||
| 199 | SetGlobalUser(aniUser) | ||
| 200 | if err := EnsureConfiguredTrackersReady(&tempConfig, aniUser); err != nil { | ||
| 201 | t.Fatalf("ensure AniList mode ready: %v", err) | ||
| 202 | } | ||
| 203 | if err := RefreshUserAnimeList(&tempConfig, aniUser); err != nil { | ||
| 204 | t.Fatalf("refresh AniList mode: %v", err) | ||
| 205 | } | ||
| 206 | assertEntryState(t, aniUser.AnimeList, aniEntry) | ||
| 207 | assertEntryMissing(t, aniUser.AnimeList, testAnime[2].AniListID) | ||
| 208 | |||
| 209 | malUser := &User{} | ||
| 210 | tempConfig.TrackingRemote = TrackingRemoteMyAnimeList | ||
| 211 | SetGlobalUser(malUser) | ||
| 212 | if err := EnsureConfiguredTrackersReady(&tempConfig, malUser); err != nil { | ||
| 213 | t.Fatalf("ensure MAL mode ready: %v", err) | ||
| 214 | } | ||
| 215 | if err := RefreshUserAnimeList(&tempConfig, malUser); err != nil { | ||
| 216 | t.Fatalf("refresh MAL mode: %v", err) | ||
| 217 | } | ||
| 218 | assertEntryState(t, malUser.AnimeList, malEntry) | ||
| 219 | |||
| 220 | bothUser := &User{} | ||
| 221 | tempConfig.TrackingRemote = TrackingRemoteBoth | ||
| 222 | SetGlobalUser(bothUser) | ||
| 223 | if err := EnsureConfiguredTrackersReady(&tempConfig, bothUser); err != nil { | ||
| 224 | t.Fatalf("ensure both mode ready: %v", err) | ||
| 225 | } | ||
| 226 | if err := RefreshUserAnimeList(&tempConfig, bothUser); err != nil { | ||
| 227 | t.Fatalf("refresh both mode: %v", err) | ||
| 228 | } | ||
| 229 | assertEntryState(t, bothUser.AnimeList, aniEntry) | ||
| 230 | assertEntryState(t, bothUser.AnimeList, malEntry) | ||
| 231 | }) | ||
| 232 | } | ||
| 233 | |||
| 234 | func TestTrackerLiveRuntimeIntegration(t *testing.T) { | ||
| 235 | config, anilistToken, _, cleanup := loadLiveTrackerTestContext(t) | ||
| 236 | defer cleanup() | ||
| 237 | |||
| 238 | testAnime := resolveLiveTestAnime(t) | ||
| 239 | |||
| 240 | t.Run("runtime helpers update both trackers in dual mode", func(t *testing.T) { | ||
| 241 | resetLiveTrackerState(t, config, anilistToken) | ||
| 242 | |||
| 243 | bothConfig := *config | ||
| 244 | bothConfig.TrackingRemote = TrackingRemoteBoth | ||
| 245 | SetGlobalConfig(&bothConfig) | ||
| 246 | |||
| 247 | if err := AddAnimeToWatchingList(testAnime[0].AniListID, anilistToken); err != nil { | ||
| 248 | t.Fatalf("add anime to watching list: %v", err) | ||
| 249 | } | ||
| 250 | if err := UpdateAnimeProgress(anilistToken, testAnime[0].AniListID, 3); err != nil { | ||
| 251 | t.Fatalf("update anime progress: %v", err) | ||
| 252 | } | ||
| 253 | if err := UpdateAnimeStatus(anilistToken, testAnime[0].AniListID, "PAUSED"); err != nil { | ||
| 254 | t.Fatalf("update anime status: %v", err) | ||
| 255 | } | ||
| 256 | withInjectedStdin(t, "9\n", func() { | ||
| 257 | if err := RateAnime(anilistToken, testAnime[0].AniListID); err != nil { | ||
| 258 | t.Fatalf("rate anime: %v", err) | ||
| 259 | } | ||
| 260 | }) | ||
| 261 | |||
| 262 | aniList, myAnimeList := fetchBothLists(t, &bothConfig, anilistToken) | ||
| 263 | expected := liveEntry(testAnime[0], "PAUSED", 3, 9, FuzzyDate{}, FuzzyDate{}) | ||
| 264 | for _, list := range []AnimeList{aniList, myAnimeList} { | ||
| 265 | assertEntryState(t, list, expected) | ||
| 266 | } | ||
| 267 | }) | ||
| 268 | |||
| 269 | t.Run("runtime rewatch cycle updates both trackers", func(t *testing.T) { | ||
| 270 | resetLiveTrackerState(t, config, anilistToken) | ||
| 271 | |||
| 272 | bothConfig := *config | ||
| 273 | bothConfig.TrackingRemote = TrackingRemoteBoth | ||
| 274 | SetGlobalConfig(&bothConfig) | ||
| 275 | |||
| 276 | completed := liveEntry(testAnime[1], "COMPLETED", 12, 8, FuzzyDate{Year: 2025, Month: 1, Day: 1}, FuzzyDate{Year: 2025, Month: 2, Day: 2}) | ||
| 277 | if err := saveAniListTrackedEntry(anilistToken, completed); err != nil { | ||
| 278 | t.Fatalf("seed AniList completed entry: %v", err) | ||
| 279 | } | ||
| 280 | if err := saveMyAnimeListTrackedEntry(&bothConfig, completed); err != nil { | ||
| 281 | t.Fatalf("seed MAL completed entry: %v", err) | ||
| 282 | } | ||
| 283 | seededAniList, _ := fetchBothLists(t, &bothConfig, anilistToken) | ||
| 284 | existingEntry := findEntryByMediaID(seededAniList, testAnime[1].AniListID) | ||
| 285 | if existingEntry == nil { | ||
| 286 | t.Fatalf("expected seeded completed entry to exist") | ||
| 287 | } | ||
| 288 | finalProgress := existingEntry.Progress | ||
| 289 | |||
| 290 | anime := Anime{ | ||
| 291 | AnilistId: testAnime[1].AniListID, | ||
| 292 | MalId: testAnime[1].MalID, | ||
| 293 | Repeat: 0, | ||
| 294 | StartedAt: completed.StartedAt, | ||
| 295 | CompletedAt: completed.CompletedAt, | ||
| 296 | Ep: Episode{ | ||
| 297 | Number: finalProgress, | ||
| 298 | }, | ||
| 299 | } | ||
| 300 | if err := StartAnimeRewatch(anilistToken, anime); err != nil { | ||
| 301 | t.Fatalf("start rewatch: %v", err) | ||
| 302 | } | ||
| 303 | |||
| 304 | aniList, myAnimeList := fetchBothLists(t, &bothConfig, anilistToken) | ||
| 305 | rewatching := liveEntry(testAnime[1], "REPEATING", 0, 8, FuzzyDate{}, FuzzyDate{}) | ||
| 306 | for _, list := range []AnimeList{aniList, myAnimeList} { | ||
| 307 | assertEntryState(t, list, rewatching) | ||
| 308 | } | ||
| 309 | |||
| 310 | if err := CompleteAnimeRewatch(anilistToken, anime); err != nil { | ||
| 311 | t.Fatalf("complete rewatch: %v", err) | ||
| 312 | } | ||
| 313 | |||
| 314 | aniList, myAnimeList = fetchBothLists(t, &bothConfig, anilistToken) | ||
| 315 | rewatchDone := liveEntry(testAnime[1], "COMPLETED", finalProgress, 8, FuzzyDate{}, FuzzyDate{}) | ||
| 316 | rewatchDone.Repeat = 1 | ||
| 317 | assertEntryState(t, aniList, rewatchDone) | ||
| 318 | assertEntryState(t, myAnimeList, liveEntry(testAnime[1], "COMPLETED", finalProgress, 8, FuzzyDate{}, FuzzyDate{})) | ||
| 319 | |||
| 320 | combinedUser := &User{} | ||
| 321 | SetGlobalConfig(&bothConfig) | ||
| 322 | SetGlobalUser(combinedUser) | ||
| 323 | if err := RefreshUserAnimeList(&bothConfig, combinedUser); err != nil { | ||
| 324 | t.Fatalf("refresh combined user after rewatch completion: %v", err) | ||
| 325 | } | ||
| 326 | assertEntryState(t, combinedUser.AnimeList, rewatchDone) | ||
| 327 | }) | ||
| 328 | |||
| 329 | t.Run("runtime AniList-only updates sync later in dual mode", func(t *testing.T) { | ||
| 330 | resetLiveTrackerState(t, config, anilistToken) | ||
| 331 | |||
| 332 | aniConfig := *config | ||
| 333 | aniConfig.TrackingRemote = TrackingRemoteAniList | ||
| 334 | SetGlobalConfig(&aniConfig) | ||
| 335 | |||
| 336 | if err := AddAnimeToWatchingList(testAnime[2].AniListID, anilistToken); err != nil { | ||
| 337 | t.Fatalf("add AniList-only anime: %v", err) | ||
| 338 | } | ||
| 339 | if err := UpdateAnimeProgress(anilistToken, testAnime[2].AniListID, 4); err != nil { | ||
| 340 | t.Fatalf("update AniList-only progress: %v", err) | ||
| 341 | } | ||
| 342 | |||
| 343 | _, myAnimeList := fetchBothLists(t, &aniConfig, anilistToken) | ||
| 344 | assertEntryMissing(t, myAnimeList, testAnime[2].AniListID) | ||
| 345 | |||
| 346 | refreshBothTrackers(t, &aniConfig) | ||
| 347 | |||
| 348 | _, myAnimeList = fetchBothLists(t, &aniConfig, anilistToken) | ||
| 349 | assertEntryState(t, myAnimeList, liveEntry(testAnime[2], "CURRENT", 4, 0, FuzzyDate{}, FuzzyDate{})) | ||
| 350 | }) | ||
| 351 | |||
| 352 | t.Run("runtime MyAnimeList-only updates sync later in dual mode", func(t *testing.T) { | ||
| 353 | resetLiveTrackerState(t, config, anilistToken) | ||
| 354 | |||
| 355 | malConfig := *config | ||
| 356 | malConfig.TrackingRemote = TrackingRemoteMyAnimeList | ||
| 357 | SetGlobalConfig(&malConfig) | ||
| 358 | |||
| 359 | if err := AddAnimeToWatchingList(testAnime[3].AniListID, anilistToken); err != nil { | ||
| 360 | t.Fatalf("add MAL-only anime: %v", err) | ||
| 361 | } | ||
| 362 | if err := UpdateAnimeStatus(anilistToken, testAnime[3].AniListID, "PAUSED"); err != nil { | ||
| 363 | t.Fatalf("pause MAL-only anime: %v", err) | ||
| 364 | } | ||
| 365 | |||
| 366 | aniList, _ := fetchBothLists(t, &malConfig, anilistToken) | ||
| 367 | assertEntryMissing(t, aniList, testAnime[3].AniListID) | ||
| 368 | |||
| 369 | refreshBothTrackers(t, &malConfig) | ||
| 370 | |||
| 371 | aniList, _ = fetchBothLists(t, &malConfig, anilistToken) | ||
| 372 | assertEntryState(t, aniList, liveEntry(testAnime[3], "PAUSED", 0, 0, FuzzyDate{}, FuzzyDate{})) | ||
| 373 | }) | ||
| 374 | |||
| 375 | t.Run("next episode runtime path updates local history and tracker progress", func(t *testing.T) { | ||
| 376 | resetLiveTrackerState(t, config, anilistToken) | ||
| 377 | |||
| 378 | bothConfig := *config | ||
| 379 | bothConfig.TrackingRemote = TrackingRemoteBoth | ||
| 380 | SetGlobalConfig(&bothConfig) | ||
| 381 | |||
| 382 | if err := AddAnimeToWatchingList(testAnime[4].AniListID, anilistToken); err != nil { | ||
| 383 | t.Fatalf("seed next-episode anime: %v", err) | ||
| 384 | } | ||
| 385 | |||
| 386 | tempStorage := t.TempDir() | ||
| 387 | localHistoryPath := filepath.Join(tempStorage, "curd_history.txt") | ||
| 388 | anime := &Anime{ | ||
| 389 | Title: AnimeTitle{ | ||
| 390 | English: testAnime[4].Title, | ||
| 391 | Romaji: testAnime[4].Title, | ||
| 392 | }, | ||
| 393 | AnilistId: testAnime[4].AniListID, | ||
| 394 | MalId: testAnime[4].MalID, | ||
| 395 | TotalEpisodes: 12, | ||
| 396 | ProviderId: "runtime-provider-id", | ||
| 397 | Ep: Episode{ | ||
| 398 | Number: 1, | ||
| 399 | }, | ||
| 400 | } | ||
| 401 | |||
| 402 | StartNextEpisode(anime, &bothConfig, localHistoryPath, anilistToken) | ||
| 403 | waitForAsyncTrackerUpdate() | ||
| 404 | |||
| 405 | if anime.Ep.Number != 2 { | ||
| 406 | t.Fatalf("expected next episode number 2, got %d", anime.Ep.Number) | ||
| 407 | } | ||
| 408 | |||
| 409 | localList := BuildLocalAnimeList(tempStorage) | ||
| 410 | assertEntryState(t, localList, Entry{ | ||
| 411 | Media: Media{ID: testAnime[4].AniListID}, | ||
| 412 | Status: "CURRENT", | ||
| 413 | Progress: 1, | ||
| 414 | }) | ||
| 415 | |||
| 416 | aniList, myAnimeList := fetchBothLists(t, &bothConfig, anilistToken) | ||
| 417 | expected := liveEntry(testAnime[4], "CURRENT", 1, 0, FuzzyDate{}, FuzzyDate{}) | ||
| 418 | for _, list := range []AnimeList{aniList, myAnimeList} { | ||
| 419 | assertEntryState(t, list, expected) | ||
| 420 | } | ||
| 421 | }) | ||
| 422 | } | ||
| 423 | |||
| 424 | func loadLiveTrackerTestContext(t *testing.T) (*CurdConfig, string, []liveTestAnime, func()) { | ||
| 425 | t.Helper() | ||
| 426 | |||
| 427 | if os.Getenv("CURD_RUN_TRACKER_LIVE_INTEGRATION") != "1" { | ||
| 428 | t.Skip("set CURD_RUN_TRACKER_LIVE_INTEGRATION=1 to run live tracker integration tests") | ||
| 429 | } | ||
| 430 | |||
| 431 | configPath := os.Getenv("CURD_CONFIG_PATH") | ||
| 432 | if configPath == "" { | ||
| 433 | homeDir, err := os.UserHomeDir() | ||
| 434 | if err != nil { | ||
| 435 | t.Fatalf("resolve home dir: %v", err) | ||
| 436 | } | ||
| 437 | configPath = filepath.Join(homeDir, ".config", "curd", "curd.conf") | ||
| 438 | } | ||
| 439 | |||
| 440 | config, err := LoadConfig(configPath) | ||
| 441 | if err != nil { | ||
| 442 | t.Fatalf("load config: %v", err) | ||
| 443 | } | ||
| 444 | config.TrackingConfigured = true | ||
| 445 | config.TrackingLocal = true | ||
| 446 | |||
| 447 | previousGlobalConfig := GetGlobalConfig() | ||
| 448 | previousGlobalUser := GetGlobalUser() | ||
| 449 | SetGlobalConfig(&config) | ||
| 450 | |||
| 451 | user := &User{} | ||
| 452 | SetGlobalUser(user) | ||
| 453 | if err := EnsureConfiguredTrackersReady(&config, user); err != nil { | ||
| 454 | t.Fatalf("ensure trackers ready: %v", err) | ||
| 455 | } | ||
| 456 | |||
| 457 | anilistToken, err := GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")) | ||
| 458 | if err != nil { | ||
| 459 | t.Fatalf("load AniList token: %v", err) | ||
| 460 | } | ||
| 461 | |||
| 462 | originalAniList, err := fetchAniListAnimeListFromToken(anilistToken) | ||
| 463 | if err != nil { | ||
| 464 | t.Fatalf("fetch original AniList state: %v", err) | ||
| 465 | } | ||
| 466 | originalMyAnimeList, err := FetchLatestMyAnimeList(&config, &User{}) | ||
| 467 | if err != nil { | ||
| 468 | t.Fatalf("fetch original MyAnimeList state: %v", err) | ||
| 469 | } | ||
| 470 | |||
| 471 | cleanup := func() { | ||
| 472 | restoreLiveTrackerState(t, &config, anilistToken, originalAniList, originalMyAnimeList) | ||
| 473 | SetGlobalConfig(previousGlobalConfig) | ||
| 474 | SetGlobalUser(previousGlobalUser) | ||
| 475 | } | ||
| 476 | |||
| 477 | return &config, anilistToken, resolveLiveTestAnime(t), cleanup | ||
| 478 | } | ||
| 479 | |||
| 480 | func resolveLiveTestAnime(t *testing.T) []liveTestAnime { | ||
| 481 | t.Helper() | ||
| 482 | |||
| 483 | resolveLiveTestAnimeOnce.Do(func() { | ||
| 484 | titles := []string{ | ||
| 485 | "Cowboy Bebop", | ||
| 486 | "Odd Taxi", | ||
| 487 | "Barakamon", | ||
| 488 | "Death Parade", | ||
| 489 | "A Place Further than the Universe", | ||
| 490 | } | ||
| 491 | |||
| 492 | results := make([]liveTestAnime, 0, len(titles)) | ||
| 493 | for _, title := range titles { | ||
| 494 | options, err := SearchAnimeAnilist(title, "") | ||
| 495 | if err != nil { | ||
| 496 | resolvedLiveTestAnimeErr = err | ||
| 497 | return | ||
| 498 | } | ||
| 499 | if len(options) == 0 { | ||
| 500 | resolvedLiveTestAnimeErr = fmt.Errorf("no AniList result for %q", title) | ||
| 501 | return | ||
| 502 | } | ||
| 503 | anilistID, err := strconv.Atoi(options[0].Key) | ||
| 504 | if err != nil { | ||
| 505 | resolvedLiveTestAnimeErr = err | ||
| 506 | return | ||
| 507 | } | ||
| 508 | malID, err := GetAnimeMalID(anilistID) | ||
| 509 | if err != nil { | ||
| 510 | resolvedLiveTestAnimeErr = err | ||
| 511 | return | ||
| 512 | } | ||
| 513 | if malID == 0 { | ||
| 514 | resolvedLiveTestAnimeErr = fmt.Errorf("AniList title %q has no MAL mapping", title) | ||
| 515 | return | ||
| 516 | } | ||
| 517 | results = append(results, liveTestAnime{ | ||
| 518 | Title: title, | ||
| 519 | AniListID: anilistID, | ||
| 520 | MalID: malID, | ||
| 521 | }) | ||
| 522 | } | ||
| 523 | resolvedLiveTestAnime = results | ||
| 524 | }) | ||
| 525 | |||
| 526 | if resolvedLiveTestAnimeErr != nil { | ||
| 527 | t.Fatalf("resolve live test anime: %v", resolvedLiveTestAnimeErr) | ||
| 528 | } | ||
| 529 | return resolvedLiveTestAnime | ||
| 530 | } | ||
| 531 | |||
| 532 | func restoreLiveTrackerState(t *testing.T, config *CurdConfig, anilistToken string, aniListSnapshot, myAnimeListSnapshot AnimeList) { | ||
| 533 | t.Helper() | ||
| 534 | |||
| 535 | if err := wipeAniListRemote(config); err != nil { | ||
| 536 | t.Fatalf("wipe AniList during restore: %v", err) | ||
| 537 | } | ||
| 538 | if err := wipeMyAnimeListRemote(config); err != nil { | ||
| 539 | t.Fatalf("wipe MyAnimeList during restore: %v", err) | ||
| 540 | } | ||
| 541 | if err := upsertAnimeListToAniList(anilistToken, aniListSnapshot); err != nil { | ||
| 542 | t.Fatalf("restore AniList snapshot: %v", err) | ||
| 543 | } | ||
| 544 | if err := upsertAnimeListToMyAnimeList(config, myAnimeListSnapshot); err != nil { | ||
| 545 | t.Fatalf("restore MyAnimeList snapshot: %v", err) | ||
| 546 | } | ||
| 547 | } | ||
| 548 | |||
| 549 | func resetLiveTrackerState(t *testing.T, config *CurdConfig, _ string) { | ||
| 550 | t.Helper() | ||
| 551 | |||
| 552 | if err := wipeAniListRemote(config); err != nil { | ||
| 553 | t.Fatalf("wipe AniList for test: %v", err) | ||
| 554 | } | ||
| 555 | if err := wipeMyAnimeListRemote(config); err != nil { | ||
| 556 | t.Fatalf("wipe MyAnimeList for test: %v", err) | ||
| 557 | } | ||
| 558 | } | ||
| 559 | |||
| 560 | func liveEntry(anime liveTestAnime, status string, progress int, score float64, startedAt, completedAt FuzzyDate) Entry { | ||
| 561 | return Entry{ | ||
| 562 | Media: Media{ | ||
| 563 | ID: anime.AniListID, | ||
| 564 | MalID: anime.MalID, | ||
| 565 | Title: AnimeTitle{ | ||
| 566 | English: anime.Title, | ||
| 567 | Romaji: anime.Title, | ||
| 568 | }, | ||
| 569 | }, | ||
| 570 | Progress: progress, | ||
| 571 | Score: score, | ||
| 572 | Status: status, | ||
| 573 | StartedAt: startedAt, | ||
| 574 | CompletedAt: completedAt, | ||
| 575 | } | ||
| 576 | } | ||
| 577 | |||
| 578 | func refreshBothTrackers(t *testing.T, config *CurdConfig) { | ||
| 579 | t.Helper() | ||
| 580 | |||
| 581 | testConfig := *config | ||
| 582 | testConfig.TrackingRemote = TrackingRemoteBoth | ||
| 583 | testUser := &User{} | ||
| 584 | SetGlobalConfig(&testConfig) | ||
| 585 | SetGlobalUser(testUser) | ||
| 586 | if err := RefreshUserAnimeList(&testConfig, testUser); err != nil { | ||
| 587 | t.Fatalf("refresh both trackers: %v", err) | ||
| 588 | } | ||
| 589 | } | ||
| 590 | |||
| 591 | func fetchBothLists(t *testing.T, config *CurdConfig, anilistToken string) (AnimeList, AnimeList) { | ||
| 592 | t.Helper() | ||
| 593 | |||
| 594 | aniList, err := fetchAniListAnimeListFromToken(anilistToken) | ||
| 595 | if err != nil { | ||
| 596 | t.Fatalf("fetch AniList: %v", err) | ||
| 597 | } | ||
| 598 | myAnimeList, err := FetchLatestMyAnimeList(config, &User{}) | ||
| 599 | if err != nil { | ||
| 600 | t.Fatalf("fetch MyAnimeList: %v", err) | ||
| 601 | } | ||
| 602 | return aniList, myAnimeList | ||
| 603 | } | ||
| 604 | |||
| 605 | func findEntryByMediaID(list AnimeList, mediaID int) *Entry { | ||
| 606 | for _, entry := range getEntriesByCategory(list, "ALL") { | ||
| 607 | if entry.Media.ID == mediaID { | ||
| 608 | copied := entry | ||
| 609 | return &copied | ||
| 610 | } | ||
| 611 | } | ||
| 612 | return nil | ||
| 613 | } | ||
| 614 | |||
| 615 | func assertEntryState(t *testing.T, list AnimeList, expected Entry) { | ||
| 616 | t.Helper() | ||
| 617 | |||
| 618 | entry := findEntryByMediaID(list, expected.Media.ID) | ||
| 619 | if entry == nil { | ||
| 620 | t.Fatalf("expected media ID %d to exist", expected.Media.ID) | ||
| 621 | } | ||
| 622 | if entry.Status != expected.Status { | ||
| 623 | t.Fatalf("media ID %d status = %s, want %s", expected.Media.ID, entry.Status, expected.Status) | ||
| 624 | } | ||
| 625 | if entry.Progress != expected.Progress { | ||
| 626 | t.Fatalf("media ID %d progress = %d, want %d", expected.Media.ID, entry.Progress, expected.Progress) | ||
| 627 | } | ||
| 628 | if entry.Score != expected.Score { | ||
| 629 | t.Fatalf("media ID %d score = %.1f, want %.1f", expected.Media.ID, entry.Score, expected.Score) | ||
| 630 | } | ||
| 631 | if expected.Repeat != 0 && entry.Repeat != expected.Repeat { | ||
| 632 | t.Fatalf("media ID %d repeat = %d, want %d", expected.Media.ID, entry.Repeat, expected.Repeat) | ||
| 633 | } | ||
| 634 | if expected.StartedAt != (FuzzyDate{}) && entry.StartedAt != expected.StartedAt { | ||
| 635 | t.Fatalf("media ID %d startedAt = %+v, want %+v", expected.Media.ID, entry.StartedAt, expected.StartedAt) | ||
| 636 | } | ||
| 637 | if expected.CompletedAt != (FuzzyDate{}) && entry.CompletedAt != expected.CompletedAt { | ||
| 638 | t.Fatalf("media ID %d completedAt = %+v, want %+v", expected.Media.ID, entry.CompletedAt, expected.CompletedAt) | ||
| 639 | } | ||
| 640 | } | ||
| 641 | |||
| 642 | func assertEntryMissing(t *testing.T, list AnimeList, mediaID int) { | ||
| 643 | t.Helper() | ||
| 644 | |||
| 645 | if entry := findEntryByMediaID(list, mediaID); entry != nil { | ||
| 646 | t.Fatalf("expected media ID %d to be missing, found %+v", mediaID, *entry) | ||
| 647 | } | ||
| 648 | } | ||
| 649 | |||
| 650 | func copyTrackerFileForTest(t *testing.T, sourcePath, destinationPath string) { | ||
| 651 | t.Helper() | ||
| 652 | |||
| 653 | data, err := os.ReadFile(sourcePath) | ||
| 654 | if err != nil { | ||
| 655 | t.Fatalf("read %s: %v", sourcePath, err) | ||
| 656 | } | ||
| 657 | if err := os.WriteFile(destinationPath, data, 0o600); err != nil { | ||
| 658 | t.Fatalf("write %s: %v", destinationPath, err) | ||
| 659 | } | ||
| 660 | } | ||
| 661 | |||
| 662 | func waitForRemoteTimestampTick() { | ||
| 663 | time.Sleep(2 * time.Second) | ||
| 664 | } | ||
| 665 | |||
| 666 | func waitForAsyncTrackerUpdate() { | ||
| 667 | time.Sleep(3 * time.Second) | ||
| 668 | } | ||
| 669 | |||
| 670 | func withInjectedStdin(t *testing.T, input string, fn func()) { | ||
| 671 | t.Helper() | ||
| 672 | |||
| 673 | tempFile, err := os.CreateTemp(t.TempDir(), "stdin-*") | ||
| 674 | if err != nil { | ||
| 675 | t.Fatalf("create temp stdin file: %v", err) | ||
| 676 | } | ||
| 677 | if _, err := tempFile.WriteString(input); err != nil { | ||
| 678 | t.Fatalf("write temp stdin file: %v", err) | ||
| 679 | } | ||
| 680 | if _, err := tempFile.Seek(0, 0); err != nil { | ||
| 681 | t.Fatalf("seek temp stdin file: %v", err) | ||
| 682 | } | ||
| 683 | |||
| 684 | originalStdin := os.Stdin | ||
| 685 | os.Stdin = tempFile | ||
| 686 | defer func() { | ||
| 687 | os.Stdin = originalStdin | ||
| 688 | tempFile.Close() | ||
| 689 | }() | ||
| 690 | |||
| 691 | fn() | ||
| 692 | } | ||
internal/tracking_test.go added +251
| @@ -0,0 +1,251 @@ | |||
| 1 | package internal | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "testing" | ||
| 5 | "time" | ||
| 6 | ) | ||
| 7 | |||
| 8 | func TestNormalizeRemoteTrackerAliases(t *testing.T) { | ||
| 9 | t.Parallel() | ||
| 10 | |||
| 11 | cases := map[string]string{ | ||
| 12 | "": "none", | ||
| 13 | "none": "none", | ||
| 14 | "off": "none", | ||
| 15 | "local": "none", | ||
| 16 | "anilist": "anilist", | ||
| 17 | "ani-list": "anilist", | ||
| 18 | "mal": "myanimelist", | ||
| 19 | "myanimelist": "myanimelist", | ||
| 20 | "my-anime-list": "myanimelist", | ||
| 21 | "my_anime_list": "myanimelist", | ||
| 22 | "both": "anilist+myanimelist", | ||
| 23 | "anilist,myanimelist": "anilist+myanimelist", | ||
| 24 | "not-a-provider": "", | ||
| 25 | } | ||
| 26 | |||
| 27 | for input, want := range cases { | ||
| 28 | if got := normalizeRemoteTracker(input); got != want { | ||
| 29 | t.Fatalf("normalizeRemoteTracker(%q) = %q, want %q", input, got, want) | ||
| 30 | } | ||
| 31 | } | ||
| 32 | } | ||
| 33 | |||
| 34 | func TestNormalizeTrackingConfigAlwaysKeepsLocalHistoryEnabled(t *testing.T) { | ||
| 35 | t.Parallel() | ||
| 36 | |||
| 37 | config := &CurdConfig{ | ||
| 38 | TrackingLocal: false, | ||
| 39 | TrackingRemote: "none", | ||
| 40 | TrackingConfigured: true, | ||
| 41 | } | ||
| 42 | |||
| 43 | normalizeTrackingConfig(config) | ||
| 44 | |||
| 45 | if !config.TrackingLocal { | ||
| 46 | t.Fatalf("expected local tracking to be re-enabled when both trackers are disabled") | ||
| 47 | } | ||
| 48 | if config.TrackingRemote != TrackingRemoteNone { | ||
| 49 | t.Fatalf("expected remote tracking to stay disabled, got %q", config.TrackingRemote) | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | func TestNormalizeTrackingConfigMarksInvalidRemoteForPrompt(t *testing.T) { | ||
| 54 | t.Parallel() | ||
| 55 | |||
| 56 | config := &CurdConfig{ | ||
| 57 | TrackingLocal: true, | ||
| 58 | TrackingRemote: "totally-invalid", | ||
| 59 | TrackingConfigured: true, | ||
| 60 | } | ||
| 61 | |||
| 62 | normalizeTrackingConfig(config) | ||
| 63 | |||
| 64 | if config.TrackingConfigured { | ||
| 65 | t.Fatalf("expected invalid tracking config to require setup prompt") | ||
| 66 | } | ||
| 67 | if config.TrackingRemote != TrackingRemoteAniList { | ||
| 68 | t.Fatalf("expected invalid remote tracker to normalize to the legacy AniList default, got %q", config.TrackingRemote) | ||
| 69 | } | ||
| 70 | if !config.TrackingLocal { | ||
| 71 | t.Fatalf("expected local history to stay enabled after normalization") | ||
| 72 | } | ||
| 73 | } | ||
| 74 | |||
| 75 | func TestGetOrderedCategoriesHidesRemoteOnlyEntriesForLocalTracking(t *testing.T) { | ||
| 76 | t.Parallel() | ||
| 77 | |||
| 78 | config := &CurdConfig{ | ||
| 79 | MenuOrder: "CURRENT,UPDATE,PLANNING,ALL,PROVIDER", | ||
| 80 | TrackingLocal: true, | ||
| 81 | TrackingRemote: TrackingRemoteNone, | ||
| 82 | } | ||
| 83 | |||
| 84 | categories := getOrderedCategories(config) | ||
| 85 | if len(categories) != 4 { | ||
| 86 | t.Fatalf("expected 4 visible categories, got %d", len(categories)) | ||
| 87 | } | ||
| 88 | if categories[0].Key != "CURRENT" || categories[1].Key != "ALL" || categories[2].Key != "PROVIDER" || categories[3].Key != "TRACKER" { | ||
| 89 | t.Fatalf("unexpected categories for local-only tracking: %+v", categories) | ||
| 90 | } | ||
| 91 | } | ||
| 92 | |||
| 93 | func TestLocalAnimeListFromHistoryUsesNextEpisodeAsProgressBase(t *testing.T) { | ||
| 94 | t.Parallel() | ||
| 95 | |||
| 96 | list := localAnimeListFromHistory([]Anime{ | ||
| 97 | { | ||
| 98 | AnilistId: 123, | ||
| 99 | MalId: 456, | ||
| 100 | Title: AnimeTitle{ | ||
| 101 | English: "Frieren", | ||
| 102 | Romaji: "Sousou no Frieren", | ||
| 103 | }, | ||
| 104 | Ep: Episode{ | ||
| 105 | Number: 7, | ||
| 106 | }, | ||
| 107 | TotalEpisodes: 28, | ||
| 108 | }, | ||
| 109 | }) | ||
| 110 | |||
| 111 | if len(list.Watching) != 1 { | ||
| 112 | t.Fatalf("expected one local entry, got %d", len(list.Watching)) | ||
| 113 | } | ||
| 114 | |||
| 115 | entry := list.Watching[0] | ||
| 116 | if entry.Media.ID != 123 || entry.Media.MalID != 456 { | ||
| 117 | t.Fatalf("unexpected IDs in local entry: %+v", entry.Media) | ||
| 118 | } | ||
| 119 | if entry.Progress != 6 { | ||
| 120 | t.Fatalf("expected progress 6 from next-episode value 7, got %d", entry.Progress) | ||
| 121 | } | ||
| 122 | if entry.Status != "CURRENT" { | ||
| 123 | t.Fatalf("expected CURRENT status, got %q", entry.Status) | ||
| 124 | } | ||
| 125 | } | ||
| 126 | |||
| 127 | func TestMyAnimeListStatusConversion(t *testing.T) { | ||
| 128 | t.Parallel() | ||
| 129 | |||
| 130 | if got := myAnimeListStatusToAniListStatus("watching", true); got != "REPEATING" { | ||
| 131 | t.Fatalf("expected rewatching MAL entry to map to REPEATING, got %q", got) | ||
| 132 | } | ||
| 133 | if got := myAnimeListStatusToAniListStatus("on_hold", false); got != "PAUSED" { | ||
| 134 | t.Fatalf("expected on_hold to map to PAUSED, got %q", got) | ||
| 135 | } | ||
| 136 | if got := aniListStatusToMyAnimeListStatus("REPEATING"); got != "watching" { | ||
| 137 | t.Fatalf("expected REPEATING to map to watching, got %q", got) | ||
| 138 | } | ||
| 139 | if got := aniListStatusToMyAnimeListStatus("PLANNING"); got != "plan_to_watch" { | ||
| 140 | t.Fatalf("expected PLANNING to map to plan_to_watch, got %q", got) | ||
| 141 | } | ||
| 142 | } | ||
| 143 | |||
| 144 | func TestDualSyncModeEnablesBothRemoteTrackers(t *testing.T) { | ||
| 145 | t.Parallel() | ||
| 146 | |||
| 147 | config := &CurdConfig{TrackingRemote: TrackingRemoteBoth} | ||
| 148 | if !UsesAniListTracking(config) { | ||
| 149 | t.Fatalf("expected dual-sync mode to include AniList") | ||
| 150 | } | ||
| 151 | if !UsesMyAnimeListTracking(config) { | ||
| 152 | t.Fatalf("expected dual-sync mode to include MyAnimeList") | ||
| 153 | } | ||
| 154 | if !UsesDualRemoteTracking(config) { | ||
| 155 | t.Fatalf("expected dual-sync mode to report itself as dual remote") | ||
| 156 | } | ||
| 157 | } | ||
| 158 | |||
| 159 | func TestExtractOAuthCodeFromInput(t *testing.T) { | ||
| 160 | t.Parallel() | ||
| 161 | |||
| 162 | code, err := extractOAuthCodeFromInput("http://localhost:8123/oauth/callback?code=test-code&state=expected", "expected") | ||
| 163 | if err != nil { | ||
| 164 | t.Fatalf("expected callback URL to parse, got error: %v", err) | ||
| 165 | } | ||
| 166 | if code != "test-code" { | ||
| 167 | t.Fatalf("expected parsed code to be test-code, got %q", code) | ||
| 168 | } | ||
| 169 | |||
| 170 | code, err = extractOAuthCodeFromInput("raw-code", "expected") | ||
| 171 | if err != nil { | ||
| 172 | t.Fatalf("expected raw code to parse, got error: %v", err) | ||
| 173 | } | ||
| 174 | if code != "raw-code" { | ||
| 175 | t.Fatalf("expected raw code passthrough, got %q", code) | ||
| 176 | } | ||
| 177 | |||
| 178 | if _, err := extractOAuthCodeFromInput("http://localhost:8123/oauth/callback?code=test-code&state=wrong", "expected"); err == nil { | ||
| 179 | t.Fatalf("expected state mismatch to fail") | ||
| 180 | } | ||
| 181 | } | ||
| 182 | |||
| 183 | func TestMergeAnimeEntriesPrefersNewestRemoteUpdate(t *testing.T) { | ||
| 184 | t.Parallel() | ||
| 185 | |||
| 186 | older := Entry{ | ||
| 187 | Media: Media{ID: 1, MalID: 101}, | ||
| 188 | Status: "CURRENT", | ||
| 189 | Progress: 3, | ||
| 190 | UpdatedAt: time.Date(2026, 5, 17, 10, 0, 0, 0, time.UTC), | ||
| 191 | } | ||
| 192 | newer := Entry{ | ||
| 193 | Media: Media{ID: 1, MalID: 101}, | ||
| 194 | Status: "COMPLETED", | ||
| 195 | Progress: 12, | ||
| 196 | UpdatedAt: time.Date(2026, 5, 17, 12, 0, 0, 0, time.UTC), | ||
| 197 | } | ||
| 198 | |||
| 199 | merged := mergeAnimeEntries(older, newer) | ||
| 200 | if merged.Status != "COMPLETED" || merged.Progress != 12 { | ||
| 201 | t.Fatalf("expected latest entry to win, got %+v", merged) | ||
| 202 | } | ||
| 203 | } | ||
| 204 | |||
| 205 | func TestBuildDualRemoteSyncPlanUsesNewestEntryAndPropagatesMissingAnime(t *testing.T) { | ||
| 206 | t.Parallel() | ||
| 207 | |||
| 208 | aniList := AnimeList{ | ||
| 209 | Watching: []Entry{{ | ||
| 210 | Media: Media{ID: 1, MalID: 101}, | ||
| 211 | Status: "CURRENT", | ||
| 212 | Progress: 2, | ||
| 213 | UpdatedAt: time.Date(2026, 5, 17, 9, 0, 0, 0, time.UTC), | ||
| 214 | }}, | ||
| 215 | } | ||
| 216 | myAnimeList := AnimeList{ | ||
| 217 | Completed: []Entry{{ | ||
| 218 | Media: Media{ID: 1, MalID: 101}, | ||
| 219 | Status: "COMPLETED", | ||
| 220 | Progress: 12, | ||
| 221 | UpdatedAt: time.Date(2026, 5, 17, 11, 0, 0, 0, time.UTC), | ||
| 222 | }}, | ||
| 223 | Planning: []Entry{{ | ||
| 224 | Media: Media{ID: 2, MalID: 202}, | ||
| 225 | Status: "PLANNING", | ||
| 226 | UpdatedAt: time.Date(2026, 5, 17, 8, 0, 0, 0, time.UTC), | ||
| 227 | }}, | ||
| 228 | } | ||
| 229 | |||
| 230 | plan := buildDualRemoteSyncPlan(aniList, myAnimeList) | ||
| 231 | if len(plan.AniListUpdates) != 2 { | ||
| 232 | t.Fatalf("expected AniList to receive 2 updates, got %d", len(plan.AniListUpdates)) | ||
| 233 | } | ||
| 234 | if len(plan.MyAnimeListUpdates) != 0 { | ||
| 235 | t.Fatalf("expected MyAnimeList to already match the winning entries, got %d updates", len(plan.MyAnimeListUpdates)) | ||
| 236 | } | ||
| 237 | |||
| 238 | var mergedFirst *Entry | ||
| 239 | for _, entry := range getEntriesByCategory(plan.Merged, "ALL") { | ||
| 240 | if entry.Media.ID == 1 { | ||
| 241 | mergedFirst = &entry | ||
| 242 | break | ||
| 243 | } | ||
| 244 | } | ||
| 245 | if mergedFirst == nil { | ||
| 246 | t.Fatalf("expected merged list to contain media ID 1") | ||
| 247 | } | ||
| 248 | if mergedFirst.Status != "COMPLETED" || mergedFirst.Progress != 12 { | ||
| 249 | t.Fatalf("expected merged entry to keep latest MAL state, got %+v", *mergedFirst) | ||
| 250 | } | ||
| 251 | } | ||