internal/localTracking.go

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