internal/curd.go
2057 lines · 67399 bytes
1package internal
2
3import (
4 "crypto/md5"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "regexp"
13 "runtime"
14 "strconv"
15 "strings"
16 "time"
17
18 "github.com/gen2brain/beeep"
19 "github.com/pkg/browser"
20)
21
22var alternateScreenActive bool
23
24func EditConfig(configFilePath string) {
25 // Get the user's preferred editor from the EDITOR environment variable
26 editor := os.Getenv("EDITOR")
27 if editor == "" {
28 // If EDITOR is not set, use system-specific defaults
29 if runtime.GOOS == "windows" {
30 // Try Notepad++ first
31 if _, err := exec.LookPath("notepad++"); err == nil {
32 editor = "notepad++"
33 } else {
34 editor = "notepad.exe"
35 }
36 } else {
37 if _, err := exec.LookPath("vim"); err == nil {
38 editor = "vim"
39 } else {
40 editor = "nano"
41 }
42 }
43 }
44
45 // Construct the command to open the config file
46 cmd := exec.Command(editor, configFilePath)
47
48 // Set the command to run in the current terminal
49 cmd.Stdin = os.Stdin
50 cmd.Stdout = os.Stdout
51 cmd.Stderr = os.Stderr
52
53 // Run the editor command
54 err := cmd.Run()
55 if err != nil {
56 CurdOut(fmt.Sprintf("Error opening config file: %v", err))
57 return
58 }
59
60 CurdOut("Config file edited successfully.")
61}
62
63// ClearLogFile removes all contents from the specified log file
64func ClearLogFile(logFile string) error {
65 if err := os.MkdirAll(filepath.Dir(logFile), 0755); err != nil {
66 return fmt.Errorf("failed to create log directory: %w", err)
67 }
68
69 // Open the file with truncate flag to clear its contents.
70 file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
71 if err != nil {
72 return fmt.Errorf("failed to open log file: %w", err)
73 }
74 defer file.Close()
75
76 return nil
77}
78
79// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
80func Log(data interface{}) error {
81 logFile := GetGlobalLogFile()
82 // Open or create the log file
83 file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
84 if err != nil {
85 return err
86 }
87 defer file.Close()
88
89 // Attempt to marshal the data into JSON
90 jsonData, err := json.Marshal(data)
91 if err != nil {
92 return err
93 }
94
95 // Get the caller information
96 _, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
97 if !ok {
98 return fmt.Errorf("unable to get caller information")
99 }
100
101 // Log the current time and the JSON representation along with caller info
102 currentTime := time.Now().Format("2006/01/02 15:04:05")
103 logMessage := fmt.Sprintf("[LOG] %s %s:%d: %s\n", currentTime, filename, lineNumber, jsonData)
104 _, err = fmt.Fprint(file, logMessage) // Write to the file
105 if err != nil {
106 return err
107 }
108
109 return nil
110}
111
112// ClearScreen clears the terminal screen and saves the state
113func ClearScreen() {
114 userCurdConfig := GetGlobalConfig()
115 if userCurdConfig == nil {
116 return
117 }
118
119 if userCurdConfig.AlternateScreen == false {
120 return
121 }
122
123 fmt.Print("\033[?1049h") // Switch to alternate screen buffer
124 fmt.Print("\033[2J") // Clear the entire screen
125 fmt.Print("\033[H") // Move cursor to the top left
126 alternateScreenActive = true
127}
128
129// RestoreScreen restores the original terminal state
130func RestoreScreen() {
131 if !alternateScreenActive {
132 return
133 }
134
135 fmt.Print("\033[?1049l") // Switch back to the main screen buffer
136 alternateScreenActive = false
137}
138
139func ExitCurd(err error) {
140 RestoreScreen()
141
142 anime := GetGlobalAnime()
143 socketPath := ""
144 if (anime != nil) && (anime.Ep.Player.SocketPath != "") {
145 socketPath = anime.Ep.Player.SocketPath
146 _, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
147 if err != nil {
148 Log("Error closing MPV: " + err.Error())
149 }
150 }
151
152 CurdOut("Have a great day!")
153 // If the error is not about the connection refused, print the error
154 if err != nil && (socketPath == "" || !strings.Contains(err.Error(), "dial unix "+socketPath+": connect: connection refused")) {
155 CurdOut(fmt.Sprintf("Error: %v", err))
156 if runtime.GOOS == "windows" {
157 fmt.Println("Press Enter to exit")
158 var wait string
159 fmt.Scanln(&wait)
160 exitWithRestore(1)
161 } else {
162 exitWithRestore(1)
163 }
164 }
165 exitWithRestore(0)
166}
167
168func CurdOut(data interface{}) {
169 userCurdConfig := GetGlobalConfig()
170 if userCurdConfig == nil {
171 userCurdConfig = &CurdConfig{}
172 }
173 if !userCurdConfig.RofiSelection {
174 fmt.Println(fmt.Sprintf("%v", data))
175 } else {
176 switch runtime.GOOS {
177 case "windows":
178 err := beeep.Notify(
179 "Curd",
180 fmt.Sprintf("%v", data),
181 "",
182 )
183
184 if err != nil {
185 Log(fmt.Sprintf("Failed to send notification: %v", err))
186 }
187 case "linux":
188 // Check if the input starts with "-i" for image notification
189 dataStr := fmt.Sprintf("%v", data)
190 if strings.HasPrefix(dataStr, "-i") && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
191 // Split the string to get image path and message
192 parts := strings.SplitN(dataStr, " ", 3)
193 if len(parts) == 3 {
194 // Remove quotes from the message
195 message := strings.Trim(parts[2], "\"")
196 cmd := exec.Command("notify-send",
197 "-a", "Curd",
198 "-h", "string:x-canonical-private-synchronous:curd-notification",
199 "Curd",
200 "-i", parts[1],
201 message)
202 err := cmd.Run()
203 if err != nil {
204 Log(fmt.Sprintf("%v", cmd))
205 Log(fmt.Sprintf("Failed to send notification: %v", err))
206 }
207 }
208 } else {
209 cmd := exec.Command("notify-send",
210 "-a", "Curd",
211 "-h", "string:x-canonical-private-synchronous:curd-notification",
212 "Curd",
213 dataStr)
214 err := cmd.Run()
215 if err != nil {
216 Log(fmt.Sprintf("%v", cmd))
217 Log(fmt.Sprintf("Failed to send notification: %v", err))
218 }
219 }
220 }
221 }
222}
223
224func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
225 if !UsesRemoteTracking(userCurdConfig) {
226 CurdOut("Remote tracking is disabled in your config.")
227 return
228 }
229
230 // Create update options
231 updateOptions := []SelectionOption{
232 {Key: "CATEGORY", Label: "Change Anime Category"},
233 {Key: "PROGRESS", Label: "Change Progress"},
234 {Key: "SCORE", Label: "Add/Change Score"},
235 }
236
237 // Navigation loop for update option selection
238updateOptionLoop:
239 for {
240 // Select update option
241 updateSelection, err := DynamicSelect(updateOptions)
242 if err != nil {
243 Log(fmt.Sprintf("Failed to select update option: %v", err))
244 ExitCurd(fmt.Errorf("Failed to select update option"))
245 }
246
247 if updateSelection.Key == "-1" {
248 ExitCurd(nil)
249 }
250
251 // Back from update selection returns to home menu
252 if updateSelection.Key == "-2" {
253 return // Return to caller (home menu)
254 }
255
256 // Get user's anime list
257 var animeListOptions []SelectionOption
258 var animeListMapPreview map[string]RofiSelectPreview
259
260 if user.ListSync != nil {
261 user.AnimeList = user.ListSync.Current()
262 }
263
264 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
265 animeListMapPreview = buildCategoryPreviewOptions(user.AnimeList, "ALL")
266 } else {
267 animeListOptions = buildCategorySelectionOptions(user.AnimeList, "ALL")
268 }
269
270 // Anime selection loop
271 animeSelectLoop:
272 for {
273 // Select anime to update
274 var selectedAnime SelectionOption
275 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
276 selectedAnime, err = DynamicSelectPreviewWithRefresh(animeListMapPreview, false, &PreviewSelectionRefreshConfig{
277 Updates: user.ListSync.Updates(),
278 BuildOptions: func(list AnimeList) map[string]RofiSelectPreview {
279 return buildCategoryPreviewOptions(list, "ALL")
280 },
281 })
282 } else {
283 selectedAnime, err = DynamicSelectWithRefresh(animeListOptions, &SelectionRefreshConfig{
284 Updates: user.ListSync.Updates(),
285 BuildOptions: func(list AnimeList) []SelectionOption {
286 return buildCategorySelectionOptions(list, "ALL")
287 },
288 })
289 }
290 if err != nil {
291 Log(fmt.Sprintf("Failed to select anime: %v", err))
292 ExitCurd(fmt.Errorf("Failed to select anime"))
293 }
294
295 if selectedAnime.Key == "-1" {
296 ExitCurd(nil)
297 }
298
299 // Back from anime selection goes to update option selection
300 if selectedAnime.Key == "-2" {
301 ClearScreen()
302 continue updateOptionLoop
303 }
304
305 animeID, err := strconv.Atoi(selectedAnime.Key)
306 if err != nil {
307 Log(fmt.Sprintf("Failed to convert anime ID: %v", err))
308 ExitCurd(fmt.Errorf("Failed to convert anime ID"))
309 }
310
311 if user.ListSync != nil {
312 user.AnimeList = user.ListSync.Current()
313 }
314
315 // After getting animeID, get the current anime entry
316 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key)
317 if err != nil {
318 Log(fmt.Sprintf("Can not find the anime in tracked anime list: %v", err))
319 ExitCurd(fmt.Errorf("Can not find the anime in tracked anime list"))
320 }
321 ClearScreen()
322
323 // Final selection loop (for category/progress/score)
324 for {
325 switch updateSelection.Key {
326 case "CATEGORY":
327 categories := []SelectionOption{
328 {Key: "CURRENT", Label: "Currently Watching"},
329 {Key: "COMPLETED", Label: "Completed"},
330 {Key: "PAUSED", Label: "On Hold"},
331 {Key: "DROPPED", Label: "Dropped"},
332 {Key: "PLANNING", Label: "Plan to Watch"},
333 {Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
334 }
335
336 currentStatus := "None"
337 if selectedAnilistAnime.Status != "" {
338 // Find the label for the current status
339 for _, cat := range categories {
340 if cat.Key == selectedAnilistAnime.Status {
341 currentStatus = cat.Label
342 break
343 }
344 }
345 }
346 CurdOut(fmt.Sprintf("Current category: %s", currentStatus))
347
348 categorySelection, err := DynamicSelect(categories)
349 if err != nil {
350 Log(fmt.Sprintf("Failed to select category: %v", err))
351 ExitCurd(fmt.Errorf("Failed to select category"))
352 }
353
354 if categorySelection.Key == "-1" {
355 ExitCurd(nil)
356 }
357
358 // Back from category selection goes to anime selection
359 if categorySelection.Key == "-2" {
360 ClearScreen()
361 continue animeSelectLoop
362 }
363
364 err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
365 if err != nil {
366 Log(fmt.Sprintf("Failed to update anime status: %v", err))
367 ExitCurd(fmt.Errorf("Failed to update anime status"))
368 }
369
370 case "PROGRESS":
371 currentProgress := "None"
372 if selectedAnilistAnime.Progress > 0 {
373 currentProgress = strconv.Itoa(selectedAnilistAnime.Progress)
374 }
375
376 var progress string
377 if userCurdConfig.RofiSelection {
378 progress, err = GetUserInputFromRofi(fmt.Sprintf("Current progress: %s - Enter new progress (episode number)", currentProgress))
379 if err != nil {
380 Log(fmt.Sprintf("Failed to get progress input: %v", err))
381 ExitCurd(fmt.Errorf("Failed to get progress input"))
382 }
383 } else {
384 CurdOut(fmt.Sprintf("Current progress: %s", currentProgress))
385 CurdOut("Enter new progress (episode number):")
386 fmt.Scanln(&progress)
387 }
388
389 progressNum, err := parseNonNegativeIntInput(progress, "progress")
390 if err != nil {
391 Log(fmt.Sprintf("Failed to convert progress to number: %v", err))
392 ExitCurd(fmt.Errorf("Failed to convert progress to number"))
393 }
394
395 err = UpdateAnimeProgress(user.Token, animeID, progressNum)
396 if err != nil {
397 Log(fmt.Sprintf("Failed to update anime progress: %v", err))
398 ExitCurd(fmt.Errorf("Failed to update anime progress"))
399 }
400
401 case "SCORE":
402 currentScore := "None"
403 if selectedAnilistAnime.Score > 0 {
404 currentScore = strconv.Itoa(int(selectedAnilistAnime.Score))
405 }
406 CurdOut(fmt.Sprintf("Current score: %s", currentScore))
407
408 err = RateAnime(user.Token, animeID)
409 if err != nil {
410 Log(fmt.Sprintf("Failed to update anime score: %v", err))
411 ExitCurd(fmt.Errorf("Failed to update anime score"))
412 }
413 }
414
415 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
416 Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
417 ExitCurd(fmt.Errorf("Failed to refresh anime list"))
418 }
419
420 CurdOut("Anime updated successfully!")
421 return
422 }
423 }
424 }
425}
426
427func UpdateCurd(repo, fileName string) error {
428 // Get the path of the currently running executable
429 executablePath, err := os.Executable()
430 if err != nil {
431 return fmt.Errorf("unable to find current executable: %v", err)
432 }
433 // Resolve symlinks so we replace the real binary (e.g. /usr/local/bin/curd).
434 if resolved, resolveErr := filepath.EvalSymlinks(executablePath); resolveErr == nil && resolved != "" {
435 executablePath = resolved
436 }
437
438 binaryName, err := curdReleaseBinaryName()
439 if err != nil {
440 return err
441 }
442 _ = fileName // retained for call-site compatibility
443
444 if strings.TrimSpace(repo) == "" {
445 repo = defaultUpdateRepo
446 }
447 // GitHub release URL for curd
448 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName)
449
450 // Prefer a temp file next to the executable (same filesystem → atomic rename).
451 // Fall back to OS temp dir when the install dir is not writable (e.g. /usr/bin).
452 tmpPath, out, err := createUpdateTempFile(executablePath, binaryName)
453 if err != nil {
454 return fmt.Errorf("failed to create temporary file: %v", err)
455 }
456
457 // Download the curd executable
458 client := sharedHTTPClient
459 if client == nil {
460 client = &http.Client{Timeout: 5 * time.Minute}
461 }
462 resp, err := client.Get(url)
463 if err != nil {
464 out.Close()
465 _ = os.Remove(tmpPath)
466 return fmt.Errorf("failed to download file: %v", err)
467 }
468 defer resp.Body.Close()
469
470 // Check if the download was successful
471 if resp.StatusCode != http.StatusOK {
472 out.Close()
473 _ = os.Remove(tmpPath)
474 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
475 }
476
477 // Copy the downloaded content to the temporary file
478 if _, err := io.Copy(out, resp.Body); err != nil {
479 out.Close()
480 _ = os.Remove(tmpPath)
481 return fmt.Errorf("failed to write to temporary file: %v", err)
482 }
483 if err := out.Chmod(0755); err != nil {
484 out.Close()
485 _ = os.Remove(tmpPath)
486 return fmt.Errorf("failed to set file permissions: %v", err)
487 }
488 if err := out.Close(); err != nil {
489 _ = os.Remove(tmpPath)
490 return fmt.Errorf("failed to close temporary file: %v", err)
491 }
492
493 // Replace the old executable (prompts for sudo if the install path is not writable).
494 if err := replaceExecutable(tmpPath, executablePath); err != nil {
495 _ = os.Remove(tmpPath)
496 return err
497 }
498 return nil
499}
500
501func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
502 var query string
503 // Remove the redeclared variable declaration since animeOptions is already declared above
504 var animeMapPreview map[string]RofiSelectPreview
505 var animeOptions []SelectionOption
506 var err error
507 var anilistSelectedOption SelectionOption
508
509 query, err = promptText(userCurdConfig, "Enter the anime name", false)
510 if err != nil {
511 Log("Error getting user input: " + err.Error())
512 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
513 }
514 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
515 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
516 } else {
517 animeOptions, err = SearchAnimeAnilist(query, user.Token)
518 if err != nil {
519 Log(fmt.Sprintf("Failed to search anime: %v", err))
520 ExitCurd(fmt.Errorf("Failed to search anime"))
521 }
522 }
523 if err != nil {
524 Log(fmt.Sprintf("Failed to search anime: %v", err))
525 ExitCurd(fmt.Errorf("Failed to search anime"))
526 }
527 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
528 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
529 } else {
530 anilistSelectedOption, err = DynamicSelect(animeOptions)
531 }
532 if err != nil {
533 Log(fmt.Sprintf("No anime available: %v", err))
534 ExitCurd(fmt.Errorf("No anime available"))
535 }
536
537 if anilistSelectedOption.Key == "-1" {
538 ExitCurd(nil)
539 }
540
541 // Handle back button - return to caller
542 if anilistSelectedOption.Key == "-2" {
543 return SelectionOption{Key: "-2", Label: "Back"}
544 }
545
546 animeID, err := strconv.Atoi(anilistSelectedOption.Key)
547 if err != nil {
548 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err))
549 ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
550 }
551
552 if !UsesRemoteTracking(userCurdConfig) {
553 return anilistSelectedOption
554 }
555
556 // Add category selection before adding to list
557 categories := []SelectionOption{
558 {Key: "CURRENT", Label: "Currently Watching"},
559 {Key: "COMPLETED", Label: "Completed"},
560 {Key: "PAUSED", Label: "On Hold"},
561 {Key: "DROPPED", Label: "Dropped"},
562 {Key: "PLANNING", Label: "Plan to Watch"},
563 {Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
564 }
565
566 ClearScreen()
567 CurdOut("Select which list to add the anime to:")
568
569 categorySelection, err := DynamicSelect(categories)
570 if err != nil {
571 Log(fmt.Sprintf("Failed to select category: %v", err))
572 ExitCurd(fmt.Errorf("Failed to select category"))
573 }
574
575 if categorySelection.Key == "-1" {
576 ExitCurd(nil)
577 }
578
579 // Handle back button - return to caller
580 if categorySelection.Key == "-2" {
581 return SelectionOption{Key: "-2", Label: "Back"}
582 }
583
584 err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
585 if err != nil {
586 Log(fmt.Sprintf("Failed to add anime to list: %v", err))
587 ExitCurd(fmt.Errorf("Failed to add anime to list"))
588 }
589
590 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
591 Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
592 ExitCurd(fmt.Errorf("Failed to refresh anime list"))
593 }
594
595 return anilistSelectedOption
596}
597
598func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) {
599 var err error
600 var startingRewatch bool
601
602 // Filter anime list based on selected category
603 var animeListOptions []SelectionOption
604 var animeListMapPreview map[string]RofiSelectPreview
605
606 // Initialize anime list. On a cache hit this is instant (reads from disk) and
607 // the user ID is seeded from the cached payload, avoiding a blocking network
608 // round-trip to AniList. The real user ID + latest list are refreshed in the
609 // background goroutine inside InitializeUserAnimeList.
610 if err := InitializeUserAnimeList(userCurdConfig, user); err != nil {
611 Log(fmt.Sprintf("Failed to initialize anime list: %v", err))
612 ExitCurd(fmt.Errorf("Failed to get user data\nYou can reset the token by running `curd -change-token`"))
613 }
614
615 // Variables for selection results (used in both branches and after)
616 var anilistSelectedOption SelectionOption
617 var selectedAllanimeAnime SelectionOption
618 var userQuery string
619 _ = selectedAllanimeAnime // Used later in the function
620
621 // Navigation loop for the entire setup process
622 for {
623 startingRewatch = false
624
625 // If continueLast flag is set, directly get the last watched anime
626 if anime.Ep.ContinueLast {
627 // Get the last anime ID from the curd_id file
628 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
629 idBytes, err := os.ReadFile(idFilePath)
630 if err != nil {
631 Log("Error reading curd_id file: " + err.Error())
632 ExitCurd(fmt.Errorf("No last watched anime found"))
633 }
634
635 anilistID, err := strconv.Atoi(string(idBytes))
636 if err != nil {
637 Log("Error converting anilist ID: " + err.Error())
638 ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
639 }
640
641 // Find the anime in database
642 animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
643 if animePointer == nil {
644 ExitCurd(fmt.Errorf("Last watched anime not found in database"))
645 }
646
647 // Set the anime details
648 anime.AnilistId = animePointer.AnilistId
649 anilistSelectedOption.Key = strconv.Itoa(animePointer.AnilistId)
650 // anime.ProviderId = animePointer.ProviderId
651 // anime.Title = animePointer.Title
652 // anime.Ep.Number = animePointer.Ep.Number
653 // anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
654 // anime.Ep.Resume = true
655
656 } else {
657 // Navigation loop for category and anime selection
658 categorySelectionLoop:
659 for {
660 // Skip category selection if Current flag is set
661 var categorySelection SelectionOption
662 if userCurdConfig.CurrentCategory {
663 categorySelection = SelectionOption{
664 Key: "CURRENT",
665 Label: "Currently Watching",
666 }
667 } else {
668 // Create category selection map
669 // Get ordered categories
670 orderedCategories := getOrderedCategories(userCurdConfig)
671
672 // Use DynamicSelect with ordered categories directly
673 categorySelection, err = DynamicSelect(orderedCategories)
674
675 if err != nil {
676 Log(fmt.Sprintf("Failed to select category: %v", err))
677 ExitCurd(fmt.Errorf("Failed to select category"))
678 }
679
680 categorySelection = NormalizeSelectionKey(categorySelection)
681 if SelectionMeansQuit(categorySelection) {
682 ExitCurd(nil)
683 }
684
685 if SelectionMeansBack(categorySelection) {
686 continue
687 }
688 if categorySelection.Key == "" {
689 // Empty/cancelled selection — re-show category menu.
690 continue
691 }
692
693 // Handle options
694 if categorySelection.Key == "PROVIDER" {
695 ClearScreen()
696 ChangeProvider(userCurdConfig)
697 ClearScreen()
698 continue categorySelectionLoop
699 } else if categorySelection.Key == "TRACKER" {
700 ClearScreen()
701 ChangeTracker(userCurdConfig, user)
702 ClearScreen()
703 continue categorySelectionLoop
704 } else if categorySelection.Key == "UPDATE" {
705 ClearScreen()
706 UpdateAnimeEntry(userCurdConfig, user)
707 // If UpdateAnimeEntry returns, user pressed back - continue to category selection
708 ClearScreen()
709 continue categorySelectionLoop
710 } else if categorySelection.Key == "UNTRACKED" {
711 ClearScreen()
712 WatchUntracked(userCurdConfig)
713 // If WatchUntracked returns, user pressed back OR watched is done- continue to category selection
714 ClearScreen()
715 continue categorySelectionLoop
716 } else if categorySelection.Key == "REMAP_PROVIDER" {
717 ClearScreen()
718 RemapProviderAnime(userCurdConfig, user, databaseAnimes)
719 ClearScreen()
720 continue categorySelectionLoop
721 } else if categorySelection.Key == "CONTINUE_LAST" {
722 anime.Ep.ContinueLast = true
723 }
724
725 ClearScreen()
726 }
727
728 if user.ListSync != nil {
729 user.AnimeList = user.ListSync.Current()
730 }
731
732 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
733 animeListMapPreview = buildCategoryPreviewOptions(user.AnimeList, categorySelection.Key)
734 } else {
735 animeListOptions = buildCategorySelectionOptions(user.AnimeList, categorySelection.Key)
736 }
737
738 // Anime selection loop (for back navigation)
739 animeSelectionLoop:
740 for {
741 if anime.Ep.ContinueLast {
742 // Get the last watched anime ID from the curd_id file
743 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
744 curdIDBytes, err := os.ReadFile(curdIDPath)
745 if err != nil {
746 Log(fmt.Sprintf("Error reading curd_id file: %v", err))
747 ExitCurd(fmt.Errorf("Error reading curd_id file"))
748 }
749
750 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
751 if err != nil {
752 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err))
753 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
754 }
755
756 anime.AnilistId = lastWatchedID
757 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
758 break categorySelectionLoop
759 }
760
761 // Select anime to watch (Anilist)
762 var err error
763 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
764 anilistSelectedOption, err = DynamicSelectPreviewWithRefresh(animeListMapPreview, true, &PreviewSelectionRefreshConfig{
765 Updates: user.ListSync.Updates(),
766 BuildOptions: func(list AnimeList) map[string]RofiSelectPreview {
767 return buildCategoryPreviewOptions(list, categorySelection.Key)
768 },
769 })
770 } else {
771 // Add "Add new anime" option to the slice
772 tempOptions := make([]SelectionOption, len(animeListOptions))
773 copy(tempOptions, animeListOptions)
774
775 tempOptions = append(tempOptions, SelectionOption{
776 Key: "add_new",
777 Label: "Add new anime",
778 })
779
780 anilistSelectedOption, err = DynamicSelectWithRefresh(tempOptions, &SelectionRefreshConfig{
781 Updates: user.ListSync.Updates(),
782 BuildOptions: func(list AnimeList) []SelectionOption {
783 updatedOptions := buildCategorySelectionOptions(list, categorySelection.Key)
784
785 updatedOptions = append(updatedOptions, SelectionOption{
786 Key: "add_new",
787 Label: "Add new anime",
788 })
789 return updatedOptions
790 },
791 })
792 }
793 if err != nil {
794 Log(fmt.Sprintf("Error selecting anime: %v", err))
795 ExitCurd(fmt.Errorf("Error selecting anime"))
796 }
797
798 Log(anilistSelectedOption)
799
800 anilistSelectedOption = NormalizeSelectionKey(anilistSelectedOption)
801 if SelectionMeansQuit(anilistSelectedOption) {
802 ExitCurd(nil)
803 }
804
805 // Handle back navigation - go back to category selection
806 if SelectionMeansBack(anilistSelectedOption) {
807 if userCurdConfig.CurrentCategory {
808 // If CurrentCategory is forced, back means quit
809 ExitCurd(nil)
810 }
811 ClearScreen()
812 continue categorySelectionLoop
813 }
814 if anilistSelectedOption.Key == "" {
815 continue animeSelectionLoop
816 }
817
818 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
819 addResult := AddNewAnime(userCurdConfig, anime, user, databaseAnimes)
820 if addResult.Key == "-2" {
821 // Back from add new anime goes to anime selection
822 ClearScreen()
823 continue animeSelectionLoop
824 }
825 anilistSelectedOption = addResult
826 }
827
828 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
829 if err != nil {
830 Log(fmt.Sprintf("Error converting Anilist ID: %v", err))
831 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
832 }
833
834 // Successfully selected anime, break out of both loops
835 break categorySelectionLoop
836 }
837 }
838 }
839 // Wait for the background refresh goroutine to finish before reading
840 // progress+1. RefreshDone() is a channel that is closed (broadcast) the
841 // instant the goroutine completes — no polling, no race with the UI
842 // Updates consumer that already drained the updates channel.
843 if user.ListSync != nil {
844 select {
845 case <-user.ListSync.RefreshDone():
846 Log("Background refresh done, using latest anime list for playback")
847 case <-time.After(10 * time.Second):
848 Log("Timed out waiting for background anime list refresh; using cached list")
849 }
850 user.AnimeList = user.ListSync.Current()
851 }
852
853 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
854
855 // Get anime entry
856 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
857 if err != nil {
858 if UsesRemoteTracking(userCurdConfig) {
859 Log(fmt.Sprintf("Can not find the anime in tracked anime list: %v", err))
860 ExitCurd(fmt.Errorf("Can not find the anime in tracked anime list"))
861 }
862
863 fallbackAnime, fallbackErr := GetAnimeDataByID(anime.AnilistId, "")
864 if fallbackErr != nil {
865 Log(fmt.Sprintf("Failed to fetch fallback anime data: %v", fallbackErr))
866 ExitCurd(fmt.Errorf("Failed to get anime data"))
867 }
868
869 selectedAnilistAnime = &Entry{
870 Media: Media{
871 ID: fallbackAnime.AnilistId,
872 MalID: fallbackAnime.MalId,
873 Episodes: fallbackAnime.TotalEpisodes,
874 Title: fallbackAnime.Title,
875 Status: "FINISHED",
876 },
877 Progress: 0,
878 Status: "CURRENT",
879 CoverImage: fallbackAnime.CoverImage,
880 }
881 }
882
883 if selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED" {
884 handleUnreleasedAnime(userCurdConfig, user, anime, *selectedAnilistAnime)
885 ClearScreen()
886 continue
887 }
888
889 // Set anime entry
890 anime.Title = selectedAnilistAnime.Media.Title
891 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
892 anime.CoverImage = selectedAnilistAnime.CoverImage
893 if selectedAnilistAnime.Media.MalID != 0 {
894 anime.MalId = selectedAnilistAnime.Media.MalID
895 }
896 if anime.MalId == 0 {
897 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
898 }
899 anime.IsAiring = selectedAnilistAnime.Media.Status == "RELEASING" || selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED"
900 anime.Rewatching = selectedAnilistAnime.Status == "REPEATING"
901 anime.Repeat = selectedAnilistAnime.Repeat
902 anime.StartedAt = selectedAnilistAnime.StartedAt
903 anime.CompletedAt = selectedAnilistAnime.CompletedAt
904 anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
905 userQuery = anime.Title.Romaji
906
907 if selectedAnilistAnime.Status == "COMPLETED" {
908 CurdOut("This anime is completed. Start rewatch from episode 1? Continue without updating tracker? Open details?")
909 selectedOption, err := promptSelect([]SelectionOption{
910 {Key: "rewatch", Label: "Start rewatch from episode 1"},
911 {Key: "continue", Label: "Continue without updating tracker"},
912 {Key: "details", Label: "Open details"},
913 })
914 if err != nil {
915 Log(fmt.Sprintf("Error in completed anime prompt: %v", err))
916 ExitCurd(fmt.Errorf("Failed to select completed anime action"))
917 }
918
919 switch selectedOption.Key {
920 case "rewatch":
921 err = StartAnimeRewatch(user.Token, *anime)
922 if err != nil {
923 Log(fmt.Sprintf("Error starting anime rewatch: %v", err))
924 ExitCurd(fmt.Errorf("Failed to move anime to rewatching"))
925 }
926
927 anime.Rewatching = true
928 anime.SkipRemoteSync = false
929 anime.Ep.Number = 1
930 anime.Ep.Player.PlaybackTime = 0
931 anime.Ep.Resume = false
932 startingRewatch = true
933 CurdOut("Moved anime to Rewatching and restarting from episode 1.")
934
935 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
936 Log("Error refreshing anime list: " + err.Error())
937 ExitCurd(err)
938 }
939 case "continue":
940 anime.Rewatching = false
941 anime.SkipRemoteSync = true
942 anime.Ep.Number = 1
943 anime.Ep.Player.PlaybackTime = 0
944 anime.Ep.Resume = false
945 startingRewatch = true
946 CurdOut("Starting episode 1 without updating your tracker.")
947 case "details":
948 url := fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId)
949 CurdOut(fmt.Sprintf("Opening %s", url))
950 if err := browser.OpenURL(url); err != nil {
951 Log(fmt.Sprintf("Error opening browser: %v", err))
952 CurdOut("Failed to open browser.")
953 }
954 anime.Ep.ContinueLast = false
955 continue
956 case "-1":
957 ExitCurd(nil)
958 default:
959 anime.Ep.ContinueLast = false
960 continue
961 }
962 }
963
964 // Check if we need to research provider ID
965 needsProviderSearch := false
966 if animePointer == nil {
967 needsProviderSearch = true
968 } else if animePointer.ProviderId == "" {
969 needsProviderSearch = true
970 } else if animePointer.ProviderName != "" && !ProviderStackContains(userCurdConfig, animePointer.ProviderName) {
971 needsProviderSearch = true
972 }
973
974 // if anime not found in database or provider changed, find it in animeList
975 if needsProviderSearch {
976 Log("Anime not found in database for current provider, searching in animeList...")
977 mappingOutcome, mappingErr := ResolveAnimeProviderMapping(userCurdConfig, anime, string(userQuery), selectedAnilistAnime)
978 if mappingErr != nil {
979 Log(fmt.Sprintf("Provider mapping failed: %v", mappingErr))
980 ExitCurd(mappingErr)
981 }
982 switch mappingOutcome {
983 case ProviderMappingBack:
984 CurdOut("Going back to main menu...")
985 RestoreScreen()
986 if anime.Ep.ContinueLast {
987 anime.Ep.ContinueLast = false
988 }
989 continue
990 case ProviderMappingQuit:
991 ExitCurd(nil)
992 }
993 }
994
995 // if anime found in database, use its playback state
996 if animePointer != nil {
997 if !needsProviderSearch {
998 anime.ProviderId = animePointer.ProviderId
999 anime.ProviderName = animePointer.ProviderName
1000 }
1001 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
1002 if anime.Ep.Number == animePointer.Ep.Number {
1003 anime.Ep.Resume = true
1004 }
1005
1006 // If local history episode is ahead of AniList upstream, prompt user
1007 anilistEpisode := nextEpisodeFromProgress(selectedAnilistAnime.Progress)
1008 if animePointer.Ep.Number > anilistEpisode {
1009 trackerLabel := RemoteTrackingDisplayName(userCurdConfig)
1010 Log(fmt.Sprintf("Local history episode (%d) is ahead of %s episode (%d), prompting user", animePointer.Ep.Number, trackerLabel, anilistEpisode))
1011 options := []SelectionOption{
1012 {Key: "update_upstream", Label: fmt.Sprintf("Use Curd episode %d", animePointer.Ep.Number)},
1013 {Key: "use_anilist", Label: fmt.Sprintf("Use %s episode %d", trackerLabel, anilistEpisode)},
1014 }
1015 CurdOut(fmt.Sprintf("Curd has episode %d. %s has episode %d. Pick one.", animePointer.Ep.Number, trackerLabel, anilistEpisode))
1016 selectedOption, err := DynamicSelect(options)
1017 if err != nil {
1018 Log("Error in episode conflict selection: " + err.Error())
1019 } else if selectedOption.Key == "-1" {
1020 ExitCurd(nil)
1021 } else if selectedOption.Key == "update_upstream" {
1022 // Update remote progress to match local history (progress = local ep - 1, since local ep is "next to watch")
1023 progressToUpdate := animePointer.Ep.Number - 1
1024 if err := UpdateAnimeProgress(user.Token, anime.AnilistId, progressToUpdate); err != nil {
1025 Log(fmt.Sprintf("Error updating %s progress to %d: %v", trackerLabel, progressToUpdate, err))
1026 } else {
1027 Log(fmt.Sprintf("Updated %s progress to %d", trackerLabel, progressToUpdate))
1028 }
1029 anime.Ep.Number = animePointer.Ep.Number
1030 anime.Ep.Resume = true
1031 } else if selectedOption.Key == "use_anilist" {
1032 // Use remote next-episode number (already set from selectedAnilistAnime.Progress + 1)
1033 anime.Ep.Number = anilistEpisode
1034 anime.Ep.Player.PlaybackTime = 0
1035 anime.Ep.Resume = false
1036 }
1037 } else {
1038 anime.Ep.Number = animePointer.Ep.Number
1039 }
1040 }
1041
1042 if startingRewatch {
1043 anime.Ep.Player.PlaybackTime = 0
1044 anime.Ep.Resume = false
1045 }
1046
1047 if selectedAllanimeAnime.Key == "-1" {
1048 ExitCurd(nil)
1049 }
1050
1051 // If anime is not in watching list, prompt user to add it into watching list
1052 isInWatchingList := false
1053 for _, entry := range user.AnimeList.Watching {
1054 if entry.Media.ID == anime.AnilistId {
1055 isInWatchingList = true
1056 break
1057 }
1058 }
1059 if !isInWatchingList {
1060 for _, entry := range user.AnimeList.Rewatching {
1061 if entry.Media.ID == anime.AnilistId {
1062 isInWatchingList = true
1063 break
1064 }
1065 }
1066 }
1067 if anime.Rewatching {
1068 isInWatchingList = true
1069 }
1070
1071 if ShouldWriteRemoteTracking(userCurdConfig, anime) && !isInWatchingList {
1072 // Create options for the prompt
1073 options := []SelectionOption{
1074 {Key: "yes", Label: "Add to watching list"},
1075 {Key: "no", Label: "Continue without adding"},
1076 }
1077
1078 var selectedOption SelectionOption
1079 var err error
1080
1081 // Use rofi for selection
1082 selectedOption, err = DynamicSelect(options)
1083 if err != nil {
1084 Log("Error in selection: " + err.Error())
1085 ExitCurd(err)
1086 }
1087
1088 if selectedOption.Key == "yes" {
1089 err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
1090 if err != nil {
1091 Log("Error adding anime to watching list: " + err.Error())
1092 ExitCurd(err)
1093 }
1094 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
1095 Log("Error refreshing anime list: " + err.Error())
1096 ExitCurd(err)
1097 }
1098 } else if selectedOption.Key == "-1" {
1099 ExitCurd(nil)
1100 } else if selectedOption.Key == "-2" {
1101 // Handle back button - go back to main menu
1102 CurdOut("Going back to main menu...")
1103 RestoreScreen()
1104 // If we were continuing last, disable it so we go to menu next loop
1105 if anime.Ep.ContinueLast {
1106 anime.Ep.ContinueLast = false
1107 }
1108 continue
1109 }
1110 }
1111
1112 // If upstream is ahead, update the episode number
1113 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
1114 upstreamNextEpisode := nextEpisodeFromProgress(temp_anime.Progress)
1115 if upstreamNextEpisode > anime.Ep.Number {
1116 anime.Ep.Number = upstreamNextEpisode
1117 anime.Ep.Player.PlaybackTime = 0
1118 anime.Ep.Resume = false
1119 }
1120 }
1121
1122 if anime.TotalEpisodes == 0 {
1123 // Get updated anime data
1124 Log(selectedAllanimeAnime)
1125 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
1126 Log(updatedAnime)
1127 if err != nil {
1128 Log(fmt.Sprintf("Error getting updated anime data: %v", err))
1129 } else {
1130 anime.TotalEpisodes = updatedAnime.TotalEpisodes
1131 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
1132 }
1133 }
1134
1135 if anime.TotalEpisodes == 0 { // If failed to get anime data
1136 CurdOut("AniList/MAL did not return total episodes. Attempting to retrieve from provider episode list.")
1137 providerName, providerID := AnimeProviderID(anime)
1138 providerTotal, err := GetProviderTotalEpisodes(QualifyProviderID(providerName, providerID), userCurdConfig.SubOrDub)
1139 if err != nil {
1140 Log(fmt.Sprintf("Failed to retrieve total episodes from provider episode list: %v", err))
1141 } else {
1142 anime.TotalEpisodes = providerTotal
1143 CurdOut(fmt.Sprintf("Retrieved total episodes from provider: %d", anime.TotalEpisodes))
1144 }
1145 }
1146
1147 if anime.TotalEpisodes == 0 { // If provider episode list did not have a usable total
1148 CurdOut("Attempting to retrieve total episodes from anime search results.")
1149 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
1150 if err != nil {
1151 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
1152 } else {
1153 for _, option := range animeList {
1154 optionProviderName, optionProviderID, ok := ParseProviderQualifiedID(option.Key)
1155 if !ok {
1156 optionProviderName = configuredProviderNames(userCurdConfig)[0]
1157 optionProviderID = option.Key
1158 }
1159 if optionProviderID == anime.ProviderId && optionProviderName == CurrentAnimeProviderName(anime) {
1160 // Extract total episodes from the label
1161 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 {
1162 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
1163 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
1164 break
1165 }
1166 }
1167 }
1168 }
1169
1170 if anime.TotalEpisodes == 0 {
1171 CurdOut("Still unable to determine total episodes.")
1172 CurdOut(fmt.Sprintf("Your %s progress: %d", RemoteTrackingDisplayName(userCurdConfig), selectedAnilistAnime.Progress))
1173 episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, "Enter the episode you want to start from")
1174 if err != nil {
1175 Log("Invalid episode input: " + err.Error())
1176 ExitCurd(fmt.Errorf("Invalid episode number"))
1177 }
1178 anime.Ep.Number = episodeNumber
1179 } else {
1180 anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
1181 }
1182 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
1183 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
1184 var answer string
1185 if userCurdConfig.RofiSelection {
1186 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
1187 if err != nil {
1188 Log("Error getting user input: " + err.Error())
1189 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1190 }
1191 answer = userInput
1192 } else {
1193 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
1194 fmt.Scanln(&answer)
1195 }
1196 if isAffirmativeAnswer(answer) {
1197 anime.Ep.Number = 1
1198 } else {
1199 anime.Ep.Number = anime.TotalEpisodes
1200 }
1201 }
1202
1203 // If we reached here successfully, break the loop
1204 break
1205 }
1206}
1207
1208// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
1209func WriteTokenToFile(token string, filePath string) error {
1210 // Extract the directory path
1211 dir := filepath.Dir(filePath)
1212
1213 // Create all necessary parent directories
1214 if err := os.MkdirAll(dir, 0755); err != nil {
1215 return fmt.Errorf("failed to create directories: %v", err)
1216 }
1217
1218 // Write the token to the file, creating it if it doesn't exist
1219 err := os.WriteFile(filePath, []byte(token), 0644)
1220 if err != nil {
1221 return fmt.Errorf("failed to write token to file: %v", err)
1222 }
1223
1224 return nil
1225}
1226
1227func handleUnreleasedAnime(userCurdConfig *CurdConfig, user *User, anime *Anime, entry Entry) {
1228 title := entry.Media.Title.Romaji
1229 if userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" && entry.Media.Title.English != "" {
1230 title = entry.Media.Title.English
1231 }
1232 if title == "" {
1233 title = strconv.Itoa(entry.Media.ID)
1234 }
1235
1236 CurdOut(fmt.Sprintf("%s is not released yet.", title))
1237 options := []SelectionOption{}
1238 if UsesRemoteTracking(userCurdConfig) {
1239 options = append(options, SelectionOption{Key: "planning", Label: "Add to Plan to Watch"})
1240 }
1241 options = append(options,
1242 SelectionOption{Key: "details", Label: "Open AniList details"},
1243 SelectionOption{Key: "back", Label: "Back to list"},
1244 )
1245
1246 selected, err := promptSelect(options)
1247 if err != nil {
1248 Log(fmt.Sprintf("Error in unreleased anime prompt: %v", err))
1249 anime.Ep.ContinueLast = false
1250 return
1251 }
1252
1253 switch selected.Key {
1254 case "planning":
1255 if err := AddAnimeToList(entry.Media.ID, "PLANNING", user.Token); err != nil {
1256 Log(fmt.Sprintf("Error adding unreleased anime to planning: %v", err))
1257 CurdOut("Failed to add to Plan to Watch.")
1258 } else {
1259 CurdOut("Added to Plan to Watch.")
1260 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
1261 Log("Error refreshing anime list: " + err.Error())
1262 }
1263 }
1264 case "details":
1265 url := fmt.Sprintf("https://anilist.co/anime/%d", entry.Media.ID)
1266 CurdOut(fmt.Sprintf("Opening %s", url))
1267 if err := browser.OpenURL(url); err != nil {
1268 Log(fmt.Sprintf("Error opening browser: %v", err))
1269 CurdOut("Failed to open browser.")
1270 }
1271 case "-1":
1272 ExitCurd(nil)
1273 }
1274 anime.Ep.ContinueLast = false
1275}
1276
1277func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1278 if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil {
1279 Log(fmt.Sprintf("Failed to resolve provider id: %v", err))
1280 CurdOut("Failed to resolve anime provider id: " + err.Error())
1281 exitWithRestore(1)
1282 }
1283
1284 // Validate inputs
1285 if anime.ProviderId == "" {
1286 CurdOut("Error: No anime ID found")
1287 exitWithRestore(1)
1288 }
1289 if anime.Ep.Number <= 0 {
1290 CurdOut("Error: Invalid episode number")
1291 exitWithRestore(1)
1292 }
1293
1294 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1295 anime.Ep.Links = anime.Ep.NextEpisode.Links
1296 anime.Ep.StreamReferrer = ""
1297 anime.Ep.SubtitleURL = ""
1298 if anime.Ep.NextEpisode.ProviderName != "" {
1299 anime.ProviderName = anime.Ep.NextEpisode.ProviderName
1300 anime.ProviderId = anime.Ep.NextEpisode.ProviderId
1301 }
1302 } else {
1303 // Preferred-first resolve; diagnosed recovery only after that fails.
1304 episodeResult, ok := resolveEpisodeLinksWithRecovery(userCurdConfig, anime, nil, true)
1305 if !ok {
1306 RestoreScreen()
1307 return ""
1308 }
1309 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(episodeResult.Links)))
1310 anime.Ep.Links = episodeResult.Links
1311 applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1312 }
1313
1314 if len(anime.Ep.Links) == 0 {
1315 CurdOut("No episode links found")
1316 RestoreScreen()
1317 return ""
1318 }
1319 Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links)))
1320
1321 // Modify the goroutine in main.go where next episode links are fetched
1322 // Get next episode link in parallel
1323 go func() {
1324 nextEpNum := anime.Ep.Number + 1
1325 if nextEpNum <= anime.TotalEpisodes {
1326 // Get next canon episode number if filler skip is enabled
1327 if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) {
1328 nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum)
1329 }
1330 nextEpisode := *anime
1331 nextEpisode.ProviderId = anime.ProviderId
1332 nextEpisode.ProviderName = anime.ProviderName
1333 nextResult, err := ResolveEpisodeURL(*userCurdConfig, &nextEpisode, nextEpNum)
1334 if err != nil {
1335 Log(fmt.Sprintf("Error getting next episode link for ep %d: %v", nextEpNum, err))
1336 } else {
1337 anime.Ep.NextEpisode = NextEpisode{
1338 Number: nextEpNum,
1339 Links: nextResult.Links,
1340 ProviderName: nextResult.ProviderName,
1341 ProviderId: nextResult.ProviderID,
1342 Mode: nextResult.Mode,
1343 }
1344 }
1345 } else {
1346 Log(fmt.Sprintf("Next episode %d exceeds total episodes %d, skipping prefetch", nextEpNum, anime.TotalEpisodes))
1347 }
1348 }()
1349
1350 // Write anime.AnilistId to curd_id in the storage path
1351 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1352 Log(fmt.Sprintf("idFilePath: %v", idFilePath))
1353 if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
1354 Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err))
1355 } else {
1356 if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
1357 Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err))
1358 }
1359 }
1360
1361 // Display starting message with cover image and episode info
1362 if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
1363 // Get the cached image path
1364 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
1365 filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
1366 cachePath := filepath.Join(cacheDir, filename)
1367
1368 // Display the image if it exists in cache
1369 _, err := os.Stat(cachePath)
1370 if err == nil {
1371 // File exists
1372 Log(fmt.Sprintf("Image found at %s", cachePath))
1373 CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
1374 } else {
1375 // File does not exist
1376 Log(fmt.Sprintf("Image does not exist at %s", cachePath))
1377 CurdOut(fmt.Sprintf("%s - Episode %d",
1378 GetAnimeName(*anime),
1379 anime.Ep.Number))
1380
1381 }
1382 } else {
1383 CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
1384 }
1385 title := fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number)
1386 return StartVideoWithProviderFallback(userCurdConfig, anime, title)
1387}
1388
1389func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
1390 if anime == nil || anime.ProviderId == "" {
1391 return nil
1392 }
1393
1394 providerName, providerID := AnimeProviderID(anime)
1395 if providerName != "animepahe" || !ProviderEnabled("animepahe") {
1396 return nil
1397 }
1398 if !ProviderStackContains(userCurdConfig, "animepahe") {
1399 return nil
1400 }
1401
1402 provider, err := ProviderByName(providerName)
1403 if err != nil {
1404 return err
1405 }
1406
1407 query := GetAnimeName(*anime)
1408 if query == "" {
1409 query = anime.Title.Romaji
1410 }
1411 if query == "" {
1412 query = anime.Title.English
1413 }
1414
1415 resolved, err := resolveProviderID(provider, providerID, query)
1416 if err != nil {
1417 return err
1418 }
1419 if resolved != "" && resolved != providerID {
1420 Log(fmt.Sprintf("Resolved Animepahe provider id %s to runtime id %s", providerID, resolved))
1421 anime.ProviderId = resolved
1422 anime.ProviderName = providerName
1423 }
1424
1425 return nil
1426}
1427
1428func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason error) bool {
1429 providerName, _ := AnimeProviderID(anime)
1430 if providerName != "animepahe" || !ProviderEnabled("animepahe") {
1431 return false
1432 }
1433
1434 if reason != nil {
1435 Log(fmt.Sprintf("Attempting Animepahe provider reselect after error: %v", reason))
1436 }
1437
1438 query := GetAnimeName(*anime)
1439 if query == "" {
1440 query = anime.Title.Romaji
1441 }
1442 if query == "" {
1443 query = anime.Title.English
1444 }
1445 if query == "" {
1446 return false
1447 }
1448
1449 options, err := SearchAnime(query, userCurdConfig.SubOrDub)
1450 if err != nil {
1451 Log(fmt.Sprintf("Animepahe provider reselect search failed for %q: %v", query, err))
1452 return false
1453 }
1454 if len(options) == 0 {
1455 Log(fmt.Sprintf("Animepahe provider reselect found no results for %q", query))
1456 return false
1457 }
1458
1459 CurdOut("The saved Animepahe mapping is stale. Please select the anime again.")
1460 var trackerEntry *Entry
1461 if anime.TotalEpisodes > 0 {
1462 trackerEntry = &Entry{Media: Media{Episodes: anime.TotalEpisodes}}
1463 }
1464 selected, err := promptProviderSearchSelection(userCurdConfig, options, trackerEntry)
1465 if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" {
1466 if err != nil {
1467 Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err))
1468 }
1469 return false
1470 }
1471
1472 if selectedProviderName, rawProviderID, ok := ParseProviderQualifiedID(selected.Key); ok {
1473 anime.ProviderName = selectedProviderName
1474 anime.ProviderId = rawProviderID
1475 } else {
1476 anime.ProviderName = "animepahe"
1477 anime.ProviderId = selected.Key
1478 }
1479 anime.Ep.NextEpisode = NextEpisode{}
1480 Log(fmt.Sprintf("Updated Animepahe ProviderId to %s after stale mapping", anime.ProviderId))
1481 return true
1482}
1483
1484func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1485 // Create storage directory if it doesn't exist
1486 storagePath = os.ExpandEnv(storagePath)
1487 if err := os.MkdirAll(storagePath, 0755); err != nil {
1488 return fmt.Errorf("failed to create storage directory: %v", err)
1489 }
1490
1491 // Base URL for downloading config files
1492 baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
1493
1494 // Check each file
1495 for _, fileName := range filesToCheck {
1496 filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
1497
1498 // Skip if file already exists
1499 if _, err := os.Stat(filePath); err == nil {
1500 continue
1501 }
1502
1503 // Download file if it doesn't exist
1504 resp, err := sharedHTTPClient.Get(baseURL + fileName)
1505 if err != nil {
1506 return fmt.Errorf("failed to download %s: %v", fileName, err)
1507 }
1508 if resp.StatusCode != http.StatusOK {
1509 resp.Body.Close()
1510 return fmt.Errorf("failed to download %s: received status code %d", fileName, resp.StatusCode)
1511 }
1512
1513 // Create the file
1514 out, err := os.Create(filePath)
1515 if err != nil {
1516 resp.Body.Close()
1517 return fmt.Errorf("failed to create file %s: %v", fileName, err)
1518 }
1519
1520 // Write the content
1521 if _, err := io.Copy(out, resp.Body); err != nil {
1522 resp.Body.Close()
1523 out.Close()
1524 return fmt.Errorf("failed to write file %s: %v", fileName, err)
1525 }
1526 resp.Body.Close()
1527 if err := out.Close(); err != nil {
1528 return fmt.Errorf("failed to close file %s: %v", fileName, err)
1529 }
1530 }
1531
1532 return nil
1533}
1534
1535func getEntriesByCategory(list AnimeList, category string) []Entry {
1536 switch category {
1537 case "ALL":
1538 // Combine all categories into one slice. Dedupe by Media.ID so Show All
1539 // never surfaces the same anime twice (e.g. stale cache / dual-track edge cases).
1540 allEntries := make([]Entry, 0)
1541 allEntries = append(allEntries, list.Watching...)
1542 allEntries = append(allEntries, list.Completed...)
1543 allEntries = append(allEntries, list.Paused...)
1544 allEntries = append(allEntries, list.Dropped...)
1545 allEntries = append(allEntries, list.Planning...)
1546 allEntries = append(allEntries, list.Rewatching...)
1547 return dedupeEntriesByMediaID(allEntries)
1548 case "CURRENT":
1549 currentEntries := make([]Entry, 0, len(list.Watching)+len(list.Rewatching))
1550 currentEntries = append(currentEntries, list.Watching...)
1551 currentEntries = append(currentEntries, list.Rewatching...)
1552 return dedupeEntriesByMediaID(currentEntries)
1553 case "COMPLETED":
1554 return dedupeEntriesByMediaID(list.Completed)
1555 case "PAUSED":
1556 return dedupeEntriesByMediaID(list.Paused)
1557 case "DROPPED":
1558 return dedupeEntriesByMediaID(list.Dropped)
1559 case "PLANNING":
1560 return dedupeEntriesByMediaID(list.Planning)
1561 case "REWATCHING": // Added for completeness, though "ALL" covers it.
1562 return dedupeEntriesByMediaID(list.Rewatching)
1563 default:
1564 return []Entry{}
1565 }
1566}
1567
1568func NextEpisodePromptCLI(userCurdConfig *CurdConfig) bool {
1569 anime := GetGlobalAnime()
1570
1571 // Show the next episode number that will be started
1572 nextEpisodeNum := anime.Ep.Number + 1
1573 isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1574 if isLastKnownEpisode {
1575 CurdOut("Finish this series?")
1576 } else {
1577 CurdOut(fmt.Sprintf("Start next episode (%d)?", nextEpisodeNum))
1578 }
1579
1580 // Create options for the selection - no "quit" option since it's built into selection menu
1581 label := fmt.Sprintf("Yes, continue to episode %d", nextEpisodeNum)
1582 if isLastKnownEpisode {
1583 label = "Yes, finish series"
1584 }
1585 options := []SelectionOption{
1586 {Key: "yes", Label: label},
1587 }
1588
1589 // Use DynamicSelect for CLI mode
1590 selectedOption, err := DynamicSelect(options)
1591 if err != nil {
1592 Log(fmt.Sprintf("Error in CLI next episode prompt selection: %v", err))
1593 return false
1594 }
1595
1596 Log(fmt.Sprintf("CLI User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1597
1598 if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1599 // User selected to quit/back via the built-in option
1600 CurdOut("Exiting")
1601 return false
1602 }
1603
1604 return selectedOption.Key == "yes"
1605}
1606
1607// NextEpisodePromptContinuous provides a continuous next episode prompt for CLI mode
1608// This runs throughout the episode duration and handles completion logic
1609func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1610 anime := GetGlobalAnime()
1611
1612 for {
1613 // Check if episode has started
1614 if !anime.Ep.Started {
1615 time.Sleep(1 * time.Second)
1616 continue
1617 }
1618
1619 // Show the next episode number that will be started
1620 nextEpisodeNum := anime.Ep.Number + 1
1621 isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1622 if isLastKnownEpisode {
1623 CurdOut("Finish this series or quit?")
1624 } else {
1625 CurdOut(fmt.Sprintf("Continue to next episode (%d) or quit?", nextEpisodeNum))
1626 }
1627
1628 // Create options for the selection - no "quit" option since it's built into selection menu
1629 label := "Yes, start next episode now"
1630 if isLastKnownEpisode {
1631 label = "Yes, finish series"
1632 }
1633 options := []SelectionOption{
1634 {Key: "yes", Label: label},
1635 }
1636
1637 // Use DynamicSelect for CLI mode
1638 selectedOption, err := DynamicSelect(options)
1639 if err != nil {
1640 Log(fmt.Sprintf("Error in CLI continuous next episode prompt: %v", err))
1641 break
1642 }
1643
1644 Log(fmt.Sprintf("CLI Continuous User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1645
1646 if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1647 // User selected to quit/back via the built-in option
1648
1649 // Check completion percentage
1650 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
1651
1652 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
1653 // Episode is considered completed, mark it and update progress
1654 anime.Ep.IsCompleted = true
1655
1656 // Handle completion if this was the last episode
1657 if anime.Ep.Number == anime.TotalEpisodes {
1658 HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
1659 }
1660
1661 // Update local database
1662 if updateErr := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime), CurrentAnimeProviderName(anime)); updateErr != nil {
1663 Log("Error updating local database on quit: " + updateErr.Error())
1664 }
1665
1666 if !(anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && anime.Rewatching) {
1667 completedEpisode := anime.Ep.Number
1668 go func(progressEpisode int) {
1669 if progressErr := UpdateAnimeProgress(userToken, anime.AnilistId, progressEpisode); progressErr != nil {
1670 Log("Error updating Anilist progress on quit: " + progressErr.Error())
1671 }
1672 }(completedEpisode)
1673 }
1674
1675 CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched))
1676 } else {
1677 CurdOut(fmt.Sprintf("Episode not completed (%.1f%% watched). Exiting.", percentageWatched))
1678 }
1679
1680 ExitMPV(anime.Ep.Player.SocketPath)
1681 ExitCurd(nil)
1682 return
1683 }
1684
1685 if selectedOption.Key == "yes" {
1686 // User wants to start next episode immediately
1687 anime.Ep.IsCompleted = true
1688 socketPath := anime.Ep.Player.SocketPath
1689 if anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes {
1690 ExitMPV(socketPath)
1691 }
1692 StartNextEpisode(anime, userCurdConfig, databaseFile, userToken)
1693 ExitMPV(socketPath)
1694 return // Exit this function, let the main loop handle next episode
1695 }
1696 }
1697}
1698
1699// Simple next episode prompt for Rofi mode - just asks if user wants to continue
1700func NextEpisodePromptRofi(userCurdConfig *CurdConfig) bool {
1701 anime := GetGlobalAnime()
1702
1703 // Show the next episode number that will be started
1704 nextEpisodeNum := anime.Ep.Number + 1
1705 isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1706
1707 // Create options for the selection
1708 label := fmt.Sprintf("Yes, start episode %d", nextEpisodeNum)
1709 if isLastKnownEpisode {
1710 label = "Yes, finish series"
1711 }
1712 options := []SelectionOption{
1713 {Key: "yes", Label: label},
1714 }
1715
1716 // Use DynamicSelect for Rofi mode
1717 selectedOption, err := DynamicSelect(options)
1718 if err != nil {
1719 Log(fmt.Sprintf("Error in next episode prompt selection: %v", err))
1720 return false
1721 }
1722
1723 Log(fmt.Sprintf("Rofi User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1724
1725 return selectedOption.Key == "yes"
1726}
1727
1728// StartNextEpisode handles the logic for starting the next episode
1729// It updates the episode number, resets necessary flags, and handles database updates
1730func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1731 // Save previous episode number for progress update
1732 prevEpisode := anime.Ep.Number
1733
1734 // Check if we just completed the last episode
1735 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1736 // Handle scoring and completion for the last episode
1737 HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
1738
1739 if !anime.Rewatching {
1740 err := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1741 if err != nil {
1742 Log("Error updating Anilist progress: " + err.Error())
1743 }
1744 }
1745 // Note: UpdateAnimeProgress already outputs a message on success
1746
1747 CurdOut("Series completed!")
1748 ExitCurd(nil)
1749 return
1750 }
1751
1752 // Increment episode number
1753 anime.Ep.Number++
1754
1755 // Check if we've reached the end of the series
1756 if anime.TotalEpisodes > 0 && anime.Ep.Number > anime.TotalEpisodes {
1757 CurdOut("Reached end of series")
1758 ExitCurd(nil)
1759 return
1760 }
1761
1762 // Use prefetched links if available for the next episode
1763 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1764 anime.Ep.Links = anime.Ep.NextEpisode.Links
1765 anime.Ep.StreamReferrer = ""
1766 anime.Ep.SubtitleURL = ""
1767 if anime.Ep.NextEpisode.ProviderName != "" {
1768 anime.ProviderName = anime.Ep.NextEpisode.ProviderName
1769 anime.ProviderId = anime.Ep.NextEpisode.ProviderId
1770 }
1771 Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number))
1772 } else {
1773 // Clear links to force fetching new ones
1774 anime.Ep.Links = []string{}
1775 Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
1776 }
1777
1778 // Reset episode flags
1779 anime.Ep.Started = false
1780 anime.Ep.IsCompleted = false
1781
1782 // Log the transition
1783 Log("Completed episode, starting next.")
1784
1785 // Update local database
1786 err := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, GetAnimeName(*anime), CurrentAnimeProviderName(anime))
1787 if err != nil {
1788 Log("Error updating local database: " + err.Error())
1789 }
1790
1791 go func() {
1792 if progressErr := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode); progressErr != nil {
1793 Log("Error updating Anilist progress: " + progressErr.Error())
1794 }
1795 }()
1796
1797 // Output message to user
1798 CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
1799}
1800
1801// HandleLastEpisodeCompletion handles scoring and completion for the last episode
1802func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
1803 if anime.TotalEpisodes <= 0 || anime.Ep.Number != anime.TotalEpisodes {
1804 return
1805 }
1806
1807 summary := []string{}
1808 canWriteRemote := ShouldWriteRemoteTracking(userCurdConfig, anime)
1809
1810 if userCurdConfig.ScoreOnCompletion && !anime.IsAiring && canWriteRemote {
1811 CurdOut("You've completed this anime! Would you like to rate it?")
1812
1813 scoreOptions := []SelectionOption{
1814 {Key: "yes", Label: "Yes, rate this anime"},
1815 {Key: "no", Label: "No, skip rating"},
1816 }
1817
1818 selectedOption, err := DynamicSelect(scoreOptions)
1819 if err != nil {
1820 Log(fmt.Sprintf("Error in score prompt selection: %v", err))
1821 } else if selectedOption.Key == "yes" {
1822 err = RateAnime(userToken, anime.AnilistId)
1823 if err != nil {
1824 Log(fmt.Sprintf("Error rating anime: %v", err))
1825 CurdOut("Failed to rate anime")
1826 summary = append(summary, "rating failed")
1827 } else {
1828 CurdOut("Anime rated successfully!")
1829 summary = append(summary, "rating saved")
1830 }
1831 } else {
1832 summary = append(summary, "rating skipped")
1833 }
1834 // Back (-2) and no are treated as skip
1835 } else {
1836 summary = append(summary, "rating skipped")
1837 }
1838
1839 if !anime.IsAiring && canWriteRemote {
1840 if anime.Rewatching {
1841 err := CompleteAnimeRewatch(userToken, *anime)
1842 if err != nil {
1843 Log("Error completing anime rewatch: " + err.Error())
1844 summary = append(summary, "rewatch completion failed")
1845 } else {
1846 summary = append(summary, "rewatch completed")
1847 }
1848 } else {
1849 err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED")
1850 if err != nil {
1851 Log("Error updating anime status to completed: " + err.Error())
1852 summary = append(summary, "status update failed")
1853 } else {
1854 summary = append(summary, "marked completed")
1855 }
1856 }
1857 } else if !anime.IsAiring {
1858 summary = append(summary, "tracker updates skipped")
1859 }
1860
1861 if sequelSummary := handleSequelCheck(userCurdConfig, anime, userToken); sequelSummary != "" {
1862 summary = append(summary, sequelSummary)
1863 }
1864 if len(summary) > 0 {
1865 CurdOut("Completion summary: " + strings.Join(summary, "; "))
1866 }
1867}
1868
1869// handleSequelCheck checks for sequels and prompts the user accordingly
1870func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken string) (summary string) {
1871 if !ShouldWriteRemoteTracking(userCurdConfig, anime) {
1872 return "sequel check skipped"
1873 }
1874
1875 // Recover from any panics in this function to prevent crashes
1876 defer func() {
1877 if r := recover(); r != nil {
1878 Log(fmt.Sprintf("Recovered from panic in handleSequelCheck: %v", r))
1879 summary = "sequel check failed"
1880 }
1881 }()
1882
1883 // Fetch sequel information
1884 sequels, err := GetAnimeSequel(anime.AnilistId, userToken)
1885 if err != nil {
1886 Log(fmt.Sprintf("Error fetching sequel information: %v", err))
1887 return "sequel check failed"
1888 }
1889
1890 if len(sequels) == 0 {
1891 Log("No sequel found for this anime")
1892 return "no sequel found"
1893 }
1894
1895 sequel := &sequels[0]
1896 if len(sequels) > 1 {
1897 selectedSequel, ok := selectSequel(userCurdConfig, sequels)
1898 if !ok {
1899 return "sequel skipped"
1900 }
1901 sequel = selectedSequel
1902 }
1903
1904 return promptSequelAction(userCurdConfig, sequel, userToken)
1905}
1906
1907func selectSequel(userCurdConfig *CurdConfig, sequels []SequelInfo) (*SequelInfo, bool) {
1908 CurdOut("Multiple sequels found.")
1909 options := make([]SelectionOption, 0, len(sequels)+1)
1910 for i := range sequels {
1911 title := sequelDisplayTitle(userCurdConfig, &sequels[i])
1912 status := strings.ToLower(strings.ReplaceAll(sequels[i].Status, "_", " "))
1913 options = append(options, SelectionOption{
1914 Key: strconv.Itoa(i),
1915 Label: fmt.Sprintf("%s (%s)", title, status),
1916 })
1917 }
1918 options = append(options, SelectionOption{Key: "skip", Label: "Skip"})
1919
1920 selected, err := promptSelect(options)
1921 if err != nil {
1922 Log(fmt.Sprintf("Error selecting sequel: %v", err))
1923 return nil, false
1924 }
1925 if selected.Key == "skip" || selected.Key == "-1" || selected.Key == "-2" {
1926 return nil, false
1927 }
1928 index, err := strconv.Atoi(selected.Key)
1929 if err != nil || index < 0 || index >= len(sequels) {
1930 return nil, false
1931 }
1932 return &sequels[index], true
1933}
1934
1935func sequelDisplayTitle(userCurdConfig *CurdConfig, sequel *SequelInfo) string {
1936 if sequel == nil {
1937 return ""
1938 }
1939 if userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" && sequel.Title.English != "" {
1940 return sequel.Title.English
1941 }
1942 if sequel.Title.Romaji != "" {
1943 return sequel.Title.Romaji
1944 }
1945 return strconv.Itoa(sequel.ID)
1946}
1947
1948func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToken string) string {
1949 if sequel == nil {
1950 return ""
1951 }
1952
1953 sequelTitle := sequelDisplayTitle(userCurdConfig, sequel)
1954 Log(fmt.Sprintf("Found sequel: %s (ID: %d)", sequelTitle, sequel.ID))
1955
1956 currentUser := GetGlobalUser()
1957 userAnimeList := AnimeList{}
1958 if currentUser != nil {
1959 userAnimeList = currentUser.AnimeList
1960 }
1961 sequelStatus, isInList := "", false
1962 if hasAnyEntries(userAnimeList) {
1963 sequelStatus, isInList = FindSequelInAnimeList(userAnimeList, sequel.ID)
1964 }
1965
1966 if isInList {
1967 CurdOut(fmt.Sprintf("Sequel found: %s (%s)", sequelTitle, sequelStatus))
1968 } else {
1969 CurdOut(fmt.Sprintf("Sequel found: %s", sequelTitle))
1970 }
1971
1972 options := []SelectionOption{}
1973 if sequel.Status != "NOT_YET_RELEASED" {
1974 if !isInList || sequelStatus == "PLANNING" || sequelStatus == "PAUSED" || sequelStatus == "DROPPED" {
1975 options = append(options, SelectionOption{Key: "watching", Label: "Add to Watching"})
1976 }
1977 }
1978 if !isInList || sequelStatus != "PLANNING" {
1979 options = append(options, SelectionOption{Key: "planning", Label: "Add to Plan to Watch"})
1980 }
1981 options = append(options,
1982 SelectionOption{Key: "details", Label: "Open AniList details"},
1983 SelectionOption{Key: "skip", Label: "Skip"},
1984 )
1985
1986 selected, err := promptSelect(options)
1987 if err != nil {
1988 Log(fmt.Sprintf("Error in sequel action prompt: %v", err))
1989 return "sequel action failed"
1990 }
1991
1992 switch selected.Key {
1993 case "watching":
1994 if err := AddAnimeToList(sequel.ID, "CURRENT", userToken); err != nil {
1995 Log(fmt.Sprintf("Error adding sequel to watching list: %v", err))
1996 CurdOut("Failed to add sequel to Watching.")
1997 return "sequel add failed"
1998 } else {
1999 CurdOut(fmt.Sprintf("Added '%s' to Watching.", sequelTitle))
2000 return "sequel added to Watching"
2001 }
2002 case "planning":
2003 if err := AddAnimeToList(sequel.ID, "PLANNING", userToken); err != nil {
2004 Log(fmt.Sprintf("Error adding sequel to planning list: %v", err))
2005 CurdOut("Failed to add sequel to Plan to Watch.")
2006 return "sequel add failed"
2007 } else {
2008 CurdOut(fmt.Sprintf("Added '%s' to Plan to Watch.", sequelTitle))
2009 return "sequel added to Plan to Watch"
2010 }
2011 case "details":
2012 url := sequel.SiteURL
2013 if url == "" {
2014 url = fmt.Sprintf("https://anilist.co/anime/%d", sequel.ID)
2015 }
2016 CurdOut(fmt.Sprintf("Opening %s", url))
2017 if err := browser.OpenURL(url); err != nil {
2018 Log(fmt.Sprintf("Error opening browser: %v", err))
2019 CurdOut("Failed to open browser.")
2020 return "sequel details failed"
2021 }
2022 return "sequel details opened"
2023 case "skip", "-1", "-2":
2024 Log("User skipped sequel action")
2025 }
2026 return "sequel skipped"
2027}
2028
2029// ChangeProvider allows the user to switch the anime provider
2030func ChangeProvider(userCurdConfig *CurdConfig) {
2031 options := providerSelectionOptions()
2032 if len(options) == 0 {
2033 CurdOut("\nNo providers are currently enabled.\n")
2034 return
2035 }
2036
2037 selected, err := DynamicSelect(options)
2038 if err != nil || selected.Key == "-1" || selected.Key == "-2" {
2039 return
2040 }
2041
2042 // Update the config
2043 providerValue := canonicalProviderConfigValue(selected.Key)
2044 userCurdConfig.Provider = providerValue
2045 CurrentProvider = nil // reset the provider instance
2046
2047 // Save to config file
2048 configPath := GlobalConfigPath
2049 configMap, err := LoadConfigFromFile(configPath)
2050 if err == nil {
2051 configMap["Provider"] = providerValue
2052 SaveConfigToFile(configPath, configMap)
2053 }
2054
2055 CurdOut(fmt.Sprintf("\nProvider successfully changed to %s.\n", providerConfigDisplayLabel(userCurdConfig.Provider)))
2056 time.Sleep(1 * time.Second)
2057}