internal/curd.go
330 lines · 9792 bytes
1package internal
2
3import (
4 "encoding/json"
5 "fmt"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "runtime"
10 "strconv"
11 "strings"
12 "time"
13)
14
15func GetTokenFromFile(filePath string) (string, error) {
16 // Read the token from the file
17 data, err := os.ReadFile(filePath)
18 if err != nil {
19 return "", fmt.Errorf("failed to read token from file: %w", err)
20 }
21
22 // Convert the byte slice to a string and remove any surrounding whitespace or newlines
23 token := strings.TrimSpace(string(data))
24
25 return token, nil
26}
27
28func EditConfig(configFilePath string) {
29 // Get the user's preferred editor from the EDITOR environment variable
30 editor := os.Getenv("EDITOR")
31 if editor == "" {
32 // If EDITOR is not set, default to "vim"
33 editor = "vim"
34 }
35
36 // Construct the command to open the config file
37 cmd := exec.Command(editor, configFilePath)
38
39 // Set the command to run in the current terminal
40 cmd.Stdin = os.Stdin
41 cmd.Stdout = os.Stdout
42 cmd.Stderr = os.Stderr
43
44 // Run the editor command
45 err := cmd.Run()
46 if err != nil {
47 fmt.Printf("Error opening config file: %v\n", err)
48 return
49 }
50
51 fmt.Println("Config file edited successfully.")
52}
53
54// ClearLogFile removes all contents from the specified log file
55func ClearLogFile(logFile string) error {
56 // Open the file with truncate flag to clear its contents
57 file, err := os.OpenFile(logFile, os.O_WRONLY|os.O_TRUNC, 0666)
58 if err != nil {
59 return fmt.Errorf("failed to open log file: %w", err)
60 }
61 defer file.Close()
62
63 return nil
64}
65
66// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
67func Log(data interface{}, logFile string) error {
68 // Open or create the log file
69 file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
70 if err != nil {
71 return err
72 }
73 defer file.Close() // Ensure the file is closed when done
74
75 // Attempt to marshal the data into JSON
76 jsonData, err := json.Marshal(data)
77 if err != nil {
78 return err
79 }
80
81 // Get the caller information
82 _, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
83 if !ok {
84 return fmt.Errorf("unable to get caller information")
85 }
86
87 // Log the current time and the JSON representation along with caller info
88 currentTime := time.Now().Format("2006/01/02 15:04:05")
89 logMessage := fmt.Sprintf("[LOG] %s %s %d: %s\n", currentTime, filename, lineNumber, jsonData)
90 _, err = fmt.Fprint(file, logMessage) // Write to the file
91 if err != nil {
92 return err
93 }
94
95 return nil
96}
97
98// ClearScreen clears the terminal screen and saves the state
99func ClearScreen() {
100 fmt.Print("\033[?1049h") // Switch to alternate screen buffer
101 fmt.Print("\033[2J") // Clear the entire screen
102 fmt.Print("\033[H") // Move cursor to the top left
103}
104
105// RestoreScreen restores the original terminal state
106func RestoreScreen() {
107 fmt.Print("\033[?1049l") // Switch back to the main screen buffer
108}
109
110func ExitCurd() {
111 // RestoreScreen()
112 fmt.Println("Have a great day!")
113 os.Exit(0)
114}
115
116func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
117 var err error
118
119 // Get user id, username and Anime list
120 user.Id, user.Username, err = GetAnilistUserID(user.Token)
121 anilistUserData, err := GetUserData(user.Token, user.Id)
122 user.AnimeList = ParseAnimeList(anilistUserData)
123 animeListMap := GetAnimeMap(user.AnimeList)
124 var anilistSelectedOption SelectionOption
125 var userQuery string
126
127 if anime.Ep.ContinueLast {
128 // Get the last watched anime ID from the curd_id file
129 curdIDPath := filepath.Join(os.Getenv(userCurdConfig.StoragePath), "curd_id")
130 curdIDBytes, err := os.ReadFile(curdIDPath)
131 if err != nil {
132 Log(fmt.Sprintf("Error reading curd_id file: %v", err), logFile)
133 ExitCurd()
134 }
135
136 lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
137 if err != nil {
138 Log(fmt.Sprintf("Error converting curd_id to integer: %v", err), logFile)
139 ExitCurd()
140 }
141
142 anime.AnilistId = lastWatchedID
143 anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
144 } else {
145 // Select anime to watch (Anilist)
146 var err error
147 anilistSelectedOption, err = DynamicSelect(animeListMap)
148 if err != nil {
149 Log(fmt.Sprintf("Error selecting anime: %v", err), logFile)
150 ExitCurd()
151 }
152
153 if anilistSelectedOption.Key == "-1" || anilistSelectedOption.Label == "quit" {
154 ExitCurd()
155 }
156
157 if anilistSelectedOption.Label == "add_new" {
158 fmt.Println("Enter the anime name:")
159 var query string
160 fmt.Scanln(&query)
161 animeMap, err := SearchAnimeAnilist(query, user.Token)
162 if err != nil {
163 Log(fmt.Sprintf("Failed to search anime: %v", err), logFile)
164 ExitCurd()
165 }
166 anilistSelectedOption, err = DynamicSelect(animeMap)
167 if err != nil {
168 Log(fmt.Sprintf("No anime available: %v", err), logFile)
169 ExitCurd()
170 }
171 animeID, err := strconv.Atoi(anilistSelectedOption.Key)
172 if err != nil {
173 Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err), logFile)
174 ExitCurd()
175 }
176 err = AddAnimeToWatchingList(animeID, user.Token)
177 if err != nil {
178 Log(fmt.Sprintf("Failed to add anime to watching list: %v", err), logFile)
179 ExitCurd()
180 }
181 anilistUserData, err := GetUserData(user.Token, user.Id)
182 if err != nil {
183 Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
184 ExitCurd()
185 }
186 user.AnimeList = ParseAnimeList(anilistUserData)
187 }
188
189 userQuery = anilistSelectedOption.Label
190 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
191 if err != nil {
192 Log(fmt.Sprintf("Error converting Anilist ID: %v", err), logFile)
193 ExitCurd()
194 }
195 }
196 // Find anime in Local history
197 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
198
199 // Get anime entry
200 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
201 if err != nil {
202 fmt.Println("Can not find the anime in anilist animelist")
203 }
204
205 // Set anime entry
206 anime.Title = selectedAnilistAnime.Media.Title
207 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
208 anime.Ep.Number = selectedAnilistAnime.Progress+1
209
210 // if anime not found in database, find it in animeList
211 if animePointer == nil {
212 // Get Anime list (All anime)
213 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
214 if err != nil {
215 fmt.Println("Failed to select anime", logFile)
216 os.Exit(1)
217 }
218 if len(animeList) == 0 {
219 fmt.Println("No results found.")
220 ExitCurd()
221 }
222
223 // find anime in animeList
224 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
225
226 // If unable to get Allanime id automatically get manually
227 if anime.AllanimeId == "" {
228 fmt.Println("Failed to automatically select anime")
229 selectedAllanimeAnime, err := DynamicSelect(animeList)
230 if err != nil {
231 fmt.Println("No anime available")
232 ExitCurd()
233 }
234 anime.AllanimeId = selectedAllanimeAnime.Key
235 }
236 } else {
237 // if anime found in database, use it
238 anime.AllanimeId = animePointer.AllanimeId
239 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
240 anime.Ep.Resume = true
241 anime.Ep.Number = animePointer.Ep.Number
242 }
243
244
245 // Handel weird cases
246 if anime.TotalEpisodes < anime.Ep.Number {
247 if anime.TotalEpisodes == 0 {
248 time.Sleep(2 * time.Second)
249 }
250 Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
251 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
252 var answer string
253 fmt.Scanln(&answer)
254 if answer == "y" {
255 anime.Ep.Number = 1
256 } else {
257 anime.Ep.Number = anime.TotalEpisodes
258 }
259 }
260}
261
262// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
263func WriteTokenToFile(token string, filePath string) error {
264 // Extract the directory path
265 dir := filepath.Dir(filePath)
266
267 // Create all necessary parent directories
268 if err := os.MkdirAll(dir, 0755); err != nil {
269 return fmt.Errorf("failed to create directories: %v", err)
270 }
271
272 // Write the token to the file, creating it if it doesn't exist
273 err := os.WriteFile(filePath, []byte(token), 0644)
274 if err != nil {
275 return fmt.Errorf("failed to write token to file: %v", err)
276 }
277
278 return nil
279}
280
281func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
282
283 // Get episode link
284 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
285 if err != nil {
286 // If unable to get episode link automatically get manually
287 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
288 if err != nil {
289 fmt.Println("No episode list found")
290 RestoreScreen()
291 os.Exit(1)
292 }
293 fmt.Printf("Enter the episode (%v episodes)\n", episodeList[len(episodeList)-1])
294 fmt.Scanln(&anime.Ep.Number)
295 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
296 if err != nil {
297 fmt.Println("Failed to get episode link")
298 os.Exit(1)
299 }
300 // anime.Ep.Links = link
301 }
302 anime.Ep.Links = link
303
304 if len(anime.Ep.Links) == 0 {
305 fmt.Println("No episode links found")
306 os.Exit(1)
307 }
308
309 Log(anime, logFile)
310
311 // Write anime.AnilistId to .local/share/curd/curd_id
312 idFilePath := filepath.Join(os.Getenv(userCurdConfig.StoragePath), "curd_id")
313 if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
314 Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
315 } else {
316 if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
317 Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
318 }
319 }
320
321 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{})
322
323 if err != nil {
324 Log("Failed to start mpv", logFile)
325 os.Exit(1)
326 }
327
328 return mpvSocketPath
329}
330