internal/curd.go

206 lines · 6024 bytes

  1package internal
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"os"
  7	"runtime"
  8	"strconv"
  9	"strings"
 10	"time"
 11)
 12
 13func GetTokenFromFile(filePath string) (string, error) {
 14	// Read the token from the file
 15	data, err := os.ReadFile(filePath)
 16	if err != nil {
 17		return "", fmt.Errorf("failed to read token from file: %w", err)
 18	}
 19
 20	// Convert the byte slice to a string and remove any surrounding whitespace or newlines
 21	token := strings.TrimSpace(string(data))
 22
 23	return token, nil
 24}
 25
 26// ClearLogFile removes all contents from the specified log file
 27func ClearLogFile(logFile string) error {
 28	// Open the file with truncate flag to clear its contents
 29	file, err := os.OpenFile(logFile, os.O_WRONLY|os.O_TRUNC, 0666)
 30	if err != nil {
 31		return fmt.Errorf("failed to open log file: %w", err)
 32	}
 33	defer file.Close()
 34
 35	return nil
 36}
 37
 38// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
 39func Log(data interface{}, logFile string) error {
 40	// Open or create the log file
 41	file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
 42	if err != nil {
 43		return err
 44	}
 45	defer file.Close() // Ensure the file is closed when done
 46
 47	// Attempt to marshal the data into JSON
 48	jsonData, err := json.Marshal(data)
 49	if err != nil {
 50		return err
 51	}
 52
 53	// Get the caller information
 54	_, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
 55	if !ok {
 56		return fmt.Errorf("unable to get caller information")
 57	}
 58
 59	// Log the current time and the JSON representation along with caller info
 60	currentTime := time.Now().Format("2006/01/02 15:04:05")
 61	logMessage := fmt.Sprintf("[LOG] %s %s %d: %s\n", currentTime, filename, lineNumber, jsonData)
 62	_, err = fmt.Fprint(file, logMessage) // Write to the file
 63	if err != nil {
 64		return err
 65	}
 66
 67	return nil
 68}
 69
 70// ClearScreen clears the terminal screen and saves the state
 71func ClearScreen() {
 72    fmt.Print("\033[?1049h") // Switch to alternate screen buffer
 73    fmt.Print("\033[2J")     // Clear the entire screen
 74    fmt.Print("\033[H")      // Move cursor to the top left
 75}
 76
 77// RestoreScreen restores the original terminal state
 78func RestoreScreen() {
 79    fmt.Print("\033[?1049l") // Switch back to the main screen buffer
 80}
 81
 82func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
 83	var err error
 84
 85	// Get user id, username and Anime list
 86	user.Id, user.Username, err = GetAnilistUserID(user.Token)
 87	anilistUserData, err := GetUserData(user.Token, user.Id)
 88	user.AnimeList = ParseAnimeList(anilistUserData)
 89	animeListMap := GetAnimeMap(user.AnimeList)
 90
 91	// Select anime to watch (Anilist)
 92	anilistSelectedOption, err := DynamicSelect(animeListMap)
 93	if anilistSelectedOption.Key == "-1" || anilistSelectedOption.Label == "quit" {
 94		os.Exit(0)
 95	}
 96	if anilistSelectedOption.Label == "add_new" { // Todo: Add new anime
 97		os.Exit(0)
 98	}
 99	userQuery := anilistSelectedOption.Label
100	anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
101	if err != nil {
102		fmt.Println("Error converting Anilist ID:", err)
103		os.Exit(1)
104	}
105
106	// Find anime in Local history
107	animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")	
108	
109	// Get anime entry
110	selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
111	if err != nil {
112		fmt.Println("Can not find the anime in anilist animelist")
113	}
114
115	// Set anime entry
116	anime.Title = selectedAnilistAnime.Media.Title
117	anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
118	anime.Ep.Number = selectedAnilistAnime.Progress+1
119
120	// if anime not found in database, find it in animeList
121	if animePointer == nil {
122		// Get Anime list (All anime)
123		animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
124		if err != nil {
125			fmt.Println("Failed to select anime", logFile)
126			os.Exit(1)
127		}
128		if len(animeList) == 0 {
129			fmt.Println("No results found.")
130			os.Exit(0)
131		}
132
133		// find anime in animeList
134		anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
135			
136		// If unable to get Allanime id automatically get manually
137		if anime.AllanimeId == "" {
138			fmt.Println("Failed to automatically select anime")
139			selectedAllanimeAnime, err := DynamicSelect(animeList)
140			if err != nil {
141				fmt.Println("No anime available")
142				os.Exit(0)
143			}
144			anime.AllanimeId = selectedAllanimeAnime.Key
145		}
146	} else {
147		// if anime found in database, use it
148		anime.AllanimeId = animePointer.AllanimeId
149		anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
150		anime.Ep.Resume = true
151		anime.Ep.Number = animePointer.Ep.Number
152	}
153
154	// Handel weird cases
155	if anime.TotalEpisodes < anime.Ep.Number {
156		fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
157		anime.Rewatching = true
158		var answer string
159		fmt.Scanln(&answer)
160		if answer == "y" {
161			anime.Ep.Number = 1
162		} else {
163			anime.Ep.Number = anime.TotalEpisodes
164		}
165	}
166}
167
168func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
169
170	// Get episode link
171	link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
172	if err != nil {
173		// If unable to get episode link automatically get manually
174		episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
175		if err != nil {
176			fmt.Println("No episode list found")
177			RestoreScreen()
178			os.Exit(1)
179		}
180		fmt.Printf("Enter the episode (%v episodes)\n", episodeList[len(episodeList)-1])
181		fmt.Scanln(&anime.Ep.Number)
182		link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
183		if err != nil {
184			fmt.Println("Failed to get episode link")
185			os.Exit(1)
186		}
187		// anime.Ep.Links = link
188	}
189	anime.Ep.Links = link
190
191	if len(anime.Ep.Links) == 0 {
192		fmt.Println("No episode links found")
193		os.Exit(1)
194	}
195
196	Log(anime, logFile)
197	mpvSocketPath, err := StartVideo(anime.Ep.Links[len(anime.Ep.Links)-1], []string{})
198
199	if err != nil {
200		Log("Failed to start mpv", logFile)
201		os.Exit(1)
202	}
203
204	return mpvSocketPath
205}
206