Commit b81dbbadc2

b81dbbadc2eafb588273bd40e7467ec2c0f69482

parent: 21baf6f4e0

Unregistered key

Rushikesh Gaikwad <81632222+Wraient@users.noreply.github.com> · 2025-07-24 13:59 UTC
committer: <noreply@github.com>

Fix next episode prompt (#65)

* fix: Next episode prompt and many bugs completely.

* Fix: Use prefetched links

* Update: todo list

Layout: unified · split

README.md −3
@@ -360,10 +360,7 @@ config file is located at ```~/.config/curd/curd.conf```
360| `SkipFiller` | Boolean | `true`, `false` | Skips filler episodes when supported. | 360| `SkipFiller` | Boolean | `true`, `false` | Skips filler episodes when supported. |
361 361
362## Todo (fix) 362## Todo (fix)
363- Config: Nextepisodeprompt, Cli Mode, Problem: Quitting with quit button while ep is still playing doesnt update progress, even if past Mark Complete Threshold (Regression)
364- Use Powershell for windows token input instead of notepad or cmd 363- Use Powershell for windows token input instead of notepad or cmd
365- Add Rewatching list to "Show All" Option
366- Last episode doesnt prompt for anime score (Regression)
367- Find a way to get "Watching" instead of "Playing" Activity type in discord rpc (Implemented in [Dantotsu](https://github.com/aayush2622/Dartotsu) and [Premid](https://github.com/PreMiD/PreMiD)) 364- Find a way to get "Watching" instead of "Playing" Activity type in discord rpc (Implemented in [Dantotsu](https://github.com/aayush2622/Dartotsu) and [Premid](https://github.com/PreMiD/PreMiD))
368- Add a better way to do commands in windows (Convinience for users) 365- Add a better way to do commands in windows (Convinience for users)
369 366
cmd/curd/main.go +117 −62
@@ -329,9 +329,14 @@ func main() {
329 } 329 }
330 330
331 anime.Ep.IsCompleted = true 331 anime.Ep.IsCompleted = true
332 if !userCurdConfig.NextEpisodePrompt || userCurdConfig.RofiSelection { 332 if !userCurdConfig.NextEpisodePrompt {
333 // fmt.Println("[DEBUG] Starting next episode from filler/recap skip") 333 // fmt.Println("[DEBUG] Starting next episode from filler/recap skip")
334 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile) 334 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
335 } else {
336 // When NextEpisodePrompt is enabled, just call StartNextEpisode - it handles Rofi prompting internally
337 internal.ExitMPV(anime.Ep.Player.SocketPath)
338 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
339 return
335 } 340 }
336 // Send command to close MPV 341 // Send command to close MPV
337 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"}) 342 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
@@ -414,27 +419,20 @@ func main() {
414 } 419 }
415 }() 420 }()
416 421
417 // Thread to prompt for next episode in CLI Mode 422 // Thread for continuous next episode prompt in CLI mode (throughout episode duration)
418 go func() { 423 go func() {
419 if !userCurdConfig.RofiSelection && userCurdConfig.NextEpisodePrompt { 424 if userCurdConfig.NextEpisodePrompt && !userCurdConfig.RofiSelection {
420 for { 425 internal.NextEpisodePromptContinuous(&userCurdConfig, databaseFile, user.Token)
421 select { 426 // If the function returns, it means user made a decision
422 case <-skipLoopDone: 427 // Exit the skip loop - only close if not already closed
423 return 428 select {
424 default: 429 case isClosed := <-skipLoopClosed:
425 internal.NextEpisodePrompt(&userCurdConfig) 430 if !isClosed {
426 // Exit the skip loop - only close if not already closed 431 close(skipLoopDone)
427 select { 432 skipLoopClosed <- true // Mark as closed
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 } 433 }
434 default:
435 // Channel is busy, another goroutine is handling closure
438 } 436 }
439 } 437 }
440 }() 438 }()
@@ -456,6 +454,11 @@ func main() {
456 if err != nil { 454 if err != nil {
457 internal.Log("Error getting playback time: " + err.Error()) 455 internal.Log("Error getting playback time: " + err.Error())
458 456
457 // For CLI mode with next episode prompt, let the continuous prompt handle everything
458 if userCurdConfig.NextEpisodePrompt && !userCurdConfig.RofiSelection {
459 continue
460 }
461
459 // Check if the error is due to invalid JSON 462 // Check if the error is due to invalid JSON
460 // User closed the video 463 // User closed the video
461 if anime.Ep.Started { 464 if anime.Ep.Started {
@@ -469,20 +472,50 @@ func main() {
469 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete { 472 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
470 anime.Ep.IsCompleted = true 473 anime.Ep.IsCompleted = true
471 if !userCurdConfig.NextEpisodePrompt { 474 if !userCurdConfig.NextEpisodePrompt {
472 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile) 475 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
473 } else { 476 } else {
474 // When NextEpisodePrompt is enabled, show the prompt in both modes 477 // For Rofi mode, show prompt immediately after completion
475 if userCurdConfig.RofiSelection { 478 if userCurdConfig.RofiSelection {
476 // For Rofi mode 479 shouldContinue := internal.NextEpisodePromptRofi(&userCurdConfig)
477 internal.CurdOut("Showing next episode prompt in Rofi mode (playback ended)") 480 if shouldContinue {
478 internal.ExitMPV(anime.Ep.Player.SocketPath) 481 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
479 internal.NextEpisodePrompt(&userCurdConfig) 482 } else {
480 return 483 // Episode was already marked as completed above
484 // Update local database with completed episode
485 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime))
486 if err != nil {
487 internal.Log("Error updating local database on quit: " + err.Error())
488 }
489
490 // Update Anilist progress if not rewatching
491 if !anime.Rewatching {
492 go func() {
493 err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number)
494 if err != nil {
495 internal.Log("Error updating Anilist progress on quit: " + err.Error())
496 } else {
497 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
498 }
499 }()
500 }
501
502 internal.ExitCurd(nil)
503 }
481 } else { 504 } else {
482 // For CLI mode 505 // For CLI mode, let the continuous prompt handle it
483 internal.NextEpisodePrompt(&userCurdConfig) 506 internal.Log("Episode completed, exiting monitoring to let CLI prompt handle next episode")
484 return
485 } 507 }
508 // Exit the skip loop - only close if not already closed
509 select {
510 case isClosed := <-skipLoopClosed:
511 if !isClosed {
512 close(skipLoopDone)
513 skipLoopClosed <- true // Mark as closed
514 }
515 default:
516 // Channel is busy, another goroutine is handling closure
517 }
518 return
486 } 519 }
487 } else { 520 } else {
488 internal.Log("Episode is not completed, exiting") 521 internal.Log("Episode is not completed, exiting")
@@ -555,6 +588,11 @@ func main() {
555 if err != nil { 588 if err != nil {
556 internal.Log("Error checking playback status: " + err.Error()) 589 internal.Log("Error checking playback status: " + err.Error())
557 } else if !hasPlayback { 590 } else if !hasPlayback {
591 // For CLI mode with next episode prompt, let the continuous prompt handle everything
592 if userCurdConfig.NextEpisodePrompt && !userCurdConfig.RofiSelection {
593 continue
594 }
595
558 // Nothing is playing, check percentage watched 596 // Nothing is playing, check percentage watched
559 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration) 597 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
560 // fmt.Printf("[DEBUG] Playback stopped - Percentage watched: %d%%, Required: %d%%\n", 598 // fmt.Printf("[DEBUG] Playback stopped - Percentage watched: %d%%, Required: %d%%\n",
@@ -564,20 +602,50 @@ func main() {
564 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete { 602 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
565 anime.Ep.IsCompleted = true 603 anime.Ep.IsCompleted = true
566 if !userCurdConfig.NextEpisodePrompt { 604 if !userCurdConfig.NextEpisodePrompt {
567 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile) 605 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
568 } else { 606 } else {
569 // When NextEpisodePrompt is enabled, show the prompt in both modes 607 // For Rofi mode, show prompt immediately after completion
570 if userCurdConfig.RofiSelection { 608 if userCurdConfig.RofiSelection {
571 // For Rofi mode 609 shouldContinue := internal.NextEpisodePromptRofi(&userCurdConfig)
572 internal.CurdOut("Showing next episode prompt in Rofi mode (playback ended)") 610 if shouldContinue {
573 internal.ExitMPV(anime.Ep.Player.SocketPath) 611 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
574 internal.NextEpisodePrompt(&userCurdConfig) 612 } else {
575 return 613 // Episode was already marked as completed above
614 // Update local database with completed episode
615 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime))
616 if err != nil {
617 internal.Log("Error updating local database on quit: " + err.Error())
618 }
619
620 // Update Anilist progress if not rewatching
621 if !anime.Rewatching {
622 go func() {
623 err = internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number)
624 if err != nil {
625 internal.Log("Error updating Anilist progress on quit: " + err.Error())
626 } else {
627 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
628 }
629 }()
630 }
631
632 internal.ExitCurd(nil)
633 }
576 } else { 634 } else {
577 // For CLI mode 635 // For CLI mode, let the continuous prompt handle it
578 internal.NextEpisodePrompt(&userCurdConfig) 636 internal.Log("Episode completed, exiting monitoring to let CLI prompt handle next episode")
579 return
580 } 637 }
638 // Exit the skip loop - only close if not already closed
639 select {
640 case isClosed := <-skipLoopClosed:
641 if !isClosed {
642 close(skipLoopDone)
643 skipLoopClosed <- true // Mark as closed
644 }
645 default:
646 // Channel is busy, another goroutine is handling closure
647 }
648 return
581 } 649 }
582 } else { 650 } else {
583 internal.Log("Episode is not completed, exiting") 651 internal.Log("Episode is not completed, exiting")
@@ -697,29 +765,16 @@ func main() {
697 // Handle next episode logic based on config 765 // Handle next episode logic based on config
698 if anime.Ep.IsCompleted { 766 if anime.Ep.IsCompleted {
699 if userCurdConfig.NextEpisodePrompt { 767 if userCurdConfig.NextEpisodePrompt {
700 // Handle the special case where playback is still active (might happen with Rofi) 768 if !userCurdConfig.RofiSelection {
701 // This ensures we don't show duplicate prompts if it was already handled in the playback monitor 769 // For CLI mode, the continuous prompt handles everything
702 isPlaying, err := internal.HasActivePlayback(anime.Ep.Player.SocketPath) 770 internal.CurdOut("CLI mode: continuous prompt handling next episode logic")
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 } 771 }
772 // For both modes, if we reach here, it means the monitoring thread exited
773 // and the episode should transition. Let the normal flow continue.
719 } else { 774 } else {
720 // When NextEpisodePrompt is off, we continue automatically in both CLI and Rofi modes 775 // When NextEpisodePrompt is off, continue automatically
721 internal.CurdOut("Auto-continuing to next episode") 776 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
722 // Don't need to do anything - the loop will continue naturally 777 continue
723 } 778 }
724 } 779 }
725 780
internal/curd.go +162 −231
@@ -1088,39 +1088,6 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1088 anime.Ep.Number = anime.TotalEpisodes 1088 anime.Ep.Number = anime.TotalEpisodes
1089 } 1089 }
1090 } 1090 }
1091
1092 // Check if this is the last episode - prompt user if needed
1093 if userCurdConfig.NextEpisodePrompt && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !userCurdConfig.RofiSelection {
1094 // Ensure the terminal state is clean for the prompt
1095 fmt.Print("\r\033[K") // Carriage return and clear line
1096 episodeNum := anime.Ep.Number
1097 if !userCurdConfig.RofiSelection {
1098 episodeNum++
1099 }
1100
1101 CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum))
1102
1103 // Create options for the selection
1104 options := []SelectionOption{
1105 {Key: "yes", Label: "Yes, start next episode"},
1106 // "no": "No, quit",
1107 }
1108
1109 // Use DynamicSelect for both CLI and Rofi modes
1110 selectedOption, err := DynamicSelect(options)
1111 if err != nil {
1112 ExitCurd(err)
1113 }
1114
1115 if selectedOption.Key == "-1" {
1116 // User selected to quit
1117 fmt.Print("\r\033[K") // Carriage return and clear line
1118 ExitMPV(anime.Ep.Player.SocketPath)
1119 CurdOut("Exiting without starting next episode")
1120 ExitCurd(nil)
1121 return
1122 }
1123 }
1124} 1091}
1125 1092
1126// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it 1093// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
@@ -1338,189 +1305,196 @@ func getEntriesByCategory(list AnimeList, category string) []Entry {
1338 } 1305 }
1339} 1306}
1340 1307
1341func NextEpisodePrompt(userCurdConfig *CurdConfig) { 1308func NextEpisodePromptCLI(userCurdConfig *CurdConfig) bool {
1342 anime := GetGlobalAnime() 1309 anime := GetGlobalAnime()
1343 1310
1344 // Check if we just completed the last episode 1311 // Show the next episode number that will be started
1345 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes { 1312 nextEpisodeNum := anime.Ep.Number + 1
1346 // Handle scoring and completion for the last episode 1313 CurdOut(fmt.Sprintf("Start next episode (%d)?", nextEpisodeNum))
1347 HandleLastEpisodeCompletion(userCurdConfig, anime)
1348 1314
1349 // Exit after completing the series 1315 // Create options for the selection - no "quit" option since it's built into selection menu
1350 fmt.Print("\r\033[K") // Carriage return and clear line
1351 ExitMPV(anime.Ep.Player.SocketPath)
1352 CurdOut("Series completed!")
1353 ExitCurd(nil)
1354 return
1355 }
1356
1357 // If in CLI mode (not Rofi), we need to show the next episode number
1358 episodeNum := anime.Ep.Number
1359 if !userCurdConfig.RofiSelection {
1360 episodeNum++
1361 }
1362
1363 CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum))
1364
1365 // Create options for the selection
1366 options := []SelectionOption{ 1316 options := []SelectionOption{
1367 {Key: "yes", Label: "Yes, start next episode"}, 1317 {Key: "yes", Label: fmt.Sprintf("Yes, continue to episode %d", nextEpisodeNum)},
1368 // {Key: "-1", Label: "No, quit"},
1369 } 1318 }
1370 1319
1371 // Use DynamicSelect for both CLI and Rofi modes 1320 // Use DynamicSelect for CLI mode
1372 selectedOption, err := DynamicSelect(options) 1321 selectedOption, err := DynamicSelect(options)
1373 if err != nil { 1322 if err != nil {
1374 Log(fmt.Sprintf("Error in next episode prompt selection: %v", err)) 1323 Log(fmt.Sprintf("Error in CLI next episode prompt selection: %v", err))
1375 ExitCurd(err) 1324 return false
1376 } 1325 }
1377 1326
1378 Log(fmt.Sprintf("User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label)) 1327 Log(fmt.Sprintf("CLI User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1379 1328
1380 if selectedOption.Key == "-1" { 1329 if selectedOption.Key == "-1" {
1381 // User selected to quit 1330 // User selected to quit via the built-in quit option
1382 fmt.Print("\r\033[K") // Carriage return and clear line 1331 CurdOut("Exiting")
1383 ExitMPV(anime.Ep.Player.SocketPath) 1332 return false
1384 CurdOut("Exiting without starting next episode")
1385 ExitCurd(nil)
1386 return
1387 }
1388
1389 if selectedOption.Key != "yes" {
1390 // User selected something other than yes (shouldn't happen, but safety check)
1391 Log(fmt.Sprintf("Unexpected selection key: %s", selectedOption.Key))
1392 fmt.Print("\r\033[K") // Carriage return and clear line
1393 ExitMPV(anime.Ep.Player.SocketPath)
1394 CurdOut("Exiting without starting next episode")
1395 ExitCurd(nil)
1396 return
1397 } 1333 }
1398 1334
1399 // If yes, start the next episode 1335 return selectedOption.Key == "yes"
1400 prevEpisode := anime.Ep.Number 1336}
1401 anime.Ep.Number++
1402 anime.Ep.Started = false
1403 anime.Ep.IsCompleted = false // Reset completion flag for the new episode
1404
1405 // Clear current line to avoid visual glitches
1406 fmt.Print("\r\033[K") // Carriage return and clear line
1407 1337
1408 CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number)) 1338// NextEpisodePromptContinuous provides a continuous next episode prompt for CLI mode
1339// This runs throughout the episode duration and handles completion logic
1340func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1341 anime := GetGlobalAnime()
1342
1343 for {
1344 // Check if episode has started
1345 if !anime.Ep.Started {
1346 time.Sleep(1 * time.Second)
1347 continue
1348 }
1409 1349
1410 // Get database file path for StartNextEpisode 1350 // Show the next episode number that will be started
1411 homeDir := "" 1351 nextEpisodeNum := anime.Ep.Number + 1
1412 if runtime.GOOS == "windows" { 1352 CurdOut(fmt.Sprintf("Continue to next episode (%d) or quit?", nextEpisodeNum))
1413 homeDir = os.Getenv("USERPROFILE")
1414 } else {
1415 homeDir = os.Getenv("HOME")
1416 }
1417 configFilePath := filepath.Join(homeDir, ".config", "curd", "curd.conf")
1418 config, err := LoadConfig(configFilePath)
1419 if err != nil {
1420 Log("Error loading config for database path: " + err.Error())
1421 ExitCurd(err)
1422 }
1423 databaseFile := filepath.Join(os.ExpandEnv(config.StoragePath), "curd_history.txt")
1424 1353
1425 // Update local database for the new episode 1354 // Create options for the selection - no "quit" option since it's built into selection menu
1426 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, GetAnimeName(*anime)) 1355 options := []SelectionOption{
1427 if err != nil { 1356 {Key: "yes", Label: "Yes, start next episode now"},
1428 Log("Error updating local database: " + err.Error()) 1357 }
1429 }
1430 1358
1431 // Update Anilist progress for the previous episode if not rewatching 1359 // Use DynamicSelect for CLI mode
1432 if !anime.Rewatching { 1360 selectedOption, err := DynamicSelect(options)
1433 user := &User{}
1434 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "token"))
1435 if err != nil { 1361 if err != nil {
1436 Log("Error reading token for progress update: " + err.Error()) 1362 Log(fmt.Sprintf("Error in CLI continuous next episode prompt: %v", err))
1437 } else { 1363 break
1438 go func() {
1439 err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode)
1440 if err != nil {
1441 Log("Error updating Anilist progress: " + err.Error())
1442 } else {
1443 CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1444 }
1445 }()
1446 } 1364 }
1447 }
1448 1365
1449 // Close current MPV instance 1366 Log(fmt.Sprintf("CLI Continuous User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1450 ExitMPV(anime.Ep.Player.SocketPath)
1451 1367
1452 // Check if we have prefetched links for the next episode 1368 if selectedOption.Key == "-1" {
1453 if anime.Ep.NextEpisode.Number == anime.Ep.Number && len(anime.Ep.NextEpisode.Links) > 0 { 1369 // User selected to quit via the built-in quit option
1454 Log("Using prefetched next episode link") 1370
1455 anime.Ep.Links = anime.Ep.NextEpisode.Links 1371 // Check completion percentage
1456 } else { 1372 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
1457 // No prefetched links available, need to fetch them 1373
1458 CurdOut("Fetching links for next episode...") 1374 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
1375 // Episode is considered completed, mark it and update progress
1376 anime.Ep.IsCompleted = true
1377
1378 // Update local database
1379 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime))
1380 if err != nil {
1381 Log("Error updating local database on quit: " + err.Error())
1382 }
1459 1383
1460 // Wait for up to 5 seconds for prefetched links to become available 1384 // Update Anilist progress if not rewatching
1461 for i := 0; i < 5; i++ { 1385 if !anime.Rewatching {
1462 if anime.Ep.NextEpisode.Number == anime.Ep.Number && len(anime.Ep.NextEpisode.Links) > 0 { 1386 go func() {
1463 CurdOut("Using newly fetched next episode link") 1387 err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number)
1464 anime.Ep.Links = anime.Ep.NextEpisode.Links 1388 if err != nil {
1465 break 1389 Log("Error updating Anilist progress on quit: " + err.Error())
1390 } else {
1391 CurdOut(fmt.Sprintf("Episode marked as completed! Progress updated: %d", anime.Ep.Number))
1392 }
1393 }()
1394 }
1395
1396 CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched))
1397 } else {
1398 CurdOut(fmt.Sprintf("Episode not completed (%.1f%% watched). Exiting.", percentageWatched))
1466 } 1399 }
1467 time.Sleep(1 * time.Second) 1400
1401 ExitMPV(anime.Ep.Player.SocketPath)
1402 ExitCurd(nil)
1403 return
1468 } 1404 }
1469 1405
1470 // If we still don't have links, get them now 1406 if selectedOption.Key == "yes" {
1471 if len(anime.Ep.Links) == 0 { 1407 // User wants to start next episode immediately
1472 links, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number) 1408 anime.Ep.IsCompleted = true
1409
1410 // Update database with completed episode first
1411 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime))
1473 if err != nil { 1412 if err != nil {
1474 Log("Failed to get episode links: " + err.Error()) 1413 Log("Error updating local database with completed episode: " + err.Error())
1475 CurdOut("Failed to get episode links. Try again later.")
1476 ExitCurd(fmt.Errorf("failed to get episode links: %v", err))
1477 return
1478 } 1414 }
1479 anime.Ep.Links = links 1415
1416 // Update Anilist progress for the completed episode if not rewatching
1417 if !anime.Rewatching {
1418 go func() {
1419 err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number)
1420 if err != nil {
1421 Log("Error updating Anilist progress: " + err.Error())
1422 } else {
1423 CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
1424 }
1425 }()
1426 }
1427
1428 // Increment to next episode and update database with next episode number and 0 playback time
1429 anime.Ep.Number++
1430
1431 // Use prefetched links if available for the next episode
1432 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1433 anime.Ep.Links = anime.Ep.NextEpisode.Links
1434 Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number))
1435 } else {
1436 // Clear links to force fetching new ones
1437 anime.Ep.Links = []string{}
1438 Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
1439 }
1440
1441 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, GetAnimeName(*anime))
1442 if err != nil {
1443 Log("Error updating local database with next episode: " + err.Error())
1444 }
1445
1446 CurdOut("Starting next episode now...")
1447 ExitMPV(anime.Ep.Player.SocketPath)
1448 return // Exit this function, let the main loop handle next episode
1480 } 1449 }
1481 } 1450 }
1451}
1482 1452
1483 // Verify that we have links before starting 1453// Simple next episode prompt for Rofi mode - just asks if user wants to continue
1484 if len(anime.Ep.Links) == 0 { 1454func NextEpisodePromptRofi(userCurdConfig *CurdConfig) bool {
1485 CurdOut("No episode links found. Try again later.") 1455 anime := GetGlobalAnime()
1486 ExitCurd(fmt.Errorf("no episode links found")) 1456
1487 return 1457 // Show the next episode number that will be started
1458 nextEpisodeNum := anime.Ep.Number + 1
1459
1460 // Create options for the selection
1461 options := []SelectionOption{
1462 {Key: "yes", Label: fmt.Sprintf("Yes, start episode %d", nextEpisodeNum)},
1463 }
1464
1465 // Use DynamicSelect for Rofi mode
1466 selectedOption, err := DynamicSelect(options)
1467 if err != nil {
1468 Log(fmt.Sprintf("Error in next episode prompt selection: %v", err))
1469 return false
1488 } 1470 }
1489 1471
1490 // Actually start the next episode 1472 Log(fmt.Sprintf("Rofi User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1491 anime.Ep.Player.SocketPath = StartCurd(userCurdConfig, anime)
1492 1473
1493 // We don't exit, instead we let the main loop continue with the new episode 1474 return selectedOption.Key == "yes"
1494} 1475}
1495 1476
1496// StartNextEpisode handles the logic for starting the next episode 1477// StartNextEpisode handles the logic for starting the next episode
1497// It updates the episode number, resets necessary flags, and handles database updates 1478// It updates the episode number, resets necessary flags, and handles database updates
1498func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile string) { 1479func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1499 // Save previous episode number for progress update 1480 // Save previous episode number for progress update
1500 prevEpisode := anime.Ep.Number 1481 prevEpisode := anime.Ep.Number
1501 1482
1502 // Check if we just completed the last episode 1483 // Check if we just completed the last episode
1503 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes { 1484 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1504 // Handle scoring and completion for the last episode 1485 // Handle scoring and completion for the last episode
1505 HandleLastEpisodeCompletion(userCurdConfig, anime) 1486 HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
1506 1487
1507 // Update Anilist progress for the last episode if not rewatching 1488 // Update Anilist progress for the last episode if not rewatching
1508 if !anime.Rewatching { 1489 if !anime.Rewatching {
1509 user := &User{} 1490 go func() {
1510 var err error 1491 err := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1511 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token")) 1492 if err != nil {
1512 if err != nil { 1493 Log("Error updating Anilist progress: " + err.Error())
1513 Log("Error reading token for progress update: " + err.Error()) 1494 } else {
1514 } else { 1495 CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1515 go func() { 1496 }
1516 err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode) 1497 }()
1517 if err != nil {
1518 Log("Error updating Anilist progress: " + err.Error())
1519 } else {
1520 CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1521 }
1522 }()
1523 }
1524 } 1498 }
1525 1499
1526 CurdOut("Series completed!") 1500 CurdOut("Series completed!")
@@ -1538,28 +1512,14 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
1538 return 1512 return
1539 } 1513 }
1540 1514
1541 // Check if this is the last episode - prompt user if needed 1515 // Use prefetched links if available for the next episode
1542 if userCurdConfig.NextEpisodePrompt && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !userCurdConfig.RofiSelection { 1516 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1543 // Ensure the terminal state is clean for the prompt 1517 anime.Ep.Links = anime.Ep.NextEpisode.Links
1544 fmt.Print("\r\033[K") // Carriage return and clear line 1518 Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number))
1545 CurdOut(fmt.Sprintf("Last episode (%d). Are you sure you want to watch it?", anime.Ep.Number)) 1519 } else {
1546 1520 // Clear links to force fetching new ones
1547 // Simple yes/no selection for the last episode 1521 anime.Ep.Links = []string{}
1548 selectedOption, err := DynamicSelect([]SelectionOption{{Key: "yes", Label: "Yes"}}) 1522 Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
1549 if err != nil {
1550 ExitCurd(err)
1551 }
1552
1553 if selectedOption.Key != "yes" {
1554 // User selected to quitd
1555 fmt.Print("\r\033[K") // Carriage return and clear line
1556 CurdOut("Exiting without watching the last episode.")
1557 ExitCurd(nil)
1558 return
1559 }
1560
1561 // User chose to continue to the last episode
1562 fmt.Print("\r\033[K") // Carriage return and clear line
1563 } 1523 }
1564 1524
1565 // Reset episode flags 1525 // Reset episode flags
@@ -1577,20 +1537,14 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
1577 1537
1578 // Update Anilist progress for the previous episode if not rewatching 1538 // Update Anilist progress for the previous episode if not rewatching
1579 if !anime.Rewatching { 1539 if !anime.Rewatching {
1580 user := &User{} 1540 go func() {
1581 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token")) 1541 err = UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1582 if err != nil { 1542 if err != nil {
1583 Log("Error reading token for progress update: " + err.Error()) 1543 Log("Error updating Anilist progress: " + err.Error())
1584 } else { 1544 } else {
1585 go func() { 1545 CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1586 err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode) 1546 }
1587 if err != nil { 1547 }()
1588 Log("Error updating Anilist progress: " + err.Error())
1589 } else {
1590 CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1591 }
1592 }()
1593 }
1594 } 1548 }
1595 1549
1596 // Output message to user 1550 // Output message to user
@@ -1598,32 +1552,9 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
1598} 1552}
1599 1553
1600// HandleLastEpisodeCompletion handles scoring and completion for the last episode 1554// HandleLastEpisodeCompletion handles scoring and completion for the last episode
1601func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime) { 1555func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
1602 // Check if this is the last episode and scoring is enabled 1556 // Check if this is the last episode and scoring is enabled
1603 if userCurdConfig.ScoreOnCompletion && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes { 1557 if userCurdConfig.ScoreOnCompletion && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1604 // Get user token for scoring
1605 user := &User{}
1606
1607 // Get config for storage path
1608 homeDir := ""
1609 if runtime.GOOS == "windows" {
1610 homeDir = os.Getenv("USERPROFILE")
1611 } else {
1612 homeDir = os.Getenv("HOME")
1613 }
1614 configFilePath := filepath.Join(homeDir, ".config", "curd", "curd.conf")
1615 config, err := LoadConfig(configFilePath)
1616 if err != nil {
1617 Log("Error loading config for scoring: " + err.Error())
1618 return
1619 }
1620
1621 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "token"))
1622 if err != nil {
1623 Log("Error reading token for scoring: " + err.Error())
1624 return
1625 }
1626
1627 // Prompt user to score the anime 1558 // Prompt user to score the anime
1628 CurdOut("You've completed this anime! Would you like to rate it?") 1559 CurdOut("You've completed this anime! Would you like to rate it?")
1629 1560
@@ -1639,7 +1570,7 @@ func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime) {
1639 } 1570 }
1640 1571
1641 if selectedOption.Key == "yes" { 1572 if selectedOption.Key == "yes" {
1642 err = RateAnime(user.Token, anime.AnilistId) 1573 err = RateAnime(userToken, anime.AnilistId)
1643 if err != nil { 1574 if err != nil {
1644 Log(fmt.Sprintf("Error rating anime: %v", err)) 1575 Log(fmt.Sprintf("Error rating anime: %v", err))
1645 CurdOut("Failed to rate anime") 1576 CurdOut("Failed to rate anime")
@@ -1651,7 +1582,7 @@ func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime) {
1651 // Update anime status to completed on AniList 1582 // Update anime status to completed on AniList
1652 if !anime.Rewatching { 1583 if !anime.Rewatching {
1653 go func() { 1584 go func() {
1654 err = UpdateAnimeStatus(user.Token, anime.AnilistId, "COMPLETED") 1585 err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED")
1655 if err != nil { 1586 if err != nil {
1656 Log("Error updating anime status to completed: " + err.Error()) 1587 Log("Error updating anime status to completed: " + err.Error())
1657 } else { 1588 } else {