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