internal/curd.go
1013 lines · 34354 bytes
1package internal
2
3import (
4 "crypto/md5"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "os"
10 "os/exec"
11 "github.com/gen2brain/beeep"
12 "path/filepath"
13 "regexp"
14 "runtime"
15 "strconv"
16 "strings"
17 "time"
18)
19
20func GetTokenFromFile(filePath string) (string, error) {
21 // Read the token from the file
22 data, err := os.ReadFile(filePath)
23 if err != nil {
24 return "", fmt.Errorf("failed to read token from file: %w", err)
25 }
26
27 // Convert the byte slice to a string and remove any surrounding whitespace or newlines
28 token := strings.TrimSpace(string(data))
29
30 return token, nil
31}
32
33func EditConfig(configFilePath string) {
34 // Get the user's preferred editor from the EDITOR environment variable
35 editor := os.Getenv("EDITOR")
36 if editor == "" {
37 // If EDITOR is not set, default to "vim"
38 editor = "vim"
39 }
40
41 // Construct the command to open the config file
42 cmd := exec.Command(editor, configFilePath)
43
44 // Set the command to run in the current terminal
45 cmd.Stdin = os.Stdin
46 cmd.Stdout = os.Stdout
47 cmd.Stderr = os.Stderr
48
49 // Run the editor command
50 err := cmd.Run()
51 if err != nil {
52 CurdOut(fmt.Sprintf("Error opening config file: %v", err))
53 return
54 }
55
56 CurdOut("Config file edited successfully.")
57}
58
59// ClearLogFile removes all contents from the specified log file
60func ClearLogFile(logFile string) error {
61 // Open the file with truncate flag to clear its contents
62 file, err := os.OpenFile(logFile, os.O_WRONLY|os.O_TRUNC, 0666)
63 if err != nil {
64 return fmt.Errorf("failed to open log file: %w", err)
65 }
66 defer file.Close()
67
68 return nil
69}
70
71// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
72func Log(data interface{}, logFile string) error {
73 // Open or create the log file
74 file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
75 if err != nil {
76 return err
77 }
78 defer file.Close() // Ensure the file is closed when done
79
80 // Attempt to marshal the data into JSON
81 jsonData, err := json.Marshal(data)
82 if err != nil {
83 return err
84 }
85
86 // Get the caller information
87 _, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
88 if !ok {
89 return fmt.Errorf("unable to get caller information")
90 }
91
92 // Log the current time and the JSON representation along with caller info
93 currentTime := time.Now().Format("2006/01/02 15:04:05")
94 logMessage := fmt.Sprintf("[LOG] %s %s:%d: %s\n", currentTime, filename, lineNumber, jsonData)
95 _, err = fmt.Fprint(file, logMessage) // Write to the file
96 if err != nil {
97 return err
98 }
99
100 return nil
101}
102
103// ClearScreen clears the terminal screen and saves the state
104func ClearScreen() {
105 fmt.Print("\033[?1049h") // Switch to alternate screen buffer
106 fmt.Print("\033[2J") // Clear the entire screen
107 fmt.Print("\033[H") // Move cursor to the top left
108}
109
110// RestoreScreen restores the original terminal state
111func RestoreScreen() {
112 fmt.Print("\033[?1049l") // Switch back to the main screen buffer
113}
114
115func ExitCurd(err error) {
116 RestoreScreen()
117 CurdOut("Have a great day!")
118 if err != nil {
119 CurdOut(err)
120 if runtime.GOOS == "windows" {
121 fmt.Println("Press Enter to exit")
122 var wait string
123 fmt.Scanln(&wait)
124 os.Exit(1)
125 } else {
126 os.Exit(1)
127 }
128 }
129 os.Exit(0)
130}
131
132func CurdOut(data interface{}) {
133 userCurdConfig := GetGlobalConfig()
134 if userCurdConfig == nil {
135 userCurdConfig = &CurdConfig{}
136 }
137 if !userCurdConfig.RofiSelection {
138 fmt.Println(fmt.Sprintf("%v", data))
139 } else {
140 switch runtime.GOOS {
141 case "windows":
142 err := beeep.Notify(
143 "Curd",
144 fmt.Sprintf("%v", data),
145 "",
146 )
147
148 if err != nil {
149 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile)
150 }
151 case "linux":
152 // Check if the input starts with "-i" for image notification
153 dataStr := fmt.Sprintf("%v", data)
154 if strings.HasPrefix(dataStr, "-i") && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
155 // Split the string to get image path and message
156 parts := strings.SplitN(dataStr, " ", 3)
157 if len(parts) == 3 {
158 // Remove quotes from the message
159 message := strings.Trim(parts[2], "\"")
160 cmd := exec.Command("notify-send", "-i", parts[1], message)
161 err := cmd.Run()
162 if err != nil {
163 Log(fmt.Sprintf("%v", cmd), logFile)
164 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile)
165 }
166 }
167 } else {
168 cmd := exec.Command("notify-send", dataStr)
169 err := cmd.Run()
170 if err != nil {
171 Log(fmt.Sprintf("%v", cmd), logFile)
172 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile)
173 }
174 }
175 }
176 }
177}
178
179func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User, logFile string) {
180 // Create update options map
181 updateOptions := map[string]string{
182 "CATEGORY": "Change Anime Category",
183 "PROGRESS": "Change Progress",
184 "SCORE": "Add/Change Score",
185 }
186
187 // Select update option
188 updateSelection, err := DynamicSelect(updateOptions, false)
189 if err != nil {
190 Log(fmt.Sprintf("Failed to select update option: %v", err), logFile)
191 ExitCurd(fmt.Errorf("Failed to select update option"))
192 }
193
194 if updateSelection.Key == "-1" {
195 ExitCurd(nil)
196 }
197
198 // Get user's anime list
199 var animeListMap map[string]string
200 var animeListMapPreview map[string]RofiSelectPreview
201
202 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
203 animeListMapPreview = make(map[string]RofiSelectPreview)
204 // Include anime from all categories
205 for _, entry := range user.AnimeList.Watching {
206 title := entry.Media.Title.English
207 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
208 title = entry.Media.Title.Romaji
209 }
210 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
211 Title: title,
212 CoverImage: entry.CoverImage,
213 }
214 }
215 for _, entry := range user.AnimeList.Completed {
216 title := entry.Media.Title.English
217 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
218 title = entry.Media.Title.Romaji
219 }
220 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
221 Title: title,
222 CoverImage: entry.CoverImage,
223 }
224 }
225 for _, entry := range user.AnimeList.Paused {
226 title := entry.Media.Title.English
227 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
228 title = entry.Media.Title.Romaji
229 }
230 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
231 Title: title,
232 CoverImage: entry.CoverImage,
233 }
234 }
235 for _, entry := range user.AnimeList.Dropped {
236 title := entry.Media.Title.English
237 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
238 title = entry.Media.Title.Romaji
239 }
240 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
241 Title: title,
242 CoverImage: entry.CoverImage,
243 }
244 }
245 for _, entry := range user.AnimeList.Planning {
246 title := entry.Media.Title.English
247 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
248 title = entry.Media.Title.Romaji
249 }
250 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
251 Title: title,
252 CoverImage: entry.CoverImage,
253 }
254 }
255 } else {
256 animeListMap = make(map[string]string)
257 // Include anime from all categories
258 for _, entry := range user.AnimeList.Watching {
259 title := entry.Media.Title.English
260 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
261 title = entry.Media.Title.Romaji
262 }
263 animeListMap[strconv.Itoa(entry.Media.ID)] = title
264 }
265 for _, entry := range user.AnimeList.Completed {
266 title := entry.Media.Title.English
267 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
268 title = entry.Media.Title.Romaji
269 }
270 animeListMap[strconv.Itoa(entry.Media.ID)] = title
271 }
272 for _, entry := range user.AnimeList.Paused {
273 title := entry.Media.Title.English
274 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
275 title = entry.Media.Title.Romaji
276 }
277 animeListMap[strconv.Itoa(entry.Media.ID)] = title
278 }
279 for _, entry := range user.AnimeList.Dropped {
280 title := entry.Media.Title.English
281 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
282 title = entry.Media.Title.Romaji
283 }
284 animeListMap[strconv.Itoa(entry.Media.ID)] = title
285 }
286 for _, entry := range user.AnimeList.Planning {
287 title := entry.Media.Title.English
288 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
289 title = entry.Media.Title.Romaji
290 }
291 animeListMap[strconv.Itoa(entry.Media.ID)] = title
292 }
293 }
294
295 // Select anime to update
296 var selectedAnime SelectionOption
297 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
298 selectedAnime, err = DynamicSelectPreview(animeListMapPreview, false)
299 } else {
300 selectedAnime, err = DynamicSelect(animeListMap, false)
301 }
302 if err != nil {
303 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
304 ExitCurd(fmt.Errorf("Failed to select anime"))
305 }
306
307 if selectedAnime.Key == "-1" {
308 ExitCurd(nil)
309 }
310
311 animeID, err := strconv.Atoi(selectedAnime.Key)
312 if err != nil {
313 Log(fmt.Sprintf("Failed to convert anime ID: %v", err), logFile)
314 ExitCurd(fmt.Errorf("Failed to convert anime ID"))
315 }
316
317 // After getting animeID, get the current anime entry
318 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key)
319 if err != nil {
320 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err), logFile)
321 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
322 }
323 ClearScreen()
324 switch updateSelection.Key {
325 case "CATEGORY":
326 categories := map[string]string{
327 "CURRENT": "Currently Watching",
328 "COMPLETED": "Completed",
329 "PAUSED": "On Hold",
330 "DROPPED": "Dropped",
331 "PLANNING": "Plan to Watch",
332 }
333
334 currentStatus := "None"
335 if selectedAnilistAnime.Status != "" {
336 currentStatus = categories[selectedAnilistAnime.Status]
337 }
338 CurdOut(fmt.Sprintf("Current category: %s", currentStatus))
339
340 categorySelection, err := DynamicSelect(categories, false)
341 if err != nil {
342 Log(fmt.Sprintf("Failed to select category: %v", err), logFile)
343 ExitCurd(fmt.Errorf("Failed to select category"))
344 }
345
346 if categorySelection.Key == "-1" {
347 ExitCurd(nil)
348 }
349
350 err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
351 if err != nil {
352 Log(fmt.Sprintf("Failed to update anime status: %v", err), logFile)
353 ExitCurd(fmt.Errorf("Failed to update anime status"))
354 }
355
356 case "PROGRESS":
357 currentProgress := "None"
358 if selectedAnilistAnime.Progress > 0 {
359 currentProgress = strconv.Itoa(selectedAnilistAnime.Progress)
360 }
361
362 var progress string
363 if userCurdConfig.RofiSelection {
364 progress, err = GetUserInputFromRofi(fmt.Sprintf("Current progress: %s\nEnter new progress (episode number)", currentProgress))
365 if err != nil {
366 Log(fmt.Sprintf("Failed to get progress input: %v", err), logFile)
367 ExitCurd(fmt.Errorf("Failed to get progress input"))
368 }
369 } else {
370 CurdOut(fmt.Sprintf("Current progress: %s", currentProgress))
371 CurdOut("Enter new progress (episode number):")
372 fmt.Scanln(&progress)
373 }
374
375 progressNum, err := strconv.Atoi(progress)
376 if err != nil {
377 Log(fmt.Sprintf("Failed to convert progress to number: %v", err), logFile)
378 ExitCurd(fmt.Errorf("Failed to convert progress to number"))
379 }
380
381 err = UpdateAnimeProgress(user.Token, animeID, progressNum)
382 if err != nil {
383 Log(fmt.Sprintf("Failed to update anime progress: %v", err), logFile)
384 ExitCurd(fmt.Errorf("Failed to update anime progress"))
385 }
386
387 case "SCORE":
388 currentScore := "None"
389 if selectedAnilistAnime.Score > 0 {
390 currentScore = strconv.Itoa(int(selectedAnilistAnime.Score))
391 }
392 CurdOut(fmt.Sprintf("Current score: %s", currentScore))
393
394 err = RateAnime(user.Token, animeID)
395 if err != nil {
396 Log(fmt.Sprintf("Failed to update anime score: %v", err), logFile)
397 ExitCurd(fmt.Errorf("Failed to update anime score"))
398 }
399 }
400
401 CurdOut("Anime updated successfully!")
402}
403
404func UpdateCurd(repo, fileName string) error {
405 // Get the path of the currently running executable
406 executablePath, err := os.Executable()
407 if err != nil {
408 return fmt.Errorf("unable to find current executable: %v", err)
409 }
410
411 // Adjust file name for Windows
412 if runtime.GOOS == "windows" {
413 fileName += ".exe"
414 }
415
416 // GitHub release URL for curd
417 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, fileName)
418
419 // Temporary path for the downloaded curd executable
420 tmpPath := executablePath + ".tmp"
421
422 // Download the curd executable
423 resp, err := http.Get(url)
424 if err != nil {
425 return fmt.Errorf("failed to download file: %v", err)
426 }
427 defer resp.Body.Close()
428
429 // Check if the download was successful
430 if resp.StatusCode != http.StatusOK {
431 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
432 }
433
434 // Create a new temporary file
435 out, err := os.Create(tmpPath)
436 if err != nil {
437 return fmt.Errorf("failed to create temporary file: %v", err)
438 }
439 defer out.Close()
440
441 // Write the downloaded content to the temporary file
442 _, err = io.Copy(out, resp.Body)
443 if err != nil {
444 return fmt.Errorf("failed to save downloaded file: %v", err)
445 }
446
447 // Close and rename the temporary file to replace the current executable
448 out.Close()
449
450 // Replace the current executable with the downloaded curd
451 if err := os.Rename(tmpPath, executablePath); err != nil {
452 return fmt.Errorf("failed to replace the current executable: %v", err)
453 }
454 CurdOut(fmt.Sprintf("Downloaded curd executable to %v", executablePath))
455
456 if runtime.GOOS != "windows" {
457 // Ensure the new file has executable permissions
458 if err := os.Chmod(executablePath, 0755); err != nil {
459 return fmt.Errorf("failed to set permissions on the new file: %v", err)
460 }
461 }
462
463 return nil
464}
465
466func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) SelectionOption {
467 var query string
468 var animeMap map[string]string
469 var animeMapPreview map[string]RofiSelectPreview
470 var err error
471 var anilistSelectedOption SelectionOption
472 var anilistUserData map[string]interface{}
473 var anilistUserDataPreview map[string]interface{}
474
475 if userCurdConfig.RofiSelection {
476 userInput, err := GetUserInputFromRofi("Enter the anime name")
477 if err != nil {
478 Log("Error getting user input: "+err.Error(), logFile)
479 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
480 }
481 query = userInput
482 } else {
483 CurdOut("Enter the anime name:")
484 fmt.Scanln(&query)
485 }
486 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
487 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
488 } else {
489 animeMap, err = SearchAnimeAnilist(query, user.Token)
490 }
491 if err != nil {
492 Log(fmt.Sprintf("Failed to search anime: %v", err), logFile)
493 ExitCurd(fmt.Errorf("Failed to search anime"))
494 }
495 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
496 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
497 } else {
498 anilistSelectedOption, err = DynamicSelect(animeMap, false)
499 }
500
501 if anilistSelectedOption.Key == "-1" {
502 ExitCurd(nil)
503 }
504
505 if err != nil {
506 Log(fmt.Sprintf("No anime available: %v", err), logFile)
507 ExitCurd(fmt.Errorf("No anime available"))
508 }
509 animeID, err := strconv.Atoi(anilistSelectedOption.Key)
510 if err != nil {
511 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err), logFile)
512 ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
513 }
514 err = AddAnimeToWatchingList(animeID, user.Token)
515 if err != nil {
516 Log(fmt.Sprintf("Failed to add anime to watching list: %v", err), logFile)
517 ExitCurd(fmt.Errorf("Failed to add anime to watching list"))
518 }
519 if user.Id == 0 {
520 user.Id, user.Username, err = GetAnilistUserID(user.Token)
521 if err != nil {
522 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
523 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
524 }
525 }
526 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
527 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
528 } else {
529 anilistUserData, err = GetUserData(user.Token, user.Id)
530 }
531 if err != nil {
532 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
533 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
534 }
535 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
536 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
537 } else {
538 user.AnimeList = ParseAnimeList(anilistUserData)
539 }
540
541 return anilistSelectedOption
542}
543
544func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
545 var err error
546 var anilistUserData map[string]interface{}
547 var anilistUserDataPreview map[string]interface{}
548
549 // Get user id, username and Anime list
550 user.Id, user.Username, err = GetAnilistUserID(user.Token)
551 if err != nil {
552 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
553 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
554 }
555
556 // Get the anime list data
557 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
558 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
559 if err != nil {
560 Log(fmt.Sprintf("Failed to get user data preview: %v", err), logFile)
561 ExitCurd(fmt.Errorf("Failed to get user data preview"))
562 }
563 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
564 } else {
565 anilistUserData, err = GetUserData(user.Token, user.Id)
566 if err != nil {
567 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
568 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
569 }
570 user.AnimeList = ParseAnimeList(anilistUserData)
571 }
572
573 // Skip category selection if Current flag is set
574 var categorySelection SelectionOption
575 if userCurdConfig.CurrentCategory {
576 categorySelection = SelectionOption{
577 Key: "CURRENT",
578 Label: "Currently Watching",
579 }
580 } else {
581 // Create category selection map
582 categories := map[string]string{
583 "ALL": "Show All",
584 "CURRENT": "Currently Watching",
585 "PAUSED": "On Hold",
586 "PLANNING": "Plan to Watch",
587 "COMPLETED": "Completed",
588 "DROPPED": "Dropped",
589 "UPDATE": "Update Anime Entry",
590 "UNTRACKED": "Untracked Watching",
591 }
592
593 // Select category using DynamicSelect
594 var err error
595 categorySelection, err = DynamicSelect(categories, false)
596 if err != nil {
597 Log(fmt.Sprintf("Failed to select category: %v", err), logFile)
598 ExitCurd(fmt.Errorf("Failed to select category"))
599 }
600
601 if categorySelection.Key == "-1" {
602 ExitCurd(nil)
603 }
604
605 // Handle UPDATE option
606 if categorySelection.Key == "UPDATE" {
607 ClearScreen()
608 UpdateAnimeEntry(userCurdConfig, user, logFile)
609 ExitCurd(nil)
610 } else if categorySelection.Key == "UNTRACKED" {
611 ClearScreen()
612 WatchUntracked(userCurdConfig, logFile)
613 }
614
615 ClearScreen()
616 }
617
618 // Filter anime list based on selected category
619 var animeListMap map[string]string
620 var animeListMapPreview map[string]RofiSelectPreview
621
622 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
623 animeListMapPreview = make(map[string]RofiSelectPreview)
624 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
625 title := entry.Media.Title.English
626 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
627 title = entry.Media.Title.Romaji
628 }
629 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
630 Title: title,
631 CoverImage: entry.CoverImage,
632 }
633 }
634 } else {
635 animeListMap = make(map[string]string)
636 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
637 title := entry.Media.Title.English
638 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
639 title = entry.Media.Title.Romaji
640 }
641 animeListMap[strconv.Itoa(entry.Media.ID)] = title
642 }
643 }
644
645 var anilistSelectedOption SelectionOption
646 var selectedAllanimeAnime SelectionOption
647 var userQuery string
648
649 if anime.Ep.ContinueLast {
650 // Get the last watched anime ID from the curd_id file
651 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
652 curdIDBytes, err := os.ReadFile(curdIDPath)
653 if err != nil {
654 Log(fmt.Sprintf("Error reading curd_id file: %v", err), logFile)
655 ExitCurd(fmt.Errorf("Error reading curd_id file"))
656 }
657
658 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
659 if err != nil {
660 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err), logFile)
661 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
662 }
663
664 anime.AnilistId = lastWatchedID
665 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
666 } else {
667 // Select anime to watch (Anilist)
668 var err error
669 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
670 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
671 } else {
672 anilistSelectedOption, err = DynamicSelect(animeListMap, true)
673 }
674 if err != nil {
675 Log(fmt.Sprintf("Error selecting anime: %v", err), logFile)
676 ExitCurd(fmt.Errorf("Error selecting anime"))
677 }
678
679 Log(anilistSelectedOption, logFile)
680
681 if anilistSelectedOption.Key == "-1" {
682 ExitCurd(nil)
683 }
684
685 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
686 anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile)
687 }
688
689 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
690 if err != nil {
691 Log(fmt.Sprintf("Error converting Anilist ID: %v", err), logFile)
692 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
693 }
694 }
695 // Find anime in Local history
696 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
697
698 // Get anime entry
699 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
700 if err != nil {
701 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err), logFile)
702 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
703 }
704
705 // Set anime entry
706 anime.Title = selectedAnilistAnime.Media.Title
707 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
708 anime.Ep.Number = selectedAnilistAnime.Progress+1
709 var animeList map[string]string
710 userQuery = anime.Title.Romaji
711
712 // if anime not found in database, find it in animeList
713 if animePointer == nil {
714 Log("Anime not found in database, searching in animeList...", logFile)
715 // Get Anime list (All anime)
716 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub), logFile)
717
718 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
719 Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err), logFile)
720 if err != nil {
721 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
722 ExitCurd(fmt.Errorf("Failed to select anime"))
723 }
724 if len(animeList) == 0 {
725 ExitCurd(fmt.Errorf("No results found."))
726 }
727
728 // find anime in animeList
729 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
730 if err != nil {
731 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile)
732 }
733
734 // If unable to get Allanime id automatically get manually
735 if anime.AllanimeId == "" {
736 CurdOut("Failed to automatically select anime")
737 selectedAllanimeAnime, err := DynamicSelect(animeList, false)
738
739 if selectedAllanimeAnime.Key == "-1" {
740 ExitCurd(nil)
741 }
742
743 if err != nil {
744 // fmt.Println("No anime available")
745 ExitCurd(fmt.Errorf("No anime available"))
746 }
747 anime.AllanimeId = selectedAllanimeAnime.Key
748 }
749 } else {
750 // if anime found in database, use it
751 anime.AllanimeId = animePointer.AllanimeId
752 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
753 anime.Ep.Resume = true
754 anime.Ep.Number = animePointer.Ep.Number
755 }
756
757 if selectedAllanimeAnime.Key == "-1" {
758 ExitCurd(nil)
759 }
760
761 // If upstream is ahead, update the episode number
762 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
763 if temp_anime.Progress > anime.Ep.Number {
764 anime.Ep.Number = temp_anime.Progress
765 anime.Ep.Player.PlaybackTime = 0
766 anime.Ep.Resume = false
767 }
768 }
769
770 if anime.TotalEpisodes == 0 {
771 // Get updated anime data
772 Log(selectedAllanimeAnime, logFile)
773 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
774 Log(updatedAnime, logFile)
775 if err != nil {
776 Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile)
777 } else {
778 anime.TotalEpisodes = updatedAnime.TotalEpisodes
779 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile)
780 }
781 }
782
783 if anime.TotalEpisodes == 0 { // If failed to get anime data
784 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
785 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
786 if err != nil {
787 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
788 } else {
789 for allanimeId, label := range animeList {
790 if allanimeId == anime.AllanimeId {
791 // Extract total episodes from the label
792 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
793 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
794 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
795 break
796 }
797 }
798 }
799 }
800
801 if anime.TotalEpisodes == 0 {
802 CurdOut("Still unable to determine total episodes.")
803 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
804 var episodeNumber int
805 if userCurdConfig.RofiSelection {
806 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
807 if err != nil {
808 Log("Error getting user input: "+err.Error(), logFile)
809 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
810 }
811 episodeNumber, err = strconv.Atoi(userInput)
812 } else {
813 fmt.Print("Enter the episode you want to start from: ")
814 fmt.Scanln(&episodeNumber)
815 }
816 anime.Ep.Number = episodeNumber
817 } else {
818 anime.Ep.Number = selectedAnilistAnime.Progress + 1
819 }
820 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
821 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
822 var answer string
823 if userCurdConfig.RofiSelection {
824 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
825 if err != nil {
826 Log("Error getting user input: "+err.Error(), logFile)
827 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
828 }
829 answer = userInput
830 } else {
831 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
832 fmt.Scanln(&answer)
833 }
834 if answer == "y" {
835 anime.Ep.Number = 1
836 } else {
837 anime.Ep.Number = anime.TotalEpisodes
838 }
839 }
840
841}
842
843// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
844func WriteTokenToFile(token string, filePath string) error {
845 // Extract the directory path
846 dir := filepath.Dir(filePath)
847
848 // Create all necessary parent directories
849 if err := os.MkdirAll(dir, 0755); err != nil {
850 return fmt.Errorf("failed to create directories: %v", err)
851 }
852
853 // Write the token to the file, creating it if it doesn't exist
854 err := os.WriteFile(filePath, []byte(token), 0644)
855 if err != nil {
856 return fmt.Errorf("failed to write token to file: %v", err)
857 }
858
859 return nil
860}
861
862func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
863
864 // Get episode link
865 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
866 if err != nil {
867 // If unable to get episode link automatically get manually
868 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
869 if err != nil {
870 CurdOut("No episode list found")
871 RestoreScreen()
872 os.Exit(1)
873 }
874 if userCurdConfig.RofiSelection {
875 userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
876 if err != nil {
877 Log("Error getting user input: "+err.Error(), logFile)
878 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
879 }
880 anime.Ep.Number, err = strconv.Atoi(userInput)
881 } else {
882 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
883 fmt.Scanln(&anime.Ep.Number)
884 }
885 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
886 if err != nil {
887 CurdOut("Failed to get episode link")
888 os.Exit(1)
889 }
890 // anime.Ep.Links = link
891 }
892 anime.Ep.Links = link
893
894 if len(anime.Ep.Links) == 0 {
895 CurdOut("No episode links found")
896 os.Exit(1)
897 }
898
899 Log(anime, logFile)
900
901 // Write anime.AnilistId to curd_id in the storage path
902 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
903 Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile)
904 if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
905 Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
906 } else {
907 if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
908 Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
909 }
910 }
911
912 // Display starting message with cover image and episode info
913 if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
914 // Get the cached image path
915 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
916 filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
917 cachePath := filepath.Join(cacheDir, filename)
918
919 // Display the image if it exists in cache
920 _, err := os.Stat(cachePath)
921 if err == nil {
922 // File exists
923 Log(fmt.Sprintf("Image found at %s", cachePath), logFile)
924 CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
925 } else {
926 // File does not exist
927 Log(fmt.Sprintf("Image does not exist at %s", cachePath), logFile)
928 CurdOut(fmt.Sprintf("%s - Episode %d",
929 GetAnimeName(*anime),
930 anime.Ep.Number))
931
932 }
933 } else {
934 CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
935 }
936 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{})
937
938 if err != nil {
939 Log("Failed to start mpv", logFile)
940 os.Exit(1)
941 }
942
943 return mpvSocketPath
944}
945
946func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
947 // Create storage directory if it doesn't exist
948 storagePath = os.ExpandEnv(storagePath)
949 if err := os.MkdirAll(storagePath, 0755); err != nil {
950 return fmt.Errorf("failed to create storage directory: %v", err)
951 }
952
953 // Base URL for downloading config files
954 baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
955
956 // Check each file
957 for _, fileName := range filesToCheck {
958 filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
959
960 // Skip if file already exists
961 if _, err := os.Stat(filePath); err == nil {
962 continue
963 }
964
965 // Download file if it doesn't exist
966 resp, err := http.Get(baseURL + fileName)
967 if err != nil {
968 return fmt.Errorf("failed to download %s: %v", fileName, err)
969 }
970 defer resp.Body.Close()
971
972 // Create the file
973 out, err := os.Create(filePath)
974 if err != nil {
975 return fmt.Errorf("failed to create file %s: %v", fileName, err)
976 }
977 defer out.Close()
978
979 // Write the content
980 if _, err := io.Copy(out, resp.Body); err != nil {
981 return fmt.Errorf("failed to write file %s: %v", fileName, err)
982 }
983 }
984
985 return nil
986}
987
988func getEntriesByCategory(list AnimeList, category string) []Entry {
989 switch category {
990 case "ALL":
991 // Combine all categories into one slice
992 allEntries := make([]Entry, 0)
993 allEntries = append(allEntries, list.Watching...)
994 allEntries = append(allEntries, list.Completed...)
995 allEntries = append(allEntries, list.Paused...)
996 allEntries = append(allEntries, list.Dropped...)
997 allEntries = append(allEntries, list.Planning...)
998 return allEntries
999 case "CURRENT":
1000 return list.Watching
1001 case "COMPLETED":
1002 return list.Completed
1003 case "PAUSED":
1004 return list.Paused
1005 case "DROPPED":
1006 return list.Dropped
1007 case "PLANNING":
1008 return list.Planning
1009 default:
1010 return []Entry{}
1011 }
1012}
1013