Commit 91d9fbbcc6
Unsigned
Layout: unified · split
cmd/curd/main.go +179 −41
| @@ -231,18 +231,29 @@ func main() { | ||
| 231 | 231 | // Create a channel to signal when to exit the skip loop |
| 232 | 232 | var wg sync.WaitGroup |
| 233 | 233 | skipLoopDone := make(chan struct{}) |
| 234 | skipLoopClosed := make(chan bool, 1) // Channel to track if skipLoopDone has been closed | |
| 235 | skipLoopClosed <- false // Initialize to false (not closed yet) | |
| 234 | 236 | |
| 235 | 237 | // Get MalId and CoverImage (only if discord presence is enabled) |
| 236 | 238 | if userCurdConfig.DiscordPresence { |
| 237 | internal.LoginClient(discordClientId) | |
| 238 | ||
| 239 | anime.MalId, anime.CoverImage, err = internal.GetAnimeIDAndImage(anime.AnilistId) | |
| 239 | discordAvailable := true | |
| 240 | err := internal.LoginClient(discordClientId) | |
| 240 | 241 | if err != nil { |
| 241 | internal.Log("Error getting anime ID and image: " + err.Error()) | |
| 242 | internal.Log("Discord connection failed, disabling presence: " + err.Error()) | |
| 243 | discordAvailable = false | |
| 244 | userCurdConfig.DiscordPresence = false // Disable for this session | |
| 242 | 245 | } |
| 243 | err = internal.DiscordPresence(anime, false) | |
| 244 | if err != nil { | |
| 245 | internal.Log("Error setting Discord presence: " + err.Error()) | |
| 246 | ||
| 247 | if discordAvailable { | |
| 248 | anime.MalId, anime.CoverImage, err = internal.GetAnimeIDAndImage(anime.AnilistId) | |
| 249 | if err != nil { | |
| 250 | internal.Log("Error getting anime ID and image: " + err.Error()) | |
| 251 | } | |
| 252 | err = internal.DiscordPresence(anime, false) | |
| 253 | if err != nil { | |
| 254 | internal.Log("Discord presence error, disabling: " + err.Error()) | |
| 255 | userCurdConfig.DiscordPresence = false | |
| 256 | } | |
| 246 | 257 | } |
| 247 | 258 | } else if anime.MalId == 0 { |
| 248 | 259 | anime.MalId, err = internal.GetAnimeMalID(anime.AnilistId) |
| @@ -316,18 +327,27 @@ func main() { | ||
| 316 | 327 | internal.CurdOut(fmt.Sprint("Recap Episode, starting next episode: ", anime.Ep.Number+1)) |
| 317 | 328 | internal.Log("Recap episode detected") |
| 318 | 329 | } |
| 319 | anime.Ep.Number++ | |
| 320 | anime.Ep.Started = false | |
| 330 | ||
| 321 | 331 | anime.Ep.IsCompleted = true |
| 322 | internal.Log("Skipping filler episode, starting next.") | |
| 323 | internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime)) | |
| 332 | if !userCurdConfig.NextEpisodePrompt || userCurdConfig.RofiSelection { | |
| 333 | // fmt.Println("[DEBUG] Starting next episode from filler/recap skip") | |
| 334 | internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile) | |
| 335 | } | |
| 324 | 336 | // Send command to close MPV |
| 325 | 337 | _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"}) |
| 326 | 338 | if err != nil { |
| 327 | 339 | internal.Log("Error closing MPV: " + err.Error()) |
| 328 | 340 | } |
| 329 | // Exit the skip loop | |
| 330 | close(skipLoopDone) | |
| 341 | // Exit the skip loop - only close if not already closed | |
| 342 | select { | |
| 343 | case isClosed := <-skipLoopClosed: | |
| 344 | if !isClosed { | |
| 345 | close(skipLoopDone) | |
| 346 | skipLoopClosed <- true // Mark as closed | |
| 347 | } | |
| 348 | default: | |
| 349 | // Channel is busy, another goroutine is handling closure | |
| 350 | } | |
| 331 | 351 | } |
| 332 | 352 | } |
| 333 | 353 | }() |
| @@ -397,13 +417,25 @@ func main() { | ||
| 397 | 417 | // Thread to prompt for next episode in CLI Mode |
| 398 | 418 | go func() { |
| 399 | 419 | if !userCurdConfig.RofiSelection && userCurdConfig.NextEpisodePrompt { |
| 400 | internal.NextEpisodePrompt(&userCurdConfig) | |
| 401 | anime.Ep.Number++ | |
| 402 | anime.Ep.Started = false | |
| 403 | internal.Log("Completed episode, starting next.") | |
| 404 | anime.Ep.IsCompleted = true | |
| 405 | // Exit the skip loop | |
| 406 | close(skipLoopDone) | |
| 420 | for { | |
| 421 | select { | |
| 422 | case <-skipLoopDone: | |
| 423 | return | |
| 424 | default: | |
| 425 | internal.NextEpisodePrompt(&userCurdConfig) | |
| 426 | // Exit the skip loop - only close if not already closed | |
| 427 | select { | |
| 428 | case isClosed := <-skipLoopClosed: | |
| 429 | if !isClosed { | |
| 430 | close(skipLoopDone) | |
| 431 | skipLoopClosed <- true // Mark as closed | |
| 432 | } | |
| 433 | default: | |
| 434 | // Channel is busy, another goroutine is handling closure | |
| 435 | } | |
| 436 | return | |
| 437 | } | |
| 438 | } | |
| 407 | 439 | } |
| 408 | 440 | }() |
| 409 | 441 | |
| @@ -435,18 +467,38 @@ func main() { | ||
| 435 | 467 | internal.Log(fmt.Sprint(anime.Ep.Duration)) |
| 436 | 468 | internal.Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete)) |
| 437 | 469 | if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete { |
| 438 | anime.Ep.Number++ | |
| 439 | anime.Ep.Started = false | |
| 440 | internal.Log("Completed episode, starting next.") | |
| 441 | 470 | anime.Ep.IsCompleted = true |
| 442 | // Exit the skip loop | |
| 443 | close(skipLoopDone) | |
| 444 | } else if fmt.Sprintf("%v", err) == "invalid character '{' after top-level value" { // Episode is not completed | |
| 445 | internal.Log("Received invalid JSON response, continuing...") | |
| 471 | if !userCurdConfig.NextEpisodePrompt { | |
| 472 | internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile) | |
| 473 | } else { | |
| 474 | // When NextEpisodePrompt is enabled, show the prompt in both modes | |
| 475 | if userCurdConfig.RofiSelection { | |
| 476 | // For Rofi mode | |
| 477 | internal.CurdOut("Showing next episode prompt in Rofi mode (playback ended)") | |
| 478 | internal.ExitMPV(anime.Ep.Player.SocketPath) | |
| 479 | internal.NextEpisodePrompt(&userCurdConfig) | |
| 480 | return | |
| 481 | } else { | |
| 482 | // For CLI mode | |
| 483 | internal.NextEpisodePrompt(&userCurdConfig) | |
| 484 | return | |
| 485 | } | |
| 486 | } | |
| 446 | 487 | } else { |
| 447 | 488 | internal.Log("Episode is not completed, exiting") |
| 448 | 489 | internal.ExitCurd(nil) |
| 449 | 490 | } |
| 491 | // Exit the skip loop - only close if not already closed | |
| 492 | select { | |
| 493 | case isClosed := <-skipLoopClosed: | |
| 494 | if !isClosed { | |
| 495 | close(skipLoopDone) | |
| 496 | skipLoopClosed <- true // Mark as closed | |
| 497 | } | |
| 498 | default: | |
| 499 | // Channel is busy, another goroutine is handling closure | |
| 500 | } | |
| 501 | return | |
| 450 | 502 | } |
| 451 | 503 | } |
| 452 | 504 | |
| @@ -487,13 +539,10 @@ func main() { | ||
| 487 | 539 | err = internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime)) |
| 488 | 540 | if err != nil { |
| 489 | 541 | internal.Log("Error updating local database: " + err.Error()) |
| 490 | } else { | |
| 491 | // internal.Log(fmt.Sprintf("Updated database: AnilistId=%d, AllanimeId=%s, EpNumber=%d, PlaybackTime=%d", | |
| 492 | // anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime)) | |
| 493 | 542 | } |
| 494 | 543 | } |
| 495 | 544 | |
| 496 | // Check if anything is playing, if nothing is playing and episode was started, start next episode | |
| 545 | // Check if anything is playing, if nothing is playing and episode was started, handle completion | |
| 497 | 546 | hasPlayback, err := internal.HasActivePlayback(anime.Ep.Player.SocketPath) |
| 498 | 547 | if err != nil { |
| 499 | 548 | internal.Log("Error checking playback status: " + err.Error()) |
| @@ -506,12 +555,44 @@ func main() { | ||
| 506 | 555 | if err != nil { |
| 507 | 556 | internal.Log("Error checking playback status: " + err.Error()) |
| 508 | 557 | } else if !hasPlayback { |
| 509 | // Nothing is playing, start next episode | |
| 510 | internal.Log("Nothing playing in MPV, starting next episode") | |
| 511 | anime.Ep.Number++ | |
| 512 | anime.Ep.Started = false | |
| 513 | anime.Ep.IsCompleted = true | |
| 514 | close(skipLoopDone) | |
| 558 | // Nothing is playing, check percentage watched | |
| 559 | percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration) | |
| 560 | // fmt.Printf("[DEBUG] Playback stopped - Percentage watched: %d%%, Required: %d%%\n", | |
| 561 | // int(percentageWatched), | |
| 562 | // userCurdConfig.PercentageToMarkComplete) | |
| 563 | ||
| 564 | if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete { | |
| 565 | anime.Ep.IsCompleted = true | |
| 566 | if !userCurdConfig.NextEpisodePrompt { | |
| 567 | internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile) | |
| 568 | } else { | |
| 569 | // When NextEpisodePrompt is enabled, show the prompt in both modes | |
| 570 | if userCurdConfig.RofiSelection { | |
| 571 | // For Rofi mode | |
| 572 | internal.CurdOut("Showing next episode prompt in Rofi mode (playback ended)") | |
| 573 | internal.ExitMPV(anime.Ep.Player.SocketPath) | |
| 574 | internal.NextEpisodePrompt(&userCurdConfig) | |
| 575 | return | |
| 576 | } else { | |
| 577 | // For CLI mode | |
| 578 | internal.NextEpisodePrompt(&userCurdConfig) | |
| 579 | return | |
| 580 | } | |
| 581 | } | |
| 582 | } else { | |
| 583 | internal.Log("Episode is not completed, exiting") | |
| 584 | internal.ExitCurd(nil) | |
| 585 | } | |
| 586 | // Exit the skip loop - only close if not already closed | |
| 587 | select { | |
| 588 | case isClosed := <-skipLoopClosed: | |
| 589 | if !isClosed { | |
| 590 | close(skipLoopDone) | |
| 591 | skipLoopClosed <- true // Mark as closed | |
| 592 | } | |
| 593 | default: | |
| 594 | // Channel is busy, another goroutine is handling closure | |
| 595 | } | |
| 515 | 596 | return |
| 516 | 597 | } |
| 517 | 598 | } |
| @@ -556,6 +637,12 @@ func main() { | ||
| 556 | 637 | // Reset the WaitGroup for the next loop |
| 557 | 638 | wg = sync.WaitGroup{} |
| 558 | 639 | |
| 640 | // Exit the program if we're starting an episode beyond the total episodes | |
| 641 | if anime.Ep.Number > anime.TotalEpisodes && anime.TotalEpisodes > 0 { | |
| 642 | internal.CurdOut("Reached end of series") | |
| 643 | internal.ExitCurd(nil) | |
| 644 | } | |
| 645 | ||
| 559 | 646 | if anime.Ep.IsCompleted && !anime.Rewatching { |
| 560 | 647 | // Update progress for both regular episodes and skipped fillers |
| 561 | 648 | if anime.TotalEpisodes > 0 && anime.Ep.Number-1 != anime.TotalEpisodes { |
| @@ -607,12 +694,63 @@ func main() { | ||
| 607 | 694 | internal.ExitCurd(nil) |
| 608 | 695 | } |
| 609 | 696 | |
| 610 | if anime.Ep.IsCompleted && userCurdConfig.RofiSelection && userCurdConfig.NextEpisodePrompt { | |
| 611 | internal.NextEpisodePrompt(&userCurdConfig) | |
| 697 | // Handle next episode logic based on config | |
| 698 | if anime.Ep.IsCompleted { | |
| 699 | if userCurdConfig.NextEpisodePrompt { | |
| 700 | // Handle the special case where playback is still active (might happen with Rofi) | |
| 701 | // This ensures we don't show duplicate prompts if it was already handled in the playback monitor | |
| 702 | isPlaying, err := internal.HasActivePlayback(anime.Ep.Player.SocketPath) | |
| 703 | if err != nil { | |
| 704 | internal.Log(fmt.Sprintf("Error checking playback for prompt: %v", err)) | |
| 705 | } | |
| 706 | ||
| 707 | // Only show the prompt here if playback is still active - otherwise it was already handled | |
| 708 | if isPlaying { | |
| 709 | internal.CurdOut("Episode completed, showing next episode prompt from main loop") | |
| 710 | if userCurdConfig.RofiSelection { | |
| 711 | internal.NextEpisodePrompt(&userCurdConfig) | |
| 712 | // Exit after NextEpisodePrompt to avoid starting a new playback loop | |
| 713 | internal.ExitCurd(nil) | |
| 714 | } | |
| 715 | // For CLI mode, the prompt will be shown elsewhere | |
| 716 | } else { | |
| 717 | internal.Log("Playback already ended, prompt handled elsewhere") | |
| 718 | } | |
| 719 | } else { | |
| 720 | // When NextEpisodePrompt is off, we continue automatically in both CLI and Rofi modes | |
| 721 | internal.CurdOut("Auto-continuing to next episode") | |
| 722 | // Don't need to do anything - the loop will continue naturally | |
| 723 | } | |
| 724 | } | |
| 725 | ||
| 726 | // Wait for up to 5 seconds for prefetched links to become available | |
| 727 | for i := 0; i < 5; i++ { | |
| 728 | if anime.Ep.NextEpisode.Number == anime.Ep.Number && len(anime.Ep.NextEpisode.Links) > 0 { | |
| 729 | internal.Log("Using prefetched next episode link") | |
| 730 | anime.Ep.Links = anime.Ep.NextEpisode.Links | |
| 731 | break | |
| 732 | } | |
| 733 | time.Sleep(1 * time.Second) | |
| 734 | } | |
| 735 | ||
| 736 | // If we still don't have links, get them now | |
| 737 | if len(anime.Ep.Links) == 0 { | |
| 738 | links, err := internal.GetEpisodeURL(userCurdConfig, anime.AllanimeId, anime.Ep.Number) | |
| 739 | if err != nil { | |
| 740 | internal.Log("Failed to get episode links: " + err.Error()) | |
| 741 | internal.CurdOut("Failed to get episode links. Try again later.") | |
| 742 | internal.ExitCurd(fmt.Errorf("failed to get episode links: %v", err)) | |
| 743 | return | |
| 744 | } | |
| 745 | anime.Ep.Links = links | |
| 612 | 746 | } |
| 613 | 747 | |
| 614 | internal.CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number)) | |
| 615 | anime.Ep.Started = false | |
| 748 | // Verify that we have links before starting | |
| 749 | if len(anime.Ep.Links) == 0 { | |
| 750 | internal.CurdOut("No episode links found. Try again later.") | |
| 751 | internal.ExitCurd(fmt.Errorf("no episode links found")) | |
| 752 | return | |
| 753 | } | |
| 616 | 754 | |
| 617 | 755 | } |
| 618 | 756 | } |
internal/curd.go +168 −4
| @@ -1022,6 +1022,11 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni | ||
| 1022 | 1022 | } |
| 1023 | 1023 | } |
| 1024 | 1024 | |
| 1025 | // Check if this is the last episode - prompt user if needed | |
| 1026 | if userCurdConfig.NextEpisodePrompt && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !userCurdConfig.RofiSelection { | |
| 1027 | // Ensure the terminal state is clean for the prompt | |
| 1028 | fmt.Print("\r\033[K") // Carriage return and clear line | |
| 1029 | } | |
| 1025 | 1030 | } |
| 1026 | 1031 | |
| 1027 | 1032 | // CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it |
| @@ -1047,7 +1052,7 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string { | ||
| 1047 | 1052 | |
| 1048 | 1053 | if anime.Ep.NextEpisode.Number == anime.Ep.Number { |
| 1049 | 1054 | anime.Ep.Links = anime.Ep.NextEpisode.Links |
| 1050 | fmt.Println("using prefetched next episode link") | |
| 1055 | Log("using prefetched next episode link") | |
| 1051 | 1056 | } else { |
| 1052 | 1057 | // Get episode link |
| 1053 | 1058 | link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number) |
| @@ -1232,27 +1237,168 @@ func NextEpisodePrompt(userCurdConfig *CurdConfig) { | ||
| 1232 | 1237 | |
| 1233 | 1238 | CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum)) |
| 1234 | 1239 | |
| 1235 | selectedOption, err := DynamicSelect(map[string]string{"yes": "Yes"}) | |
| 1240 | // Create options for the selection | |
| 1241 | options := map[string]string{ | |
| 1242 | "yes": "Yes, start next episode", | |
| 1243 | // "no": "No, quit", | |
| 1244 | } | |
| 1245 | ||
| 1246 | // Use DynamicSelect for both CLI and Rofi modes | |
| 1247 | selectedOption, err := DynamicSelect(options) | |
| 1236 | 1248 | if err != nil { |
| 1249 | Log(fmt.Sprintf("Error in next episode prompt selection: %v", err)) | |
| 1237 | 1250 | ExitCurd(err) |
| 1238 | 1251 | } |
| 1239 | 1252 | |
| 1240 | 1253 | if selectedOption.Key != "yes" { |
| 1254 | // User selected to quit | |
| 1255 | fmt.Print("\r\033[K") // Carriage return and clear line | |
| 1241 | 1256 | ExitMPV(anime.Ep.Player.SocketPath) |
| 1257 | CurdOut("Exiting without starting next episode") | |
| 1242 | 1258 | ExitCurd(nil) |
| 1259 | return | |
| 1260 | } | |
| 1261 | ||
| 1262 | // If yes, start the next episode | |
| 1263 | prevEpisode := anime.Ep.Number | |
| 1264 | anime.Ep.Number++ | |
| 1265 | anime.Ep.Started = false | |
| 1266 | anime.Ep.IsCompleted = false // Reset completion flag for the new episode | |
| 1267 | ||
| 1268 | // Clear current line to avoid visual glitches | |
| 1269 | fmt.Print("\r\033[K") // Carriage return and clear line | |
| 1270 | ||
| 1271 | CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number)) | |
| 1272 | ||
| 1273 | // Get database file path for StartNextEpisode | |
| 1274 | homeDir := "" | |
| 1275 | if runtime.GOOS == "windows" { | |
| 1276 | homeDir = os.Getenv("USERPROFILE") | |
| 1277 | } else { | |
| 1278 | homeDir = os.Getenv("HOME") | |
| 1279 | } | |
| 1280 | configFilePath := filepath.Join(homeDir, ".config", "curd", "curd.conf") | |
| 1281 | config, err := LoadConfig(configFilePath) | |
| 1282 | if err != nil { | |
| 1283 | Log("Error loading config for database path: " + err.Error()) | |
| 1284 | ExitCurd(err) | |
| 1243 | 1285 | } |
| 1244 | // If yes or any other case, continue with the next episode | |
| 1286 | databaseFile := filepath.Join(os.ExpandEnv(config.StoragePath), "curd_history.txt") | |
| 1287 | ||
| 1288 | // Update local database for the new episode | |
| 1289 | err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, GetAnimeName(*anime)) | |
| 1290 | if err != nil { | |
| 1291 | Log("Error updating local database: " + err.Error()) | |
| 1292 | } | |
| 1293 | ||
| 1294 | // Update Anilist progress for the previous episode if not rewatching | |
| 1295 | if !anime.Rewatching { | |
| 1296 | user := &User{} | |
| 1297 | user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "token")) | |
| 1298 | if err != nil { | |
| 1299 | Log("Error reading token for progress update: " + err.Error()) | |
| 1300 | } else { | |
| 1301 | go func() { | |
| 1302 | err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode) | |
| 1303 | if err != nil { | |
| 1304 | Log("Error updating Anilist progress: " + err.Error()) | |
| 1305 | } else { | |
| 1306 | CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode)) | |
| 1307 | } | |
| 1308 | }() | |
| 1309 | } | |
| 1310 | } | |
| 1311 | ||
| 1312 | // Close current MPV instance | |
| 1313 | ExitMPV(anime.Ep.Player.SocketPath) | |
| 1314 | ||
| 1315 | // Check if we have prefetched links for the next episode | |
| 1316 | if anime.Ep.NextEpisode.Number == anime.Ep.Number && len(anime.Ep.NextEpisode.Links) > 0 { | |
| 1317 | Log("Using prefetched next episode link") | |
| 1318 | anime.Ep.Links = anime.Ep.NextEpisode.Links | |
| 1319 | } else { | |
| 1320 | // No prefetched links available, need to fetch them | |
| 1321 | CurdOut("Fetching links for next episode...") | |
| 1322 | ||
| 1323 | // Wait for up to 5 seconds for prefetched links to become available | |
| 1324 | for i := 0; i < 5; i++ { | |
| 1325 | if anime.Ep.NextEpisode.Number == anime.Ep.Number && len(anime.Ep.NextEpisode.Links) > 0 { | |
| 1326 | CurdOut("Using newly fetched next episode link") | |
| 1327 | anime.Ep.Links = anime.Ep.NextEpisode.Links | |
| 1328 | break | |
| 1329 | } | |
| 1330 | time.Sleep(1 * time.Second) | |
| 1331 | } | |
| 1332 | ||
| 1333 | // If we still don't have links, get them now | |
| 1334 | if len(anime.Ep.Links) == 0 { | |
| 1335 | links, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number) | |
| 1336 | if err != nil { | |
| 1337 | Log("Failed to get episode links: " + err.Error()) | |
| 1338 | CurdOut("Failed to get episode links. Try again later.") | |
| 1339 | ExitCurd(fmt.Errorf("failed to get episode links: %v", err)) | |
| 1340 | return | |
| 1341 | } | |
| 1342 | anime.Ep.Links = links | |
| 1343 | } | |
| 1344 | } | |
| 1345 | ||
| 1346 | // Verify that we have links before starting | |
| 1347 | if len(anime.Ep.Links) == 0 { | |
| 1348 | CurdOut("No episode links found. Try again later.") | |
| 1349 | ExitCurd(fmt.Errorf("no episode links found")) | |
| 1350 | return | |
| 1351 | } | |
| 1352 | ||
| 1353 | // Actually start the next episode | |
| 1354 | anime.Ep.Player.SocketPath = StartCurd(userCurdConfig, anime) | |
| 1355 | ||
| 1356 | // We don't exit, instead we let the main loop continue with the new episode | |
| 1245 | 1357 | } |
| 1246 | 1358 | |
| 1247 | 1359 | // StartNextEpisode handles the logic for starting the next episode |
| 1248 | 1360 | // It updates the episode number, resets necessary flags, and handles database updates |
| 1249 | 1361 | func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile string) { |
| 1362 | // Save previous episode number for progress update | |
| 1363 | prevEpisode := anime.Ep.Number | |
| 1364 | ||
| 1250 | 1365 | // Increment episode number |
| 1251 | 1366 | anime.Ep.Number++ |
| 1252 | 1367 | |
| 1368 | // Check if we've reached the end of the series | |
| 1369 | if anime.TotalEpisodes > 0 && anime.Ep.Number > anime.TotalEpisodes { | |
| 1370 | CurdOut("Reached end of series") | |
| 1371 | ExitCurd(nil) | |
| 1372 | return | |
| 1373 | } | |
| 1374 | ||
| 1375 | // Check if this is the last episode - prompt user if needed | |
| 1376 | if userCurdConfig.NextEpisodePrompt && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !userCurdConfig.RofiSelection { | |
| 1377 | // Ensure the terminal state is clean for the prompt | |
| 1378 | fmt.Print("\r\033[K") // Carriage return and clear line | |
| 1379 | CurdOut(fmt.Sprintf("Last episode (%d). Are you sure you want to watch it?", anime.Ep.Number)) | |
| 1380 | ||
| 1381 | // Simple yes/no selection for the last episode | |
| 1382 | selectedOption, err := DynamicSelect(map[string]string{"yes": "Yes"}) | |
| 1383 | if err != nil { | |
| 1384 | ExitCurd(err) | |
| 1385 | } | |
| 1386 | ||
| 1387 | if selectedOption.Key != "yes" { | |
| 1388 | // User selected to quitd | |
| 1389 | fmt.Print("\r\033[K") // Carriage return and clear line | |
| 1390 | CurdOut("Exiting without watching the last episode.") | |
| 1391 | ExitCurd(nil) | |
| 1392 | return | |
| 1393 | } | |
| 1394 | ||
| 1395 | // User chose to continue to the last episode | |
| 1396 | fmt.Print("\r\033[K") // Carriage return and clear line | |
| 1397 | } | |
| 1398 | ||
| 1253 | 1399 | // Reset episode flags |
| 1254 | 1400 | anime.Ep.Started = false |
| 1255 | anime.Ep.IsCompleted = true | |
| 1401 | anime.Ep.IsCompleted = false | |
| 1256 | 1402 | |
| 1257 | 1403 | // Log the transition |
| 1258 | 1404 | Log("Completed episode, starting next.") |
| @@ -1263,6 +1409,24 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str | ||
| 1263 | 1409 | Log("Error updating local database: " + err.Error()) |
| 1264 | 1410 | } |
| 1265 | 1411 | |
| 1412 | // Update Anilist progress for the previous episode if not rewatching | |
| 1413 | if !anime.Rewatching { | |
| 1414 | user := &User{} | |
| 1415 | user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token")) | |
| 1416 | if err != nil { | |
| 1417 | Log("Error reading token for progress update: " + err.Error()) | |
| 1418 | } else { | |
| 1419 | go func() { | |
| 1420 | err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode) | |
| 1421 | if err != nil { | |
| 1422 | Log("Error updating Anilist progress: " + err.Error()) | |
| 1423 | } else { | |
| 1424 | CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode)) | |
| 1425 | } | |
| 1426 | }() | |
| 1427 | } | |
| 1428 | } | |
| 1429 | ||
| 1266 | 1430 | // Output message to user |
| 1267 | 1431 | CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number)) |
| 1268 | 1432 | } |
internal/player.go +149 −51
| @@ -127,6 +127,33 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string, | ||
| 127 | 127 | CurdOut("Error: Failed to start mpv process") |
| 128 | 128 | return "", fmt.Errorf("failed to start mpv: %w", err) |
| 129 | 129 | } |
| 130 | ||
| 131 | // Wait for the socket to become available with retries | |
| 132 | socketReady := false | |
| 133 | maxRetries := 10 | |
| 134 | retryDelay := 300 * time.Millisecond | |
| 135 | ||
| 136 | Log(fmt.Sprintf("Waiting for MPV socket to be ready at %s", mpvSocketPath)) | |
| 137 | for i := 0; i < maxRetries; i++ { | |
| 138 | time.Sleep(retryDelay) | |
| 139 | ||
| 140 | // Try to connect to the socket | |
| 141 | conn, err := connectToPipe(mpvSocketPath) | |
| 142 | if err == nil { | |
| 143 | conn.Close() | |
| 144 | socketReady = true | |
| 145 | Log(fmt.Sprintf("MPV socket ready after %d attempts", i+1)) | |
| 146 | break | |
| 147 | } | |
| 148 | ||
| 149 | Log(fmt.Sprintf("Attempt %d/%d - Socket not ready yet: %v", i+1, maxRetries, err)) | |
| 150 | } | |
| 151 | ||
| 152 | if !socketReady { | |
| 153 | Log(fmt.Sprintf("Failed to connect to MPV socket after %d attempts", maxRetries)) | |
| 154 | // Don't fail here, just warn and continue - the next commands will handle any further issues | |
| 155 | } | |
| 156 | ||
| 130 | 157 | return mpvSocketPath, nil |
| 131 | 158 | } |
| 132 | 159 | |
| @@ -143,42 +170,70 @@ func joinArgs(args []string) string { | ||
| 143 | 170 | } |
| 144 | 171 | |
| 145 | 172 | func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, error) { |
| 146 | conn, err := connectToPipe(ipcSocketPath) | |
| 147 | if err != nil { | |
| 148 | return nil, err | |
| 149 | } | |
| 150 | defer conn.Close() | |
| 173 | // Use a retry mechanism for transient errors | |
| 174 | var lastErr error | |
| 175 | maxRetries := 3 | |
| 176 | retryDelay := 100 * time.Millisecond | |
| 177 | ||
| 178 | for attempt := 0; attempt < maxRetries; attempt++ { | |
| 179 | if attempt > 0 { | |
| 180 | time.Sleep(retryDelay) | |
| 181 | Log(fmt.Sprintf("Retrying MPV command, attempt %d/%d", attempt+1, maxRetries)) | |
| 182 | } | |
| 151 | 183 | |
| 152 | commandStr, err := json.Marshal(map[string]interface{}{ | |
| 153 | "command": command, | |
| 154 | }) | |
| 155 | if err != nil { | |
| 156 | return nil, err | |
| 157 | } | |
| 184 | conn, err := connectToPipe(ipcSocketPath) | |
| 185 | if err != nil { | |
| 186 | lastErr = err | |
| 187 | Log(fmt.Sprintf("Connect error (attempt %d/%d): %v", attempt+1, maxRetries, err)) | |
| 188 | continue // Try again | |
| 189 | } | |
| 190 | defer conn.Close() | |
| 158 | 191 | |
| 159 | // Send the command | |
| 160 | _, err = conn.Write(append(commandStr, '\n')) | |
| 161 | if err != nil { | |
| 162 | return nil, err | |
| 163 | } | |
| 192 | commandStr, err := json.Marshal(map[string]interface{}{ | |
| 193 | "command": command, | |
| 194 | }) | |
| 195 | if err != nil { | |
| 196 | return nil, err // Don't retry on JSON marshalling errors | |
| 197 | } | |
| 164 | 198 | |
| 165 | // Receive the response | |
| 166 | buf := make([]byte, 4096) | |
| 167 | n, err := conn.Read(buf) | |
| 168 | if err != nil { | |
| 169 | return nil, err | |
| 170 | } | |
| 199 | // Send the command | |
| 200 | _, err = conn.Write(append(commandStr, '\n')) | |
| 201 | if err != nil { | |
| 202 | lastErr = err | |
| 203 | Log(fmt.Sprintf("Write error (attempt %d/%d): %v", attempt+1, maxRetries, err)) | |
| 204 | continue // Try again | |
| 205 | } | |
| 171 | 206 | |
| 172 | var response map[string]interface{} | |
| 173 | if err := json.Unmarshal(buf[:n], &response); err != nil { | |
| 174 | return nil, err | |
| 175 | } | |
| 207 | // Receive the response with timeout | |
| 208 | buf := make([]byte, 4096) | |
| 209 | // Set read deadline for 1 second | |
| 210 | if deadline, ok := conn.(interface{ SetReadDeadline(time.Time) error }); ok { | |
| 211 | deadline.SetReadDeadline(time.Now().Add(1 * time.Second)) | |
| 212 | } | |
| 176 | 213 | |
| 177 | if data, exists := response["data"]; exists { | |
| 178 | return data, nil | |
| 214 | n, err := conn.Read(buf) | |
| 215 | if err != nil { | |
| 216 | lastErr = err | |
| 217 | Log(fmt.Sprintf("Read error (attempt %d/%d): %v", attempt+1, maxRetries, err)) | |
| 218 | continue // Try again | |
| 219 | } | |
| 220 | ||
| 221 | var response map[string]interface{} | |
| 222 | if err := json.Unmarshal(buf[:n], &response); err != nil { | |
| 223 | lastErr = err | |
| 224 | Log(fmt.Sprintf("JSON parse error (attempt %d/%d): %v", attempt+1, maxRetries, err)) | |
| 225 | continue // Try again | |
| 226 | } | |
| 227 | ||
| 228 | // Success! | |
| 229 | if data, exists := response["data"]; exists { | |
| 230 | return data, nil | |
| 231 | } | |
| 232 | return nil, nil | |
| 179 | 233 | } |
| 180 | 234 | |
| 181 | return nil, nil | |
| 235 | // All retries failed | |
| 236 | return nil, fmt.Errorf("command failed after %d attempts: %w", maxRetries, lastErr) | |
| 182 | 237 | } |
| 183 | 238 | |
| 184 | 239 | func SeekMPV(ipcSocketPath string, time int) (interface{}, error) { |
| @@ -245,24 +300,49 @@ func PercentageWatched(playbackTime int, duration int) float64 { | ||
| 245 | 300 | } |
| 246 | 301 | |
| 247 | 302 | func HasActivePlayback(ipcSocketPath string) (bool, error) { |
| 248 | // Get the time-pos property from MPV | |
| 249 | timePos, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "time-pos"}) | |
| 250 | if err != nil { | |
| 251 | // Check specifically for "property unavailable" error | |
| 252 | if strings.Contains(err.Error(), "property unavailable") { | |
| 253 | // This indicates nothing is playing | |
| 254 | return false, nil | |
| 303 | maxRetries := 3 | |
| 304 | var lastErr error | |
| 305 | ||
| 306 | for attempt := 0; attempt < maxRetries; attempt++ { | |
| 307 | if attempt > 0 { | |
| 308 | time.Sleep(200 * time.Millisecond) | |
| 309 | } | |
| 310 | ||
| 311 | // Get the time-pos property from MPV | |
| 312 | timePos, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "time-pos"}) | |
| 313 | ||
| 314 | if err != nil { | |
| 315 | // Check specifically for "property unavailable" error - this is a valid state | |
| 316 | if strings.Contains(err.Error(), "property unavailable") { | |
| 317 | Log("HasActivePlayback: Property unavailable, nothing is playing") | |
| 318 | return false, nil | |
| 319 | } | |
| 320 | ||
| 321 | // Check for socket connection errors - these might be temporary | |
| 322 | if strings.Contains(err.Error(), "connect: connection refused") || | |
| 323 | strings.Contains(err.Error(), "connect: no such file or directory") { | |
| 324 | lastErr = err | |
| 325 | Log(fmt.Sprintf("HasActivePlayback: Connection error (attempt %d/%d): %v", | |
| 326 | attempt+1, maxRetries, err)) | |
| 327 | continue // Try again | |
| 328 | } | |
| 329 | ||
| 330 | // Other errors should be returned | |
| 331 | return false, fmt.Errorf("error getting time-pos: %w", err) | |
| 255 | 332 | } |
| 256 | return false, fmt.Errorf("error getting time-pos: %w", err) | |
| 257 | } | |
| 258 | 333 | |
| 259 | // If we got a valid response, something is playing | |
| 260 | if timePos != nil { | |
| 261 | return true, nil | |
| 334 | // If we got a valid response, something is playing | |
| 335 | if timePos != nil { | |
| 336 | return true, nil | |
| 337 | } | |
| 338 | ||
| 339 | // No error but no position either - likely nothing is playing | |
| 340 | return false, nil | |
| 262 | 341 | } |
| 263 | 342 | |
| 264 | // Default to false if we can't determine the status | |
| 265 | return false, nil | |
| 343 | // If we get here, all retries failed | |
| 344 | Log(fmt.Sprintf("HasActivePlayback: Failed after %d attempts: %v", maxRetries, lastErr)) | |
| 345 | return false, fmt.Errorf("failed to check playback status: %w", lastErr) | |
| 266 | 346 | } |
| 267 | 347 | |
| 268 | 348 | func IsMPVRunning(socketPath string) bool { |
| @@ -270,16 +350,34 @@ func IsMPVRunning(socketPath string) bool { | ||
| 270 | 350 | return false |
| 271 | 351 | } |
| 272 | 352 | |
| 273 | // Try to connect to the socket | |
| 274 | conn, err := connectToPipe(socketPath) | |
| 275 | if err != nil { | |
| 276 | return false | |
| 353 | maxRetries := 3 | |
| 354 | for attempt := 0; attempt < maxRetries; attempt++ { | |
| 355 | if attempt > 0 { | |
| 356 | time.Sleep(200 * time.Millisecond) | |
| 357 | Log(fmt.Sprintf("Retrying MPV connection check, attempt %d/%d", attempt+1, maxRetries)) | |
| 358 | } | |
| 359 | ||
| 360 | // Try to connect to the socket | |
| 361 | conn, err := connectToPipe(socketPath) | |
| 362 | if err != nil { | |
| 363 | Log(fmt.Sprintf("IsMPVRunning: Connection error (attempt %d/%d): %v", | |
| 364 | attempt+1, maxRetries, err)) | |
| 365 | continue | |
| 366 | } | |
| 367 | defer conn.Close() | |
| 368 | ||
| 369 | // Send a simple command to check if MPV responds | |
| 370 | _, err = MPVSendCommand(socketPath, []interface{}{"get_property", "pid"}) | |
| 371 | if err == nil { | |
| 372 | return true | |
| 373 | } | |
| 374 | ||
| 375 | Log(fmt.Sprintf("IsMPVRunning: Command failed (attempt %d/%d): %v", | |
| 376 | attempt+1, maxRetries, err)) | |
| 277 | 377 | } |
| 278 | defer conn.Close() | |
| 279 | 378 | |
| 280 | // Send a simple command to check if MPV responds | |
| 281 | _, err = MPVSendCommand(socketPath, []interface{}{"get_property", "pid"}) | |
| 282 | return err == nil | |
| 379 | // After all retries, conclude MPV is not running | |
| 380 | return false | |
| 283 | 381 | } |
| 284 | 382 | |
| 285 | 383 | func ExitMPV(ipcSocketPath string) error { |
internal/selection_menu.go +7 −2
| @@ -380,7 +380,7 @@ func RofiSelect(options map[string]string) (SelectionOption, error) { | ||
| 380 | 380 | |
| 381 | 381 | // Add "Quit" options |
| 382 | 382 | optionsList = append(optionsList, "Quit") |
| 383 | ||
| 383 | ||
| 384 | 384 | // Join all options into a single string, separated by newlines |
| 385 | 385 | optionsString := strings.Join(optionsList, "\n") |
| 386 | 386 | |
| @@ -458,12 +458,13 @@ func DynamicSelect(options map[string]string) (SelectionOption, error) { | ||
| 458 | 458 | filteredKeys: orderedOptions, |
| 459 | 459 | } |
| 460 | 460 | |
| 461 | ||
| 462 | 461 | model.filteredKeys = append(model.filteredKeys, SelectionOption{ |
| 463 | 462 | Label: "Quit", |
| 464 | 463 | Key: "-1", |
| 465 | 464 | }) |
| 466 | 465 | |
| 466 | // Create a program with altScreen option turned off to maintain the terminal state | |
| 467 | // This prevents the terminal from switching to an alternate screen | |
| 467 | 468 | p := tea.NewProgram(model) |
| 468 | 469 | |
| 469 | 470 | finalModel, err := p.Run() |
| @@ -471,6 +472,10 @@ func DynamicSelect(options map[string]string) (SelectionOption, error) { | ||
| 471 | 472 | return SelectionOption{}, err |
| 472 | 473 | } |
| 473 | 474 | |
| 475 | // Explicitly reset the terminal state | |
| 476 | fmt.Print("\033[?25h") // Show cursor | |
| 477 | fmt.Print("\033[?7h") // Enable line wrapping | |
| 478 | ||
| 474 | 479 | finalSelectionModel, ok := finalModel.(*Model) |
| 475 | 480 | if !ok { |
| 476 | 481 | return SelectionOption{}, fmt.Errorf("unexpected model type") |