internal/localTracking.go

425 lines · 11052 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		anime.Title.English = selectedAnime.Label
301		break
302	}
303
304	// Get episode number
305	var episodeNumber int
306	if userCurdConfig.RofiSelection {
307		userInput, err := GetUserInputFromRofi("Enter the episode number")
308		if err != nil {
309			Log("Error getting episode number: " + err.Error())
310			ExitCurd(fmt.Errorf("Error getting episode number: " + err.Error()))
311		}
312		episodeNumber, err = strconv.Atoi(userInput)
313		if err != nil {
314			Log(fmt.Sprintf("Invalid episode number: %v", err))
315			ExitCurd(fmt.Errorf("Invalid episode number"))
316		}
317	} else {
318		CurdOut("Enter the episode number:")
319		fmt.Scanln(&episodeNumber)
320	}
321
322	anime.Ep.Number = episodeNumber
323
324	for {
325		// Get episode link
326		link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
327		if err != nil {
328			Log(fmt.Sprintf("Failed to get episode link: %v", err))
329			ExitCurd(fmt.Errorf("Failed to get episode link"))
330		}
331
332		if len(link) == 0 {
333			ExitCurd(fmt.Errorf("No episode links found"))
334		}
335
336		CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(anime), anime.Ep.Number))
337
338		// Start video playback
339		mpvSocketPath, err := StartVideo(PrioritizeLink(link), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(anime), anime.Ep.Number), &anime)
340		if err != nil {
341			Log("Failed to start mpv")
342			os.Exit(1)
343		}
344
345		anime.Ep.Player.SocketPath = mpvSocketPath
346		anime.Ep.Started = false
347
348		Log(fmt.Sprintf("Started mpv with socket path: %s", anime.Ep.Player.SocketPath))
349
350		// Get video duration
351		go func() {
352			for {
353				if anime.Ep.Started {
354					if anime.Ep.Duration == 0 {
355						// Get video duration
356						durationPos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "duration"})
357						if err != nil {
358							Log("Error getting video duration: " + err.Error())
359						} else if durationPos != nil {
360							if duration, ok := durationPos.(float64); ok {
361								anime.Ep.Duration = int(duration + 0.5) // Round to nearest integer
362								Log(fmt.Sprintf("Video duration: %d seconds", anime.Ep.Duration))
363							} else {
364								Log("Error: duration is not a float64")
365							}
366						}
367						break
368					}
369				}
370				time.Sleep(1 * time.Second)
371			}
372		}()
373
374		// Listen for video started
375		for {
376			timePos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"})
377			if err != nil {
378				Log("Error getting playback time: " + err.Error())
379
380				// Check if the error is due to invalid JSON
381				// User closed the video
382				if anime.Ep.Started {
383					percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
384					// Episode is completed
385					Log(fmt.Sprint(percentageWatched))
386					Log(fmt.Sprint(anime.Ep.Player.PlaybackTime))
387					Log(fmt.Sprint(anime.Ep.Duration))
388					Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete))
389					if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
390						anime.Ep.Number++
391						anime.Ep.Started = false
392						Log("Completed episode, starting next.")
393						anime.Ep.IsCompleted = true
394						// Exit the skip loop
395						break
396					} else if fmt.Sprintf("%v", err) == "invalid character '{' after top-level value" { // Episode is not completed
397						Log("Received invalid JSON response, continuing...")
398					} else {
399						Log("Episode is not completed, exiting")
400						ExitCurd(nil)
401					}
402				}
403			}
404
405			// Convert timePos to integer
406			if timePos != nil {
407				if !anime.Ep.Started {
408					anime.Ep.Started = true
409				}
410
411				animePosition, ok := timePos.(float64)
412				if !ok {
413					Log("Error: timePos is not a float64")
414					continue
415				}
416
417				anime.Ep.Player.PlaybackTime = int(animePosition + 0.5) // Round to nearest integer
418			}
419			time.Sleep(1 * time.Second)
420
421		}
422	}
423
424}
425