internal/localTracking.go
430 lines · 11233 bytes
1package internal
2
3import (
4 "encoding/csv"
5 "fmt"
6 "os"
7 "path/filepath"
8 "strconv"
9 "time"
10)
11
12// Function to add an anime entry
13func LocalAddAnime(databaseFile string, anilistID int, allanimeID string, watchingEpisode int, watchingTime int, animeDuration int, animeName string) {
14 file, err := os.OpenFile(databaseFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
15 if err != nil {
16 CurdOut(fmt.Sprintf("Error opening file: %v", err))
17 return
18 }
19 defer file.Close()
20
21 writer := csv.NewWriter(file)
22 defer writer.Flush()
23
24 err = writer.Write([]string{
25 strconv.Itoa(anilistID),
26 allanimeID,
27 strconv.Itoa(watchingEpisode),
28 strconv.Itoa(watchingTime),
29 strconv.Itoa(animeDuration),
30 animeName,
31 })
32 if err != nil {
33 CurdOut(fmt.Sprintf("Error writing to file: %v", err))
34 } else {
35 CurdOut("Written to file")
36 }
37}
38
39// Function to delete an anime entry by Anilist ID and Allanime ID
40func LocalDeleteAnime(databaseFile string, anilistID int, allanimeID string) {
41 animeList := [][]string{}
42 file, err := os.Open(databaseFile)
43 if err != nil {
44 CurdOut(fmt.Sprintf("Error opening file: %v", err))
45 return
46 }
47 defer file.Close()
48
49 reader := csv.NewReader(file)
50 records, err := reader.ReadAll()
51 if err != nil {
52 CurdOut(fmt.Sprintf("Error reading file: %v", err))
53 return
54 }
55
56 // Filter out the anime entry
57 for _, row := range records {
58 aid, _ := strconv.Atoi(row[0]) // Anilist ID
59 if aid != anilistID || row[1] != allanimeID {
60 animeList = append(animeList, row)
61 }
62 }
63
64 // Write the filtered list back to the file
65 fileWrite, err := os.OpenFile(databaseFile, os.O_WRONLY|os.O_TRUNC, 0644)
66 if err != nil {
67 CurdOut(fmt.Sprintf("Error opening file for writing: %v", err))
68 return
69 }
70 defer fileWrite.Close()
71
72 writer := csv.NewWriter(fileWrite)
73 defer writer.Flush()
74
75 err = writer.WriteAll(animeList)
76 if err != nil {
77 CurdOut(fmt.Sprintf("Error writing to file: %v", err))
78 }
79}
80
81// Function to get all anime entries from the database
82func LocalGetAllAnime(databaseFile string) []Anime {
83 animeList := []Anime{}
84
85 // Ensure the directory exists
86 dir := filepath.Dir(databaseFile)
87 if err := os.MkdirAll(dir, 0755); err != nil {
88 CurdOut(fmt.Sprintf("Error creating directory: %v", err))
89 return animeList
90 }
91
92 // Open the file, create if it doesn't exist
93 file, err := os.OpenFile(databaseFile, os.O_RDONLY|os.O_CREATE, 0644)
94 if err != nil {
95 CurdOut(fmt.Sprintf("Error opening or creating file: %v", err))
96 return animeList
97 }
98 defer file.Close()
99
100 // If the file was just created, it will be empty, so return an empty list
101 fileInfo, err := file.Stat()
102 if err != nil {
103 CurdOut(fmt.Sprintf("Error getting file info: %v", err))
104 return animeList
105 }
106 if fileInfo.Size() == 0 {
107 return animeList
108 }
109
110 reader := csv.NewReader(file)
111 records, err := reader.ReadAll()
112 if err != nil {
113 CurdOut(fmt.Sprintf("Error reading file: %v", err))
114 return animeList
115 }
116
117 for _, row := range records {
118 anime := parseAnimeRow(row)
119 if anime != nil {
120 animeList = append(animeList, *anime)
121 }
122 }
123
124 return animeList
125}
126
127// Function to parse a single row of anime data
128func parseAnimeRow(row []string) *Anime {
129 if len(row) < 5 {
130 CurdOut(fmt.Sprintf("Invalid row format: %v", row))
131 return nil
132 }
133
134 anilistID, _ := strconv.Atoi(row[0])
135 watchingEpisode, _ := strconv.Atoi(row[2])
136 playbackTime, _ := strconv.Atoi(row[3])
137 animeDuration, _ := strconv.Atoi(row[4])
138
139 anime := &Anime{
140 AnilistId: anilistID,
141 AllanimeId: row[1],
142 Ep: Episode{
143 Number: watchingEpisode,
144 Player: playingVideo{
145 PlaybackTime: playbackTime,
146 },
147 Duration: animeDuration,
148 },
149 }
150
151 if len(row) == 6 {
152 anime.Title = AnimeTitle{
153 English: row[5],
154 Romaji: row[5],
155 }
156 } else if len(row) == 5 {
157 anime.Title = AnimeTitle{
158 English: row[4],
159 Romaji: row[4],
160 }
161 }
162
163 return anime
164}
165
166// Function to get the anime name (English or Romaji) from an Anime struct
167func GetAnimeName(anime Anime) string {
168 userCurdConfig := GetGlobalConfig()
169 if anime.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
170 return anime.Title.English
171 }
172 return anime.Title.Romaji
173}
174
175// Function to update or add a new anime entry
176func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, watchingEpisode int, playbackTime int, animeDuration int, animeName string) error {
177 // Read existing entries
178 animeList := LocalGetAllAnime(databaseFile)
179
180 // Find and update existing entry or add new one
181 updated := false
182 for i, anime := range animeList {
183 if anime.AnilistId == anilistID && anime.AllanimeId == allanimeID {
184 animeList[i].Ep.Number = watchingEpisode
185 animeList[i].Ep.Player.PlaybackTime = playbackTime
186 animeList[i].Ep.Duration = animeDuration
187 animeList[i].Title.English = animeName
188 animeList[i].Title.Romaji = animeName
189 updated = true
190 break
191 }
192 }
193
194 if !updated {
195 newAnime := Anime{
196 AnilistId: anilistID,
197 AllanimeId: allanimeID,
198 Ep: Episode{
199 Number: watchingEpisode,
200 Player: playingVideo{
201 PlaybackTime: playbackTime,
202 },
203 Duration: animeDuration,
204 },
205 Title: AnimeTitle{
206 English: animeName,
207 Romaji: animeName,
208 },
209 }
210 animeList = append(animeList, newAnime)
211 }
212
213 // Write updated list back to file
214 file, err := os.Create(databaseFile)
215 if err != nil {
216 CurdOut(fmt.Sprintf("Error creating file: %v", err))
217 return err
218 }
219 defer file.Close()
220
221 writer := csv.NewWriter(file)
222 defer writer.Flush()
223
224 for _, anime := range animeList {
225 record := []string{
226 strconv.Itoa(anime.AnilistId),
227 anime.AllanimeId,
228 strconv.Itoa(anime.Ep.Number),
229 strconv.Itoa(anime.Ep.Player.PlaybackTime),
230 strconv.Itoa(anime.Ep.Duration),
231 GetAnimeName(anime),
232 }
233 if err := writer.Write(record); err != nil {
234 CurdOut(fmt.Sprintf("Error writing record: %v", err))
235 }
236 }
237
238 return nil
239}
240
241// Function to find an anime by either Anilist ID or Allanime ID
242func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime {
243 for _, anime := range animeList {
244 if anime.AnilistId == anilistID || anime.AllanimeId == allanimeID {
245 return &anime
246 }
247 }
248 return nil
249}
250
251func WatchUntracked(userCurdConfig *CurdConfig) {
252 var query string
253 var animeList []SelectionOption
254 var err error
255 var anime Anime
256
257 // Anime search and selection loop
258 for {
259 // Get anime name from user
260 if userCurdConfig.RofiSelection {
261 userInput, err := GetUserInputFromRofi("Enter the anime name")
262 if err != nil {
263 Log("Error getting user input: " + err.Error())
264 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
265 }
266 query = userInput
267 } else {
268 CurdOut("Enter the anime name:")
269 fmt.Scanln(&query)
270 }
271
272 // Search for the anime
273 animeList, err = SearchAnime(query, userCurdConfig.SubOrDub)
274 if err != nil {
275 Log(fmt.Sprintf("Failed to search anime: %v", err))
276 ExitCurd(fmt.Errorf("Failed to search anime"))
277 }
278
279 if len(animeList) == 0 {
280 ExitCurd(fmt.Errorf("No results found."))
281 }
282
283 // Select anime from search results
284 selectedAnime, err := DynamicSelect(animeList)
285 if err != nil {
286 Log(fmt.Sprintf("Failed to select anime: %v", err))
287 ExitCurd(fmt.Errorf("Failed to select anime"))
288 }
289
290 if selectedAnime.Key == "-1" {
291 ExitCurd(nil)
292 }
293
294 // Back goes to home menu
295 if selectedAnime.Key == "-2" {
296 return // Return to caller (home menu)
297 }
298
299 anime.AllanimeId = selectedAnime.Key
300 if selectedAnime.Title != "" {
301 anime.Title.English = selectedAnime.Title
302 anime.Title.Romaji = selectedAnime.Title
303 } else {
304 anime.Title.English = selectedAnime.Label
305 anime.Title.Romaji = selectedAnime.Label
306 }
307 break
308 }
309
310 // Get episode number
311 var episodeNumber int
312 if userCurdConfig.RofiSelection {
313 userInput, err := GetUserInputFromRofi("Enter the episode number")
314 if err != nil {
315 Log("Error getting episode number: " + err.Error())
316 ExitCurd(fmt.Errorf("Error getting episode number: " + err.Error()))
317 }
318 episodeNumber, err = strconv.Atoi(userInput)
319 if err != nil {
320 Log(fmt.Sprintf("Invalid episode number: %v", err))
321 ExitCurd(fmt.Errorf("Invalid episode number"))
322 }
323 } else {
324 CurdOut("Enter the episode number:")
325 fmt.Scanln(&episodeNumber)
326 }
327
328 anime.Ep.Number = episodeNumber
329
330 for {
331 // Get episode link
332 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
333 if err != nil {
334 Log(fmt.Sprintf("Failed to get episode link: %v", err))
335 ExitCurd(fmt.Errorf("Failed to get episode link"))
336 }
337
338 if len(link) == 0 {
339 ExitCurd(fmt.Errorf("No episode links found"))
340 }
341
342 CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(anime), anime.Ep.Number))
343
344 // Start video playback
345 mpvSocketPath, err := StartVideo(PrioritizeLink(link), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(anime), anime.Ep.Number), &anime)
346 if err != nil {
347 Log("Failed to start mpv")
348 os.Exit(1)
349 }
350
351 anime.Ep.Player.SocketPath = mpvSocketPath
352 anime.Ep.Started = false
353
354 Log(fmt.Sprintf("Started mpv with socket path: %s", anime.Ep.Player.SocketPath))
355
356 // Get video duration
357 go func() {
358 for {
359 if anime.Ep.Started {
360 if anime.Ep.Duration == 0 {
361 // Get video duration
362 durationPos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "duration"})
363 if err != nil {
364 Log("Error getting video duration: " + err.Error())
365 } else if durationPos != nil {
366 if duration, ok := durationPos.(float64); ok {
367 anime.Ep.Duration = int(duration + 0.5) // Round to nearest integer
368 Log(fmt.Sprintf("Video duration: %d seconds", anime.Ep.Duration))
369 } else {
370 Log("Error: duration is not a float64")
371 }
372 }
373 break
374 }
375 }
376 time.Sleep(1 * time.Second)
377 }
378 }()
379
380 // Listen for video started
381 for {
382 timePos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"})
383 if err != nil {
384 Log("Error getting playback time: " + err.Error())
385
386 // Check if the error is due to invalid JSON
387 // User closed the video
388 if anime.Ep.Started {
389 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
390 // Episode is completed
391 Log(fmt.Sprint(percentageWatched))
392 Log(fmt.Sprint(anime.Ep.Player.PlaybackTime))
393 Log(fmt.Sprint(anime.Ep.Duration))
394 Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete))
395 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
396 anime.Ep.Number++
397 anime.Ep.Started = false
398 Log("Completed episode, starting next.")
399 anime.Ep.IsCompleted = true
400 // Exit the skip loop
401 break
402 } else if fmt.Sprintf("%v", err) == "invalid character '{' after top-level value" { // Episode is not completed
403 Log("Received invalid JSON response, continuing...")
404 } else {
405 Log("Episode is not completed, exiting")
406 ExitCurd(nil)
407 }
408 }
409 }
410
411 // Convert timePos to integer
412 if timePos != nil {
413 if !anime.Ep.Started {
414 anime.Ep.Started = true
415 }
416
417 animePosition, ok := timePos.(float64)
418 if !ok {
419 Log("Error: timePos is not a float64")
420 continue
421 }
422
423 anime.Ep.Player.PlaybackTime = int(animePosition + 0.5) // Round to nearest integer
424 }
425 time.Sleep(1 * time.Second)
426
427 }
428 }
429
430}