internal/curd.go
1009 lines · 33596 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 == "" {
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 == "" {
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 == "" {
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 == "" {
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 == "" {
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 == "" {
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 == "" {
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 == "" {
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 == "" {
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 == "" {
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 }
591
592 // Select category using DynamicSelect
593 var err error
594 categorySelection, err = DynamicSelect(categories, false)
595 if err != nil {
596 Log(fmt.Sprintf("Failed to select category: %v", err), logFile)
597 ExitCurd(fmt.Errorf("Failed to select category"))
598 }
599
600 if categorySelection.Key == "-1" {
601 ExitCurd(nil)
602 }
603
604 // Handle UPDATE option
605 if categorySelection.Key == "UPDATE" {
606 ClearScreen()
607 UpdateAnimeEntry(userCurdConfig, user, logFile)
608 ExitCurd(nil)
609 }
610
611 ClearScreen()
612 }
613
614 // Filter anime list based on selected category
615 var animeListMap map[string]string
616 var animeListMapPreview map[string]RofiSelectPreview
617
618 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
619 animeListMapPreview = make(map[string]RofiSelectPreview)
620 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
621 title := entry.Media.Title.English
622 if title == "" {
623 title = entry.Media.Title.Romaji
624 }
625 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
626 Title: title,
627 CoverImage: entry.CoverImage,
628 }
629 }
630 } else {
631 animeListMap = make(map[string]string)
632 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
633 title := entry.Media.Title.English
634 if title == "" {
635 title = entry.Media.Title.Romaji
636 }
637 animeListMap[strconv.Itoa(entry.Media.ID)] = title
638 }
639 }
640
641 var anilistSelectedOption SelectionOption
642 var selectedAllanimeAnime SelectionOption
643 var userQuery string
644
645 if anime.Ep.ContinueLast {
646 // Get the last watched anime ID from the curd_id file
647 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
648 curdIDBytes, err := os.ReadFile(curdIDPath)
649 if err != nil {
650 Log(fmt.Sprintf("Error reading curd_id file: %v", err), logFile)
651 ExitCurd(fmt.Errorf("Error reading curd_id file"))
652 }
653
654 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
655 if err != nil {
656 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err), logFile)
657 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
658 }
659
660 anime.AnilistId = lastWatchedID
661 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
662 } else {
663 // Select anime to watch (Anilist)
664 var err error
665 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
666 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
667 } else {
668 anilistSelectedOption, err = DynamicSelect(animeListMap, true)
669 }
670 if err != nil {
671 Log(fmt.Sprintf("Error selecting anime: %v", err), logFile)
672 ExitCurd(fmt.Errorf("Error selecting anime"))
673 }
674
675 Log(anilistSelectedOption, logFile)
676
677 if anilistSelectedOption.Key == "-1" {
678 ExitCurd(nil)
679 }
680
681 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
682 anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile)
683 }
684
685 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
686 if err != nil {
687 Log(fmt.Sprintf("Error converting Anilist ID: %v", err), logFile)
688 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
689 }
690 }
691 // Find anime in Local history
692 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
693
694 // Get anime entry
695 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
696 if err != nil {
697 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err), logFile)
698 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
699 }
700
701 // Set anime entry
702 anime.Title = selectedAnilistAnime.Media.Title
703 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
704 anime.Ep.Number = selectedAnilistAnime.Progress+1
705 var animeList map[string]string
706 userQuery = anime.Title.Romaji
707
708 // if anime not found in database, find it in animeList
709 if animePointer == nil {
710 Log("Anime not found in database, searching in animeList...", logFile)
711 // Get Anime list (All anime)
712 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub), logFile)
713
714 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
715 Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err), logFile)
716 if err != nil {
717 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
718 ExitCurd(fmt.Errorf("Failed to select anime"))
719 }
720 if len(animeList) == 0 {
721 ExitCurd(fmt.Errorf("No results found."))
722 }
723
724 // find anime in animeList
725 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
726 if err != nil {
727 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile)
728 }
729
730 // If unable to get Allanime id automatically get manually
731 if anime.AllanimeId == "" {
732 CurdOut("Failed to automatically select anime")
733 selectedAllanimeAnime, err := DynamicSelect(animeList, false)
734
735 if selectedAllanimeAnime.Key == "-1" {
736 ExitCurd(nil)
737 }
738
739 if err != nil {
740 // fmt.Println("No anime available")
741 ExitCurd(fmt.Errorf("No anime available"))
742 }
743 anime.AllanimeId = selectedAllanimeAnime.Key
744 }
745 } else {
746 // if anime found in database, use it
747 anime.AllanimeId = animePointer.AllanimeId
748 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
749 anime.Ep.Resume = true
750 anime.Ep.Number = animePointer.Ep.Number
751 }
752
753 if selectedAllanimeAnime.Key == "-1" {
754 ExitCurd(nil)
755 }
756
757 // If upstream is ahead, update the episode number
758 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
759 if temp_anime.Progress > anime.Ep.Number {
760 anime.Ep.Number = temp_anime.Progress
761 anime.Ep.Player.PlaybackTime = 0
762 anime.Ep.Resume = false
763 }
764 }
765
766 if anime.TotalEpisodes == 0 {
767 // Get updated anime data
768 Log(selectedAllanimeAnime, logFile)
769 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
770 Log(updatedAnime, logFile)
771 if err != nil {
772 Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile)
773 } else {
774 anime.TotalEpisodes = updatedAnime.TotalEpisodes
775 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile)
776 }
777 }
778
779 if anime.TotalEpisodes == 0 { // If failed to get anime data
780 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
781 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
782 if err != nil {
783 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
784 } else {
785 for allanimeId, label := range animeList {
786 if allanimeId == anime.AllanimeId {
787 // Extract total episodes from the label
788 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
789 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
790 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
791 break
792 }
793 }
794 }
795 }
796
797 if anime.TotalEpisodes == 0 {
798 CurdOut("Still unable to determine total episodes.")
799 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
800 var episodeNumber int
801 if userCurdConfig.RofiSelection {
802 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
803 if err != nil {
804 Log("Error getting user input: "+err.Error(), logFile)
805 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
806 }
807 episodeNumber, err = strconv.Atoi(userInput)
808 } else {
809 fmt.Print("Enter the episode you want to start from: ")
810 fmt.Scanln(&episodeNumber)
811 }
812 anime.Ep.Number = episodeNumber
813 } else {
814 anime.Ep.Number = selectedAnilistAnime.Progress + 1
815 }
816 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
817 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
818 var answer string
819 if userCurdConfig.RofiSelection {
820 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
821 if err != nil {
822 Log("Error getting user input: "+err.Error(), logFile)
823 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
824 }
825 answer = userInput
826 } else {
827 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
828 fmt.Scanln(&answer)
829 }
830 if answer == "y" {
831 anime.Ep.Number = 1
832 } else {
833 anime.Ep.Number = anime.TotalEpisodes
834 }
835 }
836
837}
838
839// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
840func WriteTokenToFile(token string, filePath string) error {
841 // Extract the directory path
842 dir := filepath.Dir(filePath)
843
844 // Create all necessary parent directories
845 if err := os.MkdirAll(dir, 0755); err != nil {
846 return fmt.Errorf("failed to create directories: %v", err)
847 }
848
849 // Write the token to the file, creating it if it doesn't exist
850 err := os.WriteFile(filePath, []byte(token), 0644)
851 if err != nil {
852 return fmt.Errorf("failed to write token to file: %v", err)
853 }
854
855 return nil
856}
857
858func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
859
860 // Get episode link
861 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
862 if err != nil {
863 // If unable to get episode link automatically get manually
864 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
865 if err != nil {
866 CurdOut("No episode list found")
867 RestoreScreen()
868 os.Exit(1)
869 }
870 if userCurdConfig.RofiSelection {
871 userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
872 if err != nil {
873 Log("Error getting user input: "+err.Error(), logFile)
874 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
875 }
876 anime.Ep.Number, err = strconv.Atoi(userInput)
877 } else {
878 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
879 fmt.Scanln(&anime.Ep.Number)
880 }
881 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
882 if err != nil {
883 CurdOut("Failed to get episode link")
884 os.Exit(1)
885 }
886 // anime.Ep.Links = link
887 }
888 anime.Ep.Links = link
889
890 if len(anime.Ep.Links) == 0 {
891 CurdOut("No episode links found")
892 os.Exit(1)
893 }
894
895 Log(anime, logFile)
896
897 // Write anime.AnilistId to curd_id in the storage path
898 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
899 Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile)
900 if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
901 Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
902 } else {
903 if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
904 Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
905 }
906 }
907
908 // Display starting message with cover image and episode info
909 if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
910 // Get the cached image path
911 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
912 filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
913 cachePath := filepath.Join(cacheDir, filename)
914
915 // Display the image if it exists in cache
916 _, err := os.Stat(cachePath)
917 if err == nil {
918 // File exists
919 Log(fmt.Sprintf("Image found at %s", cachePath), logFile)
920 CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
921 } else {
922 // File does not exist
923 Log(fmt.Sprintf("Image does not exist at %s", cachePath), logFile)
924 CurdOut(fmt.Sprintf("%s - Episode %d",
925 GetAnimeName(*anime),
926 anime.Ep.Number))
927
928 }
929 } else {
930 CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
931 }
932 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{})
933
934 if err != nil {
935 Log("Failed to start mpv", logFile)
936 os.Exit(1)
937 }
938
939 return mpvSocketPath
940}
941
942func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
943 // Create storage directory if it doesn't exist
944 storagePath = os.ExpandEnv(storagePath)
945 if err := os.MkdirAll(storagePath, 0755); err != nil {
946 return fmt.Errorf("failed to create storage directory: %v", err)
947 }
948
949 // Base URL for downloading config files
950 baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
951
952 // Check each file
953 for _, fileName := range filesToCheck {
954 filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
955
956 // Skip if file already exists
957 if _, err := os.Stat(filePath); err == nil {
958 continue
959 }
960
961 // Download file if it doesn't exist
962 resp, err := http.Get(baseURL + fileName)
963 if err != nil {
964 return fmt.Errorf("failed to download %s: %v", fileName, err)
965 }
966 defer resp.Body.Close()
967
968 // Create the file
969 out, err := os.Create(filePath)
970 if err != nil {
971 return fmt.Errorf("failed to create file %s: %v", fileName, err)
972 }
973 defer out.Close()
974
975 // Write the content
976 if _, err := io.Copy(out, resp.Body); err != nil {
977 return fmt.Errorf("failed to write file %s: %v", fileName, err)
978 }
979 }
980
981 return nil
982}
983
984func getEntriesByCategory(list AnimeList, category string) []Entry {
985 switch category {
986 case "ALL":
987 // Combine all categories into one slice
988 allEntries := make([]Entry, 0)
989 allEntries = append(allEntries, list.Watching...)
990 allEntries = append(allEntries, list.Completed...)
991 allEntries = append(allEntries, list.Paused...)
992 allEntries = append(allEntries, list.Dropped...)
993 allEntries = append(allEntries, list.Planning...)
994 return allEntries
995 case "CURRENT":
996 return list.Watching
997 case "COMPLETED":
998 return list.Completed
999 case "PAUSED":
1000 return list.Paused
1001 case "DROPPED":
1002 return list.Dropped
1003 case "PLANNING":
1004 return list.Planning
1005 default:
1006 return []Entry{}
1007 }
1008}
1009