internal/curd.go
196 lines · 5761 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 SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
83 var err error
84
85 // Get user id, username and Anime list
86 user.Id, user.Username, err = GetAnilistUserID(user.Token)
87 anilistUserData, err := GetUserData(user.Token, user.Id)
88 user.AnimeList = ParseAnimeList(anilistUserData)
89 animeListMap := GetAnimeMap(user.AnimeList)
90
91 // Select anime to watch (Anilist)
92 anilistSelectedOption, err := DynamicSelect(animeListMap)
93 userQuery := anilistSelectedOption.Label
94 anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
95 if err != nil {
96 fmt.Println("Error converting Anilist ID:", err)
97 }
98
99 // Get Anime list (All anime)
100 animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
101 if err != nil {
102 fmt.Println("Failed to select anime", logFile)
103 os.Exit(1)
104 }
105 if len(animeList) == 0 {
106 fmt.Println("No results found.")
107 os.Exit(0)
108 }
109
110 // Get anime entry
111 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
112 if err != nil {
113 fmt.Println("Can not find the anime in anilist animelist")
114 }
115
116 anime.Title = selectedAnilistAnime.Media.Title
117 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
118 anime.Ep.Number = selectedAnilistAnime.Progress+1
119 // Find anime in Local history
120 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
121
122 // if anime not found in database, find it in animeList
123 if animePointer == nil {
124 // find anime in animeList
125 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
126 } else {
127 // if anime found in database, use it
128 anime.AllanimeId = animePointer.AllanimeId
129 anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
130 anime.Ep.Resume = true
131 anime.Ep.Number = animePointer.Ep.Number
132 }
133
134 // If unable to get Allanime id automatically get manually
135 if anime.AllanimeId == "" {
136 fmt.Println("Failed to automatically select anime")
137 selectedAllanimeAnime, err := DynamicSelect(animeList)
138 if err != nil {
139 fmt.Println("No anime available")
140 os.Exit(0)
141 }
142 anime.AllanimeId = selectedAllanimeAnime.Key
143 }
144
145 if anime.TotalEpisodes < anime.Ep.Number {
146 fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
147 anime.Rewatching = true
148 var answer string
149 fmt.Scanln(&answer)
150 if answer == "y" {
151 anime.Ep.Number = 1
152 } else {
153 anime.Ep.Number = anime.TotalEpisodes
154 }
155 }
156}
157
158func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
159
160 // Get episode link
161 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
162 if err != nil {
163 // If unable to get episode link automatically get manually
164 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
165 if err != nil {
166 fmt.Println("No episode list found")
167 RestoreScreen()
168 os.Exit(1)
169 }
170 fmt.Printf("Enter the episode (%v episodes)\n", episodeList[len(episodeList)-1])
171 fmt.Scanln(&anime.Ep.Number)
172 link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
173 if err != nil {
174 fmt.Println("Failed to get episode link")
175 os.Exit(1)
176 }
177 // anime.Ep.Links = link
178 }
179 anime.Ep.Links = link
180
181 if len(anime.Ep.Links) == 0 {
182 fmt.Println("No episode links found")
183 os.Exit(1)
184 }
185
186 Log(anime, logFile)
187 mpvSocketPath, err := StartVideo(anime.Ep.Links[len(anime.Ep.Links)-1], []string{})
188
189 if err != nil {
190 Log("Failed to start mpv", logFile)
191 os.Exit(1)
192 }
193
194 return mpvSocketPath
195}
196