Commit 91d9fbbcc6

91d9fbbcc6d9dac0f3f2166dbc8e6a3e4afb2af8

parent: cd949d7fec

Unsigned

Wraient <wraient.911@gmail.com> · 2025-04-16 19:42 UTC

Fix:
- NextEpisodePrompt for cli
- prefetced url minor bug fixed

Layout: unified · split

cmd/curd/main.go +179 −41
@@ -231,18 +231,29 @@ func main() {
231231 // Create a channel to signal when to exit the skip loop
232232 var wg sync.WaitGroup
233233 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)
234236
235237 // Get MalId and CoverImage (only if discord presence is enabled)
236238 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)
240241 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
242245 }
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 }
246257 }
247258 } else if anime.MalId == 0 {
248259 anime.MalId, err = internal.GetAnimeMalID(anime.AnilistId)
@@ -316,18 +327,27 @@ func main() {
316327 internal.CurdOut(fmt.Sprint("Recap Episode, starting next episode: ", anime.Ep.Number+1))
317328 internal.Log("Recap episode detected")
318329 }
319 anime.Ep.Number++
320 anime.Ep.Started = false
330
321331 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 }
324336 // Send command to close MPV
325337 _, err := internal.MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
326338 if err != nil {
327339 internal.Log("Error closing MPV: " + err.Error())
328340 }
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 }
331351 }
332352 }
333353 }()
@@ -397,13 +417,25 @@ func main() {
397417 // Thread to prompt for next episode in CLI Mode
398418 go func() {
399419 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 }
407439 }
408440 }()
409441
@@ -435,18 +467,38 @@ func main() {
435467 internal.Log(fmt.Sprint(anime.Ep.Duration))
436468 internal.Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete))
437469 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
438 anime.Ep.Number++
439 anime.Ep.Started = false
440 internal.Log("Completed episode, starting next.")
441470 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 }
446487 } else {
447488 internal.Log("Episode is not completed, exiting")
448489 internal.ExitCurd(nil)
449490 }
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
450502 }
451503 }
452504
@@ -487,13 +539,10 @@ func main() {
487539 err = internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime))
488540 if err != nil {
489541 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))
493542 }
494543 }
495544
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
497546 hasPlayback, err := internal.HasActivePlayback(anime.Ep.Player.SocketPath)
498547 if err != nil {
499548 internal.Log("Error checking playback status: " + err.Error())
@@ -506,12 +555,44 @@ func main() {
506555 if err != nil {
507556 internal.Log("Error checking playback status: " + err.Error())
508557 } 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 }
515596 return
516597 }
517598 }
@@ -556,6 +637,12 @@ func main() {
556637 // Reset the WaitGroup for the next loop
557638 wg = sync.WaitGroup{}
558639
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
559646 if anime.Ep.IsCompleted && !anime.Rewatching {
560647 // Update progress for both regular episodes and skipped fillers
561648 if anime.TotalEpisodes > 0 && anime.Ep.Number-1 != anime.TotalEpisodes {
@@ -607,12 +694,63 @@ func main() {
607694 internal.ExitCurd(nil)
608695 }
609696
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
612746 }
613747
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 }
616754
617755 }
618756}
internal/curd.go +168 −4
@@ -1022,6 +1022,11 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
10221022 }
10231023 }
10241024
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 }
10251030}
10261031
10271032// 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 {
10471052
10481053 if anime.Ep.NextEpisode.Number == anime.Ep.Number {
10491054 anime.Ep.Links = anime.Ep.NextEpisode.Links
1050 fmt.Println("using prefetched next episode link")
1055 Log("using prefetched next episode link")
10511056 } else {
10521057 // Get episode link
10531058 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
@@ -1232,27 +1237,168 @@ func NextEpisodePrompt(userCurdConfig *CurdConfig) {
12321237
12331238 CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum))
12341239
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)
12361248 if err != nil {
1249 Log(fmt.Sprintf("Error in next episode prompt selection: %v", err))
12371250 ExitCurd(err)
12381251 }
12391252
12401253 if selectedOption.Key != "yes" {
1254 // User selected to quit
1255 fmt.Print("\r\033[K") // Carriage return and clear line
12411256 ExitMPV(anime.Ep.Player.SocketPath)
1257 CurdOut("Exiting without starting next episode")
12421258 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)
12431285 }
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
12451357}
12461358
12471359// StartNextEpisode handles the logic for starting the next episode
12481360// It updates the episode number, resets necessary flags, and handles database updates
12491361func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile string) {
1362 // Save previous episode number for progress update
1363 prevEpisode := anime.Ep.Number
1364
12501365 // Increment episode number
12511366 anime.Ep.Number++
12521367
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
12531399 // Reset episode flags
12541400 anime.Ep.Started = false
1255 anime.Ep.IsCompleted = true
1401 anime.Ep.IsCompleted = false
12561402
12571403 // Log the transition
12581404 Log("Completed episode, starting next.")
@@ -1263,6 +1409,24 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
12631409 Log("Error updating local database: " + err.Error())
12641410 }
12651411
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
12661430 // Output message to user
12671431 CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
12681432}
internal/player.go +149 −51
@@ -127,6 +127,33 @@ func StartVideo(link string, args []string, title string, anime *Anime) (string,
127127 CurdOut("Error: Failed to start mpv process")
128128 return "", fmt.Errorf("failed to start mpv: %w", err)
129129 }
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
130157 return mpvSocketPath, nil
131158}
132159
@@ -143,42 +170,70 @@ func joinArgs(args []string) string {
143170}
144171
145172func 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 }
151183
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()
158191
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 }
164198
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 }
171206
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 }
176213
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
179233 }
180234
181 return nil, nil
235 // All retries failed
236 return nil, fmt.Errorf("command failed after %d attempts: %w", maxRetries, lastErr)
182237}
183238
184239func SeekMPV(ipcSocketPath string, time int) (interface{}, error) {
@@ -245,24 +300,49 @@ func PercentageWatched(playbackTime int, duration int) float64 {
245300}
246301
247302func 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)
255332 }
256 return false, fmt.Errorf("error getting time-pos: %w", err)
257 }
258333
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
262341 }
263342
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)
266346}
267347
268348func IsMPVRunning(socketPath string) bool {
@@ -270,16 +350,34 @@ func IsMPVRunning(socketPath string) bool {
270350 return false
271351 }
272352
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))
277377 }
278 defer conn.Close()
279378
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
283381}
284382
285383func ExitMPV(ipcSocketPath string) error {
internal/selection_menu.go +7 −2
@@ -380,7 +380,7 @@ func RofiSelect(options map[string]string) (SelectionOption, error) {
380380
381381 // Add "Quit" options
382382 optionsList = append(optionsList, "Quit")
383
383
384384 // Join all options into a single string, separated by newlines
385385 optionsString := strings.Join(optionsList, "\n")
386386
@@ -458,12 +458,13 @@ func DynamicSelect(options map[string]string) (SelectionOption, error) {
458458 filteredKeys: orderedOptions,
459459 }
460460
461
462461 model.filteredKeys = append(model.filteredKeys, SelectionOption{
463462 Label: "Quit",
464463 Key: "-1",
465464 })
466465
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
467468 p := tea.NewProgram(model)
468469
469470 finalModel, err := p.Run()
@@ -471,6 +472,10 @@ func DynamicSelect(options map[string]string) (SelectionOption, error) {
471472 return SelectionOption{}, err
472473 }
473474
475 // Explicitly reset the terminal state
476 fmt.Print("\033[?25h") // Show cursor
477 fmt.Print("\033[?7h") // Enable line wrapping
478
474479 finalSelectionModel, ok := finalModel.(*Model)
475480 if !ok {
476481 return SelectionOption{}, fmt.Errorf("unexpected model type")