internal/curd.go
543 lines · 17345 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) {
223 var query string
224 if userCurdConfig.RofiSelection {
225 userInput, err := GetUserInputFromRofi("Enter the anime name:")
226 if err != nil {
227 Log("Error getting user input: "+err.Error(), logFile)
228 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
229 }
230 query = userInput
231 } else {
232 CurdOut("Enter the anime name:")
233 fmt.Scanln(&query)
234 }
235 animeMap, err := SearchAnimeAnilist(query, user.Token)
236 if err != nil {
237 Log(fmt.Sprintf("Failed to search anime: %v", err), logFile)
238 ExitCurd(fmt.Errorf("Failed to search anime"))
239 }
240 anilistSelectedOption, err := DynamicSelect(animeMap)
241 if err != nil {
242 Log(fmt.Sprintf("No anime available: %v", err), logFile)
243 ExitCurd(fmt.Errorf("No anime available"))
244 }
245 animeID, err := strconv.Atoi(anilistSelectedOption.Key)
246 if err != nil {
247 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err), logFile)
248 ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
249 }
250 err = AddAnimeToWatchingList(animeID, user.Token)
251 if err != nil {
252 Log(fmt.Sprintf("Failed to add anime to watching list: %v", err), logFile)
253 ExitCurd(fmt.Errorf("Failed to add anime to watching list"))
254 }
255 if user.Id == 0 {
256 user.Id, user.Username, err = GetAnilistUserID(user.Token)
257 if err != nil {
258 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
259 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
260 }
261 }
262 anilistUserData, err := GetUserData(user.Token, user.Id)
263 if err != nil {
264 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
265 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
266 }
267 user.AnimeList = ParseAnimeList(anilistUserData)
268}
269
270func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
271 var err error
272
273 // Get user id, username and Anime list
274 user.Id, user.Username, err = GetAnilistUserID(user.Token)
275 if err != nil {
276 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
277 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
278 }
279 anilistUserData, err := GetUserData(user.Token, user.Id)
280 if err != nil {
281 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
282 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
283 }
284 user.AnimeList = ParseAnimeList(anilistUserData)
285 animeListMap := GetAnimeMap(user.AnimeList)
286 var anilistSelectedOption SelectionOption
287 var selectedAllanimeAnime SelectionOption
288 var userQuery string
289
290 if anime.Ep.ContinueLast {
291 // Get the last watched anime ID from the curd_id file
292 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
293 curdIDBytes, err := os.ReadFile(curdIDPath)
294 if err != nil {
295 Log(fmt.Sprintf("Error reading curd_id file: %v", err), logFile)
296 ExitCurd(fmt.Errorf("Error reading curd_id file"))
297 }
298
299 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
300 if err != nil {
301 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err), logFile)
302 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
303 }
304
305 anime.AnilistId = lastWatchedID
306 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
307 } else {
308 // Select anime to watch (Anilist)
309 var err error
310 anilistSelectedOption, err = DynamicSelect(animeListMap)
311 if err != nil {
312 Log(fmt.Sprintf("Error selecting anime: %v", err), logFile)
313 ExitCurd(fmt.Errorf("Error selecting anime"))
314 }
315
316 if anilistSelectedOption.Key == "-1" {
317 ExitCurd(nil)
318 }
319
320 if anilistSelectedOption.Label == "add_new" {
321 AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile)
322 }
323
324 userQuery = anilistSelectedOption.Label
325 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
326 if err != nil {
327 Log(fmt.Sprintf("Error converting Anilist ID: %v", err), logFile)
328 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
329 }
330 }
331 // Find anime in Local history
332 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
333
334 // Get anime entry
335 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
336 if err != nil {
337 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err), logFile)
338 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
339 }
340
341 // Set anime entry
342 anime.Title = selectedAnilistAnime.Media.Title
343 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
344 anime.Ep.Number = selectedAnilistAnime.Progress+1
345
346 // if anime not found in database, find it in animeList
347 if animePointer == nil {
348 // Get Anime list (All anime)
349 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
350 if err != nil {
351 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
352 ExitCurd(fmt.Errorf("Failed to select anime"))
353 }
354 if len(animeList) == 0 {
355 // fmt.Println("No results found.")
356 ExitCurd(fmt.Errorf("No results found."))
357 }
358
359 // find anime in animeList
360 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
361 if err != nil {
362 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile)
363 }
364
365 // If unable to get Allanime id automatically get manually
366 if anime.AllanimeId == "" {
367 CurdOut("Failed to automatically select anime")
368 selectedAllanimeAnime, err := DynamicSelect(animeList)
369 if err != nil {
370 // fmt.Println("No anime available")
371 ExitCurd(fmt.Errorf("No anime available"))
372 }
373 anime.AllanimeId = selectedAllanimeAnime.Key
374 }
375 } else {
376 // if anime found in database, use it
377 anime.AllanimeId = animePointer.AllanimeId
378 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
379 anime.Ep.Resume = true
380 anime.Ep.Number = animePointer.Ep.Number
381 }
382
383 // If upstream is ahead, update the episode number
384 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
385 if temp_anime.Progress > anime.Ep.Number {
386 anime.Ep.Number = temp_anime.Progress
387 anime.Ep.Player.PlaybackTime = 0
388 anime.Ep.Resume = false
389 }
390 }
391
392 if anime.TotalEpisodes == 0 {
393 // Get updated anime data
394 Log(selectedAllanimeAnime, logFile)
395 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
396 Log(updatedAnime, logFile)
397 if err != nil {
398 Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile)
399 } else {
400 anime.TotalEpisodes = updatedAnime.TotalEpisodes
401 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile)
402 }
403 }
404
405 if anime.TotalEpisodes == 0 { // If failed to get anime data
406 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
407 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
408 if err != nil {
409 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
410 } else {
411 for allanimeId, label := range animeList {
412 if allanimeId == anime.AllanimeId {
413 // Extract total episodes from the label
414 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
415 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
416 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
417 break
418 }
419 }
420 }
421 }
422
423 if anime.TotalEpisodes == 0 {
424 CurdOut("Still unable to determine total episodes.")
425 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
426 var episodeNumber int
427 if userCurdConfig.RofiSelection {
428 userInput, err := GetUserInputFromRofi("Enter the episode you want to start from:")
429 if err != nil {
430 Log("Error getting user input: "+err.Error(), logFile)
431 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
432 }
433 episodeNumber, err = strconv.Atoi(userInput)
434 } else {
435 fmt.Print("Enter the episode you want to start from: ")
436 fmt.Scanln(&episodeNumber)
437 }
438 anime.Ep.Number = episodeNumber
439 } else {
440 anime.Ep.Number = selectedAnilistAnime.Progress + 1
441 }
442 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
443 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
444 var answer string
445 if userCurdConfig.RofiSelection {
446 userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
447 if err != nil {
448 Log("Error getting user input: "+err.Error(), logFile)
449 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
450 }
451 answer = userInput
452 } else {
453 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
454 fmt.Scanln(&answer)
455 }
456 if answer == "y" {
457 anime.Ep.Number = 1
458 } else {
459 anime.Ep.Number = anime.TotalEpisodes
460 }
461 }
462
463}
464
465// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
466func WriteTokenToFile(token string, filePath string) error {
467 // Extract the directory path
468 dir := filepath.Dir(filePath)
469
470 // Create all necessary parent directories
471 if err := os.MkdirAll(dir, 0755); err != nil {
472 return fmt.Errorf("failed to create directories: %v", err)
473 }
474
475 // Write the token to the file, creating it if it doesn't exist
476 err := os.WriteFile(filePath, []byte(token), 0644)
477 if err != nil {
478 return fmt.Errorf("failed to write token to file: %v", err)
479 }
480
481 return nil
482}
483
484func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
485
486 // Get episode link
487 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
488 if err != nil {
489 // If unable to get episode link automatically get manually
490 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
491 if err != nil {
492 CurdOut("No episode list found")
493 RestoreScreen()
494 os.Exit(1)
495 }
496 if userCurdConfig.RofiSelection {
497 userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
498 if err != nil {
499 Log("Error getting user input: "+err.Error(), logFile)
500 ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
501 }
502 anime.Ep.Number, err = strconv.Atoi(userInput)
503 } else {
504 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
505 fmt.Scanln(&anime.Ep.Number)
506 }
507 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
508 if err != nil {
509 CurdOut("Failed to get episode link")
510 os.Exit(1)
511 }
512 // anime.Ep.Links = link
513 }
514 anime.Ep.Links = link
515
516 if len(anime.Ep.Links) == 0 {
517 CurdOut("No episode links found")
518 os.Exit(1)
519 }
520
521 Log(anime, logFile)
522
523 // Write anime.AnilistId to curd_id in the storage path
524 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
525 Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile)
526 if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
527 Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
528 } else {
529 if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
530 Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
531 }
532 }
533
534 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{})
535
536 if err != nil {
537 Log("Failed to start mpv", logFile)
538 os.Exit(1)
539 }
540
541 return mpvSocketPath
542}
543