internal/curd.go
2402 lines · 79234 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 os.Exit(1)
161 } else {
162 os.Exit(1)
163 }
164 }
165 os.Exit(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
434 // Determine the correct binary name based on OS and architecture
435 var binaryName string
436 switch runtime.GOOS {
437 case "windows":
438 if runtime.GOARCH == "arm64" {
439 binaryName = "curd-windows-arm64.exe"
440 } else {
441 binaryName = "curd-windows-x86_64.exe"
442 }
443 case "darwin": // macOS
444 switch runtime.GOARCH {
445 case "amd64":
446 binaryName = "curd-macos-x86_64"
447 case "arm64":
448 binaryName = "curd-macos-arm64"
449 default:
450 binaryName = "curd-macos-universal"
451 }
452 case "linux":
453 switch runtime.GOARCH {
454 case "amd64":
455 binaryName = "curd-linux-x86_64"
456 case "arm64":
457 binaryName = "curd-linux-arm64"
458 default:
459 return fmt.Errorf("unsupported Linux architecture: %s", runtime.GOARCH)
460 }
461 default:
462 return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
463 }
464
465 // GitHub release URL for curd
466 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName)
467
468 // Temporary path for the downloaded curd executable
469 tmpPath := executablePath + ".tmp"
470
471 // Download the curd executable
472 resp, err := sharedHTTPClient.Get(url)
473 if err != nil {
474 return fmt.Errorf("failed to download file: %v", err)
475 }
476 defer resp.Body.Close()
477
478 // Check if the download was successful
479 if resp.StatusCode != http.StatusOK {
480 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
481 }
482
483 // Create a new temporary file
484 out, err := os.Create(tmpPath)
485 if err != nil {
486 return fmt.Errorf("failed to create temporary file: %v", err)
487 }
488 defer out.Close()
489
490 // Set file permissions
491 if err := out.Chmod(0755); err != nil {
492 return fmt.Errorf("failed to set file permissions: %v", err)
493 }
494
495 // Copy the downloaded content to the temporary file
496 if _, err := io.Copy(out, resp.Body); err != nil {
497 return fmt.Errorf("failed to write to temporary file: %v", err)
498 }
499
500 // Close the file before renaming
501 out.Close()
502
503 // Replace the old executable with the new one
504 if runtime.GOOS == "windows" {
505 // On Windows, we need to rename the old file first
506 oldPath := executablePath + ".old"
507 err = os.Rename(executablePath, oldPath)
508 if err != nil {
509 return fmt.Errorf("failed to rename old executable: %v", err)
510 }
511 err = os.Rename(tmpPath, executablePath)
512 if err != nil {
513 // Try to restore the old executable if the rename fails
514 os.Rename(oldPath, executablePath)
515 return fmt.Errorf("failed to rename new executable: %v", err)
516 }
517 os.Remove(oldPath)
518 } else {
519 // On Unix systems, we can directly rename
520 if err := os.Rename(tmpPath, executablePath); err != nil {
521 return fmt.Errorf("failed to replace executable: %v", err)
522 }
523 }
524
525 return nil
526}
527
528func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
529 var query string
530 // Remove the redeclared variable declaration since animeOptions is already declared above
531 var animeMapPreview map[string]RofiSelectPreview
532 var animeOptions []SelectionOption
533 var err error
534 var anilistSelectedOption SelectionOption
535
536 query, err = promptText(userCurdConfig, "Enter the anime name", false)
537 if err != nil {
538 Log("Error getting user input: " + err.Error())
539 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
540 }
541 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
542 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
543 } else {
544 animeOptions, err = SearchAnimeAnilist(query, user.Token)
545 if err != nil {
546 Log(fmt.Sprintf("Failed to search anime: %v", err))
547 ExitCurd(fmt.Errorf("Failed to search anime"))
548 }
549 }
550 if err != nil {
551 Log(fmt.Sprintf("Failed to search anime: %v", err))
552 ExitCurd(fmt.Errorf("Failed to search anime"))
553 }
554 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
555 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
556 } else {
557 anilistSelectedOption, err = DynamicSelect(animeOptions)
558 }
559 if err != nil {
560 Log(fmt.Sprintf("No anime available: %v", err))
561 ExitCurd(fmt.Errorf("No anime available"))
562 }
563
564 if anilistSelectedOption.Key == "-1" {
565 ExitCurd(nil)
566 }
567
568 // Handle back button - return to caller
569 if anilistSelectedOption.Key == "-2" {
570 return SelectionOption{Key: "-2", Label: "Back"}
571 }
572
573 animeID, err := strconv.Atoi(anilistSelectedOption.Key)
574 if err != nil {
575 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err))
576 ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
577 }
578
579 if !UsesRemoteTracking(userCurdConfig) {
580 return anilistSelectedOption
581 }
582
583 // Add category selection before adding to list
584 categories := []SelectionOption{
585 {Key: "CURRENT", Label: "Currently Watching"},
586 {Key: "COMPLETED", Label: "Completed"},
587 {Key: "PAUSED", Label: "On Hold"},
588 {Key: "DROPPED", Label: "Dropped"},
589 {Key: "PLANNING", Label: "Plan to Watch"},
590 {Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
591 }
592
593 ClearScreen()
594 CurdOut("Select which list to add the anime to:")
595
596 categorySelection, err := DynamicSelect(categories)
597 if err != nil {
598 Log(fmt.Sprintf("Failed to select category: %v", err))
599 ExitCurd(fmt.Errorf("Failed to select category"))
600 }
601
602 if categorySelection.Key == "-1" {
603 ExitCurd(nil)
604 }
605
606 // Handle back button - return to caller
607 if categorySelection.Key == "-2" {
608 return SelectionOption{Key: "-2", Label: "Back"}
609 }
610
611 err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
612 if err != nil {
613 Log(fmt.Sprintf("Failed to add anime to list: %v", err))
614 ExitCurd(fmt.Errorf("Failed to add anime to list"))
615 }
616
617 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
618 Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
619 ExitCurd(fmt.Errorf("Failed to refresh anime list"))
620 }
621
622 return anilistSelectedOption
623}
624
625func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) {
626 var err error
627 var startingRewatch bool
628
629 // Filter anime list based on selected category
630 var animeListOptions []SelectionOption
631 var animeListMapPreview map[string]RofiSelectPreview
632
633 // Initialize anime list. On a cache hit this is instant (reads from disk) and
634 // the user ID is seeded from the cached payload, avoiding a blocking network
635 // round-trip to AniList. The real user ID + latest list are refreshed in the
636 // background goroutine inside InitializeUserAnimeList.
637 if err := InitializeUserAnimeList(userCurdConfig, user); err != nil {
638 Log(fmt.Sprintf("Failed to initialize anime list: %v", err))
639 ExitCurd(fmt.Errorf("Failed to get user data\nYou can reset the token by running `curd -change-token`"))
640 }
641
642 // Variables for selection results (used in both branches and after)
643 var anilistSelectedOption SelectionOption
644 var selectedAllanimeAnime SelectionOption
645 var userQuery string
646 _ = selectedAllanimeAnime // Used later in the function
647
648 // Navigation loop for the entire setup process
649 for {
650 startingRewatch = false
651
652 // If continueLast flag is set, directly get the last watched anime
653 if anime.Ep.ContinueLast {
654 // Get the last anime ID from the curd_id file
655 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
656 idBytes, err := os.ReadFile(idFilePath)
657 if err != nil {
658 Log("Error reading curd_id file: " + err.Error())
659 ExitCurd(fmt.Errorf("No last watched anime found"))
660 }
661
662 anilistID, err := strconv.Atoi(string(idBytes))
663 if err != nil {
664 Log("Error converting anilist ID: " + err.Error())
665 ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
666 }
667
668 // Find the anime in database
669 animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
670 if animePointer == nil {
671 ExitCurd(fmt.Errorf("Last watched anime not found in database"))
672 }
673
674 // Set the anime details
675 anime.AnilistId = animePointer.AnilistId
676 anilistSelectedOption.Key = strconv.Itoa(animePointer.AnilistId)
677 // anime.ProviderId = animePointer.ProviderId
678 // anime.Title = animePointer.Title
679 // anime.Ep.Number = animePointer.Ep.Number
680 // anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
681 // anime.Ep.Resume = true
682
683 } else {
684 // Navigation loop for category and anime selection
685 categorySelectionLoop:
686 for {
687 // Skip category selection if Current flag is set
688 var categorySelection SelectionOption
689 if userCurdConfig.CurrentCategory {
690 categorySelection = SelectionOption{
691 Key: "CURRENT",
692 Label: "Currently Watching",
693 }
694 } else {
695 // Create category selection map
696 // Get ordered categories
697 orderedCategories := getOrderedCategories(userCurdConfig)
698
699 // Use DynamicSelect with ordered categories directly
700 categorySelection, err = DynamicSelect(orderedCategories)
701
702 if err != nil {
703 Log(fmt.Sprintf("Failed to select category: %v", err))
704 ExitCurd(fmt.Errorf("Failed to select category"))
705 }
706
707 if categorySelection.Key == "-1" {
708 ExitCurd(nil)
709 }
710
711 if categorySelection.Key == "-2" {
712 continue
713 }
714
715 // Handle options
716 if categorySelection.Key == "PROVIDER" {
717 ClearScreen()
718 ChangeProvider(userCurdConfig)
719 ClearScreen()
720 continue categorySelectionLoop
721 } else if categorySelection.Key == "TRACKER" {
722 ClearScreen()
723 ChangeTracker(userCurdConfig, user)
724 ClearScreen()
725 continue categorySelectionLoop
726 } else if categorySelection.Key == "UPDATE" {
727 ClearScreen()
728 UpdateAnimeEntry(userCurdConfig, user)
729 // If UpdateAnimeEntry returns, user pressed back - continue to category selection
730 ClearScreen()
731 continue categorySelectionLoop
732 } else if categorySelection.Key == "UNTRACKED" {
733 ClearScreen()
734 WatchUntracked(userCurdConfig)
735 // If WatchUntracked returns, user pressed back OR watched is done- continue to category selection
736 ClearScreen()
737 continue categorySelectionLoop
738 } else if categorySelection.Key == "CONTINUE_LAST" {
739 anime.Ep.ContinueLast = true
740 }
741
742 ClearScreen()
743 }
744
745 if user.ListSync != nil {
746 user.AnimeList = user.ListSync.Current()
747 }
748
749 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
750 animeListMapPreview = buildCategoryPreviewOptions(user.AnimeList, categorySelection.Key)
751 } else {
752 animeListOptions = buildCategorySelectionOptions(user.AnimeList, categorySelection.Key)
753 }
754
755 // Anime selection loop (for back navigation)
756 animeSelectionLoop:
757 for {
758 if anime.Ep.ContinueLast {
759 // Get the last watched anime ID from the curd_id file
760 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
761 curdIDBytes, err := os.ReadFile(curdIDPath)
762 if err != nil {
763 Log(fmt.Sprintf("Error reading curd_id file: %v", err))
764 ExitCurd(fmt.Errorf("Error reading curd_id file"))
765 }
766
767 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
768 if err != nil {
769 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err))
770 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
771 }
772
773 anime.AnilistId = lastWatchedID
774 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
775 break categorySelectionLoop
776 }
777
778 // Select anime to watch (Anilist)
779 var err error
780 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
781 anilistSelectedOption, err = DynamicSelectPreviewWithRefresh(animeListMapPreview, true, &PreviewSelectionRefreshConfig{
782 Updates: user.ListSync.Updates(),
783 BuildOptions: func(list AnimeList) map[string]RofiSelectPreview {
784 return buildCategoryPreviewOptions(list, categorySelection.Key)
785 },
786 })
787 } else {
788 // Add "Add new anime" option to the slice
789 tempOptions := make([]SelectionOption, len(animeListOptions))
790 copy(tempOptions, animeListOptions)
791
792 tempOptions = append(tempOptions, SelectionOption{
793 Key: "add_new",
794 Label: "Add new anime",
795 })
796
797 anilistSelectedOption, err = DynamicSelectWithRefresh(tempOptions, &SelectionRefreshConfig{
798 Updates: user.ListSync.Updates(),
799 BuildOptions: func(list AnimeList) []SelectionOption {
800 updatedOptions := buildCategorySelectionOptions(list, categorySelection.Key)
801
802 updatedOptions = append(updatedOptions, SelectionOption{
803 Key: "add_new",
804 Label: "Add new anime",
805 })
806 return updatedOptions
807 },
808 })
809 }
810 if err != nil {
811 Log(fmt.Sprintf("Error selecting anime: %v", err))
812 ExitCurd(fmt.Errorf("Error selecting anime"))
813 }
814
815 Log(anilistSelectedOption)
816
817 if anilistSelectedOption.Key == "-1" {
818 ExitCurd(nil)
819 }
820
821 // Handle back navigation - go back to category selection
822 if anilistSelectedOption.Key == "-2" {
823 if userCurdConfig.CurrentCategory {
824 // If CurrentCategory is forced, back means quit
825 ExitCurd(nil)
826 }
827 ClearScreen()
828 continue categorySelectionLoop
829 }
830
831 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
832 addResult := AddNewAnime(userCurdConfig, anime, user, databaseAnimes)
833 if addResult.Key == "-2" {
834 // Back from add new anime goes to anime selection
835 ClearScreen()
836 continue animeSelectionLoop
837 }
838 anilistSelectedOption = addResult
839 }
840
841 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
842 if err != nil {
843 Log(fmt.Sprintf("Error converting Anilist ID: %v", err))
844 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
845 }
846
847 // Successfully selected anime, break out of both loops
848 break categorySelectionLoop
849 }
850 }
851 }
852 // Wait for the background refresh goroutine to finish before reading
853 // progress+1. RefreshDone() is a channel that is closed (broadcast) the
854 // instant the goroutine completes — no polling, no race with the UI
855 // Updates consumer that already drained the updates channel.
856 if user.ListSync != nil {
857 select {
858 case <-user.ListSync.RefreshDone():
859 Log("Background refresh done, using latest anime list for playback")
860 case <-time.After(10 * time.Second):
861 Log("Timed out waiting for background anime list refresh; using cached list")
862 }
863 user.AnimeList = user.ListSync.Current()
864 }
865
866 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
867
868 // Get anime entry
869 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
870 if err != nil {
871 if UsesRemoteTracking(userCurdConfig) {
872 Log(fmt.Sprintf("Can not find the anime in tracked anime list: %v", err))
873 ExitCurd(fmt.Errorf("Can not find the anime in tracked anime list"))
874 }
875
876 fallbackAnime, fallbackErr := GetAnimeDataByID(anime.AnilistId, "")
877 if fallbackErr != nil {
878 Log(fmt.Sprintf("Failed to fetch fallback anime data: %v", fallbackErr))
879 ExitCurd(fmt.Errorf("Failed to get anime data"))
880 }
881
882 selectedAnilistAnime = &Entry{
883 Media: Media{
884 ID: fallbackAnime.AnilistId,
885 MalID: fallbackAnime.MalId,
886 Episodes: fallbackAnime.TotalEpisodes,
887 Title: fallbackAnime.Title,
888 Status: "FINISHED",
889 },
890 Progress: 0,
891 Status: "CURRENT",
892 CoverImage: fallbackAnime.CoverImage,
893 }
894 }
895
896 if selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED" {
897 handleUnreleasedAnime(userCurdConfig, user, anime, *selectedAnilistAnime)
898 ClearScreen()
899 continue
900 }
901
902 // Set anime entry
903 anime.Title = selectedAnilistAnime.Media.Title
904 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
905 anime.CoverImage = selectedAnilistAnime.CoverImage
906 if selectedAnilistAnime.Media.MalID != 0 {
907 anime.MalId = selectedAnilistAnime.Media.MalID
908 }
909 if anime.MalId == 0 {
910 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
911 }
912 anime.IsAiring = selectedAnilistAnime.Media.Status == "RELEASING" || selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED"
913 anime.Rewatching = selectedAnilistAnime.Status == "REPEATING"
914 anime.Repeat = selectedAnilistAnime.Repeat
915 anime.StartedAt = selectedAnilistAnime.StartedAt
916 anime.CompletedAt = selectedAnilistAnime.CompletedAt
917 anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
918 var animeList []SelectionOption
919 userQuery = anime.Title.Romaji
920
921 if selectedAnilistAnime.Status == "COMPLETED" {
922 CurdOut("This anime is completed. Start rewatch from episode 1? Continue without updating tracker? Open details?")
923 selectedOption, err := promptSelect([]SelectionOption{
924 {Key: "rewatch", Label: "Start rewatch from episode 1"},
925 {Key: "continue", Label: "Continue without updating tracker"},
926 {Key: "details", Label: "Open details"},
927 })
928 if err != nil {
929 Log(fmt.Sprintf("Error in completed anime prompt: %v", err))
930 ExitCurd(fmt.Errorf("Failed to select completed anime action"))
931 }
932
933 switch selectedOption.Key {
934 case "rewatch":
935 err = StartAnimeRewatch(user.Token, *anime)
936 if err != nil {
937 Log(fmt.Sprintf("Error starting anime rewatch: %v", err))
938 ExitCurd(fmt.Errorf("Failed to move anime to rewatching"))
939 }
940
941 anime.Rewatching = true
942 anime.SkipRemoteSync = false
943 anime.Ep.Number = 1
944 anime.Ep.Player.PlaybackTime = 0
945 anime.Ep.Resume = false
946 startingRewatch = true
947 CurdOut("Moved anime to Rewatching and restarting from episode 1.")
948
949 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
950 Log("Error refreshing anime list: " + err.Error())
951 ExitCurd(err)
952 }
953 case "continue":
954 anime.Rewatching = false
955 anime.SkipRemoteSync = true
956 anime.Ep.Number = 1
957 anime.Ep.Player.PlaybackTime = 0
958 anime.Ep.Resume = false
959 startingRewatch = true
960 CurdOut("Starting episode 1 without updating your tracker.")
961 case "details":
962 url := fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId)
963 CurdOut(fmt.Sprintf("Opening %s", url))
964 if err := browser.OpenURL(url); err != nil {
965 Log(fmt.Sprintf("Error opening browser: %v", err))
966 CurdOut("Failed to open browser.")
967 }
968 anime.Ep.ContinueLast = false
969 continue
970 case "-1":
971 ExitCurd(nil)
972 default:
973 anime.Ep.ContinueLast = false
974 continue
975 }
976 }
977
978 // Check if we need to research provider ID
979 needsProviderSearch := false
980 if animePointer == nil {
981 needsProviderSearch = true
982 } else if animePointer.ProviderName != "" && !ProviderStackContains(userCurdConfig, animePointer.ProviderName) {
983 needsProviderSearch = true
984 } else if animePointer.ProviderName == "" && !ProviderStackContains(userCurdConfig, "allanime") {
985 needsProviderSearch = true
986 }
987
988 // if anime not found in database or provider changed, find it in animeList
989 if needsProviderSearch {
990 Log("Anime not found in database for current provider, searching in animeList...")
991 // Get Anime list (All anime)
992 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
993
994 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
995 if err != nil {
996 Log(fmt.Sprintf("Failed to select anime: %v", err))
997 ExitCurd(fmt.Errorf("Failed to select anime"))
998 }
999 // Prompt user for manual query only when no results were found
1000 if len(animeList) == 0 {
1001 for {
1002 var manualQuery string
1003 manualQuery, err = promptText(userCurdConfig, fmt.Sprintf("No results found for '%s'. Press Enter to search with AniList name, or enter a custom name to search on configured providers.", userQuery), true)
1004 if err != nil {
1005 Log("Error getting user input: " + err.Error())
1006 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1007 }
1008
1009 // If empty, use original AniList name
1010 if manualQuery == "" {
1011 manualQuery = string(userQuery)
1012 }
1013
1014 animeList, err = SearchAnime(manualQuery, userCurdConfig.SubOrDub)
1015 if err != nil {
1016 Log(fmt.Sprintf("Failed to search anime with query '%s': %v", manualQuery, err))
1017 ExitCurd(fmt.Errorf("Failed to search anime"))
1018 }
1019
1020 if len(animeList) > 0 {
1021 break
1022 }
1023 }
1024 }
1025
1026 // Automatic mapping using Thumbnail clues
1027 // 1. Try AniList and MAL thumbnail matching
1028 found := false
1029 anilistIDStr := strconv.Itoa(anime.AnilistId)
1030 var jikanUrls []string
1031 fetchedJikan := false
1032
1033 // Helper regex
1034 // AniList regex extracts ID from strings like "bx155348-" or "/155348.jpg"
1035 anilistRegex := regexp.MustCompile(`anilistcdn/media/anime/cover/(?:large|medium)/(?:bx)?(\d+)`)
1036 // MyAnimeList regex extracts the filename like "120128.jpg"
1037 malRegex := regexp.MustCompile(`myanimelist\.net/images/anime/[^/]+/([^/]+\.jpg)`)
1038
1039 for i, option := range animeList {
1040 Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s', Thumbnail='%s'", i, option.Key, option.Label, option.Thumbnail))
1041
1042 if strings.Contains(option.Thumbnail, "anilist.co") {
1043 matches := anilistRegex.FindStringSubmatch(option.Thumbnail)
1044 if len(matches) > 1 && matches[1] == anilistIDStr {
1045 anime.ProviderId = option.Key
1046 Log(fmt.Sprintf("Found Anilist Thumbnail match! Setting ProviderId to: %s", anime.ProviderId))
1047 found = true
1048 break
1049 }
1050 } else if strings.Contains(option.Thumbnail, "myanimelist.net") {
1051 matches := malRegex.FindStringSubmatch(option.Thumbnail)
1052 if len(matches) > 1 {
1053 fileName := matches[1]
1054
1055 // Fetch Jikan pictures lazily (only once)
1056 if !fetchedJikan {
1057 if anime.MalId == 0 {
1058 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
1059 }
1060 if anime.MalId != 0 {
1061 urls, err := FetchJikanPictures(anime.MalId)
1062 if err != nil {
1063 Log(fmt.Sprintf("Failed to fetch Jikan pictures: %v", err))
1064 } else {
1065 jikanUrls = urls
1066 }
1067 }
1068 fetchedJikan = true
1069 }
1070
1071 for _, url := range jikanUrls {
1072 if strings.HasSuffix(url, "/"+fileName) || strings.Contains(url, fileName) {
1073 anime.ProviderId = option.Key
1074 Log(fmt.Sprintf("Found MyAnimeList Thumbnail match (%s)! Setting ProviderId to: %s", fileName, anime.ProviderId))
1075 found = true
1076 break
1077 }
1078 }
1079 }
1080 if found {
1081 break
1082 }
1083 }
1084 }
1085
1086 // 2. Jikan Metadata & Exact Anilist Meta Tag Matching (for animepahe)
1087 if !found && ProviderStackContains(userCurdConfig, "animepahe") {
1088 Log("Attempting deep metadata matching and exact AniList meta tag check for Animepahe...")
1089
1090 targetAnilistID := strconv.Itoa(anime.AnilistId)
1091 var bestMatch *SelectionOption
1092 var highestScore int
1093
1094 if anime.MalId == 0 {
1095 anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
1096 }
1097
1098 var malData *JikanAnimeData
1099 if anime.MalId != 0 {
1100 malData, _ = FetchJikanAnimeData(anime.MalId)
1101 }
1102
1103 for i := range animeList {
1104 opt := &animeList[i]
1105 optionProviderName, rawProviderID, ok := ParseProviderQualifiedID(opt.Key)
1106 if ok {
1107 if optionProviderName != "animepahe" {
1108 continue
1109 }
1110 } else {
1111 rawProviderID = opt.Key
1112 if configuredProviderNames(userCurdConfig)[0] != "animepahe" {
1113 continue
1114 }
1115 }
1116 score := 0
1117
1118 if malData != nil && opt.ExtraData != nil {
1119 if paheData, ok := opt.ExtraData.(AnimepaheSearchItem); ok {
1120 paheTitleLower := strings.ToLower(paheData.Title)
1121 malTitleLower := strings.ToLower(malData.Title)
1122 malTitleEngLower := strings.ToLower(malData.TitleEnglish)
1123 malTitleJapLower := strings.ToLower(malData.TitleJapanese)
1124
1125 if paheTitleLower == malTitleLower || (malTitleEngLower != "" && paheTitleLower == malTitleEngLower) || (malTitleJapLower != "" && paheTitleLower == malTitleJapLower) {
1126 score += 5
1127 } else if strings.Contains(paheTitleLower, malTitleLower) || strings.Contains(malTitleLower, paheTitleLower) ||
1128 (malTitleEngLower != "" && (strings.Contains(paheTitleLower, malTitleEngLower) || strings.Contains(malTitleEngLower, paheTitleLower))) {
1129 score += 2
1130 }
1131
1132 if paheData.Year > 0 && malData.Year > 0 && paheData.Year == malData.Year {
1133 score += 3
1134 }
1135 if paheData.Season != "" && malData.Season != "" && strings.EqualFold(paheData.Season, malData.Season) {
1136 score += 2
1137 }
1138 if paheData.Type != "" && malData.Type != "" && strings.EqualFold(paheData.Type, malData.Type) {
1139 score += 2
1140 }
1141 if paheData.Episodes > 0 && malData.Episodes > 0 && paheData.Episodes == malData.Episodes {
1142 score += 2
1143 } else if (paheData.Episodes == 0 && malData.Status == "Currently Airing") || (malData.Episodes == 0 && paheData.Status == "Currently Airing") {
1144 score += 2
1145 }
1146 if strings.EqualFold(paheData.Status, malData.Status) {
1147 score += 1
1148 }
1149 }
1150 } else {
1151 if strings.Contains(strings.ToLower(opt.Title), strings.ToLower(string(userQuery))) {
1152 score += 2
1153 }
1154 }
1155
1156 // If it has a decent score (or there are very few options), let's verify with the exact AniList meta tag
1157 if score >= 2 || len(animeList) <= 3 {
1158 animeRef := parseAnimepaheProviderID(rawProviderID)
1159 if animeRef.Session == "" {
1160 continue
1161 }
1162 animeUrl := fmt.Sprintf("https://animepahe.pw/anime/%s", animeRef.Session)
1163 Log(fmt.Sprintf("Fetching %s to check exact AniList meta tag...", animeUrl))
1164 req, err := newAnimepahePageRequest(animeUrl)
1165 if err != nil {
1166 Log(fmt.Sprintf("Failed to build animepahe detail request %s: %v", animeUrl, err))
1167 continue
1168 }
1169
1170 resp, err := sharedHTTPClient.Do(req)
1171 if err != nil {
1172 Log(fmt.Sprintf("Failed to fetch animepahe detail page %s: %v", animeUrl, err))
1173 continue
1174 }
1175 body, readErr := io.ReadAll(resp.Body)
1176 resp.Body.Close()
1177 if readErr != nil {
1178 Log(fmt.Sprintf("Failed to read animepahe detail page %s: %v", animeUrl, readErr))
1179 continue
1180 }
1181 if resp.StatusCode == http.StatusOK {
1182 bodyStr := string(body)
1183
1184 metaTag := fmt.Sprintf(`<meta name="anilist" content="%s">`, targetAnilistID)
1185 if strings.Contains(bodyStr, metaTag) {
1186 Log(fmt.Sprintf("FOUND EXACT ANILIST META TAG MATCH in %s!", opt.Title))
1187 bestMatch = opt
1188 highestScore = 100 // Guarantee selection
1189 break
1190 } else {
1191 malMetaTag := fmt.Sprintf(`<meta name="mal" content="%d">`, anime.MalId)
1192 if anime.MalId != 0 && strings.Contains(bodyStr, malMetaTag) {
1193 Log(fmt.Sprintf("FOUND EXACT MAL META TAG MATCH in %s!", opt.Title))
1194 bestMatch = opt
1195 highestScore = 100
1196 break
1197 }
1198 }
1199 }
1200 }
1201
1202 if score > highestScore {
1203 highestScore = score
1204 bestMatch = opt
1205 }
1206 }
1207
1208 if bestMatch != nil && highestScore == 100 {
1209 anime.ProviderId = bestMatch.Key
1210 Log(fmt.Sprintf("Found EXACT meta tag match! Score: %d. Setting ProviderId to: %s", highestScore, anime.ProviderId))
1211 found = true
1212 } else if bestMatch != nil {
1213 Log(fmt.Sprintf("Highest match score was %d (needed 100 for Animepahe exact meta tag match). Not selecting automatically to prevent false positives.", highestScore))
1214 if confirmProviderMatch(*bestMatch, "Animepahe metadata") {
1215 anime.ProviderId = bestMatch.Key
1216 Log(fmt.Sprintf("User confirmed Animepahe match. Setting ProviderId to: %s", anime.ProviderId))
1217 found = true
1218 }
1219 }
1220 }
1221
1222 // 3. Fallback to naive title/episode match
1223 if !found {
1224 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes)
1225 for _, option := range animeList {
1226 if fmt.Sprintf("%s (%d episodes)", option.Title, selectedAnilistAnime.Media.Episodes) == targetLabel {
1227 if confirmProviderMatch(option, "title and episode count") {
1228 anime.ProviderId = option.Key
1229 Log(fmt.Sprintf("User confirmed exact text match. Setting ProviderId to: %s", anime.ProviderId))
1230 found = true
1231 }
1232 break
1233 }
1234 }
1235 if !found {
1236 Log(fmt.Sprintf("No exact match found for label '%s'. Will require manual selection.", targetLabel))
1237 }
1238 }
1239
1240 // If unable to get Allanime id automatically get manually
1241 if anime.ProviderId == "" {
1242 CurdOut("We didn't find any matches. Please select manually.")
1243 selectedAllanimeAnime, err := DynamicSelect(animeList)
1244 if err != nil {
1245 ExitCurd(fmt.Errorf("No anime available"))
1246 }
1247
1248 if selectedAllanimeAnime.Key == "-1" {
1249 ExitCurd(nil)
1250 }
1251
1252 // Handle back button - go back to main menu
1253 if selectedAllanimeAnime.Key == "-2" {
1254 CurdOut("Going back to main menu...")
1255 RestoreScreen()
1256 if anime.Ep.ContinueLast {
1257 anime.Ep.ContinueLast = false
1258 }
1259 continue
1260 }
1261
1262 anime.ProviderId = selectedAllanimeAnime.Key
1263 }
1264 if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
1265 anime.ProviderName = providerName
1266 anime.ProviderId = rawProviderID
1267 } else {
1268 anime.ProviderName = configuredProviderNames(userCurdConfig)[0]
1269 }
1270 }
1271
1272 // if anime found in database, use its playback state
1273 if animePointer != nil {
1274 if !needsProviderSearch {
1275 anime.ProviderId = animePointer.ProviderId
1276 anime.ProviderName = animePointer.ProviderName
1277 }
1278 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
1279 if anime.Ep.Number == animePointer.Ep.Number {
1280 anime.Ep.Resume = true
1281 }
1282
1283 // If local history episode is ahead of AniList upstream, prompt user
1284 anilistEpisode := nextEpisodeFromProgress(selectedAnilistAnime.Progress)
1285 if animePointer.Ep.Number > anilistEpisode {
1286 trackerLabel := RemoteTrackingDisplayName(userCurdConfig)
1287 Log(fmt.Sprintf("Local history episode (%d) is ahead of %s episode (%d), prompting user", animePointer.Ep.Number, trackerLabel, anilistEpisode))
1288 options := []SelectionOption{
1289 {Key: "update_upstream", Label: fmt.Sprintf("Use Curd episode %d", animePointer.Ep.Number)},
1290 {Key: "use_anilist", Label: fmt.Sprintf("Use %s episode %d", trackerLabel, anilistEpisode)},
1291 }
1292 CurdOut(fmt.Sprintf("Curd has episode %d. %s has episode %d. Pick one.", animePointer.Ep.Number, trackerLabel, anilistEpisode))
1293 selectedOption, err := DynamicSelect(options)
1294 if err != nil {
1295 Log("Error in episode conflict selection: " + err.Error())
1296 } else if selectedOption.Key == "-1" {
1297 ExitCurd(nil)
1298 } else if selectedOption.Key == "update_upstream" {
1299 // Update remote progress to match local history (progress = local ep - 1, since local ep is "next to watch")
1300 progressToUpdate := animePointer.Ep.Number - 1
1301 if err := UpdateAnimeProgress(user.Token, anime.AnilistId, progressToUpdate); err != nil {
1302 Log(fmt.Sprintf("Error updating %s progress to %d: %v", trackerLabel, progressToUpdate, err))
1303 } else {
1304 Log(fmt.Sprintf("Updated %s progress to %d", trackerLabel, progressToUpdate))
1305 }
1306 anime.Ep.Number = animePointer.Ep.Number
1307 anime.Ep.Resume = true
1308 } else if selectedOption.Key == "use_anilist" {
1309 // Use remote next-episode number (already set from selectedAnilistAnime.Progress + 1)
1310 anime.Ep.Number = anilistEpisode
1311 anime.Ep.Player.PlaybackTime = 0
1312 anime.Ep.Resume = false
1313 }
1314 } else {
1315 anime.Ep.Number = animePointer.Ep.Number
1316 }
1317 }
1318
1319 if startingRewatch {
1320 anime.Ep.Player.PlaybackTime = 0
1321 anime.Ep.Resume = false
1322 }
1323
1324 if selectedAllanimeAnime.Key == "-1" {
1325 ExitCurd(nil)
1326 }
1327
1328 // If anime is not in watching list, prompt user to add it into watching list
1329 isInWatchingList := false
1330 for _, entry := range user.AnimeList.Watching {
1331 if entry.Media.ID == anime.AnilistId {
1332 isInWatchingList = true
1333 break
1334 }
1335 }
1336 if !isInWatchingList {
1337 for _, entry := range user.AnimeList.Rewatching {
1338 if entry.Media.ID == anime.AnilistId {
1339 isInWatchingList = true
1340 break
1341 }
1342 }
1343 }
1344 if anime.Rewatching {
1345 isInWatchingList = true
1346 }
1347
1348 if ShouldWriteRemoteTracking(userCurdConfig, anime) && !isInWatchingList {
1349 // Create options for the prompt
1350 options := []SelectionOption{
1351 {Key: "yes", Label: "Add to watching list"},
1352 {Key: "no", Label: "Continue without adding"},
1353 }
1354
1355 var selectedOption SelectionOption
1356 var err error
1357
1358 // Use rofi for selection
1359 selectedOption, err = DynamicSelect(options)
1360 if err != nil {
1361 Log("Error in selection: " + err.Error())
1362 ExitCurd(err)
1363 }
1364
1365 if selectedOption.Key == "yes" {
1366 err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
1367 if err != nil {
1368 Log("Error adding anime to watching list: " + err.Error())
1369 ExitCurd(err)
1370 }
1371 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
1372 Log("Error refreshing anime list: " + err.Error())
1373 ExitCurd(err)
1374 }
1375 } else if selectedOption.Key == "-1" {
1376 ExitCurd(nil)
1377 } else if selectedOption.Key == "-2" {
1378 // Handle back button - go back to main menu
1379 CurdOut("Going back to main menu...")
1380 RestoreScreen()
1381 // If we were continuing last, disable it so we go to menu next loop
1382 if anime.Ep.ContinueLast {
1383 anime.Ep.ContinueLast = false
1384 }
1385 continue
1386 }
1387 }
1388
1389 // If upstream is ahead, update the episode number
1390 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
1391 upstreamNextEpisode := nextEpisodeFromProgress(temp_anime.Progress)
1392 if upstreamNextEpisode > anime.Ep.Number {
1393 anime.Ep.Number = upstreamNextEpisode
1394 anime.Ep.Player.PlaybackTime = 0
1395 anime.Ep.Resume = false
1396 }
1397 }
1398
1399 if anime.TotalEpisodes == 0 {
1400 // Get updated anime data
1401 Log(selectedAllanimeAnime)
1402 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
1403 Log(updatedAnime)
1404 if err != nil {
1405 Log(fmt.Sprintf("Error getting updated anime data: %v", err))
1406 } else {
1407 anime.TotalEpisodes = updatedAnime.TotalEpisodes
1408 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
1409 }
1410 }
1411
1412 if anime.TotalEpisodes == 0 { // If failed to get anime data
1413 CurdOut("AniList/MAL did not return total episodes. Attempting to retrieve from provider episode list.")
1414 providerName, providerID := AnimeProviderID(anime)
1415 providerTotal, err := GetProviderTotalEpisodes(QualifyProviderID(providerName, providerID), userCurdConfig.SubOrDub)
1416 if err != nil {
1417 Log(fmt.Sprintf("Failed to retrieve total episodes from provider episode list: %v", err))
1418 } else {
1419 anime.TotalEpisodes = providerTotal
1420 CurdOut(fmt.Sprintf("Retrieved total episodes from provider: %d", anime.TotalEpisodes))
1421 }
1422 }
1423
1424 if anime.TotalEpisodes == 0 { // If provider episode list did not have a usable total
1425 CurdOut("Attempting to retrieve total episodes from anime search results.")
1426 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
1427 if err != nil {
1428 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
1429 } else {
1430 for _, option := range animeList {
1431 optionProviderName, optionProviderID, ok := ParseProviderQualifiedID(option.Key)
1432 if !ok {
1433 optionProviderName = configuredProviderNames(userCurdConfig)[0]
1434 optionProviderID = option.Key
1435 }
1436 if optionProviderID == anime.ProviderId && optionProviderName == CurrentAnimeProviderName(anime) {
1437 // Extract total episodes from the label
1438 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 {
1439 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
1440 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
1441 break
1442 }
1443 }
1444 }
1445 }
1446
1447 if anime.TotalEpisodes == 0 {
1448 CurdOut("Still unable to determine total episodes.")
1449 CurdOut(fmt.Sprintf("Your %s progress: %d", RemoteTrackingDisplayName(userCurdConfig), selectedAnilistAnime.Progress))
1450 episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, "Enter the episode you want to start from")
1451 if err != nil {
1452 Log("Invalid episode input: " + err.Error())
1453 ExitCurd(fmt.Errorf("Invalid episode number"))
1454 }
1455 anime.Ep.Number = episodeNumber
1456 } else {
1457 anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
1458 }
1459 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
1460 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
1461 var answer string
1462 if userCurdConfig.RofiSelection {
1463 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
1464 if err != nil {
1465 Log("Error getting user input: " + err.Error())
1466 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1467 }
1468 answer = userInput
1469 } else {
1470 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
1471 fmt.Scanln(&answer)
1472 }
1473 if isAffirmativeAnswer(answer) {
1474 anime.Ep.Number = 1
1475 } else {
1476 anime.Ep.Number = anime.TotalEpisodes
1477 }
1478 }
1479
1480 // If we reached here successfully, break the loop
1481 break
1482 }
1483}
1484
1485// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
1486func WriteTokenToFile(token string, filePath string) error {
1487 // Extract the directory path
1488 dir := filepath.Dir(filePath)
1489
1490 // Create all necessary parent directories
1491 if err := os.MkdirAll(dir, 0755); err != nil {
1492 return fmt.Errorf("failed to create directories: %v", err)
1493 }
1494
1495 // Write the token to the file, creating it if it doesn't exist
1496 err := os.WriteFile(filePath, []byte(token), 0644)
1497 if err != nil {
1498 return fmt.Errorf("failed to write token to file: %v", err)
1499 }
1500
1501 return nil
1502}
1503
1504func handleUnreleasedAnime(userCurdConfig *CurdConfig, user *User, anime *Anime, entry Entry) {
1505 title := entry.Media.Title.Romaji
1506 if userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" && entry.Media.Title.English != "" {
1507 title = entry.Media.Title.English
1508 }
1509 if title == "" {
1510 title = strconv.Itoa(entry.Media.ID)
1511 }
1512
1513 CurdOut(fmt.Sprintf("%s is not released yet.", title))
1514 options := []SelectionOption{}
1515 if UsesRemoteTracking(userCurdConfig) {
1516 options = append(options, SelectionOption{Key: "planning", Label: "Add to Plan to Watch"})
1517 }
1518 options = append(options,
1519 SelectionOption{Key: "details", Label: "Open AniList details"},
1520 SelectionOption{Key: "back", Label: "Back to list"},
1521 )
1522
1523 selected, err := promptSelect(options)
1524 if err != nil {
1525 Log(fmt.Sprintf("Error in unreleased anime prompt: %v", err))
1526 anime.Ep.ContinueLast = false
1527 return
1528 }
1529
1530 switch selected.Key {
1531 case "planning":
1532 if err := AddAnimeToList(entry.Media.ID, "PLANNING", user.Token); err != nil {
1533 Log(fmt.Sprintf("Error adding unreleased anime to planning: %v", err))
1534 CurdOut("Failed to add to Plan to Watch.")
1535 } else {
1536 CurdOut("Added to Plan to Watch.")
1537 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
1538 Log("Error refreshing anime list: " + err.Error())
1539 }
1540 }
1541 case "details":
1542 url := fmt.Sprintf("https://anilist.co/anime/%d", entry.Media.ID)
1543 CurdOut(fmt.Sprintf("Opening %s", url))
1544 if err := browser.OpenURL(url); err != nil {
1545 Log(fmt.Sprintf("Error opening browser: %v", err))
1546 CurdOut("Failed to open browser.")
1547 }
1548 case "-1":
1549 ExitCurd(nil)
1550 }
1551 anime.Ep.ContinueLast = false
1552}
1553
1554func confirmProviderMatch(option SelectionOption, reason string) bool {
1555 label := option.Label
1556 if label == "" {
1557 label = option.Title
1558 }
1559 if label == "" {
1560 label = option.Key
1561 }
1562
1563 CurdOut(fmt.Sprintf("Provider match found by %s: %s", reason, label))
1564 selected, err := promptSelect([]SelectionOption{
1565 {Key: "use", Label: "Use this match"},
1566 {Key: "manual", Label: "Select manually"},
1567 })
1568 if err != nil {
1569 Log(fmt.Sprintf("Error confirming provider match: %v", err))
1570 return false
1571 }
1572 return selected.Key == "use"
1573}
1574
1575func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1576 if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil {
1577 Log(fmt.Sprintf("Failed to resolve provider id: %v", err))
1578 CurdOut("Failed to resolve anime provider id: " + err.Error())
1579 os.Exit(1)
1580 }
1581
1582 // Validate inputs
1583 if anime.ProviderId == "" {
1584 CurdOut("Error: No anime ID found")
1585 os.Exit(1)
1586 }
1587 if anime.Ep.Number <= 0 {
1588 CurdOut("Error: Invalid episode number")
1589 os.Exit(1)
1590 }
1591
1592 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1593 anime.Ep.Links = anime.Ep.NextEpisode.Links
1594 if anime.Ep.NextEpisode.ProviderName != "" {
1595 anime.ProviderName = anime.Ep.NextEpisode.ProviderName
1596 anime.ProviderId = anime.Ep.NextEpisode.ProviderId
1597 }
1598 } else {
1599 // Get episode link
1600 episodeResult, err := ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1601 link := episodeResult.Links
1602 if len(link) > 0 {
1603 Log(fmt.Sprintf("Links details from %s/%s: %+v", episodeResult.ProviderName, episodeResult.Mode, link))
1604 }
1605 if err != nil {
1606 linkErr := err
1607 Log(fmt.Sprintf("ResolveEpisodeURL failed: %v", linkErr))
1608 if reselectProviderAnime(userCurdConfig, anime, linkErr) {
1609 episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1610 link = episodeResult.Links
1611 if err == nil {
1612 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link after provider reselect. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link)))
1613 anime.Ep.Links = link
1614 goto episodeLinksReady
1615 }
1616 linkErr = err
1617 Log(fmt.Sprintf("ResolveEpisodeURL still failed after provider reselect: %v", linkErr))
1618 }
1619 // If unable to get episode link automatically get manually
1620 episodeProviderName, episodeProviderID := AnimeProviderID(anime)
1621 episodeList, listErr := EpisodesList(QualifyProviderID(episodeProviderName, episodeProviderID), userCurdConfig.SubOrDub)
1622 if listErr != nil {
1623 CurdOut("No episode list found: " + listErr.Error())
1624 Log(fmt.Sprintf("EpisodesList failed: %v", listErr))
1625 RestoreScreen()
1626 os.Exit(1)
1627 }
1628 if len(episodeList) == 0 {
1629 CurdOut("No episodes were returned by the current provider for this anime.")
1630 Log(fmt.Sprintf("EpisodesList returned no episodes for provider %s and id %s after ResolveEpisodeURL error: %v", episodeProviderName, episodeProviderID, linkErr))
1631 RestoreScreen()
1632 os.Exit(1)
1633 }
1634 episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1635 if err != nil {
1636 Log("Invalid episode input: " + err.Error())
1637 CurdOut("Invalid episode number")
1638 RestoreScreen()
1639 os.Exit(1)
1640 }
1641 anime.Ep.Number = episodeNumber
1642 episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1643 link = episodeResult.Links
1644 if err != nil {
1645 CurdOut("Failed to get episode link")
1646 os.Exit(1)
1647 }
1648 } else {
1649 Log(fmt.Sprintf("Successfully retrieved %s/%s episode link on first try. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link)))
1650 }
1651 anime.Ep.Links = link
1652 }
1653
1654episodeLinksReady:
1655 if len(anime.Ep.Links) == 0 {
1656 CurdOut("No episode links found")
1657 os.Exit(1)
1658 } else {
1659 Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links)))
1660 }
1661
1662 // Modify the goroutine in main.go where next episode links are fetched
1663 // Get next episode link in parallel
1664 go func() {
1665 nextEpNum := anime.Ep.Number + 1
1666 if nextEpNum <= anime.TotalEpisodes {
1667 // Get next canon episode number if filler skip is enabled
1668 if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) {
1669 nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum)
1670 }
1671 nextEpisode := *anime
1672 nextEpisode.ProviderId = anime.ProviderId
1673 nextEpisode.ProviderName = anime.ProviderName
1674 nextResult, err := ResolveEpisodeURL(*userCurdConfig, &nextEpisode, nextEpNum)
1675 if err != nil {
1676 Log(fmt.Sprintf("Error getting next episode link for ep %d: %v", nextEpNum, err))
1677 } else {
1678 anime.Ep.NextEpisode = NextEpisode{
1679 Number: nextEpNum,
1680 Links: nextResult.Links,
1681 ProviderName: nextResult.ProviderName,
1682 ProviderId: nextResult.ProviderID,
1683 Mode: nextResult.Mode,
1684 }
1685 }
1686 } else {
1687 Log(fmt.Sprintf("Next episode %d exceeds total episodes %d, skipping prefetch", nextEpNum, anime.TotalEpisodes))
1688 }
1689 }()
1690
1691 // Write anime.AnilistId to curd_id in the storage path
1692 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1693 Log(fmt.Sprintf("idFilePath: %v", idFilePath))
1694 if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
1695 Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err))
1696 } else {
1697 if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
1698 Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err))
1699 }
1700 }
1701
1702 // Display starting message with cover image and episode info
1703 if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
1704 // Get the cached image path
1705 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
1706 filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
1707 cachePath := filepath.Join(cacheDir, filename)
1708
1709 // Display the image if it exists in cache
1710 _, err := os.Stat(cachePath)
1711 if err == nil {
1712 // File exists
1713 Log(fmt.Sprintf("Image found at %s", cachePath))
1714 CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
1715 } else {
1716 // File does not exist
1717 Log(fmt.Sprintf("Image does not exist at %s", cachePath))
1718 CurdOut(fmt.Sprintf("%s - Episode %d",
1719 GetAnimeName(*anime),
1720 anime.Ep.Number))
1721
1722 }
1723 } else {
1724 CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
1725 }
1726 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number), anime)
1727
1728 if err != nil {
1729 Log("Failed to start mpv")
1730 os.Exit(1)
1731 }
1732
1733 return mpvSocketPath
1734}
1735
1736func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
1737 if anime == nil || anime.ProviderId == "" {
1738 return nil
1739 }
1740
1741 providerName, providerID := AnimeProviderID(anime)
1742 if providerName != "animepahe" {
1743 return nil
1744 }
1745 if !ProviderStackContains(userCurdConfig, "animepahe") {
1746 return nil
1747 }
1748
1749 provider, err := ProviderByName(providerName)
1750 if err != nil {
1751 return err
1752 }
1753 animepaheProvider, ok := provider.(*AnimepaheProvider)
1754 if !ok {
1755 return nil
1756 }
1757
1758 query := GetAnimeName(*anime)
1759 if query == "" {
1760 query = anime.Title.Romaji
1761 }
1762 if query == "" {
1763 query = anime.Title.English
1764 }
1765
1766 resolved, err := animepaheProvider.ResolveProviderID(providerID, query)
1767 if err != nil {
1768 return err
1769 }
1770 if resolved != "" && resolved != providerID {
1771 Log(fmt.Sprintf("Resolved Animepahe provider id %s to runtime id %s", providerID, resolved))
1772 anime.ProviderId = resolved
1773 anime.ProviderName = providerName
1774 }
1775
1776 return nil
1777}
1778
1779func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason error) bool {
1780 providerName, _ := AnimeProviderID(anime)
1781 if providerName != "animepahe" {
1782 return false
1783 }
1784
1785 if reason != nil {
1786 Log(fmt.Sprintf("Attempting Animepahe provider reselect after error: %v", reason))
1787 }
1788
1789 query := GetAnimeName(*anime)
1790 if query == "" {
1791 query = anime.Title.Romaji
1792 }
1793 if query == "" {
1794 query = anime.Title.English
1795 }
1796 if query == "" {
1797 return false
1798 }
1799
1800 options, err := SearchAnime(query, userCurdConfig.SubOrDub)
1801 if err != nil {
1802 Log(fmt.Sprintf("Animepahe provider reselect search failed for %q: %v", query, err))
1803 return false
1804 }
1805 if len(options) == 0 {
1806 Log(fmt.Sprintf("Animepahe provider reselect found no results for %q", query))
1807 return false
1808 }
1809
1810 CurdOut("The saved Animepahe mapping is stale. Please select the anime again.")
1811 selected, err := promptSelect(options)
1812 if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" {
1813 if err != nil {
1814 Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err))
1815 }
1816 return false
1817 }
1818
1819 if selectedProviderName, rawProviderID, ok := ParseProviderQualifiedID(selected.Key); ok {
1820 anime.ProviderName = selectedProviderName
1821 anime.ProviderId = rawProviderID
1822 } else {
1823 anime.ProviderName = "animepahe"
1824 anime.ProviderId = selected.Key
1825 }
1826 anime.Ep.NextEpisode = NextEpisode{}
1827 Log(fmt.Sprintf("Updated Animepahe ProviderId to %s after stale mapping", anime.ProviderId))
1828 return true
1829}
1830
1831func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1832 // Create storage directory if it doesn't exist
1833 storagePath = os.ExpandEnv(storagePath)
1834 if err := os.MkdirAll(storagePath, 0755); err != nil {
1835 return fmt.Errorf("failed to create storage directory: %v", err)
1836 }
1837
1838 // Base URL for downloading config files
1839 baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
1840
1841 // Check each file
1842 for _, fileName := range filesToCheck {
1843 filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
1844
1845 // Skip if file already exists
1846 if _, err := os.Stat(filePath); err == nil {
1847 continue
1848 }
1849
1850 // Download file if it doesn't exist
1851 resp, err := sharedHTTPClient.Get(baseURL + fileName)
1852 if err != nil {
1853 return fmt.Errorf("failed to download %s: %v", fileName, err)
1854 }
1855 if resp.StatusCode != http.StatusOK {
1856 resp.Body.Close()
1857 return fmt.Errorf("failed to download %s: received status code %d", fileName, resp.StatusCode)
1858 }
1859
1860 // Create the file
1861 out, err := os.Create(filePath)
1862 if err != nil {
1863 resp.Body.Close()
1864 return fmt.Errorf("failed to create file %s: %v", fileName, err)
1865 }
1866
1867 // Write the content
1868 if _, err := io.Copy(out, resp.Body); err != nil {
1869 resp.Body.Close()
1870 out.Close()
1871 return fmt.Errorf("failed to write file %s: %v", fileName, err)
1872 }
1873 resp.Body.Close()
1874 if err := out.Close(); err != nil {
1875 return fmt.Errorf("failed to close file %s: %v", fileName, err)
1876 }
1877 }
1878
1879 return nil
1880}
1881
1882func getEntriesByCategory(list AnimeList, category string) []Entry {
1883 switch category {
1884 case "ALL":
1885 // Combine all categories into one slice
1886 allEntries := make([]Entry, 0)
1887 allEntries = append(allEntries, list.Watching...)
1888 allEntries = append(allEntries, list.Completed...)
1889 allEntries = append(allEntries, list.Paused...)
1890 allEntries = append(allEntries, list.Dropped...)
1891 allEntries = append(allEntries, list.Planning...)
1892 allEntries = append(allEntries, list.Rewatching...)
1893 return allEntries
1894 case "CURRENT":
1895 currentEntries := make([]Entry, 0, len(list.Watching)+len(list.Rewatching))
1896 currentEntries = append(currentEntries, list.Watching...)
1897 currentEntries = append(currentEntries, list.Rewatching...)
1898 return currentEntries
1899 case "COMPLETED":
1900 return list.Completed
1901 case "PAUSED":
1902 return list.Paused
1903 case "DROPPED":
1904 return list.Dropped
1905 case "PLANNING":
1906 return list.Planning
1907 case "REWATCHING": // Added for completeness, though "ALL" covers it.
1908 return list.Rewatching
1909 default:
1910 return []Entry{}
1911 }
1912}
1913
1914func NextEpisodePromptCLI(userCurdConfig *CurdConfig) bool {
1915 anime := GetGlobalAnime()
1916
1917 // Show the next episode number that will be started
1918 nextEpisodeNum := anime.Ep.Number + 1
1919 isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1920 if isLastKnownEpisode {
1921 CurdOut("Finish this series?")
1922 } else {
1923 CurdOut(fmt.Sprintf("Start next episode (%d)?", nextEpisodeNum))
1924 }
1925
1926 // Create options for the selection - no "quit" option since it's built into selection menu
1927 label := fmt.Sprintf("Yes, continue to episode %d", nextEpisodeNum)
1928 if isLastKnownEpisode {
1929 label = "Yes, finish series"
1930 }
1931 options := []SelectionOption{
1932 {Key: "yes", Label: label},
1933 }
1934
1935 // Use DynamicSelect for CLI mode
1936 selectedOption, err := DynamicSelect(options)
1937 if err != nil {
1938 Log(fmt.Sprintf("Error in CLI next episode prompt selection: %v", err))
1939 return false
1940 }
1941
1942 Log(fmt.Sprintf("CLI User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1943
1944 if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1945 // User selected to quit/back via the built-in option
1946 CurdOut("Exiting")
1947 return false
1948 }
1949
1950 return selectedOption.Key == "yes"
1951}
1952
1953// NextEpisodePromptContinuous provides a continuous next episode prompt for CLI mode
1954// This runs throughout the episode duration and handles completion logic
1955func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1956 anime := GetGlobalAnime()
1957
1958 for {
1959 // Check if episode has started
1960 if !anime.Ep.Started {
1961 time.Sleep(1 * time.Second)
1962 continue
1963 }
1964
1965 // Show the next episode number that will be started
1966 nextEpisodeNum := anime.Ep.Number + 1
1967 isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1968 if isLastKnownEpisode {
1969 CurdOut("Finish this series or quit?")
1970 } else {
1971 CurdOut(fmt.Sprintf("Continue to next episode (%d) or quit?", nextEpisodeNum))
1972 }
1973
1974 // Create options for the selection - no "quit" option since it's built into selection menu
1975 label := "Yes, start next episode now"
1976 if isLastKnownEpisode {
1977 label = "Yes, finish series"
1978 }
1979 options := []SelectionOption{
1980 {Key: "yes", Label: label},
1981 }
1982
1983 // Use DynamicSelect for CLI mode
1984 selectedOption, err := DynamicSelect(options)
1985 if err != nil {
1986 Log(fmt.Sprintf("Error in CLI continuous next episode prompt: %v", err))
1987 break
1988 }
1989
1990 Log(fmt.Sprintf("CLI Continuous User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1991
1992 if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1993 // User selected to quit/back via the built-in option
1994
1995 // Check completion percentage
1996 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
1997
1998 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
1999 // Episode is considered completed, mark it and update progress
2000 anime.Ep.IsCompleted = true
2001
2002 // Handle completion if this was the last episode
2003 if anime.Ep.Number == anime.TotalEpisodes {
2004 HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
2005 }
2006
2007 // Update local database
2008 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 {
2009 Log("Error updating local database on quit: " + updateErr.Error())
2010 }
2011
2012 if !(anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && anime.Rewatching) {
2013 completedEpisode := anime.Ep.Number
2014 go func(progressEpisode int) {
2015 if progressErr := UpdateAnimeProgress(userToken, anime.AnilistId, progressEpisode); progressErr != nil {
2016 Log("Error updating Anilist progress on quit: " + progressErr.Error())
2017 }
2018 }(completedEpisode)
2019 }
2020
2021 CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched))
2022 } else {
2023 CurdOut(fmt.Sprintf("Episode not completed (%.1f%% watched). Exiting.", percentageWatched))
2024 }
2025
2026 ExitMPV(anime.Ep.Player.SocketPath)
2027 ExitCurd(nil)
2028 return
2029 }
2030
2031 if selectedOption.Key == "yes" {
2032 // User wants to start next episode immediately
2033 anime.Ep.IsCompleted = true
2034 socketPath := anime.Ep.Player.SocketPath
2035 if anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes {
2036 ExitMPV(socketPath)
2037 }
2038 StartNextEpisode(anime, userCurdConfig, databaseFile, userToken)
2039 ExitMPV(socketPath)
2040 return // Exit this function, let the main loop handle next episode
2041 }
2042 }
2043}
2044
2045// Simple next episode prompt for Rofi mode - just asks if user wants to continue
2046func NextEpisodePromptRofi(userCurdConfig *CurdConfig) bool {
2047 anime := GetGlobalAnime()
2048
2049 // Show the next episode number that will be started
2050 nextEpisodeNum := anime.Ep.Number + 1
2051 isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
2052
2053 // Create options for the selection
2054 label := fmt.Sprintf("Yes, start episode %d", nextEpisodeNum)
2055 if isLastKnownEpisode {
2056 label = "Yes, finish series"
2057 }
2058 options := []SelectionOption{
2059 {Key: "yes", Label: label},
2060 }
2061
2062 // Use DynamicSelect for Rofi mode
2063 selectedOption, err := DynamicSelect(options)
2064 if err != nil {
2065 Log(fmt.Sprintf("Error in next episode prompt selection: %v", err))
2066 return false
2067 }
2068
2069 Log(fmt.Sprintf("Rofi User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
2070
2071 return selectedOption.Key == "yes"
2072}
2073
2074// StartNextEpisode handles the logic for starting the next episode
2075// It updates the episode number, resets necessary flags, and handles database updates
2076func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile string, userToken string) {
2077 // Save previous episode number for progress update
2078 prevEpisode := anime.Ep.Number
2079
2080 // Check if we just completed the last episode
2081 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
2082 // Handle scoring and completion for the last episode
2083 HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
2084
2085 if !anime.Rewatching {
2086 err := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
2087 if err != nil {
2088 Log("Error updating Anilist progress: " + err.Error())
2089 }
2090 }
2091 // Note: UpdateAnimeProgress already outputs a message on success
2092
2093 CurdOut("Series completed!")
2094 ExitCurd(nil)
2095 return
2096 }
2097
2098 // Increment episode number
2099 anime.Ep.Number++
2100
2101 // Check if we've reached the end of the series
2102 if anime.TotalEpisodes > 0 && anime.Ep.Number > anime.TotalEpisodes {
2103 CurdOut("Reached end of series")
2104 ExitCurd(nil)
2105 return
2106 }
2107
2108 // Use prefetched links if available for the next episode
2109 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
2110 anime.Ep.Links = anime.Ep.NextEpisode.Links
2111 if anime.Ep.NextEpisode.ProviderName != "" {
2112 anime.ProviderName = anime.Ep.NextEpisode.ProviderName
2113 anime.ProviderId = anime.Ep.NextEpisode.ProviderId
2114 }
2115 Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number))
2116 } else {
2117 // Clear links to force fetching new ones
2118 anime.Ep.Links = []string{}
2119 Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
2120 }
2121
2122 // Reset episode flags
2123 anime.Ep.Started = false
2124 anime.Ep.IsCompleted = false
2125
2126 // Log the transition
2127 Log("Completed episode, starting next.")
2128
2129 // Update local database
2130 err := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, GetAnimeName(*anime), CurrentAnimeProviderName(anime))
2131 if err != nil {
2132 Log("Error updating local database: " + err.Error())
2133 }
2134
2135 go func() {
2136 if progressErr := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode); progressErr != nil {
2137 Log("Error updating Anilist progress: " + progressErr.Error())
2138 }
2139 }()
2140
2141 // Output message to user
2142 CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
2143}
2144
2145// HandleLastEpisodeCompletion handles scoring and completion for the last episode
2146func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
2147 if anime.TotalEpisodes <= 0 || anime.Ep.Number != anime.TotalEpisodes {
2148 return
2149 }
2150
2151 summary := []string{}
2152 canWriteRemote := ShouldWriteRemoteTracking(userCurdConfig, anime)
2153
2154 if userCurdConfig.ScoreOnCompletion && !anime.IsAiring && canWriteRemote {
2155 CurdOut("You've completed this anime! Would you like to rate it?")
2156
2157 scoreOptions := []SelectionOption{
2158 {Key: "yes", Label: "Yes, rate this anime"},
2159 {Key: "no", Label: "No, skip rating"},
2160 }
2161
2162 selectedOption, err := DynamicSelect(scoreOptions)
2163 if err != nil {
2164 Log(fmt.Sprintf("Error in score prompt selection: %v", err))
2165 } else if selectedOption.Key == "yes" {
2166 err = RateAnime(userToken, anime.AnilistId)
2167 if err != nil {
2168 Log(fmt.Sprintf("Error rating anime: %v", err))
2169 CurdOut("Failed to rate anime")
2170 summary = append(summary, "rating failed")
2171 } else {
2172 CurdOut("Anime rated successfully!")
2173 summary = append(summary, "rating saved")
2174 }
2175 } else {
2176 summary = append(summary, "rating skipped")
2177 }
2178 // Back (-2) and no are treated as skip
2179 } else {
2180 summary = append(summary, "rating skipped")
2181 }
2182
2183 if !anime.IsAiring && canWriteRemote {
2184 if anime.Rewatching {
2185 err := CompleteAnimeRewatch(userToken, *anime)
2186 if err != nil {
2187 Log("Error completing anime rewatch: " + err.Error())
2188 summary = append(summary, "rewatch completion failed")
2189 } else {
2190 summary = append(summary, "rewatch completed")
2191 }
2192 } else {
2193 err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED")
2194 if err != nil {
2195 Log("Error updating anime status to completed: " + err.Error())
2196 summary = append(summary, "status update failed")
2197 } else {
2198 summary = append(summary, "marked completed")
2199 }
2200 }
2201 } else if !anime.IsAiring {
2202 summary = append(summary, "tracker updates skipped")
2203 }
2204
2205 if sequelSummary := handleSequelCheck(userCurdConfig, anime, userToken); sequelSummary != "" {
2206 summary = append(summary, sequelSummary)
2207 }
2208 if len(summary) > 0 {
2209 CurdOut("Completion summary: " + strings.Join(summary, "; "))
2210 }
2211}
2212
2213// handleSequelCheck checks for sequels and prompts the user accordingly
2214func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken string) (summary string) {
2215 if !ShouldWriteRemoteTracking(userCurdConfig, anime) {
2216 return "sequel check skipped"
2217 }
2218
2219 // Recover from any panics in this function to prevent crashes
2220 defer func() {
2221 if r := recover(); r != nil {
2222 Log(fmt.Sprintf("Recovered from panic in handleSequelCheck: %v", r))
2223 summary = "sequel check failed"
2224 }
2225 }()
2226
2227 // Fetch sequel information
2228 sequels, err := GetAnimeSequel(anime.AnilistId, userToken)
2229 if err != nil {
2230 Log(fmt.Sprintf("Error fetching sequel information: %v", err))
2231 return "sequel check failed"
2232 }
2233
2234 if len(sequels) == 0 {
2235 Log("No sequel found for this anime")
2236 return "no sequel found"
2237 }
2238
2239 sequel := &sequels[0]
2240 if len(sequels) > 1 {
2241 selectedSequel, ok := selectSequel(userCurdConfig, sequels)
2242 if !ok {
2243 return "sequel skipped"
2244 }
2245 sequel = selectedSequel
2246 }
2247
2248 return promptSequelAction(userCurdConfig, sequel, userToken)
2249}
2250
2251func selectSequel(userCurdConfig *CurdConfig, sequels []SequelInfo) (*SequelInfo, bool) {
2252 CurdOut("Multiple sequels found.")
2253 options := make([]SelectionOption, 0, len(sequels)+1)
2254 for i := range sequels {
2255 title := sequelDisplayTitle(userCurdConfig, &sequels[i])
2256 status := strings.ToLower(strings.ReplaceAll(sequels[i].Status, "_", " "))
2257 options = append(options, SelectionOption{
2258 Key: strconv.Itoa(i),
2259 Label: fmt.Sprintf("%s (%s)", title, status),
2260 })
2261 }
2262 options = append(options, SelectionOption{Key: "skip", Label: "Skip"})
2263
2264 selected, err := promptSelect(options)
2265 if err != nil {
2266 Log(fmt.Sprintf("Error selecting sequel: %v", err))
2267 return nil, false
2268 }
2269 if selected.Key == "skip" || selected.Key == "-1" || selected.Key == "-2" {
2270 return nil, false
2271 }
2272 index, err := strconv.Atoi(selected.Key)
2273 if err != nil || index < 0 || index >= len(sequels) {
2274 return nil, false
2275 }
2276 return &sequels[index], true
2277}
2278
2279func sequelDisplayTitle(userCurdConfig *CurdConfig, sequel *SequelInfo) string {
2280 if sequel == nil {
2281 return ""
2282 }
2283 if userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" && sequel.Title.English != "" {
2284 return sequel.Title.English
2285 }
2286 if sequel.Title.Romaji != "" {
2287 return sequel.Title.Romaji
2288 }
2289 return strconv.Itoa(sequel.ID)
2290}
2291
2292func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToken string) string {
2293 if sequel == nil {
2294 return ""
2295 }
2296
2297 sequelTitle := sequelDisplayTitle(userCurdConfig, sequel)
2298 Log(fmt.Sprintf("Found sequel: %s (ID: %d)", sequelTitle, sequel.ID))
2299
2300 currentUser := GetGlobalUser()
2301 userAnimeList := AnimeList{}
2302 if currentUser != nil {
2303 userAnimeList = currentUser.AnimeList
2304 }
2305 sequelStatus, isInList := "", false
2306 if hasAnyEntries(userAnimeList) {
2307 sequelStatus, isInList = FindSequelInAnimeList(userAnimeList, sequel.ID)
2308 }
2309
2310 if isInList {
2311 CurdOut(fmt.Sprintf("Sequel found: %s (%s)", sequelTitle, sequelStatus))
2312 } else {
2313 CurdOut(fmt.Sprintf("Sequel found: %s", sequelTitle))
2314 }
2315
2316 options := []SelectionOption{}
2317 if sequel.Status != "NOT_YET_RELEASED" {
2318 if !isInList || sequelStatus == "PLANNING" || sequelStatus == "PAUSED" || sequelStatus == "DROPPED" {
2319 options = append(options, SelectionOption{Key: "watching", Label: "Add to Watching"})
2320 }
2321 }
2322 if !isInList || sequelStatus != "PLANNING" {
2323 options = append(options, SelectionOption{Key: "planning", Label: "Add to Plan to Watch"})
2324 }
2325 options = append(options,
2326 SelectionOption{Key: "details", Label: "Open AniList details"},
2327 SelectionOption{Key: "skip", Label: "Skip"},
2328 )
2329
2330 selected, err := promptSelect(options)
2331 if err != nil {
2332 Log(fmt.Sprintf("Error in sequel action prompt: %v", err))
2333 return "sequel action failed"
2334 }
2335
2336 switch selected.Key {
2337 case "watching":
2338 if err := AddAnimeToList(sequel.ID, "CURRENT", userToken); err != nil {
2339 Log(fmt.Sprintf("Error adding sequel to watching list: %v", err))
2340 CurdOut("Failed to add sequel to Watching.")
2341 return "sequel add failed"
2342 } else {
2343 CurdOut(fmt.Sprintf("Added '%s' to Watching.", sequelTitle))
2344 return "sequel added to Watching"
2345 }
2346 case "planning":
2347 if err := AddAnimeToList(sequel.ID, "PLANNING", userToken); err != nil {
2348 Log(fmt.Sprintf("Error adding sequel to planning list: %v", err))
2349 CurdOut("Failed to add sequel to Plan to Watch.")
2350 return "sequel add failed"
2351 } else {
2352 CurdOut(fmt.Sprintf("Added '%s' to Plan to Watch.", sequelTitle))
2353 return "sequel added to Plan to Watch"
2354 }
2355 case "details":
2356 url := sequel.SiteURL
2357 if url == "" {
2358 url = fmt.Sprintf("https://anilist.co/anime/%d", sequel.ID)
2359 }
2360 CurdOut(fmt.Sprintf("Opening %s", url))
2361 if err := browser.OpenURL(url); err != nil {
2362 Log(fmt.Sprintf("Error opening browser: %v", err))
2363 CurdOut("Failed to open browser.")
2364 return "sequel details failed"
2365 }
2366 return "sequel details opened"
2367 case "skip", "-1", "-2":
2368 Log("User skipped sequel action")
2369 }
2370 return "sequel skipped"
2371}
2372
2373// ChangeProvider allows the user to switch the anime provider
2374func ChangeProvider(userCurdConfig *CurdConfig) {
2375 options := []SelectionOption{
2376 {Key: "[\"allanime\"]", Label: "allanime"},
2377 {Key: "[\"animepahe\"]", Label: "animepahe"},
2378 {Key: "[\"allanime\",\"animepahe\"]", Label: "allanime, then animepahe"},
2379 {Key: "[\"animepahe\",\"allanime\"]", Label: "animepahe, then allanime"},
2380 }
2381
2382 selected, err := DynamicSelect(options)
2383 if err != nil || selected.Key == "-1" || selected.Key == "-2" {
2384 return
2385 }
2386
2387 // Update the config
2388 providerValue := canonicalProviderConfigValue(selected.Key)
2389 userCurdConfig.Provider = providerValue
2390 CurrentProvider = nil // reset the provider instance
2391
2392 // Save to config file
2393 configPath := GlobalConfigPath
2394 configMap, err := LoadConfigFromFile(configPath)
2395 if err == nil {
2396 configMap["Provider"] = providerValue
2397 SaveConfigToFile(configPath, configMap)
2398 }
2399
2400 CurdOut(fmt.Sprintf("\nProvider successfully changed to %s.\n", selected.Label))
2401 time.Sleep(1 * time.Second)
2402}