internal/curd.go
1432 lines · 44549 bytes
1package internal
2
3import (
4 "crypto/md5"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "regexp"
13 "runtime"
14 "strconv"
15 "strings"
16 "time"
17
18 "github.com/gen2brain/beeep"
19)
20
21func GetTokenFromFile(filePath string) (string, error) {
22 // Read the token from the file
23 data, err := os.ReadFile(filePath)
24 if err != nil {
25 return "", fmt.Errorf("failed to read token from file: %w", err)
26 }
27
28 // Convert the byte slice to a string and remove any surrounding whitespace or newlines
29 token := strings.TrimSpace(string(data))
30
31 return token, nil
32}
33
34func EditConfig(configFilePath string) {
35 // Get the user's preferred editor from the EDITOR environment variable
36 editor := os.Getenv("EDITOR")
37 if editor == "" {
38 // If EDITOR is not set, use system-specific defaults
39 if runtime.GOOS == "windows" {
40 // Try Notepad++ first
41 if _, err := exec.LookPath("notepad++"); err == nil {
42 editor = "notepad++"
43 } else {
44 editor = "notepad.exe"
45 }
46 } else {
47 if _, err := exec.LookPath("vim"); err == nil {
48 editor = "vim"
49 } else {
50 editor = "nano"
51 }
52 }
53 }
54
55 // Construct the command to open the config file
56 cmd := exec.Command(editor, configFilePath)
57
58 // Set the command to run in the current terminal
59 cmd.Stdin = os.Stdin
60 cmd.Stdout = os.Stdout
61 cmd.Stderr = os.Stderr
62
63 // Run the editor command
64 err := cmd.Run()
65 if err != nil {
66 CurdOut(fmt.Sprintf("Error opening config file: %v", err))
67 return
68 }
69
70 CurdOut("Config file edited successfully.")
71}
72
73// ClearLogFile removes all contents from the specified log file
74func ClearLogFile(logFile string) error {
75 // Open the file with truncate flag to clear its contents
76 file, err := os.OpenFile(logFile, os.O_WRONLY|os.O_TRUNC, 0666)
77 if err != nil {
78 return fmt.Errorf("failed to open log file: %w", err)
79 }
80 defer file.Close()
81
82 return nil
83}
84
85// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
86func Log(data interface{}) error {
87 logFile := GetGlobalLogFile()
88 // Open or create the log file
89 file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
90 if err != nil {
91 return err
92 }
93 defer file.Close()
94
95 // Attempt to marshal the data into JSON
96 jsonData, err := json.Marshal(data)
97 if err != nil {
98 return err
99 }
100
101 // Get the caller information
102 _, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
103 if !ok {
104 return fmt.Errorf("unable to get caller information")
105 }
106
107 // Log the current time and the JSON representation along with caller info
108 currentTime := time.Now().Format("2006/01/02 15:04:05")
109 logMessage := fmt.Sprintf("[LOG] %s %s:%d: %s\n", currentTime, filename, lineNumber, jsonData)
110 _, err = fmt.Fprint(file, logMessage) // Write to the file
111 if err != nil {
112 return err
113 }
114
115 return nil
116}
117
118// ClearScreen clears the terminal screen and saves the state
119func ClearScreen() {
120 userCurdConfig := GetGlobalConfig()
121
122 if userCurdConfig.AlternateScreen == false {
123 return
124 }
125
126 fmt.Print("\033[?1049h") // Switch to alternate screen buffer
127 fmt.Print("\033[2J") // Clear the entire screen
128 fmt.Print("\033[H") // Move cursor to the top left
129}
130
131// RestoreScreen restores the original terminal state
132func RestoreScreen() {
133 userCurdConfig := GetGlobalConfig()
134
135 if userCurdConfig.AlternateScreen == false {
136 return
137 }
138
139 fmt.Print("\033[?1049l") // Switch back to the main screen buffer
140}
141
142func ExitCurd(err error) {
143 RestoreScreen()
144
145 anime := GetGlobalAnime()
146 if anime != nil && anime.Ep.Player.SocketPath != "" {
147 _, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
148 if err != nil {
149 Log("Error closing MPV: " + err.Error())
150 }
151 }
152
153 CurdOut("Have a great day!")
154 // If the error is not about the connection refused, print the error
155 if err != nil && !strings.Contains(err.Error(), "dial unix "+anime.Ep.Player.SocketPath+": connect: connection refused") {
156 CurdOut(fmt.Sprintf("Error: %v", err))
157 if runtime.GOOS == "windows" {
158 fmt.Println("Press Enter to exit")
159 var wait string
160 fmt.Scanln(&wait)
161 os.Exit(1)
162 } else {
163 os.Exit(1)
164 }
165 }
166 os.Exit(0)
167}
168
169func CurdOut(data interface{}) {
170 userCurdConfig := GetGlobalConfig()
171 if userCurdConfig == nil {
172 userCurdConfig = &CurdConfig{}
173 }
174 if !userCurdConfig.RofiSelection {
175 fmt.Println(fmt.Sprintf("%v", data))
176 } else {
177 switch runtime.GOOS {
178 case "windows":
179 err := beeep.Notify(
180 "Curd",
181 fmt.Sprintf("%v", data),
182 "",
183 )
184
185 if err != nil {
186 Log(fmt.Sprintf("Failed to send notification: %v", err))
187 }
188 case "linux":
189 // Check if the input starts with "-i" for image notification
190 dataStr := fmt.Sprintf("%v", data)
191 if strings.HasPrefix(dataStr, "-i") && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
192 // Split the string to get image path and message
193 parts := strings.SplitN(dataStr, " ", 3)
194 if len(parts) == 3 {
195 // Remove quotes from the message
196 message := strings.Trim(parts[2], "\"")
197 cmd := exec.Command("notify-send",
198 "-a", "Curd",
199 "-h", "string:x-canonical-private-synchronous:curd-notification",
200 "Curd",
201 "-i", parts[1],
202 message)
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 } else {
210 cmd := exec.Command("notify-send",
211 "-a", "Curd",
212 "-h", "string:x-canonical-private-synchronous:curd-notification",
213 "Curd",
214 dataStr)
215 err := cmd.Run()
216 if err != nil {
217 Log(fmt.Sprintf("%v", cmd))
218 Log(fmt.Sprintf("Failed to send notification: %v", err))
219 }
220 }
221 }
222 }
223}
224
225func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
226 // Create update options map
227 updateOptions := map[string]string{
228 "CATEGORY": "Change Anime Category",
229 "PROGRESS": "Change Progress",
230 "SCORE": "Add/Change Score",
231 }
232
233 // Select update option
234 updateSelection, err := DynamicSelect(updateOptions)
235 if err != nil {
236 Log(fmt.Sprintf("Failed to select update option: %v", err))
237 ExitCurd(fmt.Errorf("Failed to select update option"))
238 }
239
240 if updateSelection.Key == "-1" {
241 ExitCurd(nil)
242 }
243
244 // Get user's anime list
245 var animeListMap map[string]string
246 var animeListMapPreview map[string]RofiSelectPreview
247
248 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
249 animeListMapPreview = make(map[string]RofiSelectPreview)
250 // Include anime from all categories
251 for _, entry := range user.AnimeList.Watching {
252 title := entry.Media.Title.English
253 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
254 title = entry.Media.Title.Romaji
255 }
256 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
257 Title: title,
258 CoverImage: entry.CoverImage,
259 }
260 }
261 for _, entry := range user.AnimeList.Completed {
262 title := entry.Media.Title.English
263 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
264 title = entry.Media.Title.Romaji
265 }
266 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
267 Title: title,
268 CoverImage: entry.CoverImage,
269 }
270 }
271 for _, entry := range user.AnimeList.Paused {
272 title := entry.Media.Title.English
273 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
274 title = entry.Media.Title.Romaji
275 }
276 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
277 Title: title,
278 CoverImage: entry.CoverImage,
279 }
280 }
281 for _, entry := range user.AnimeList.Dropped {
282 title := entry.Media.Title.English
283 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
284 title = entry.Media.Title.Romaji
285 }
286 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
287 Title: title,
288 CoverImage: entry.CoverImage,
289 }
290 }
291 for _, entry := range user.AnimeList.Planning {
292 title := entry.Media.Title.English
293 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
294 title = entry.Media.Title.Romaji
295 }
296 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
297 Title: title,
298 CoverImage: entry.CoverImage,
299 }
300 }
301 } else {
302 animeListMap = make(map[string]string)
303 // Include anime from all categories
304 for _, entry := range user.AnimeList.Watching {
305 title := entry.Media.Title.English
306 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
307 title = entry.Media.Title.Romaji
308 }
309 animeListMap[strconv.Itoa(entry.Media.ID)] = title
310 }
311 for _, entry := range user.AnimeList.Completed {
312 title := entry.Media.Title.English
313 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
314 title = entry.Media.Title.Romaji
315 }
316 animeListMap[strconv.Itoa(entry.Media.ID)] = title
317 }
318 for _, entry := range user.AnimeList.Paused {
319 title := entry.Media.Title.English
320 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
321 title = entry.Media.Title.Romaji
322 }
323 animeListMap[strconv.Itoa(entry.Media.ID)] = title
324 }
325 for _, entry := range user.AnimeList.Dropped {
326 title := entry.Media.Title.English
327 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
328 title = entry.Media.Title.Romaji
329 }
330 animeListMap[strconv.Itoa(entry.Media.ID)] = title
331 }
332 for _, entry := range user.AnimeList.Planning {
333 title := entry.Media.Title.English
334 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
335 title = entry.Media.Title.Romaji
336 }
337 animeListMap[strconv.Itoa(entry.Media.ID)] = title
338 }
339 }
340
341 // Select anime to update
342 var selectedAnime SelectionOption
343 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
344 selectedAnime, err = DynamicSelectPreview(animeListMapPreview, false)
345 } else {
346 selectedAnime, err = DynamicSelect(animeListMap)
347 }
348 if err != nil {
349 Log(fmt.Sprintf("Failed to select anime: %v", err))
350 ExitCurd(fmt.Errorf("Failed to select anime"))
351 }
352
353 if selectedAnime.Key == "-1" {
354 ExitCurd(nil)
355 }
356
357 animeID, err := strconv.Atoi(selectedAnime.Key)
358 if err != nil {
359 Log(fmt.Sprintf("Failed to convert anime ID: %v", err))
360 ExitCurd(fmt.Errorf("Failed to convert anime ID"))
361 }
362
363 // After getting animeID, get the current anime entry
364 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key)
365 if err != nil {
366 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err))
367 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
368 }
369 ClearScreen()
370 switch updateSelection.Key {
371 case "CATEGORY":
372 categories := map[string]string{
373 "CURRENT": "Currently Watching",
374 "COMPLETED": "Completed",
375 "PAUSED": "On Hold",
376 "DROPPED": "Dropped",
377 "PLANNING": "Plan to Watch",
378 }
379
380 currentStatus := "None"
381 if selectedAnilistAnime.Status != "" {
382 currentStatus = categories[selectedAnilistAnime.Status]
383 }
384 CurdOut(fmt.Sprintf("Current category: %s", currentStatus))
385
386 categorySelection, err := DynamicSelect(categories)
387 if err != nil {
388 Log(fmt.Sprintf("Failed to select category: %v", err))
389 ExitCurd(fmt.Errorf("Failed to select category"))
390 }
391
392 if categorySelection.Key == "-1" {
393 ExitCurd(nil)
394 }
395
396 err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
397 if err != nil {
398 Log(fmt.Sprintf("Failed to update anime status: %v", err))
399 ExitCurd(fmt.Errorf("Failed to update anime status"))
400 }
401
402 case "PROGRESS":
403 currentProgress := "None"
404 if selectedAnilistAnime.Progress > 0 {
405 currentProgress = strconv.Itoa(selectedAnilistAnime.Progress)
406 }
407
408 var progress string
409 if userCurdConfig.RofiSelection {
410 progress, err = GetUserInputFromRofi(fmt.Sprintf("Current progress: %s\nEnter new progress (episode number)", currentProgress))
411 if err != nil {
412 Log(fmt.Sprintf("Failed to get progress input: %v", err))
413 ExitCurd(fmt.Errorf("Failed to get progress input"))
414 }
415 } else {
416 CurdOut(fmt.Sprintf("Current progress: %s", currentProgress))
417 CurdOut("Enter new progress (episode number):")
418 fmt.Scanln(&progress)
419 }
420
421 progressNum, err := strconv.Atoi(progress)
422 if err != nil {
423 Log(fmt.Sprintf("Failed to convert progress to number: %v", err))
424 ExitCurd(fmt.Errorf("Failed to convert progress to number"))
425 }
426
427 err = UpdateAnimeProgress(user.Token, animeID, progressNum)
428 if err != nil {
429 Log(fmt.Sprintf("Failed to update anime progress: %v", err))
430 ExitCurd(fmt.Errorf("Failed to update anime progress"))
431 }
432
433 case "SCORE":
434 currentScore := "None"
435 if selectedAnilistAnime.Score > 0 {
436 currentScore = strconv.Itoa(int(selectedAnilistAnime.Score))
437 }
438 CurdOut(fmt.Sprintf("Current score: %s", currentScore))
439
440 err = RateAnime(user.Token, animeID)
441 if err != nil {
442 Log(fmt.Sprintf("Failed to update anime score: %v", err))
443 ExitCurd(fmt.Errorf("Failed to update anime score"))
444 }
445 }
446
447 CurdOut("Anime updated successfully!")
448}
449
450func UpdateCurd(repo, fileName string) error {
451 // Get the path of the currently running executable
452 executablePath, err := os.Executable()
453 if err != nil {
454 return fmt.Errorf("unable to find current executable: %v", err)
455 }
456
457 // Determine the correct binary name based on OS and architecture
458 var binaryName string
459 switch runtime.GOOS {
460 case "windows":
461 if runtime.GOARCH == "arm64" {
462 binaryName = "curd-windows-arm64.exe"
463 } else {
464 binaryName = "curd-windows-x86_64.exe"
465 }
466 case "darwin": // macOS
467 switch runtime.GOARCH {
468 case "amd64":
469 binaryName = "curd-macos-x86_64"
470 case "arm64":
471 binaryName = "curd-macos-arm64"
472 default:
473 binaryName = "curd-macos-universal"
474 }
475 case "linux":
476 switch runtime.GOARCH {
477 case "amd64":
478 binaryName = "curd-linux-x86_64"
479 case "arm64":
480 binaryName = "curd-linux-arm64"
481 default:
482 return fmt.Errorf("unsupported Linux architecture: %s", runtime.GOARCH)
483 }
484 default:
485 return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
486 }
487
488 // GitHub release URL for curd
489 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName)
490
491 // Temporary path for the downloaded curd executable
492 tmpPath := executablePath + ".tmp"
493
494 // Download the curd executable
495 resp, err := http.Get(url)
496 if err != nil {
497 return fmt.Errorf("failed to download file: %v", err)
498 }
499 defer resp.Body.Close()
500
501 // Check if the download was successful
502 if resp.StatusCode != http.StatusOK {
503 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
504 }
505
506 // Create a new temporary file
507 out, err := os.Create(tmpPath)
508 if err != nil {
509 return fmt.Errorf("failed to create temporary file: %v", err)
510 }
511 defer out.Close()
512
513 // Set file permissions
514 if err := out.Chmod(0755); err != nil {
515 return fmt.Errorf("failed to set file permissions: %v", err)
516 }
517
518 // Copy the downloaded content to the temporary file
519 if _, err := io.Copy(out, resp.Body); err != nil {
520 return fmt.Errorf("failed to write to temporary file: %v", err)
521 }
522
523 // Close the file before renaming
524 out.Close()
525
526 // Replace the old executable with the new one
527 if runtime.GOOS == "windows" {
528 // On Windows, we need to rename the old file first
529 oldPath := executablePath + ".old"
530 err = os.Rename(executablePath, oldPath)
531 if err != nil {
532 return fmt.Errorf("failed to rename old executable: %v", err)
533 }
534 err = os.Rename(tmpPath, executablePath)
535 if err != nil {
536 // Try to restore the old executable if the rename fails
537 os.Rename(oldPath, executablePath)
538 return fmt.Errorf("failed to rename new executable: %v", err)
539 }
540 os.Remove(oldPath)
541 } else {
542 // On Unix systems, we can directly rename
543 if err := os.Rename(tmpPath, executablePath); err != nil {
544 return fmt.Errorf("failed to replace executable: %v", err)
545 }
546 }
547
548 return nil
549}
550
551func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
552 var query string
553 var animeMap map[string]string
554 var animeMapPreview map[string]RofiSelectPreview
555 var err error
556 var anilistSelectedOption SelectionOption
557
558 if userCurdConfig.RofiSelection {
559 userInput, err := GetUserInputFromRofi("Enter the anime name")
560 if err != nil {
561 Log("Error getting user input: " + err.Error())
562 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
563 }
564 query = userInput
565 } else {
566 CurdOut("Enter the anime name:")
567 fmt.Scanln(&query)
568 }
569 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
570 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
571 } else {
572 animeMap, err = SearchAnimeAnilist(query, user.Token)
573 }
574 if err != nil {
575 Log(fmt.Sprintf("Failed to search anime: %v", err))
576 ExitCurd(fmt.Errorf("Failed to search anime"))
577 }
578 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
579 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
580 } else {
581 anilistSelectedOption, err = DynamicSelect(animeMap)
582 }
583
584 if anilistSelectedOption.Key == "-1" {
585 ExitCurd(nil)
586 }
587
588 if err != nil {
589 Log(fmt.Sprintf("No anime available: %v", err))
590 ExitCurd(fmt.Errorf("No anime available"))
591 }
592 animeID, err := strconv.Atoi(anilistSelectedOption.Key)
593 if err != nil {
594 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err))
595 ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
596 }
597
598 // Add category selection before adding to list
599 categories := map[string]string{
600 "CURRENT": "Currently Watching",
601 "COMPLETED": "Completed",
602 "PAUSED": "On Hold",
603 "DROPPED": "Dropped",
604 "PLANNING": "Plan to Watch",
605 }
606
607 ClearScreen()
608 CurdOut("Select which list to add the anime to:")
609
610 categorySelection, err := DynamicSelect(categories)
611 if err != nil {
612 Log(fmt.Sprintf("Failed to select category: %v", err))
613 ExitCurd(fmt.Errorf("Failed to select category"))
614 }
615
616 if categorySelection.Key == "-1" {
617 ExitCurd(nil)
618 }
619
620 err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
621 if err != nil {
622 Log(fmt.Sprintf("Failed to add anime to list: %v", err))
623 ExitCurd(fmt.Errorf("Failed to add anime to list"))
624 }
625
626 // Refresh user's anime list after adding
627 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
628 anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id)
629 if err != nil {
630 Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
631 ExitCurd(fmt.Errorf("Failed to refresh anime list"))
632 }
633 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
634 } else {
635 anilistUserData, err := GetUserData(user.Token, user.Id)
636 if err != nil {
637 Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
638 ExitCurd(fmt.Errorf("Failed to refresh anime list"))
639 }
640 user.AnimeList = ParseAnimeList(anilistUserData)
641 }
642
643 return anilistSelectedOption
644}
645
646func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) {
647 var err error
648 var anilistUserData map[string]interface{}
649 var anilistUserDataPreview map[string]interface{}
650
651 // Filter anime list based on selected category
652 var animeListMap map[string]string
653 var animeListMapPreview map[string]RofiSelectPreview
654
655 // Get user id, username and Anime list
656 user.Id, user.Username, err = GetAnilistUserID(user.Token)
657 if err != nil {
658 Log(fmt.Sprintf("Failed to get user ID: %v", err))
659 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
660 }
661
662 // Get the anime list data
663 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
664 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
665 if err != nil {
666 Log(fmt.Sprintf("Failed to get user data preview: %v", err))
667 ExitCurd(fmt.Errorf("Failed to get user data preview"))
668 }
669 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
670 } else {
671 anilistUserData, err = GetUserData(user.Token, user.Id)
672 if err != nil {
673 Log(fmt.Sprintf("Failed to get user data: %v", err))
674 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
675 }
676 user.AnimeList = ParseAnimeList(anilistUserData)
677 }
678
679 // If continueLast flag is set, directly get the last watched anime
680 if anime.Ep.ContinueLast {
681 // Get the last anime ID from the curd_id file
682 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
683 idBytes, err := os.ReadFile(idFilePath)
684 if err != nil {
685 Log("Error reading curd_id file: " + err.Error())
686 ExitCurd(fmt.Errorf("No last watched anime found"))
687 }
688
689 anilistID, err := strconv.Atoi(string(idBytes))
690 if err != nil {
691 Log("Error converting anilist ID: " + err.Error())
692 ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
693 }
694
695 // Find the anime in database
696 animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
697 if animePointer == nil {
698 ExitCurd(fmt.Errorf("Last watched anime not found in database"))
699 }
700
701 // Set the anime details
702 anime.AnilistId = animePointer.AnilistId
703 // anime.AllanimeId = animePointer.AllanimeId
704 // anime.Title = animePointer.Title
705 // anime.Ep.Number = animePointer.Ep.Number
706 // anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
707 // anime.Ep.Resume = true
708
709 } else {
710 // Skip category selection if Current flag is set
711 var categorySelection SelectionOption
712 if userCurdConfig.CurrentCategory {
713 categorySelection = SelectionOption{
714 Key: "CURRENT",
715 Label: "Currently Watching",
716 }
717 } else {
718 // Create category selection map
719 categories := getOrderedCategories(userCurdConfig)
720
721 // Select category using DynamicSelect
722 var err error
723 categorySelection, err = DynamicSelect(categories)
724 if err != nil {
725 Log(fmt.Sprintf("Failed to select category: %v", err))
726 ExitCurd(fmt.Errorf("Failed to select category"))
727 }
728
729 if categorySelection.Key == "-1" {
730 ExitCurd(nil)
731 }
732
733 // Handle options
734 if categorySelection.Key == "UPDATE" {
735 ClearScreen()
736 UpdateAnimeEntry(userCurdConfig, user)
737 ExitCurd(nil)
738 } else if categorySelection.Key == "UNTRACKED" {
739 ClearScreen()
740 WatchUntracked(userCurdConfig)
741 } else if categorySelection.Key == "CONTINUE_LAST" {
742 anime.Ep.ContinueLast = true
743 }
744
745 ClearScreen()
746 }
747
748 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
749 animeListMapPreview = make(map[string]RofiSelectPreview)
750 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
751 title := entry.Media.Title.English
752 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
753 title = entry.Media.Title.Romaji
754 }
755 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
756 Title: title,
757 CoverImage: entry.CoverImage,
758 }
759 }
760 } else {
761 animeListMap = make(map[string]string)
762 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
763 title := entry.Media.Title.English
764 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
765 title = entry.Media.Title.Romaji
766 }
767 animeListMap[strconv.Itoa(entry.Media.ID)] = title
768 }
769 }
770 }
771
772 var anilistSelectedOption SelectionOption
773 var selectedAllanimeAnime SelectionOption
774 var userQuery string
775
776 if anime.Ep.ContinueLast {
777 // Get the last watched anime ID from the curd_id file
778 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
779 curdIDBytes, err := os.ReadFile(curdIDPath)
780 if err != nil {
781 Log(fmt.Sprintf("Error reading curd_id file: %v", err))
782 ExitCurd(fmt.Errorf("Error reading curd_id file"))
783 }
784
785 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
786 if err != nil {
787 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err))
788 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
789 }
790
791 anime.AnilistId = lastWatchedID
792 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
793 } else {
794 // Select anime to watch (Anilist)
795 var err error
796 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
797 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
798 } else {
799 // Add "Add new anime" option to the map
800 animeListMap["add_new"] = "Add new anime"
801
802 anilistSelectedOption, err = DynamicSelect(animeListMap)
803 }
804 if err != nil {
805 Log(fmt.Sprintf("Error selecting anime: %v", err))
806 ExitCurd(fmt.Errorf("Error selecting anime"))
807 }
808
809 Log(anilistSelectedOption)
810
811 if anilistSelectedOption.Key == "-1" {
812 ExitCurd(nil)
813 }
814
815 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
816 anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes)
817 }
818
819 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
820 if err != nil {
821 Log(fmt.Sprintf("Error converting Anilist ID: %v", err))
822 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
823 }
824 }
825 // Find anime in Local history
826 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
827
828 // Get anime entry
829 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
830 if err != nil {
831 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err))
832 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
833 }
834
835 // Set anime entry
836 anime.Title = selectedAnilistAnime.Media.Title
837 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
838 anime.Ep.Number = selectedAnilistAnime.Progress + 1
839 var animeList map[string]string
840 userQuery = anime.Title.Romaji
841
842 // if anime not found in database, find it in animeList
843 if animePointer == nil {
844 Log("Anime not found in database, searching in animeList...")
845 // Get Anime list (All anime)
846 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
847
848 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
849 Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err))
850 if err != nil {
851 Log(fmt.Sprintf("Failed to select anime: %v", err))
852 ExitCurd(fmt.Errorf("Failed to select anime"))
853 }
854 if len(animeList) == 0 {
855 ExitCurd(fmt.Errorf("No results found."))
856 }
857
858 // find anime in animeList
859 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
860 if err != nil {
861 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err))
862 }
863
864 // If unable to get Allanime id automatically get manually
865 if anime.AllanimeId == "" {
866 CurdOut("Failed to automatically select anime")
867 selectedAllanimeAnime, err := DynamicSelect(animeList)
868
869 if selectedAllanimeAnime.Key == "-1" {
870 ExitCurd(nil)
871 }
872
873 if err != nil {
874 // fmt.Println("No anime available")
875 ExitCurd(fmt.Errorf("No anime available"))
876 }
877 anime.AllanimeId = selectedAllanimeAnime.Key
878 }
879 } else {
880 // if anime found in database, use it
881 anime.AllanimeId = animePointer.AllanimeId
882 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
883 if anime.Ep.Number == animePointer.Ep.Number {
884 anime.Ep.Resume = true
885 }
886 }
887
888 if selectedAllanimeAnime.Key == "-1" {
889 ExitCurd(nil)
890 }
891
892 // If anime is not in watching list, prompt user to add it into watching list
893 isInWatchingList := false
894 for _, entry := range user.AnimeList.Watching {
895 if entry.Media.ID == anime.AnilistId {
896 isInWatchingList = true
897 break
898 }
899 }
900
901 if !isInWatchingList {
902 // Create options for the prompt
903 options := map[string]string{
904 "yes": "Add to watching list",
905 "no": "Continue without adding",
906 }
907
908 var selectedOption SelectionOption
909 var err error
910
911 // Use rofi for selection
912 selectedOption, err = DynamicSelect(options)
913 if err != nil {
914 Log("Error in selection: " + err.Error())
915 ExitCurd(err)
916 }
917
918 if selectedOption.Key == "yes" {
919 err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
920 if err != nil {
921 Log("Error adding anime to watching list: " + err.Error())
922 ExitCurd(err)
923 }
924 // Refresh user's anime list after adding
925 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
926 anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id)
927 if err != nil {
928 Log("Error refreshing anime list: " + err.Error())
929 ExitCurd(err)
930 }
931 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
932 } else {
933 anilistUserData, err := GetUserData(user.Token, user.Id)
934 if err != nil {
935 Log("Error refreshing anime list: " + err.Error())
936 ExitCurd(err)
937 }
938 user.AnimeList = ParseAnimeList(anilistUserData)
939 }
940 } else if selectedOption.Key == "-1" {
941 ExitCurd(nil)
942 }
943 }
944
945 // If upstream is ahead, update the episode number
946 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
947 if temp_anime.Progress > anime.Ep.Number {
948 anime.Ep.Number = temp_anime.Progress
949 anime.Ep.Player.PlaybackTime = 0
950 anime.Ep.Resume = false
951 }
952 }
953
954 if anime.TotalEpisodes == 0 {
955 // Get updated anime data
956 Log(selectedAllanimeAnime)
957 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
958 Log(updatedAnime)
959 if err != nil {
960 Log(fmt.Sprintf("Error getting updated anime data: %v", err))
961 } else {
962 anime.TotalEpisodes = updatedAnime.TotalEpisodes
963 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
964 }
965 }
966
967 if anime.TotalEpisodes == 0 { // If failed to get anime data
968 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
969 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
970 if err != nil {
971 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
972 } else {
973 for allanimeId, label := range animeList {
974 if allanimeId == anime.AllanimeId {
975 // Extract total episodes from the label
976 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
977 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
978 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
979 break
980 }
981 }
982 }
983 }
984
985 if anime.TotalEpisodes == 0 {
986 CurdOut("Still unable to determine total episodes.")
987 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
988 var episodeNumber int
989 if userCurdConfig.RofiSelection {
990 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
991 if err != nil {
992 Log("Error getting user input: " + err.Error())
993 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
994 }
995 episodeNumber, err = strconv.Atoi(userInput)
996 } else {
997 fmt.Print("Enter the episode you want to start from: ")
998 fmt.Scanln(&episodeNumber)
999 }
1000 anime.Ep.Number = episodeNumber
1001 } else {
1002 anime.Ep.Number = selectedAnilistAnime.Progress + 1
1003 }
1004 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
1005 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
1006 var answer string
1007 if userCurdConfig.RofiSelection {
1008 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
1009 if err != nil {
1010 Log("Error getting user input: " + err.Error())
1011 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1012 }
1013 answer = userInput
1014 } else {
1015 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
1016 fmt.Scanln(&answer)
1017 }
1018 if answer == "y" {
1019 anime.Ep.Number = 1
1020 } else {
1021 anime.Ep.Number = anime.TotalEpisodes
1022 }
1023 }
1024
1025 // Check if this is the last episode - prompt user if needed
1026 if userCurdConfig.NextEpisodePrompt && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !userCurdConfig.RofiSelection {
1027 // Ensure the terminal state is clean for the prompt
1028 fmt.Print("\r\033[K") // Carriage return and clear line
1029 }
1030}
1031
1032// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
1033func WriteTokenToFile(token string, filePath string) error {
1034 // Extract the directory path
1035 dir := filepath.Dir(filePath)
1036
1037 // Create all necessary parent directories
1038 if err := os.MkdirAll(dir, 0755); err != nil {
1039 return fmt.Errorf("failed to create directories: %v", err)
1040 }
1041
1042 // Write the token to the file, creating it if it doesn't exist
1043 err := os.WriteFile(filePath, []byte(token), 0644)
1044 if err != nil {
1045 return fmt.Errorf("failed to write token to file: %v", err)
1046 }
1047
1048 return nil
1049}
1050
1051func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1052
1053 if anime.Ep.NextEpisode.Number == anime.Ep.Number {
1054 anime.Ep.Links = anime.Ep.NextEpisode.Links
1055 Log("using prefetched next episode link")
1056 } else {
1057 // Get episode link
1058 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1059 if err != nil {
1060 // If unable to get episode link automatically get manually
1061 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
1062 if err != nil {
1063 CurdOut("No episode list found")
1064 RestoreScreen()
1065 os.Exit(1)
1066 }
1067 if userCurdConfig.RofiSelection {
1068 userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1069 if err != nil {
1070 Log("Error getting user input: " + err.Error())
1071 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1072 }
1073 anime.Ep.Number, err = strconv.Atoi(userInput)
1074 } else {
1075 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1076 fmt.Scanln(&anime.Ep.Number)
1077 }
1078 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1079 if err != nil {
1080 CurdOut("Failed to get episode link")
1081 os.Exit(1)
1082 }
1083 // anime.Ep.Links = link
1084 }
1085 anime.Ep.Links = link
1086 }
1087
1088 if len(anime.Ep.Links) == 0 {
1089 CurdOut("No episode links found")
1090 os.Exit(1)
1091 }
1092
1093 Log(anime)
1094
1095 // Modify the goroutine in main.go where next episode links are fetched
1096 // Get next episode link in parallel
1097 go func() {
1098 nextEpNum := anime.Ep.Number + 1
1099 if nextEpNum <= anime.TotalEpisodes {
1100 // Get next canon episode number if filler skip is enabled
1101 if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) {
1102 nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum)
1103 }
1104 nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum)
1105 if err != nil {
1106 Log("Error getting next episode link: " + err.Error())
1107 } else {
1108 anime.Ep.NextEpisode = NextEpisode{
1109 Number: nextEpNum,
1110 Links: nextLinks,
1111 }
1112 Log(fmt.Sprintf("Next episode link fetched for ep %d", nextEpNum))
1113 }
1114 }
1115 }()
1116
1117 // Write anime.AnilistId to curd_id in the storage path
1118 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1119 Log(fmt.Sprintf("idFilePath: %v", idFilePath))
1120 if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
1121 Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err))
1122 } else {
1123 if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
1124 Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err))
1125 }
1126 }
1127
1128 // Display starting message with cover image and episode info
1129 if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
1130 // Get the cached image path
1131 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
1132 filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
1133 cachePath := filepath.Join(cacheDir, filename)
1134
1135 // Display the image if it exists in cache
1136 _, err := os.Stat(cachePath)
1137 if err == nil {
1138 // File exists
1139 Log(fmt.Sprintf("Image found at %s", cachePath))
1140 CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
1141 } else {
1142 // File does not exist
1143 Log(fmt.Sprintf("Image does not exist at %s", cachePath))
1144 CurdOut(fmt.Sprintf("%s - Episode %d",
1145 GetAnimeName(*anime),
1146 anime.Ep.Number))
1147
1148 }
1149 } else {
1150 CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
1151 }
1152 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number), anime)
1153
1154 if err != nil {
1155 Log("Failed to start mpv")
1156 os.Exit(1)
1157 }
1158
1159 return mpvSocketPath
1160}
1161
1162func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1163 // Create storage directory if it doesn't exist
1164 storagePath = os.ExpandEnv(storagePath)
1165 if err := os.MkdirAll(storagePath, 0755); err != nil {
1166 return fmt.Errorf("failed to create storage directory: %v", err)
1167 }
1168
1169 // Base URL for downloading config files
1170 baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
1171
1172 // Check each file
1173 for _, fileName := range filesToCheck {
1174 filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
1175
1176 // Skip if file already exists
1177 if _, err := os.Stat(filePath); err == nil {
1178 continue
1179 }
1180
1181 // Download file if it doesn't exist
1182 resp, err := http.Get(baseURL + fileName)
1183 if err != nil {
1184 return fmt.Errorf("failed to download %s: %v", fileName, err)
1185 }
1186 defer resp.Body.Close()
1187
1188 // Create the file
1189 out, err := os.Create(filePath)
1190 if err != nil {
1191 return fmt.Errorf("failed to create file %s: %v", fileName, err)
1192 }
1193 defer out.Close()
1194
1195 // Write the content
1196 if _, err := io.Copy(out, resp.Body); err != nil {
1197 return fmt.Errorf("failed to write file %s: %v", fileName, err)
1198 }
1199 }
1200
1201 return nil
1202}
1203
1204func getEntriesByCategory(list AnimeList, category string) []Entry {
1205 switch category {
1206 case "ALL":
1207 // Combine all categories into one slice
1208 allEntries := make([]Entry, 0)
1209 allEntries = append(allEntries, list.Watching...)
1210 allEntries = append(allEntries, list.Completed...)
1211 allEntries = append(allEntries, list.Paused...)
1212 allEntries = append(allEntries, list.Dropped...)
1213 allEntries = append(allEntries, list.Planning...)
1214 return allEntries
1215 case "CURRENT":
1216 return list.Watching
1217 case "COMPLETED":
1218 return list.Completed
1219 case "PAUSED":
1220 return list.Paused
1221 case "DROPPED":
1222 return list.Dropped
1223 case "PLANNING":
1224 return list.Planning
1225 default:
1226 return []Entry{}
1227 }
1228}
1229
1230func NextEpisodePrompt(userCurdConfig *CurdConfig) {
1231 anime := GetGlobalAnime()
1232 // If in CLI mode (not Rofi), we need to show the next episode number
1233 episodeNum := anime.Ep.Number
1234 if !userCurdConfig.RofiSelection {
1235 episodeNum++
1236 }
1237
1238 CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum))
1239
1240 // Create options for the selection
1241 options := map[string]string{
1242 "yes": "Yes, start next episode",
1243 // "no": "No, quit",
1244 }
1245
1246 // Use DynamicSelect for both CLI and Rofi modes
1247 selectedOption, err := DynamicSelect(options)
1248 if err != nil {
1249 Log(fmt.Sprintf("Error in next episode prompt selection: %v", err))
1250 ExitCurd(err)
1251 }
1252
1253 if selectedOption.Key != "yes" {
1254 // User selected to quit
1255 fmt.Print("\r\033[K") // Carriage return and clear line
1256 ExitMPV(anime.Ep.Player.SocketPath)
1257 CurdOut("Exiting without starting next episode")
1258 ExitCurd(nil)
1259 return
1260 }
1261
1262 // If yes, start the next episode
1263 prevEpisode := anime.Ep.Number
1264 anime.Ep.Number++
1265 anime.Ep.Started = false
1266 anime.Ep.IsCompleted = false // Reset completion flag for the new episode
1267
1268 // Clear current line to avoid visual glitches
1269 fmt.Print("\r\033[K") // Carriage return and clear line
1270
1271 CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
1272
1273 // Get database file path for StartNextEpisode
1274 homeDir := ""
1275 if runtime.GOOS == "windows" {
1276 homeDir = os.Getenv("USERPROFILE")
1277 } else {
1278 homeDir = os.Getenv("HOME")
1279 }
1280 configFilePath := filepath.Join(homeDir, ".config", "curd", "curd.conf")
1281 config, err := LoadConfig(configFilePath)
1282 if err != nil {
1283 Log("Error loading config for database path: " + err.Error())
1284 ExitCurd(err)
1285 }
1286 databaseFile := filepath.Join(os.ExpandEnv(config.StoragePath), "curd_history.txt")
1287
1288 // Update local database for the new episode
1289 err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, GetAnimeName(*anime))
1290 if err != nil {
1291 Log("Error updating local database: " + err.Error())
1292 }
1293
1294 // Update Anilist progress for the previous episode if not rewatching
1295 if !anime.Rewatching {
1296 user := &User{}
1297 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "token"))
1298 if err != nil {
1299 Log("Error reading token for progress update: " + err.Error())
1300 } else {
1301 go func() {
1302 err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode)
1303 if err != nil {
1304 Log("Error updating Anilist progress: " + err.Error())
1305 } else {
1306 CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1307 }
1308 }()
1309 }
1310 }
1311
1312 // Close current MPV instance
1313 ExitMPV(anime.Ep.Player.SocketPath)
1314
1315 // Check if we have prefetched links for the next episode
1316 if anime.Ep.NextEpisode.Number == anime.Ep.Number && len(anime.Ep.NextEpisode.Links) > 0 {
1317 Log("Using prefetched next episode link")
1318 anime.Ep.Links = anime.Ep.NextEpisode.Links
1319 } else {
1320 // No prefetched links available, need to fetch them
1321 CurdOut("Fetching links for next episode...")
1322
1323 // Wait for up to 5 seconds for prefetched links to become available
1324 for i := 0; i < 5; i++ {
1325 if anime.Ep.NextEpisode.Number == anime.Ep.Number && len(anime.Ep.NextEpisode.Links) > 0 {
1326 CurdOut("Using newly fetched next episode link")
1327 anime.Ep.Links = anime.Ep.NextEpisode.Links
1328 break
1329 }
1330 time.Sleep(1 * time.Second)
1331 }
1332
1333 // If we still don't have links, get them now
1334 if len(anime.Ep.Links) == 0 {
1335 links, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1336 if err != nil {
1337 Log("Failed to get episode links: " + err.Error())
1338 CurdOut("Failed to get episode links. Try again later.")
1339 ExitCurd(fmt.Errorf("failed to get episode links: %v", err))
1340 return
1341 }
1342 anime.Ep.Links = links
1343 }
1344 }
1345
1346 // Verify that we have links before starting
1347 if len(anime.Ep.Links) == 0 {
1348 CurdOut("No episode links found. Try again later.")
1349 ExitCurd(fmt.Errorf("no episode links found"))
1350 return
1351 }
1352
1353 // Actually start the next episode
1354 anime.Ep.Player.SocketPath = StartCurd(userCurdConfig, anime)
1355
1356 // We don't exit, instead we let the main loop continue with the new episode
1357}
1358
1359// StartNextEpisode handles the logic for starting the next episode
1360// It updates the episode number, resets necessary flags, and handles database updates
1361func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile string) {
1362 // Save previous episode number for progress update
1363 prevEpisode := anime.Ep.Number
1364
1365 // Increment episode number
1366 anime.Ep.Number++
1367
1368 // Check if we've reached the end of the series
1369 if anime.TotalEpisodes > 0 && anime.Ep.Number > anime.TotalEpisodes {
1370 CurdOut("Reached end of series")
1371 ExitCurd(nil)
1372 return
1373 }
1374
1375 // Check if this is the last episode - prompt user if needed
1376 if userCurdConfig.NextEpisodePrompt && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !userCurdConfig.RofiSelection {
1377 // Ensure the terminal state is clean for the prompt
1378 fmt.Print("\r\033[K") // Carriage return and clear line
1379 CurdOut(fmt.Sprintf("Last episode (%d). Are you sure you want to watch it?", anime.Ep.Number))
1380
1381 // Simple yes/no selection for the last episode
1382 selectedOption, err := DynamicSelect(map[string]string{"yes": "Yes"})
1383 if err != nil {
1384 ExitCurd(err)
1385 }
1386
1387 if selectedOption.Key != "yes" {
1388 // User selected to quitd
1389 fmt.Print("\r\033[K") // Carriage return and clear line
1390 CurdOut("Exiting without watching the last episode.")
1391 ExitCurd(nil)
1392 return
1393 }
1394
1395 // User chose to continue to the last episode
1396 fmt.Print("\r\033[K") // Carriage return and clear line
1397 }
1398
1399 // Reset episode flags
1400 anime.Ep.Started = false
1401 anime.Ep.IsCompleted = false
1402
1403 // Log the transition
1404 Log("Completed episode, starting next.")
1405
1406 // Update local database
1407 err := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, GetAnimeName(*anime))
1408 if err != nil {
1409 Log("Error updating local database: " + err.Error())
1410 }
1411
1412 // Update Anilist progress for the previous episode if not rewatching
1413 if !anime.Rewatching {
1414 user := &User{}
1415 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token"))
1416 if err != nil {
1417 Log("Error reading token for progress update: " + err.Error())
1418 } else {
1419 go func() {
1420 err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode)
1421 if err != nil {
1422 Log("Error updating Anilist progress: " + err.Error())
1423 } else {
1424 CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1425 }
1426 }()
1427 }
1428 }
1429
1430 // Output message to user
1431 CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
1432}