internal/curd.go
631 lines · 20265 bytes
1package internal
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "os"
9 "os/exec"
10 "github.com/gen2brain/beeep"
11 "path/filepath"
12 "regexp"
13 "runtime"
14 "strconv"
15 "strings"
16 "time"
17)
18
19func GetTokenFromFile(filePath string) (string, error) {
20 // Read the token from the file
21 data, err := os.ReadFile(filePath)
22 if err != nil {
23 return "", fmt.Errorf("failed to read token from file: %w", err)
24 }
25
26 // Convert the byte slice to a string and remove any surrounding whitespace or newlines
27 token := strings.TrimSpace(string(data))
28
29 return token, nil
30}
31
32func EditConfig(configFilePath string) {
33 // Get the user's preferred editor from the EDITOR environment variable
34 editor := os.Getenv("EDITOR")
35 if editor == "" {
36 // If EDITOR is not set, default to "vim"
37 editor = "vim"
38 }
39
40 // Construct the command to open the config file
41 cmd := exec.Command(editor, configFilePath)
42
43 // Set the command to run in the current terminal
44 cmd.Stdin = os.Stdin
45 cmd.Stdout = os.Stdout
46 cmd.Stderr = os.Stderr
47
48 // Run the editor command
49 err := cmd.Run()
50 if err != nil {
51 CurdOut(fmt.Sprintf("Error opening config file: %v", err))
52 return
53 }
54
55 CurdOut("Config file edited successfully.")
56}
57
58// ClearLogFile removes all contents from the specified log file
59func ClearLogFile(logFile string) error {
60 // Open the file with truncate flag to clear its contents
61 file, err := os.OpenFile(logFile, os.O_WRONLY|os.O_TRUNC, 0666)
62 if err != nil {
63 return fmt.Errorf("failed to open log file: %w", err)
64 }
65 defer file.Close()
66
67 return nil
68}
69
70// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
71func Log(data interface{}, logFile string) error {
72 // Open or create the log file
73 file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
74 if err != nil {
75 return err
76 }
77 defer file.Close() // Ensure the file is closed when done
78
79 // Attempt to marshal the data into JSON
80 jsonData, err := json.Marshal(data)
81 if err != nil {
82 return err
83 }
84
85 // Get the caller information
86 _, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
87 if !ok {
88 return fmt.Errorf("unable to get caller information")
89 }
90
91 // Log the current time and the JSON representation along with caller info
92 currentTime := time.Now().Format("2006/01/02 15:04:05")
93 logMessage := fmt.Sprintf("[LOG] %s %s:%d: %s\n", currentTime, filename, lineNumber, jsonData)
94 _, err = fmt.Fprint(file, logMessage) // Write to the file
95 if err != nil {
96 return err
97 }
98
99 return nil
100}
101
102// ClearScreen clears the terminal screen and saves the state
103func ClearScreen() {
104 fmt.Print("\033[?1049h") // Switch to alternate screen buffer
105 fmt.Print("\033[2J") // Clear the entire screen
106 fmt.Print("\033[H") // Move cursor to the top left
107}
108
109// RestoreScreen restores the original terminal state
110func RestoreScreen() {
111 fmt.Print("\033[?1049l") // Switch back to the main screen buffer
112}
113
114func ExitCurd(err error) {
115 RestoreScreen()
116 CurdOut("Have a great day!")
117 if err != nil {
118 CurdOut(err)
119 if runtime.GOOS == "windows" {
120 fmt.Println("Press Enter to exit")
121 var wait string
122 fmt.Scanln(&wait)
123 os.Exit(1)
124 } else {
125 os.Exit(1)
126 }
127 }
128 os.Exit(0)
129}
130
131func CurdOut(data interface{}) {
132 userCurdConfig := GetGlobalConfig()
133 if userCurdConfig == nil {
134 userCurdConfig = &CurdConfig{}
135 }
136 if !userCurdConfig.RofiSelection {
137 fmt.Println(fmt.Sprintf("%v", data))
138 } else {
139 switch runtime.GOOS {
140 case "windows":
141 err := beeep.Notify(
142 "Curd",
143 fmt.Sprintf("%v", data),
144 "",
145 )
146
147 if err != nil {
148 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile)
149 }
150 case "linux":
151 cmd := exec.Command("notify-send", fmt.Sprintf("%v", data))
152 err := cmd.Run()
153 if err != nil {
154 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile)
155 }
156 }
157 }
158}
159
160func UpdateCurd(repo, fileName string) error {
161 // Get the path of the currently running executable
162 executablePath, err := os.Executable()
163 if err != nil {
164 return fmt.Errorf("unable to find current executable: %v", err)
165 }
166
167 // Adjust file name for Windows
168 if runtime.GOOS == "windows" {
169 fileName += ".exe"
170 }
171
172 // GitHub release URL for curd
173 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, fileName)
174
175 // Temporary path for the downloaded curd executable
176 tmpPath := executablePath + ".tmp"
177
178 // Download the curd executable
179 resp, err := http.Get(url)
180 if err != nil {
181 return fmt.Errorf("failed to download file: %v", err)
182 }
183 defer resp.Body.Close()
184
185 // Check if the download was successful
186 if resp.StatusCode != http.StatusOK {
187 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
188 }
189
190 // Create a new temporary file
191 out, err := os.Create(tmpPath)
192 if err != nil {
193 return fmt.Errorf("failed to create temporary file: %v", err)
194 }
195 defer out.Close()
196
197 // Write the downloaded content to the temporary file
198 _, err = io.Copy(out, resp.Body)
199 if err != nil {
200 return fmt.Errorf("failed to save downloaded file: %v", err)
201 }
202
203 // Close and rename the temporary file to replace the current executable
204 out.Close()
205
206 // Replace the current executable with the downloaded curd
207 if err := os.Rename(tmpPath, executablePath); err != nil {
208 return fmt.Errorf("failed to replace the current executable: %v", err)
209 }
210 CurdOut(fmt.Sprintf("Downloaded curd executable to %v", executablePath))
211
212 if runtime.GOOS != "windows" {
213 // Ensure the new file has executable permissions
214 if err := os.Chmod(executablePath, 0755); err != nil {
215 return fmt.Errorf("failed to set permissions on the new file: %v", err)
216 }
217 }
218
219 return nil
220}
221
222func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) SelectionOption {
223 var query string
224 var animeMap map[string]string
225 var animeMapPreview map[string]RofiSelectPreview
226 var err error
227 var anilistSelectedOption SelectionOption
228 var anilistUserData map[string]interface{}
229 var anilistUserDataPreview map[string]interface{}
230
231 if userCurdConfig.RofiSelection {
232 userInput, err := GetUserInputFromRofi("Enter the anime name:")
233 if err != nil {
234 Log("Error getting user input: "+err.Error(), logFile)
235 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
236 }
237 query = userInput
238 } else {
239 CurdOut("Enter the anime name:")
240 fmt.Scanln(&query)
241 }
242 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
243 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
244 } else {
245 animeMap, err = SearchAnimeAnilist(query, user.Token)
246 }
247 if err != nil {
248 Log(fmt.Sprintf("Failed to search anime: %v", err), logFile)
249 ExitCurd(fmt.Errorf("Failed to search anime"))
250 }
251 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
252 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
253 } else {
254 anilistSelectedOption, err = DynamicSelect(animeMap, false)
255 }
256 if err != nil {
257 Log(fmt.Sprintf("No anime available: %v", err), logFile)
258 ExitCurd(fmt.Errorf("No anime available"))
259 }
260 animeID, err := strconv.Atoi(anilistSelectedOption.Key)
261 if err != nil {
262 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err), logFile)
263 ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
264 }
265 err = AddAnimeToWatchingList(animeID, user.Token)
266 if err != nil {
267 Log(fmt.Sprintf("Failed to add anime to watching list: %v", err), logFile)
268 ExitCurd(fmt.Errorf("Failed to add anime to watching list"))
269 }
270 if user.Id == 0 {
271 user.Id, user.Username, err = GetAnilistUserID(user.Token)
272 if err != nil {
273 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
274 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
275 }
276 }
277 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
278 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
279 } else {
280 anilistUserData, err = GetUserData(user.Token, user.Id)
281 }
282 if err != nil {
283 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
284 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
285 }
286 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
287 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
288 } else {
289 user.AnimeList = ParseAnimeList(anilistUserData)
290 }
291
292 return anilistSelectedOption
293}
294
295func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
296 var err error
297 var anilistUserData map[string]interface{}
298 var anilistUserDataPreview map[string]interface{}
299 var animeListMap map[string]string
300 var animeListMapPreview map[string]RofiSelectPreview
301
302 // Get user id, username and Anime list
303 user.Id, user.Username, err = GetAnilistUserID(user.Token)
304 if err != nil {
305 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
306 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
307 }
308 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
309 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
310 Log(anilistUserDataPreview, logFile)
311 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
312 Log(user.AnimeList, logFile)
313 animeListMapPreview = GetAnimeMapPreview(user.AnimeList)
314 Log(animeListMapPreview, logFile)
315 } else {
316 anilistUserData, err = GetUserData(user.Token, user.Id)
317 if err != nil {
318 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
319 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
320 }
321 user.AnimeList = ParseAnimeList(anilistUserData)
322 animeListMap = GetAnimeMap(user.AnimeList)
323 }
324 var anilistSelectedOption SelectionOption
325 var selectedAllanimeAnime SelectionOption
326 var userQuery string
327
328 if anime.Ep.ContinueLast {
329 // Get the last watched anime ID from the curd_id file
330 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
331 curdIDBytes, err := os.ReadFile(curdIDPath)
332 if err != nil {
333 Log(fmt.Sprintf("Error reading curd_id file: %v", err), logFile)
334 ExitCurd(fmt.Errorf("Error reading curd_id file"))
335 }
336
337 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
338 if err != nil {
339 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err), logFile)
340 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
341 }
342
343 anime.AnilistId = lastWatchedID
344 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
345 } else {
346 // Select anime to watch (Anilist)
347 var err error
348 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
349 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
350 } else {
351 anilistSelectedOption, err = DynamicSelect(animeListMap, true)
352 }
353 if err != nil {
354 Log(fmt.Sprintf("Error selecting anime: %v", err), logFile)
355 ExitCurd(fmt.Errorf("Error selecting anime"))
356 }
357
358 Log(anilistSelectedOption, logFile)
359
360 if anilistSelectedOption.Key == "-1" {
361 ExitCurd(nil)
362 }
363
364 if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
365 anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile)
366 }
367
368 userQuery = anilistSelectedOption.Label
369 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
370 if err != nil {
371 Log(fmt.Sprintf("Error converting Anilist ID: %v", err), logFile)
372 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
373 }
374 }
375 // Find anime in Local history
376 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
377
378 // Get anime entry
379 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
380 if err != nil {
381 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err), logFile)
382 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
383 }
384
385 // Set anime entry
386 anime.Title = selectedAnilistAnime.Media.Title
387 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
388 anime.Ep.Number = selectedAnilistAnime.Progress+1
389 var animeList map[string]string
390
391 // if anime not found in database, find it in animeList
392 if animePointer == nil {
393 // Get Anime list (All anime)
394
395 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
396 if err != nil {
397 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
398 ExitCurd(fmt.Errorf("Failed to select anime"))
399 }
400 if len(animeList) == 0 {
401 // fmt.Println("No results found.")
402 ExitCurd(fmt.Errorf("No results found."))
403 }
404
405 // find anime in animeList
406 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
407 if err != nil {
408 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile)
409 }
410
411 // If unable to get Allanime id automatically get manually
412 if anime.AllanimeId == "" {
413 CurdOut("Failed to automatically select anime")
414 selectedAllanimeAnime, err := DynamicSelect(animeList, false)
415
416 if err != nil {
417 // fmt.Println("No anime available")
418 ExitCurd(fmt.Errorf("No anime available"))
419 }
420 anime.AllanimeId = selectedAllanimeAnime.Key
421 }
422 } else {
423 // if anime found in database, use it
424 anime.AllanimeId = animePointer.AllanimeId
425 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
426 anime.Ep.Resume = true
427 anime.Ep.Number = animePointer.Ep.Number
428 }
429
430 // If upstream is ahead, update the episode number
431 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
432 if temp_anime.Progress > anime.Ep.Number {
433 anime.Ep.Number = temp_anime.Progress
434 anime.Ep.Player.PlaybackTime = 0
435 anime.Ep.Resume = false
436 }
437 }
438
439 if anime.TotalEpisodes == 0 {
440 // Get updated anime data
441 Log(selectedAllanimeAnime, logFile)
442 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
443 Log(updatedAnime, logFile)
444 if err != nil {
445 Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile)
446 } else {
447 anime.TotalEpisodes = updatedAnime.TotalEpisodes
448 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile)
449 }
450 }
451
452 if anime.TotalEpisodes == 0 { // If failed to get anime data
453 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
454 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
455 if err != nil {
456 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
457 } else {
458 for allanimeId, label := range animeList {
459 if allanimeId == anime.AllanimeId {
460 // Extract total episodes from the label
461 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
462 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
463 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
464 break
465 }
466 }
467 }
468 }
469
470 if anime.TotalEpisodes == 0 {
471 CurdOut("Still unable to determine total episodes.")
472 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
473 var episodeNumber int
474 if userCurdConfig.RofiSelection {
475 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from:")
476 if err != nil {
477 Log("Error getting user input: "+err.Error(), logFile)
478 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
479 }
480 episodeNumber, err = strconv.Atoi(userInput)
481 } else {
482 fmt.Print("Enter the episode you want to start from: ")
483 fmt.Scanln(&episodeNumber)
484 }
485 anime.Ep.Number = episodeNumber
486 } else {
487 anime.Ep.Number = selectedAnilistAnime.Progress + 1
488 }
489 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
490 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
491 var answer string
492 if userCurdConfig.RofiSelection {
493 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
494 if err != nil {
495 Log("Error getting user input: "+err.Error(), logFile)
496 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
497 }
498 answer = userInput
499 } else {
500 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
501 fmt.Scanln(&answer)
502 }
503 if answer == "y" {
504 anime.Ep.Number = 1
505 } else {
506 anime.Ep.Number = anime.TotalEpisodes
507 }
508 }
509
510}
511
512// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
513func WriteTokenToFile(token string, filePath string) error {
514 // Extract the directory path
515 dir := filepath.Dir(filePath)
516
517 // Create all necessary parent directories
518 if err := os.MkdirAll(dir, 0755); err != nil {
519 return fmt.Errorf("failed to create directories: %v", err)
520 }
521
522 // Write the token to the file, creating it if it doesn't exist
523 err := os.WriteFile(filePath, []byte(token), 0644)
524 if err != nil {
525 return fmt.Errorf("failed to write token to file: %v", err)
526 }
527
528 return nil
529}
530
531func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
532
533 // Get episode link
534 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
535 if err != nil {
536 // If unable to get episode link automatically get manually
537 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
538 if err != nil {
539 CurdOut("No episode list found")
540 RestoreScreen()
541 os.Exit(1)
542 }
543 if userCurdConfig.RofiSelection {
544 userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
545 if err != nil {
546 Log("Error getting user input: "+err.Error(), logFile)
547 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
548 }
549 anime.Ep.Number, err = strconv.Atoi(userInput)
550 } else {
551 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
552 fmt.Scanln(&anime.Ep.Number)
553 }
554 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
555 if err != nil {
556 CurdOut("Failed to get episode link")
557 os.Exit(1)
558 }
559 // anime.Ep.Links = link
560 }
561 anime.Ep.Links = link
562
563 if len(anime.Ep.Links) == 0 {
564 CurdOut("No episode links found")
565 os.Exit(1)
566 }
567
568 Log(anime, logFile)
569
570 // Write anime.AnilistId to curd_id in the storage path
571 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
572 Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile)
573 if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
574 Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
575 } else {
576 if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
577 Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
578 }
579 }
580
581 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{})
582
583 if err != nil {
584 Log("Failed to start mpv", logFile)
585 os.Exit(1)
586 }
587
588 return mpvSocketPath
589}
590
591func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
592 // Create storage directory if it doesn't exist
593 storagePath = os.ExpandEnv(storagePath)
594 if err := os.MkdirAll(storagePath, 0755); err != nil {
595 return fmt.Errorf("failed to create storage directory: %v", err)
596 }
597
598 // Base URL for downloading config files
599 baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
600
601 // Check each file
602 for _, fileName := range filesToCheck {
603 filePath := filepath.Join(storagePath, fileName)
604
605 // Skip if file already exists
606 if _, err := os.Stat(filePath); err == nil {
607 continue
608 }
609
610 // Download file if it doesn't exist
611 resp, err := http.Get(baseURL + fileName)
612 if err != nil {
613 return fmt.Errorf("failed to download %s: %v", fileName, err)
614 }
615 defer resp.Body.Close()
616
617 // Create the file
618 out, err := os.Create(filePath)
619 if err != nil {
620 return fmt.Errorf("failed to create file %s: %v", fileName, err)
621 }
622 defer out.Close()
623
624 // Write the content
625 if _, err := io.Copy(out, resp.Body); err != nil {
626 return fmt.Errorf("failed to write file %s: %v", fileName, err)
627 }
628 }
629
630 return nil
631}