internal/localTracking.go

415 lines · 10964 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, logFile string) {
252	var query string
253	var animeList map[string]string
254	var err error
255	var anime Anime
256
257	// Get anime name from user
258	if userCurdConfig.RofiSelection {
259		userInput, err := GetUserInputFromRofi("Enter the anime name")
260		if err != nil {
261			Log("Error getting user input: "+err.Error(), logFile)
262			ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
263		}
264		query = userInput
265	} else {
266		CurdOut("Enter the anime name:")
267		fmt.Scanln(&query)
268	}
269
270	// Search for the anime
271	animeList, err = SearchAnime(query, userCurdConfig.SubOrDub)
272	if err != nil {
273		Log(fmt.Sprintf("Failed to search anime: %v", err), logFile)
274		ExitCurd(fmt.Errorf("Failed to search anime"))
275	}
276
277	if len(animeList) == 0 {
278		ExitCurd(fmt.Errorf("No results found."))
279	}
280
281	// Select anime from search results
282	selectedAnime, err := DynamicSelect(animeList, false)
283	if err != nil {
284		Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
285		ExitCurd(fmt.Errorf("Failed to select anime"))
286	}
287
288	if selectedAnime.Key == "-1" {
289		ExitCurd(nil)
290	}
291
292	anime.AllanimeId = selectedAnime.Key
293	anime.Title.English = selectedAnime.Label
294
295	// Get episode number
296	var episodeNumber int
297	if userCurdConfig.RofiSelection {
298		userInput, err := GetUserInputFromRofi("Enter the episode number")
299		if err != nil {
300			Log("Error getting episode number: "+err.Error(), logFile)
301			ExitCurd(fmt.Errorf("Error getting episode number: "+err.Error()))
302		}
303		episodeNumber, err = strconv.Atoi(userInput)
304		if err != nil {
305			Log(fmt.Sprintf("Invalid episode number: %v", err), logFile)
306			ExitCurd(fmt.Errorf("Invalid episode number"))
307		}
308	} else {
309		CurdOut("Enter the episode number:")
310		fmt.Scanln(&episodeNumber)
311	}
312
313	anime.Ep.Number = episodeNumber
314	
315	for {
316		// Get episode link
317		link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
318		if err != nil {
319			Log(fmt.Sprintf("Failed to get episode link: %v", err), logFile)
320			ExitCurd(fmt.Errorf("Failed to get episode link"))
321		}
322
323		if len(link) == 0 {
324			ExitCurd(fmt.Errorf("No episode links found"))
325		}
326
327		CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(anime), anime.Ep.Number))
328
329		// Start video playback
330		mpvSocketPath, err := StartVideo(PrioritizeLink(link), []string{})
331		if err != nil {
332			Log("Failed to start mpv", logFile)
333			os.Exit(1)
334		}
335
336		anime.Ep.Player.SocketPath = mpvSocketPath
337		anime.Ep.Started = false
338		
339		Log(fmt.Sprintf("Started mpvsocketpath ", anime.Ep.Player.SocketPath), logFile)
340
341		// Get video duration
342		go func() {
343			for {
344				if anime.Ep.Started {
345					if anime.Ep.Duration == 0 {
346						// Get video duration
347						durationPos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "duration"})
348						if err != nil {
349							Log("Error getting video duration: "+err.Error(), logFile)
350						} else if durationPos != nil {
351							if duration, ok := durationPos.(float64); ok {
352								anime.Ep.Duration = int(duration + 0.5) // Round to nearest integer
353								Log(fmt.Sprintf("Video duration: %d seconds", anime.Ep.Duration), logFile)
354							} else {
355								Log("Error: duration is not a float64", logFile)
356							}
357						}
358						break
359					}
360				}
361				time.Sleep(1 * time.Second)
362			}
363		}()
364
365		// Listen for video started
366		for {
367			timePos, err := MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"get_property", "time-pos"})
368			if err != nil {
369				Log("Error getting playback time: "+err.Error(), logFile)
370
371				// Check if the error is due to invalid JSON
372				// User closed the video
373				if anime.Ep.Started {
374					percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
375					// Episode is completed
376					Log(fmt.Sprint(percentageWatched), logFile)
377					Log(fmt.Sprint(anime.Ep.Player.PlaybackTime), logFile)
378					Log(fmt.Sprint(anime.Ep.Duration), logFile)
379					Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete), logFile)
380					if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
381						anime.Ep.Number++
382						anime.Ep.Started = false
383						Log("Completed episode, starting next.", logFile)
384						anime.Ep.IsCompleted = true
385						// Exit the skip loop
386						break
387					} else if fmt.Sprintf("%v", err) == "invalid character '{' after top-level value" { // Episode is not completed
388						Log("Received invalid JSON response, continuing...", logFile)
389					} else {
390						Log("Episode is not completed, exiting", logFile)
391						ExitCurd(nil)
392					}
393				}
394			}
395
396			// Convert timePos to integer
397			if timePos != nil {
398				if !anime.Ep.Started {
399					anime.Ep.Started = true
400				}
401
402				animePosition, ok := timePos.(float64)
403				if !ok {
404					Log("Error: timePos is not a float64", logFile)
405					continue
406				}
407
408				anime.Ep.Player.PlaybackTime = int(animePosition + 0.5) // Round to nearest integer
409			}
410			time.Sleep(1 * time.Second)
411
412		}
413	}
414
415}