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