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