internal/curd.go

211 lines · 6067 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 ExitCurd() {
 83	RestoreScreen()
 84	os.Exit(0)
 85}
 86
 87func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
 88	var err error
 89
 90	// Get user id, username and Anime list
 91	user.Id, user.Username, err = GetAnilistUserID(user.Token)
 92	anilistUserData, err := GetUserData(user.Token, user.Id)
 93	user.AnimeList = ParseAnimeList(anilistUserData)
 94	animeListMap := GetAnimeMap(user.AnimeList)
 95
 96	// Select anime to watch (Anilist)
 97	anilistSelectedOption, err := DynamicSelect(animeListMap)
 98	if anilistSelectedOption.Key == "-1" || anilistSelectedOption.Label == "quit" {
 99		ExitCurd()
100	}
101	if anilistSelectedOption.Label == "add_new" { // Todo: Add new anime
102		ExitCurd()
103	}
104	userQuery := anilistSelectedOption.Label
105	anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
106	if err != nil {
107		fmt.Println("Error converting Anilist ID:", err)
108		os.Exit(1)
109	}
110
111	// Find anime in Local history
112	animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")	
113	
114	// Get anime entry
115	selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
116	if err != nil {
117		fmt.Println("Can not find the anime in anilist animelist")
118	}
119
120	// Set anime entry
121	anime.Title = selectedAnilistAnime.Media.Title
122	anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
123	anime.Ep.Number = selectedAnilistAnime.Progress+1
124
125	// if anime not found in database, find it in animeList
126	if animePointer == nil {
127		// Get Anime list (All anime)
128		animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
129		if err != nil {
130			fmt.Println("Failed to select anime", logFile)
131			os.Exit(1)
132		}
133		if len(animeList) == 0 {
134			fmt.Println("No results found.")
135			ExitCurd()
136		}
137
138		// find anime in animeList
139		anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
140			
141		// If unable to get Allanime id automatically get manually
142		if anime.AllanimeId == "" {
143			fmt.Println("Failed to automatically select anime")
144			selectedAllanimeAnime, err := DynamicSelect(animeList)
145			if err != nil {
146				fmt.Println("No anime available")
147				ExitCurd()
148			}
149			anime.AllanimeId = selectedAllanimeAnime.Key
150		}
151	} else {
152		// if anime found in database, use it
153		anime.AllanimeId = animePointer.AllanimeId
154		anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
155		anime.Ep.Resume = true
156		anime.Ep.Number = animePointer.Ep.Number
157	}
158
159	// Handel weird cases
160	if anime.TotalEpisodes < anime.Ep.Number {
161		fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
162		anime.Rewatching = true
163		var answer string
164		fmt.Scanln(&answer)
165		if answer == "y" {
166			anime.Ep.Number = 1
167		} else {
168			anime.Ep.Number = anime.TotalEpisodes
169		}
170	}
171}
172
173func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
174
175	// Get episode link
176	link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
177	if err != nil {
178		// If unable to get episode link automatically get manually
179		episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
180		if err != nil {
181			fmt.Println("No episode list found")
182			RestoreScreen()
183			os.Exit(1)
184		}
185		fmt.Printf("Enter the episode (%v episodes)\n", episodeList[len(episodeList)-1])
186		fmt.Scanln(&anime.Ep.Number)
187		link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
188		if err != nil {
189			fmt.Println("Failed to get episode link")
190			os.Exit(1)
191		}
192		// anime.Ep.Links = link
193	}
194	anime.Ep.Links = link
195
196	if len(anime.Ep.Links) == 0 {
197		fmt.Println("No episode links found")
198		os.Exit(1)
199	}
200
201	Log(anime, logFile)
202	mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{})
203
204	if err != nil {
205		Log("Failed to start mpv", logFile)
206		os.Exit(1)
207	}
208
209	return mpvSocketPath
210}
211