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