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```
360360| `SkipFiller` | Boolean | `true`, `false` | Skips filler episodes when supported. |
361361
362362## 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)
364363- 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)
367364- 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))
368365- Add a better way to do commands in windows (Convinience for users)
369366
cmd/curd/main.go +117 −62
@@ -329,9 +329,14 @@ func main() {
329329 }
330330
331331 anime.Ep.IsCompleted = true
332 if !userCurdConfig.NextEpisodePrompt || userCurdConfig.RofiSelection {
332 if !userCurdConfig.NextEpisodePrompt {
333333 // 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
335340 }
336341 // Send command to close MPV
337342 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
@@ -414,27 +419,20 @@ func main() {
414419 }
415420 }()
416421
417 // Thread to prompt for next episode in CLI Mode
422 // Thread for continuous next episode prompt in CLI mode (throughout episode duration)
418423 go func() {
419 if !userCurdConfig.RofiSelection && userCurdConfig.NextEpisodePrompt {
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
424 if userCurdConfig.NextEpisodePrompt && !userCurdConfig.RofiSelection {
425 internal.NextEpisodePromptContinuous(&userCurdConfig, databaseFile, user.Token)
426 // If the function returns, it means user made a decision
427 // Exit the skip loop - only close if not already closed
428 select {
429 case isClosed := <-skipLoopClosed:
430 if !isClosed {
431 close(skipLoopDone)
432 skipLoopClosed <- true // Mark as closed
437433 }
434 default:
435 // Channel is busy, another goroutine is handling closure
438436 }
439437 }
440438 }()
@@ -456,6 +454,11 @@ func main() {
456454 if err != nil {
457455 internal.Log("Error getting playback time: " + err.Error())
458456
457 // For CLI mode with next episode prompt, let the continuous prompt handle everything
458 if userCurdConfig.NextEpisodePrompt && !userCurdConfig.RofiSelection {
459 continue
460 }
461
459462 // Check if the error is due to invalid JSON
460463 // User closed the video
461464 if anime.Ep.Started {
@@ -469,20 +472,50 @@ func main() {
469472 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
470473 anime.Ep.IsCompleted = true
471474 if !userCurdConfig.NextEpisodePrompt {
472 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile)
475 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
473476 } else {
474 // When NextEpisodePrompt is enabled, show the prompt in both modes
477 // For Rofi mode, show prompt immediately after completion
475478 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
479 shouldContinue := internal.NextEpisodePromptRofi(&userCurdConfig)
480 if shouldContinue {
481 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
482 } else {
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 }
481504 } else {
482 // For CLI mode
483 internal.NextEpisodePrompt(&userCurdConfig)
484 return
505 // For CLI mode, let the continuous prompt handle it
506 internal.Log("Episode completed, exiting monitoring to let CLI prompt handle next episode")
485507 }
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
486519 }
487520 } else {
488521 internal.Log("Episode is not completed, exiting")
@@ -555,6 +588,11 @@ func main() {
555588 if err != nil {
556589 internal.Log("Error checking playback status: " + err.Error())
557590 } 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
558596 // Nothing is playing, check percentage watched
559597 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
560598 // fmt.Printf("[DEBUG] Playback stopped - Percentage watched: %d%%, Required: %d%%\n",
@@ -564,20 +602,50 @@ func main() {
564602 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
565603 anime.Ep.IsCompleted = true
566604 if !userCurdConfig.NextEpisodePrompt {
567 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile)
605 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
568606 } else {
569 // When NextEpisodePrompt is enabled, show the prompt in both modes
607 // For Rofi mode, show prompt immediately after completion
570608 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
609 shouldContinue := internal.NextEpisodePromptRofi(&userCurdConfig)
610 if shouldContinue {
611 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
612 } else {
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 }
576634 } else {
577 // For CLI mode
578 internal.NextEpisodePrompt(&userCurdConfig)
579 return
635 // For CLI mode, let the continuous prompt handle it
636 internal.Log("Episode completed, exiting monitoring to let CLI prompt handle next episode")
580637 }
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
581649 }
582650 } else {
583651 internal.Log("Episode is not completed, exiting")
@@ -697,29 +765,16 @@ func main() {
697765 // Handle next episode logic based on config
698766 if anime.Ep.IsCompleted {
699767 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")
768 if !userCurdConfig.RofiSelection {
769 // For CLI mode, the continuous prompt handles everything
770 internal.CurdOut("CLI mode: continuous prompt handling next episode logic")
718771 }
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.
719774 } 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
775 // When NextEpisodePrompt is off, continue automatically
776 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
777 continue
723778 }
724779 }
725780
internal/curd.go +162 −231
@@ -1088,39 +1088,6 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
10881088 anime.Ep.Number = anime.TotalEpisodes
10891089 }
10901090 }
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 }
11241091}
11251092
11261093// 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 {
13381305 }
13391306}
13401307
1341func NextEpisodePrompt(userCurdConfig *CurdConfig) {
1308func NextEpisodePromptCLI(userCurdConfig *CurdConfig) bool {
13421309 anime := GetGlobalAnime()
13431310
1344 // Check if we just completed the last episode
1345 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1346 // Handle scoring and completion for the last episode
1347 HandleLastEpisodeCompletion(userCurdConfig, anime)
1311 // Show the next episode number that will be started
1312 nextEpisodeNum := anime.Ep.Number + 1
1313 CurdOut(fmt.Sprintf("Start next episode (%d)?", nextEpisodeNum))
13481314
1349 // Exit after completing the series
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
1315 // Create options for the selection - no "quit" option since it's built into selection menu
13661316 options := []SelectionOption{
1367 {Key: "yes", Label: "Yes, start next episode"},
1368 // {Key: "-1", Label: "No, quit"},
1317 {Key: "yes", Label: fmt.Sprintf("Yes, continue to episode %d", nextEpisodeNum)},
13691318 }
13701319
1371 // Use DynamicSelect for both CLI and Rofi modes
1320 // Use DynamicSelect for CLI mode
13721321 selectedOption, err := DynamicSelect(options)
13731322 if err != nil {
1374 Log(fmt.Sprintf("Error in next episode prompt selection: %v", err))
1375 ExitCurd(err)
1323 Log(fmt.Sprintf("Error in CLI next episode prompt selection: %v", err))
1324 return false
13761325 }
13771326
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))
13791328
13801329 if selectedOption.Key == "-1" {
1381 // User selected to quit
1382 fmt.Print("\r\033[K") // Carriage return and clear line
1383 ExitMPV(anime.Ep.Player.SocketPath)
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
1330 // User selected to quit via the built-in quit option
1331 CurdOut("Exiting")
1332 return false
13971333 }
13981334
1399 // If yes, start the next episode
1400 prevEpisode := anime.Ep.Number
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
1335 return selectedOption.Key == "yes"
1336}
14071337
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 }
14091349
1410 // Get database file path for StartNextEpisode
1411 homeDir := ""
1412 if runtime.GOOS == "windows" {
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")
1350 // Show the next episode number that will be started
1351 nextEpisodeNum := anime.Ep.Number + 1
1352 CurdOut(fmt.Sprintf("Continue to next episode (%d) or quit?", nextEpisodeNum))
14241353
1425 // Update local database for the new episode
1426 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, GetAnimeName(*anime))
1427 if err != nil {
1428 Log("Error updating local database: " + err.Error())
1429 }
1354 // Create options for the selection - no "quit" option since it's built into selection menu
1355 options := []SelectionOption{
1356 {Key: "yes", Label: "Yes, start next episode now"},
1357 }
14301358
1431 // Update Anilist progress for the previous episode if not rewatching
1432 if !anime.Rewatching {
1433 user := &User{}
1434 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "token"))
1359 // Use DynamicSelect for CLI mode
1360 selectedOption, err := DynamicSelect(options)
14351361 if err != nil {
1436 Log("Error reading token for progress update: " + err.Error())
1437 } else {
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 }()
1362 Log(fmt.Sprintf("Error in CLI continuous next episode prompt: %v", err))
1363 break
14461364 }
1447 }
14481365
1449 // Close current MPV instance
1450 ExitMPV(anime.Ep.Player.SocketPath)
1366 Log(fmt.Sprintf("CLI Continuous User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
14511367
1452 // Check if we have prefetched links for the next episode
1453 if anime.Ep.NextEpisode.Number == anime.Ep.Number && len(anime.Ep.NextEpisode.Links) > 0 {
1454 Log("Using prefetched next episode link")
1455 anime.Ep.Links = anime.Ep.NextEpisode.Links
1456 } else {
1457 // No prefetched links available, need to fetch them
1458 CurdOut("Fetching links for next episode...")
1368 if selectedOption.Key == "-1" {
1369 // User selected to quit via the built-in quit option
1370
1371 // Check completion percentage
1372 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
1373
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 }
14591383
1460 // Wait for up to 5 seconds for prefetched links to become available
1461 for i := 0; i < 5; i++ {
1462 if anime.Ep.NextEpisode.Number == anime.Ep.Number && len(anime.Ep.NextEpisode.Links) > 0 {
1463 CurdOut("Using newly fetched next episode link")
1464 anime.Ep.Links = anime.Ep.NextEpisode.Links
1465 break
1384 // Update Anilist progress if not rewatching
1385 if !anime.Rewatching {
1386 go func() {
1387 err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number)
1388 if err != nil {
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))
14661399 }
1467 time.Sleep(1 * time.Second)
1400
1401 ExitMPV(anime.Ep.Player.SocketPath)
1402 ExitCurd(nil)
1403 return
14681404 }
14691405
1470 // If we still don't have links, get them now
1471 if len(anime.Ep.Links) == 0 {
1472 links, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1406 if selectedOption.Key == "yes" {
1407 // User wants to start next episode immediately
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))
14731412 if err != nil {
1474 Log("Failed to get episode links: " + 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
1413 Log("Error updating local database with completed episode: " + err.Error())
14781414 }
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
14801449 }
14811450 }
1451}
14821452
1483 // Verify that we have links before starting
1484 if len(anime.Ep.Links) == 0 {
1485 CurdOut("No episode links found. Try again later.")
1486 ExitCurd(fmt.Errorf("no episode links found"))
1487 return
1453// Simple next episode prompt for Rofi mode - just asks if user wants to continue
1454func NextEpisodePromptRofi(userCurdConfig *CurdConfig) bool {
1455 anime := GetGlobalAnime()
1456
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
14881470 }
14891471
1490 // Actually start the next episode
1491 anime.Ep.Player.SocketPath = StartCurd(userCurdConfig, anime)
1472 Log(fmt.Sprintf("Rofi User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
14921473
1493 // We don't exit, instead we let the main loop continue with the new episode
1474 return selectedOption.Key == "yes"
14941475}
14951476
14961477// StartNextEpisode handles the logic for starting the next episode
14971478// 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) {
14991480 // Save previous episode number for progress update
15001481 prevEpisode := anime.Ep.Number
15011482
15021483 // Check if we just completed the last episode
15031484 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
15041485 // Handle scoring and completion for the last episode
1505 HandleLastEpisodeCompletion(userCurdConfig, anime)
1486 HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
15061487
15071488 // Update Anilist progress for the last episode if not rewatching
15081489 if !anime.Rewatching {
1509 user := &User{}
1510 var err error
1511 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token"))
1512 if err != nil {
1513 Log("Error reading token for progress update: " + err.Error())
1514 } else {
1515 go func() {
1516 err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode)
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 }
1490 go func() {
1491 err := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1492 if err != nil {
1493 Log("Error updating Anilist progress: " + err.Error())
1494 } else {
1495 CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1496 }
1497 }()
15241498 }
15251499
15261500 CurdOut("Series completed!")
@@ -1538,28 +1512,14 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
15381512 return
15391513 }
15401514
1541 // Check if this is the last episode - prompt user if needed
1542 if userCurdConfig.NextEpisodePrompt && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !userCurdConfig.RofiSelection {
1543 // Ensure the terminal state is clean for the prompt
1544 fmt.Print("\r\033[K") // Carriage return and clear line
1545 CurdOut(fmt.Sprintf("Last episode (%d). Are you sure you want to watch it?", anime.Ep.Number))
1546
1547 // Simple yes/no selection for the last episode
1548 selectedOption, err := DynamicSelect([]SelectionOption{{Key: "yes", Label: "Yes"}})
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
1515 // Use prefetched links if available for the next episode
1516 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1517 anime.Ep.Links = anime.Ep.NextEpisode.Links
1518 Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number))
1519 } else {
1520 // Clear links to force fetching new ones
1521 anime.Ep.Links = []string{}
1522 Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
15631523 }
15641524
15651525 // Reset episode flags
@@ -1577,20 +1537,14 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
15771537
15781538 // Update Anilist progress for the previous episode if not rewatching
15791539 if !anime.Rewatching {
1580 user := &User{}
1581 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token"))
1582 if err != nil {
1583 Log("Error reading token for progress update: " + err.Error())
1584 } else {
1585 go func() {
1586 err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode)
1587 if err != nil {
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 }
1540 go func() {
1541 err = UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1542 if err != nil {
1543 Log("Error updating Anilist progress: " + err.Error())
1544 } else {
1545 CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1546 }
1547 }()
15941548 }
15951549
15961550 // Output message to user
@@ -1598,32 +1552,9 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
15981552}
15991553
16001554// HandleLastEpisodeCompletion handles scoring and completion for the last episode
1601func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime) {
1555func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
16021556 // Check if this is the last episode and scoring is enabled
16031557 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
16271558 // Prompt user to score the anime
16281559 CurdOut("You've completed this anime! Would you like to rate it?")
16291560
@@ -1639,7 +1570,7 @@ func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime) {
16391570 }
16401571
16411572 if selectedOption.Key == "yes" {
1642 err = RateAnime(user.Token, anime.AnilistId)
1573 err = RateAnime(userToken, anime.AnilistId)
16431574 if err != nil {
16441575 Log(fmt.Sprintf("Error rating anime: %v", err))
16451576 CurdOut("Failed to rate anime")
@@ -1651,7 +1582,7 @@ func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime) {
16511582 // Update anime status to completed on AniList
16521583 if !anime.Rewatching {
16531584 go func() {
1654 err = UpdateAnimeStatus(user.Token, anime.AnilistId, "COMPLETED")
1585 err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED")
16551586 if err != nil {
16561587 Log("Error updating anime status to completed: " + err.Error())
16571588 } else {