internal/curd.go
230 lines · 6701 bytes
1package internal
2
3import (
4 "encoding/json"
5 "fmt"
6 "os"
7 "runtime"
8 "strconv"
9 "strings"
10 "time"
11)
12
13func GetTokenFromFile(filePath string) (string, error) {
14 // Read the token from the file
15 data, err := os.ReadFile(filePath)
16 if err != nil {
17 return "", fmt.Errorf("failed to read token from file: %w", err)
18 }
19
20 // Convert the byte slice to a string and remove any surrounding whitespace or newlines
21 token := strings.TrimSpace(string(data))
22
23 return token, nil
24}
25
26// ClearLogFile removes all contents from the specified log file
27func ClearLogFile(logFile string) error {
28 // Open the file with truncate flag to clear its contents
29 file, err := os.OpenFile(logFile, os.O_WRONLY|os.O_TRUNC, 0666)
30 if err != nil {
31 return fmt.Errorf("failed to open log file: %w", err)
32 }
33 defer file.Close()
34
35 return nil
36}
37
38// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
39func Log(data interface{}, logFile string) error {
40 // Open or create the log file
41 file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
42 if err != nil {
43 return err
44 }
45 defer file.Close() // Ensure the file is closed when done
46
47 // Attempt to marshal the data into JSON
48 jsonData, err := json.Marshal(data)
49 if err != nil {
50 return err
51 }
52
53 // Get the caller information
54 _, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
55 if !ok {
56 return fmt.Errorf("unable to get caller information")
57 }
58
59 // Log the current time and the JSON representation along with caller info
60 currentTime := time.Now().Format("2006/01/02 15:04:05")
61 logMessage := fmt.Sprintf("[LOG] %s %s %d: %s\n", currentTime, filename, lineNumber, jsonData)
62 _, err = fmt.Fprint(file, logMessage) // Write to the file
63 if err != nil {
64 return err
65 }
66
67 return nil
68}
69
70// ClearScreen clears the terminal screen and saves the state
71func ClearScreen() {
72 fmt.Print("\033[?1049h") // Switch to alternate screen buffer
73 fmt.Print("\033[2J") // Clear the entire screen
74 fmt.Print("\033[H") // Move cursor to the top left
75}
76
77// RestoreScreen restores the original terminal state
78func RestoreScreen() {
79 fmt.Print("\033[?1049l") // Switch back to the main screen buffer
80}
81
82func ExitCurd() {
83 RestoreScreen()
84 os.Exit(0)
85}
86
87func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
88 var err error
89
90 // Get user id, username and Anime list
91 user.Id, user.Username, err = GetAnilistUserID(user.Token)
92 anilistUserData, err := GetUserData(user.Token, user.Id)
93 user.AnimeList = ParseAnimeList(anilistUserData)
94 animeListMap := GetAnimeMap(user.AnimeList)
95
96 // Select anime to watch (Anilist)
97 anilistSelectedOption, err := DynamicSelect(animeListMap)
98 if anilistSelectedOption.Key == "-1" || anilistSelectedOption.Label == "quit" {
99 ExitCurd()
100 }
101 if anilistSelectedOption.Label == "add_new" { // Todo: Add new anime
102 ExitCurd()
103 }
104 userQuery := anilistSelectedOption.Label
105 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
106 if err != nil {
107 fmt.Println("Error converting Anilist ID:", err)
108 os.Exit(1)
109 }
110
111 // Find anime in Local history
112 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
113
114 // Get anime entry
115 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
116 if err != nil {
117 fmt.Println("Can not find the anime in anilist animelist")
118 }
119
120 // Set anime entry
121 anime.Title = selectedAnilistAnime.Media.Title
122 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
123 anime.Ep.Number = selectedAnilistAnime.Progress+1
124
125 // if anime not found in database, find it in animeList
126 if animePointer == nil {
127 // Get Anime list (All anime)
128 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
129 if err != nil {
130 fmt.Println("Failed to select anime", logFile)
131 os.Exit(1)
132 }
133 if len(animeList) == 0 {
134 fmt.Println("No results found.")
135 ExitCurd()
136 }
137
138 // find anime in animeList
139 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
140
141 // If unable to get Allanime id automatically get manually
142 if anime.AllanimeId == "" {
143 fmt.Println("Failed to automatically select anime")
144 selectedAllanimeAnime, err := DynamicSelect(animeList)
145 if err != nil {
146 fmt.Println("No anime available")
147 ExitCurd()
148 }
149 anime.AllanimeId = selectedAllanimeAnime.Key
150 }
151 } else {
152 // if anime found in database, use it
153 anime.AllanimeId = animePointer.AllanimeId
154 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
155 anime.Ep.Resume = true
156 anime.Ep.Number = animePointer.Ep.Number
157 }
158
159 // Handel weird cases
160 if anime.TotalEpisodes < anime.Ep.Number {
161 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
162 anime.Rewatching = true
163 var answer string
164 fmt.Scanln(&answer)
165 if answer == "y" {
166 anime.Ep.Number = 1
167 } else {
168 anime.Ep.Number = anime.TotalEpisodes
169 }
170 }
171}
172
173// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
174func WriteTokenToFile(token string, filePath string) error {
175 // Extract the directory path
176 dir := filepath.Dir(filePath)
177
178 // Create all necessary parent directories
179 if err := os.MkdirAll(dir, 0755); err != nil {
180 return fmt.Errorf("failed to create directories: %v", err)
181 }
182
183 // Write the token to the file, creating it if it doesn't exist
184 err := os.WriteFile(filePath, []byte(token), 0644)
185 if err != nil {
186 return fmt.Errorf("failed to write token to file: %v", err)
187 }
188
189 return nil
190}
191
192func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
193
194 // Get episode link
195 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
196 if err != nil {
197 // If unable to get episode link automatically get manually
198 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
199 if err != nil {
200 fmt.Println("No episode list found")
201 RestoreScreen()
202 os.Exit(1)
203 }
204 fmt.Printf("Enter the episode (%v episodes)\n", episodeList[len(episodeList)-1])
205 fmt.Scanln(&anime.Ep.Number)
206 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
207 if err != nil {
208 fmt.Println("Failed to get episode link")
209 os.Exit(1)
210 }
211 // anime.Ep.Links = link
212 }
213 anime.Ep.Links = link
214
215 if len(anime.Ep.Links) == 0 {
216 fmt.Println("No episode links found")
217 os.Exit(1)
218 }
219
220 Log(anime, logFile)
221 mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{})
222
223 if err != nil {
224 Log("Failed to start mpv", logFile)
225 os.Exit(1)
226 }
227
228 return mpvSocketPath
229}
230