internal/curd.go
756 lines · 25932 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 UpdateCurd(repo, fileName string) error {
180 // Get the path of the currently running executable
181 executablePath, err := os.Executable()
182 if err != nil {
183 return fmt.Errorf("unable to find current executable: %v", err)
184 }
185
186 // Adjust file name for Windows
187 if runtime.GOOS == "windows" {
188 fileName += ".exe"
189 }
190
191 // GitHub release URL for curd
192 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, fileName)
193
194 // Temporary path for the downloaded curd executable
195 tmpPath := executablePath + ".tmp"
196
197 // Download the curd executable
198 resp, err := http.Get(url)
199 if err != nil {
200 return fmt.Errorf("failed to download file: %v", err)
201 }
202 defer resp.Body.Close()
203
204 // Check if the download was successful
205 if resp.StatusCode != http.StatusOK {
206 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
207 }
208
209 // Create a new temporary file
210 out, err := os.Create(tmpPath)
211 if err != nil {
212 return fmt.Errorf("failed to create temporary file: %v", err)
213 }
214 defer out.Close()
215
216 // Write the downloaded content to the temporary file
217 _, err = io.Copy(out, resp.Body)
218 if err != nil {
219 return fmt.Errorf("failed to save downloaded file: %v", err)
220 }
221
222 // Close and rename the temporary file to replace the current executable
223 out.Close()
224
225 // Replace the current executable with the downloaded curd
226 if err := os.Rename(tmpPath, executablePath); err != nil {
227 return fmt.Errorf("failed to replace the current executable: %v", err)
228 }
229 CurdOut(fmt.Sprintf("Downloaded curd executable to %v", executablePath))
230
231 if runtime.GOOS != "windows" {
232 // Ensure the new file has executable permissions
233 if err := os.Chmod(executablePath, 0755); err != nil {
234 return fmt.Errorf("failed to set permissions on the new file: %v", err)
235 }
236 }
237
238 return nil
239}
240
241func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) SelectionOption {
242 var query string
243 var animeMap map[string]string
244 var animeMapPreview map[string]RofiSelectPreview
245 var err error
246 var anilistSelectedOption SelectionOption
247 var anilistUserData map[string]interface{}
248 var anilistUserDataPreview map[string]interface{}
249
250 if userCurdConfig.RofiSelection {
251 userInput, err := GetUserInputFromRofi("Enter the anime name")
252 if err != nil {
253 Log("Error getting user input: "+err.Error(), logFile)
254 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
255 }
256 query = userInput
257 } else {
258 CurdOut("Enter the anime name:")
259 fmt.Scanln(&query)
260 }
261 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
262 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
263 } else {
264 animeMap, err = SearchAnimeAnilist(query, user.Token)
265 }
266 if err != nil {
267 Log(fmt.Sprintf("Failed to search anime: %v", err), logFile)
268 ExitCurd(fmt.Errorf("Failed to search anime"))
269 }
270 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
271 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
272 } else {
273 anilistSelectedOption, err = DynamicSelect(animeMap, false)
274 }
275 if err != nil {
276 Log(fmt.Sprintf("No anime available: %v", err), logFile)
277 ExitCurd(fmt.Errorf("No anime available"))
278 }
279 animeID, err := strconv.Atoi(anilistSelectedOption.Key)
280 if err != nil {
281 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err), logFile)
282 ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
283 }
284 err = AddAnimeToWatchingList(animeID, user.Token)
285 if err != nil {
286 Log(fmt.Sprintf("Failed to add anime to watching list: %v", err), logFile)
287 ExitCurd(fmt.Errorf("Failed to add anime to watching list"))
288 }
289 if user.Id == 0 {
290 user.Id, user.Username, err = GetAnilistUserID(user.Token)
291 if err != nil {
292 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
293 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
294 }
295 }
296 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
297 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
298 } else {
299 anilistUserData, err = GetUserData(user.Token, user.Id)
300 }
301 if err != nil {
302 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
303 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
304 }
305 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
306 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
307 } else {
308 user.AnimeList = ParseAnimeList(anilistUserData)
309 }
310
311 return anilistSelectedOption
312}
313
314func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
315 var err error
316 var anilistUserData map[string]interface{}
317 var anilistUserDataPreview map[string]interface{}
318
319 // Get user id, username and Anime list
320 user.Id, user.Username, err = GetAnilistUserID(user.Token)
321 if err != nil {
322 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
323 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
324 }
325
326 // Get the anime list data
327 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
328 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
329 if err != nil {
330 Log(fmt.Sprintf("Failed to get user data preview: %v", err), logFile)
331 ExitCurd(fmt.Errorf("Failed to get user data preview"))
332 }
333 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
334 } else {
335 anilistUserData, err = GetUserData(user.Token, user.Id)
336 if err != nil {
337 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
338 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
339 }
340 user.AnimeList = ParseAnimeList(anilistUserData)
341 }
342
343 // Skip category selection if Current flag is set
344 var categorySelection SelectionOption
345 if userCurdConfig.CurrentCategory {
346 categorySelection = SelectionOption{
347 Key: "CURRENT",
348 Label: "Currently Watching",
349 }
350 } else {
351 // Create category selection map
352 categories := map[string]string{
353 "CURRENT": "Currently Watching",
354 "PAUSED": "On Hold",
355 "PLANNING": "Plan to Watch",
356 "COMPLETED": "Completed",
357 "DROPPED": "Dropped",
358 }
359
360 // Select category using DynamicSelect
361 var err error
362 categorySelection, err = DynamicSelect(categories, false)
363 if err != nil {
364 Log(fmt.Sprintf("Failed to select category: %v", err), logFile)
365 ExitCurd(fmt.Errorf("Failed to select category"))
366 }
367
368 if categorySelection.Key == "-1" {
369 ExitCurd(nil)
370 }
371 ClearScreen()
372 }
373
374 // Filter anime list based on selected category
375 var animeListMap map[string]string
376 var animeListMapPreview map[string]RofiSelectPreview
377
378 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
379 animeListMapPreview = make(map[string]RofiSelectPreview)
380 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
381 title := entry.Media.Title.English
382 if title == "" {
383 title = entry.Media.Title.Romaji
384 }
385 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
386 Title: title,
387 CoverImage: entry.CoverImage,
388 }
389 }
390 } else {
391 animeListMap = make(map[string]string)
392 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
393 title := entry.Media.Title.English
394 if title == "" {
395 title = entry.Media.Title.Romaji
396 }
397 animeListMap[strconv.Itoa(entry.Media.ID)] = title
398 }
399 }
400
401 var anilistSelectedOption SelectionOption
402 var selectedAllanimeAnime SelectionOption
403 var userQuery string
404
405 if anime.Ep.ContinueLast {
406 // Get the last watched anime ID from the curd_id file
407 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
408 curdIDBytes, err := os.ReadFile(curdIDPath)
409 if err != nil {
410 Log(fmt.Sprintf("Error reading curd_id file: %v", err), logFile)
411 ExitCurd(fmt.Errorf("Error reading curd_id file"))
412 }
413
414 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
415 if err != nil {
416 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err), logFile)
417 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
418 }
419
420 anime.AnilistId = lastWatchedID
421 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
422 } else {
423 // Select anime to watch (Anilist)
424 var err error
425 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
426 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
427 } else {
428 anilistSelectedOption, err = DynamicSelect(animeListMap, true)
429 }
430 if err != nil {
431 Log(fmt.Sprintf("Error selecting anime: %v", err), logFile)
432 ExitCurd(fmt.Errorf("Error selecting anime"))
433 }
434
435 Log(anilistSelectedOption, logFile)
436
437 if anilistSelectedOption.Key == "-1" {
438 ExitCurd(nil)
439 }
440
441 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
442 anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile)
443 }
444
445 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
446 if err != nil {
447 Log(fmt.Sprintf("Error converting Anilist ID: %v", err), logFile)
448 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
449 }
450 }
451 // Find anime in Local history
452 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
453
454 // Get anime entry
455 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
456 if err != nil {
457 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err), logFile)
458 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
459 }
460
461 // Set anime entry
462 anime.Title = selectedAnilistAnime.Media.Title
463 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
464 anime.Ep.Number = selectedAnilistAnime.Progress+1
465 var animeList map[string]string
466 userQuery = anime.Title.Romaji
467
468 // if anime not found in database, find it in animeList
469 if animePointer == nil {
470 Log("Anime not found in database, searching in animeList...", logFile)
471 // Get Anime list (All anime)
472 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub), logFile)
473
474 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
475 Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err), logFile)
476 if err != nil {
477 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
478 ExitCurd(fmt.Errorf("Failed to select anime"))
479 }
480 if len(animeList) == 0 {
481 ExitCurd(fmt.Errorf("No results found."))
482 }
483
484 // find anime in animeList
485 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
486 if err != nil {
487 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile)
488 }
489
490 // If unable to get Allanime id automatically get manually
491 if anime.AllanimeId == "" {
492 CurdOut("Failed to automatically select anime")
493 selectedAllanimeAnime, err := DynamicSelect(animeList, false)
494
495 if err != nil {
496 // fmt.Println("No anime available")
497 ExitCurd(fmt.Errorf("No anime available"))
498 }
499 anime.AllanimeId = selectedAllanimeAnime.Key
500 }
501 } else {
502 // if anime found in database, use it
503 anime.AllanimeId = animePointer.AllanimeId
504 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
505 anime.Ep.Resume = true
506 anime.Ep.Number = animePointer.Ep.Number
507 }
508
509 if selectedAllanimeAnime.Key == "-1" {
510 ExitCurd(nil)
511 }
512
513 // If upstream is ahead, update the episode number
514 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
515 if temp_anime.Progress > anime.Ep.Number {
516 anime.Ep.Number = temp_anime.Progress
517 anime.Ep.Player.PlaybackTime = 0
518 anime.Ep.Resume = false
519 }
520 }
521
522 if anime.TotalEpisodes == 0 {
523 // Get updated anime data
524 Log(selectedAllanimeAnime, logFile)
525 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
526 Log(updatedAnime, logFile)
527 if err != nil {
528 Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile)
529 } else {
530 anime.TotalEpisodes = updatedAnime.TotalEpisodes
531 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile)
532 }
533 }
534
535 if anime.TotalEpisodes == 0 { // If failed to get anime data
536 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
537 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
538 if err != nil {
539 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
540 } else {
541 for allanimeId, label := range animeList {
542 if allanimeId == anime.AllanimeId {
543 // Extract total episodes from the label
544 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
545 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
546 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
547 break
548 }
549 }
550 }
551 }
552
553 if anime.TotalEpisodes == 0 {
554 CurdOut("Still unable to determine total episodes.")
555 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
556 var episodeNumber int
557 if userCurdConfig.RofiSelection {
558 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
559 if err != nil {
560 Log("Error getting user input: "+err.Error(), logFile)
561 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
562 }
563 episodeNumber, err = strconv.Atoi(userInput)
564 } else {
565 fmt.Print("Enter the episode you want to start from: ")
566 fmt.Scanln(&episodeNumber)
567 }
568 anime.Ep.Number = episodeNumber
569 } else {
570 anime.Ep.Number = selectedAnilistAnime.Progress + 1
571 }
572 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
573 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
574 var answer string
575 if userCurdConfig.RofiSelection {
576 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
577 if err != nil {
578 Log("Error getting user input: "+err.Error(), logFile)
579 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
580 }
581 answer = userInput
582 } else {
583 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
584 fmt.Scanln(&answer)
585 }
586 if answer == "y" {
587 anime.Ep.Number = 1
588 } else {
589 anime.Ep.Number = anime.TotalEpisodes
590 }
591 }
592
593}
594
595// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
596func WriteTokenToFile(token string, filePath string) error {
597 // Extract the directory path
598 dir := filepath.Dir(filePath)
599
600 // Create all necessary parent directories
601 if err := os.MkdirAll(dir, 0755); err != nil {
602 return fmt.Errorf("failed to create directories: %v", err)
603 }
604
605 // Write the token to the file, creating it if it doesn't exist
606 err := os.WriteFile(filePath, []byte(token), 0644)
607 if err != nil {
608 return fmt.Errorf("failed to write token to file: %v", err)
609 }
610
611 return nil
612}
613
614func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
615
616 // Get episode link
617 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
618 if err != nil {
619 // If unable to get episode link automatically get manually
620 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
621 if err != nil {
622 CurdOut("No episode list found")
623 RestoreScreen()
624 os.Exit(1)
625 }
626 if userCurdConfig.RofiSelection {
627 userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
628 if err != nil {
629 Log("Error getting user input: "+err.Error(), logFile)
630 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
631 }
632 anime.Ep.Number, err = strconv.Atoi(userInput)
633 } else {
634 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
635 fmt.Scanln(&anime.Ep.Number)
636 }
637 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
638 if err != nil {
639 CurdOut("Failed to get episode link")
640 os.Exit(1)
641 }
642 // anime.Ep.Links = link
643 }
644 anime.Ep.Links = link
645
646 if len(anime.Ep.Links) == 0 {
647 CurdOut("No episode links found")
648 os.Exit(1)
649 }
650
651 Log(anime, logFile)
652
653 // Write anime.AnilistId to curd_id in the storage path
654 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
655 Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile)
656 if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
657 Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
658 } else {
659 if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
660 Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
661 }
662 }
663
664 // Display starting message with cover image and episode info
665 if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
666 // Get the cached image path
667 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
668 filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
669 cachePath := filepath.Join(cacheDir, filename)
670
671 // Display the image if it exists in cache
672 _, err := os.Stat(cachePath)
673 if err == nil {
674 // File exists
675 Log(fmt.Sprintf("Image found at %s", cachePath), logFile)
676 CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
677 } else {
678 // File does not exist
679 Log(fmt.Sprintf("Image does not exist at %s", cachePath), logFile)
680 CurdOut(fmt.Sprintf("%s - Episode %d",
681 GetAnimeName(*anime),
682 anime.Ep.Number))
683
684 }
685 } else {
686 CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
687 }
688 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{})
689
690 if err != nil {
691 Log("Failed to start mpv", logFile)
692 os.Exit(1)
693 }
694
695 return mpvSocketPath
696}
697
698func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
699 // Create storage directory if it doesn't exist
700 storagePath = os.ExpandEnv(storagePath)
701 if err := os.MkdirAll(storagePath, 0755); err != nil {
702 return fmt.Errorf("failed to create storage directory: %v", err)
703 }
704
705 // Base URL for downloading config files
706 baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
707
708 // Check each file
709 for _, fileName := range filesToCheck {
710 filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
711
712 // Skip if file already exists
713 if _, err := os.Stat(filePath); err == nil {
714 continue
715 }
716
717 // Download file if it doesn't exist
718 resp, err := http.Get(baseURL + fileName)
719 if err != nil {
720 return fmt.Errorf("failed to download %s: %v", fileName, err)
721 }
722 defer resp.Body.Close()
723
724 // Create the file
725 out, err := os.Create(filePath)
726 if err != nil {
727 return fmt.Errorf("failed to create file %s: %v", fileName, err)
728 }
729 defer out.Close()
730
731 // Write the content
732 if _, err := io.Copy(out, resp.Body); err != nil {
733 return fmt.Errorf("failed to write file %s: %v", fileName, err)
734 }
735 }
736
737 return nil
738}
739
740func getEntriesByCategory(list AnimeList, category string) []Entry {
741 switch category {
742 case "CURRENT":
743 return list.Watching
744 case "COMPLETED":
745 return list.Completed
746 case "PAUSED":
747 return list.Paused
748 case "DROPPED":
749 return list.Dropped
750 case "PLANNING":
751 return list.Planning
752 default:
753 return []Entry{}
754 }
755}
756