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