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