internal/curd.go
497 lines · 15513 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.RofiSelection {
134 fmt.Println(fmt.Sprintf("%v", data))
135 } else {
136 switch runtime.GOOS {
137 case "windows":
138 err := beeep.Notify(
139 "Curd",
140 fmt.Sprintf("%v", data),
141 "",
142 )
143
144 if err != nil {
145 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile)
146 }
147 case "linux":
148 cmd := exec.Command("notify-send", fmt.Sprintf("%v", data))
149 err := cmd.Run()
150 if err != nil {
151 Log(fmt.Sprintf("Failed to send notification: %v", err), logFile)
152 }
153 }
154 }
155}
156
157func UpdateCurd(repo, fileName string) error {
158 // Get the path of the currently running executable
159 executablePath, err := os.Executable()
160 if err != nil {
161 return fmt.Errorf("unable to find current executable: %v", err)
162 }
163
164 // Adjust file name for Windows
165 if runtime.GOOS == "windows" {
166 fileName += ".exe"
167 }
168
169 // GitHub release URL for curd
170 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, fileName)
171
172 // Temporary path for the downloaded curd executable
173 tmpPath := executablePath + ".tmp"
174
175 // Download the curd executable
176 resp, err := http.Get(url)
177 if err != nil {
178 return fmt.Errorf("failed to download file: %v", err)
179 }
180 defer resp.Body.Close()
181
182 // Check if the download was successful
183 if resp.StatusCode != http.StatusOK {
184 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
185 }
186
187 // Create a new temporary file
188 out, err := os.Create(tmpPath)
189 if err != nil {
190 return fmt.Errorf("failed to create temporary file: %v", err)
191 }
192 defer out.Close()
193
194 // Write the downloaded content to the temporary file
195 _, err = io.Copy(out, resp.Body)
196 if err != nil {
197 return fmt.Errorf("failed to save downloaded file: %v", err)
198 }
199
200 // Close and rename the temporary file to replace the current executable
201 out.Close()
202
203 // Replace the current executable with the downloaded curd
204 if err := os.Rename(tmpPath, executablePath); err != nil {
205 return fmt.Errorf("failed to replace the current executable: %v", err)
206 }
207 CurdOut(fmt.Sprintf("Downloaded curd executable to %v", executablePath))
208
209 if runtime.GOOS != "windows" {
210 // Ensure the new file has executable permissions
211 if err := os.Chmod(executablePath, 0755); err != nil {
212 return fmt.Errorf("failed to set permissions on the new file: %v", err)
213 }
214 }
215
216 return nil
217}
218
219func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
220 CurdOut("Enter the anime name:")
221 var query string
222 fmt.Scanln(&query)
223 animeMap, err := SearchAnimeAnilist(query, user.Token)
224 if err != nil {
225 Log(fmt.Sprintf("Failed to search anime: %v", err), logFile)
226 ExitCurd(fmt.Errorf("Failed to search anime"))
227 }
228 anilistSelectedOption, err := DynamicSelect(animeMap)
229 if err != nil {
230 Log(fmt.Sprintf("No anime available: %v", err), logFile)
231 ExitCurd(fmt.Errorf("No anime available"))
232 }
233 animeID, err := strconv.Atoi(anilistSelectedOption.Key)
234 if err != nil {
235 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err), logFile)
236 ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
237 }
238 err = AddAnimeToWatchingList(animeID, user.Token)
239 if err != nil {
240 Log(fmt.Sprintf("Failed to add anime to watching list: %v", err), logFile)
241 ExitCurd(fmt.Errorf("Failed to add anime to watching list"))
242 }
243 anilistUserData, err := GetUserData(user.Token, user.Id)
244 if err != nil {
245 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
246 ExitCurd(fmt.Errorf("Failed to get user data"))
247 }
248 user.AnimeList = ParseAnimeList(anilistUserData)
249}
250
251func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
252 var err error
253
254 // Get user id, username and Anime list
255 user.Id, user.Username, err = GetAnilistUserID(user.Token)
256 if err != nil {
257 Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
258 ExitCurd(fmt.Errorf("Failed to get user ID"))
259 }
260 anilistUserData, err := GetUserData(user.Token, user.Id)
261 if err != nil {
262 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
263 ExitCurd(fmt.Errorf("Failed to get user data"))
264 }
265 user.AnimeList = ParseAnimeList(anilistUserData)
266 animeListMap := GetAnimeMap(user.AnimeList)
267 var anilistSelectedOption SelectionOption
268 var selectedAllanimeAnime SelectionOption
269 var userQuery string
270
271 if anime.Ep.ContinueLast {
272 // Get the last watched anime ID from the curd_id file
273 curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
274 curdIDBytes, err := os.ReadFile(curdIDPath)
275 if err != nil {
276 Log(fmt.Sprintf("Error reading curd_id file: %v", err), logFile)
277 ExitCurd(fmt.Errorf("Error reading curd_id file"))
278 }
279
280 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
281 if err != nil {
282 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err), logFile)
283 ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
284 }
285
286 anime.AnilistId = lastWatchedID
287 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
288 } else {
289 // Select anime to watch (Anilist)
290 var err error
291 anilistSelectedOption, err = DynamicSelect(animeListMap)
292 if err != nil {
293 Log(fmt.Sprintf("Error selecting anime: %v", err), logFile)
294 ExitCurd(fmt.Errorf("Error selecting anime"))
295 }
296
297 if anilistSelectedOption.Key == "-1" {
298 ExitCurd(nil)
299 }
300
301 if anilistSelectedOption.Label == "add_new" {
302 AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile)
303 }
304
305 userQuery = anilistSelectedOption.Label
306 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
307 if err != nil {
308 Log(fmt.Sprintf("Error converting Anilist ID: %v", err), logFile)
309 ExitCurd(fmt.Errorf("Error converting Anilist ID"))
310 }
311 }
312 // Find anime in Local history
313 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
314
315 // Get anime entry
316 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
317 if err != nil {
318 Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err), logFile)
319 ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
320 }
321
322 // Set anime entry
323 anime.Title = selectedAnilistAnime.Media.Title
324 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
325 anime.Ep.Number = selectedAnilistAnime.Progress+1
326
327 // if anime not found in database, find it in animeList
328 if animePointer == nil {
329 // Get Anime list (All anime)
330 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
331 if err != nil {
332 Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
333 ExitCurd(fmt.Errorf("Failed to select anime"))
334 }
335 if len(animeList) == 0 {
336 // fmt.Println("No results found.")
337 ExitCurd(fmt.Errorf("No results found."))
338 }
339
340 // find anime in animeList
341 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
342 if err != nil {
343 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile)
344 }
345
346 // If unable to get Allanime id automatically get manually
347 if anime.AllanimeId == "" {
348 CurdOut("Failed to automatically select anime")
349 selectedAllanimeAnime, err := DynamicSelect(animeList)
350 if err != nil {
351 // fmt.Println("No anime available")
352 ExitCurd(fmt.Errorf("No anime available"))
353 }
354 anime.AllanimeId = selectedAllanimeAnime.Key
355 }
356 } else {
357 // if anime found in database, use it
358 anime.AllanimeId = animePointer.AllanimeId
359 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
360 anime.Ep.Resume = true
361 anime.Ep.Number = animePointer.Ep.Number
362 }
363
364 // If upstream is ahead, update the episode number
365 if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
366 if temp_anime.Progress > anime.Ep.Number {
367 anime.Ep.Number = temp_anime.Progress
368 anime.Ep.Player.PlaybackTime = 0
369 anime.Ep.Resume = false
370 }
371 }
372
373 if anime.TotalEpisodes == 0 {
374 // Get updated anime data
375 Log(selectedAllanimeAnime, logFile)
376 updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
377 Log(updatedAnime, logFile)
378 if err != nil {
379 Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile)
380 } else {
381 anime.TotalEpisodes = updatedAnime.TotalEpisodes
382 Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile)
383 }
384 }
385
386 if anime.TotalEpisodes == 0 { // If failed to get anime data
387 CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
388 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
389 if err != nil {
390 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
391 } else {
392 for allanimeId, label := range animeList {
393 if allanimeId == anime.AllanimeId {
394 // Extract total episodes from the label
395 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
396 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
397 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
398 break
399 }
400 }
401 }
402 }
403
404 if anime.TotalEpisodes == 0 {
405 CurdOut("Still unable to determine total episodes.")
406 CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
407 fmt.Print("Enter the episode you want to start from: ")
408 var episodeNumber int
409 fmt.Scanln(&episodeNumber)
410 anime.Ep.Number = episodeNumber
411 } else {
412 anime.Ep.Number = selectedAnilistAnime.Progress + 1
413 }
414 } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
415 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
416 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
417 var answer string
418 fmt.Scanln(&answer)
419 if answer == "y" {
420 anime.Ep.Number = 1
421 } else {
422 anime.Ep.Number = anime.TotalEpisodes
423 }
424 }
425
426}
427
428// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
429func WriteTokenToFile(token string, filePath string) error {
430 // Extract the directory path
431 dir := filepath.Dir(filePath)
432
433 // Create all necessary parent directories
434 if err := os.MkdirAll(dir, 0755); err != nil {
435 return fmt.Errorf("failed to create directories: %v", err)
436 }
437
438 // Write the token to the file, creating it if it doesn't exist
439 err := os.WriteFile(filePath, []byte(token), 0644)
440 if err != nil {
441 return fmt.Errorf("failed to write token to file: %v", err)
442 }
443
444 return nil
445}
446
447func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
448
449 // Get episode link
450 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
451 if err != nil {
452 // If unable to get episode link automatically get manually
453 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
454 if err != nil {
455 CurdOut("No episode list found")
456 RestoreScreen()
457 os.Exit(1)
458 }
459 CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
460 fmt.Scanln(&anime.Ep.Number)
461 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
462 if err != nil {
463 CurdOut("Failed to get episode link")
464 os.Exit(1)
465 }
466 // anime.Ep.Links = link
467 }
468 anime.Ep.Links = link
469
470 if len(anime.Ep.Links) == 0 {
471 CurdOut("No episode links found")
472 os.Exit(1)
473 }
474
475 Log(anime, logFile)
476
477 // Write anime.AnilistId to curd_id in the storage path
478 idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
479 Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile)
480 if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
481 Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
482 } else {
483 if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
484 Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
485 }
486 }
487
488 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{})
489
490 if err != nil {
491 Log("Failed to start mpv", logFile)
492 os.Exit(1)
493 }
494
495 return mpvSocketPath
496}
497