internal/localTracking.go

464 lines · 12389 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		AllanimeId: 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) == 6 {
154		anime.Title = AnimeTitle{
155			English: row[5],
156			Romaji:  row[5],
157		}
158	} else if len(row) == 5 {
159		anime.Title = AnimeTitle{
160			English: row[4],
161			Romaji:  row[4],
162		}
163	}
164
165	return anime
166}
167
168// Function to get the anime name (English or Romaji) from an Anime struct
169func GetAnimeName(anime Anime) string {
170	userCurdConfig := GetGlobalConfig()
171	if anime.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
172		return anime.Title.English
173	}
174	return anime.Title.Romaji
175}
176
177// Function to update or add a new anime entry
178func LocalUpdateAnime(databaseFile string, anilistID int, allanimeID string, watchingEpisode int, playbackTime int, animeDuration int, animeName string) error {
179	// Read existing entries
180	animeList := LocalGetAllAnime(databaseFile)
181
182	// Find and update existing entry or add new one
183	updated := false
184	for i, anime := range animeList {
185		if anime.AnilistId == anilistID && anime.AllanimeId == allanimeID {
186			animeList[i].Ep.Number = watchingEpisode
187			animeList[i].Ep.Player.PlaybackTime = playbackTime
188			animeList[i].Ep.Duration = animeDuration
189			animeList[i].Title.English = animeName
190			animeList[i].Title.Romaji = animeName
191			updated = true
192			break
193		}
194	}
195
196	if !updated {
197		newAnime := Anime{
198			AnilistId:  anilistID,
199			AllanimeId: allanimeID,
200			Ep: Episode{
201				Number: watchingEpisode,
202				Player: playingVideo{
203					PlaybackTime: playbackTime,
204				},
205				Duration: animeDuration,
206			},
207			Title: AnimeTitle{
208				English: animeName,
209				Romaji:  animeName,
210			},
211		}
212		animeList = append(animeList, newAnime)
213	}
214
215	// Write updated list back to file
216	file, err := os.Create(databaseFile)
217	if err != nil {
218		CurdOut(fmt.Sprintf("Error creating file: %v", err))
219		return err
220	}
221	defer file.Close()
222
223	writer := csv.NewWriter(file)
224	defer writer.Flush()
225
226	for _, anime := range animeList {
227		record := []string{
228			strconv.Itoa(anime.AnilistId),
229			anime.AllanimeId,
230			strconv.Itoa(anime.Ep.Number),
231			strconv.Itoa(anime.Ep.Player.PlaybackTime),
232			strconv.Itoa(anime.Ep.Duration),
233			GetAnimeName(anime),
234		}
235		if err := writer.Write(record); err != nil {
236			CurdOut(fmt.Sprintf("Error writing record: %v", err))
237		}
238	}
239
240	return nil
241}
242
243// Function to find an anime by either Anilist ID or Allanime ID
244func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime {
245	for _, anime := range animeList {
246		if anime.AnilistId == anilistID || anime.AllanimeId == allanimeID {
247			return &anime
248		}
249	}
250	return nil
251}
252
253func WatchUntracked(userCurdConfig *CurdConfig) {
254	var query string
255	var animeList []SelectionOption
256	var err error
257	var anime Anime
258
259	// Anime search and selection loop
260	for {
261		// Get anime name from user
262		if userCurdConfig.RofiSelection {
263			userInput, err := GetUserInputFromRofi("Enter the anime name")
264			if err != nil {
265				Log("Error getting user input: " + err.Error())
266				ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
267			}
268			query = userInput
269		} else {
270			CurdOut("Enter the anime name:")
271			fmt.Scanln(&query)
272		}
273
274		// Search for the anime
275		animeList, err = SearchAnime(query, userCurdConfig.SubOrDub)
276		if err != nil {
277			Log(fmt.Sprintf("Failed to search anime: %v", err))
278			ExitCurd(fmt.Errorf("Failed to search anime"))
279		}
280
281		if len(animeList) == 0 {
282			// Prompt user for manual query
283			for {
284				var manualQuery string
285				if userCurdConfig.RofiSelection {
286					userInput, err := GetUserInputFromRofi(fmt.Sprintf("No results found for '%s'.\nPress Enter to search with the original name, or enter a custom name to search on AllAnime.", query))
287					if err != nil {
288						Log("Error getting user input: " + err.Error())
289						ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
290					}
291					manualQuery = userInput
292				} else {
293					CurdOut(fmt.Sprintf("No results found for '%s'.", query))
294					CurdOut("Press Enter to search with the original name, or enter a custom name to search on AllAnime:")
295					reader := bufio.NewReader(os.Stdin)
296					input, _ := reader.ReadString('\n')
297					manualQuery = strings.TrimSpace(input)
298				}
299
300				// If empty, use original query name
301				if manualQuery == "" {
302					manualQuery = query
303				}
304
305				animeList, err = SearchAnime(manualQuery, userCurdConfig.SubOrDub)
306				if err != nil {
307					Log(fmt.Sprintf("Failed to search anime with query '%s': %v", manualQuery, err))
308					ExitCurd(fmt.Errorf("Failed to search anime"))
309				}
310
311				if len(animeList) > 0 {
312					break
313				}
314			}
315		}
316
317		// Select anime from search results
318		selectedAnime, err := DynamicSelect(animeList)
319		if err != nil {
320			Log(fmt.Sprintf("Failed to select anime: %v", err))
321			ExitCurd(fmt.Errorf("Failed to select anime"))
322		}
323
324		if selectedAnime.Key == "-1" {
325			ExitCurd(nil)
326		}
327
328		// Back goes to home menu
329		if selectedAnime.Key == "-2" {
330			return // Return to caller (home menu)
331		}
332
333		anime.AllanimeId = selectedAnime.Key
334		if selectedAnime.Title != "" {
335			anime.Title.English = selectedAnime.Title
336			anime.Title.Romaji = selectedAnime.Title
337		} else {
338			anime.Title.English = selectedAnime.Label
339			anime.Title.Romaji = selectedAnime.Label
340		}
341		break
342	}
343
344	// Get episode number
345	var episodeNumber int
346	if userCurdConfig.RofiSelection {
347		userInput, err := GetUserInputFromRofi("Enter the episode number")
348		if err != nil {
349			Log("Error getting episode number: " + err.Error())
350			ExitCurd(fmt.Errorf("Error getting episode number: " + err.Error()))
351		}
352		episodeNumber, err = strconv.Atoi(userInput)
353		if err != nil {
354			Log(fmt.Sprintf("Invalid episode number: %v", err))
355			ExitCurd(fmt.Errorf("Invalid episode number"))
356		}
357	} else {
358		CurdOut("Enter the episode number:")
359		fmt.Scanln(&episodeNumber)
360	}
361
362	anime.Ep.Number = episodeNumber
363
364	for {
365		// Get episode link
366		link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
367		if err != nil {
368			Log(fmt.Sprintf("Failed to get episode link: %v", err))
369			ExitCurd(fmt.Errorf("Failed to get episode link"))
370		}
371
372		if len(link) == 0 {
373			ExitCurd(fmt.Errorf("No episode links found"))
374		}
375
376		CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(anime), anime.Ep.Number))
377
378		// Start video playback
379		mpvSocketPath, err := StartVideo(PrioritizeLink(link), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(anime), anime.Ep.Number), &anime)
380		if err != nil {
381			Log("Failed to start mpv")
382			os.Exit(1)
383		}
384
385		anime.Ep.Player.SocketPath = mpvSocketPath
386		anime.Ep.Started = false
387
388		Log(fmt.Sprintf("Started mpv with socket path: %s", anime.Ep.Player.SocketPath))
389
390		// Get video duration
391		go func() {
392			for {
393				if anime.Ep.Started {
394					if anime.Ep.Duration == 0 {
395						// Get video duration
396						durationPos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "duration"})
397						if err != nil {
398							Log("Error getting video duration: " + err.Error())
399						} else if durationPos != nil {
400							if duration, ok := durationPos.(float64); ok {
401								anime.Ep.Duration = int(duration + 0.5) // Round to nearest integer
402								Log(fmt.Sprintf("Video duration: %d seconds", anime.Ep.Duration))
403							} else {
404								Log("Error: duration is not a float64")
405							}
406						}
407						break
408					}
409				}
410				time.Sleep(1 * time.Second)
411			}
412		}()
413
414		// Listen for video started
415		for {
416			timePos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"})
417			if err != nil {
418				Log("Error getting playback time: " + err.Error())
419
420				// Check if the error is due to invalid JSON
421				// User closed the video
422				if anime.Ep.Started {
423					percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
424					// Episode is completed
425					Log(fmt.Sprint(percentageWatched))
426					Log(fmt.Sprint(anime.Ep.Player.PlaybackTime))
427					Log(fmt.Sprint(anime.Ep.Duration))
428					Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete))
429					if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
430						anime.Ep.Number++
431						anime.Ep.Started = false
432						Log("Completed episode, starting next.")
433						anime.Ep.IsCompleted = true
434						// Exit the skip loop
435						break
436					} else if fmt.Sprintf("%v", err) == "invalid character '{' after top-level value" { // Episode is not completed
437						Log("Received invalid JSON response, continuing...")
438					} else {
439						Log("Episode is not completed, exiting")
440						ExitCurd(nil)
441					}
442				}
443			}
444
445			// Convert timePos to integer
446			if timePos != nil {
447				if !anime.Ep.Started {
448					anime.Ep.Started = true
449				}
450
451				animePosition, ok := timePos.(float64)
452				if !ok {
453					Log("Error: timePos is not a float64")
454					continue
455				}
456
457				anime.Ep.Player.PlaybackTime = int(animePosition + 0.5) // Round to nearest integer
458			}
459			time.Sleep(1 * time.Second)
460
461		}
462	}
463
464}