internal/curd.go

458 lines · 14065 bytes

  1package internal
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"io"
  7	"net/http"
  8	"os"
  9	"os/exec"
 10	"path/filepath"
 11	"regexp"
 12	"runtime"
 13	"strconv"
 14	"strings"
 15	"time"
 16)
 17
 18func GetTokenFromFile(filePath string) (string, error) {
 19	// Read the token from the file
 20	data, err := os.ReadFile(filePath)
 21	if err != nil {
 22		return "", fmt.Errorf("failed to read token from file: %w", err)
 23	}
 24
 25	// Convert the byte slice to a string and remove any surrounding whitespace or newlines
 26	token := strings.TrimSpace(string(data))
 27
 28	return token, nil
 29}
 30
 31func EditConfig(configFilePath string) {
 32	// Get the user's preferred editor from the EDITOR environment variable
 33	editor := os.Getenv("EDITOR")
 34	if editor == "" {
 35		// If EDITOR is not set, default to "vim"
 36		editor = "vim"
 37	}
 38
 39	// Construct the command to open the config file
 40	cmd := exec.Command(editor, configFilePath)
 41
 42	// Set the command to run in the current terminal
 43	cmd.Stdin = os.Stdin
 44	cmd.Stdout = os.Stdout
 45	cmd.Stderr = os.Stderr
 46
 47	// Run the editor command
 48	err := cmd.Run()
 49	if err != nil {
 50		fmt.Printf("Error opening config file: %v\n", err)
 51		return
 52	}
 53
 54	fmt.Println("Config file edited successfully.")
 55}
 56
 57// ClearLogFile removes all contents from the specified log file
 58func ClearLogFile(logFile string) error {
 59	// Open the file with truncate flag to clear its contents
 60	file, err := os.OpenFile(logFile, os.O_WRONLY|os.O_TRUNC, 0666)
 61	if err != nil {
 62		return fmt.Errorf("failed to open log file: %w", err)
 63	}
 64	defer file.Close()
 65
 66	return nil
 67}
 68
 69// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
 70func Log(data interface{}, logFile string) error {
 71	// Open or create the log file
 72	file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
 73	if err != nil {
 74		return err
 75	}
 76	defer file.Close() // Ensure the file is closed when done
 77
 78	// Attempt to marshal the data into JSON
 79	jsonData, err := json.Marshal(data)
 80	if err != nil {
 81		return err
 82	}
 83
 84	// Get the caller information
 85	_, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
 86	if !ok {
 87		return fmt.Errorf("unable to get caller information")
 88	}
 89
 90	// Log the current time and the JSON representation along with caller info
 91	currentTime := time.Now().Format("2006/01/02 15:04:05")
 92	logMessage := fmt.Sprintf("[LOG] %s %s %d: %s\n", currentTime, filename, lineNumber, jsonData)
 93	_, err = fmt.Fprint(file, logMessage) // Write to the file
 94	if err != nil {
 95		return err
 96	}
 97
 98	return nil
 99}
100
101// ClearScreen clears the terminal screen and saves the state
102func ClearScreen() {
103    fmt.Print("\033[?1049h") // Switch to alternate screen buffer
104    fmt.Print("\033[2J")     // Clear the entire screen
105    fmt.Print("\033[H")      // Move cursor to the top left
106}
107
108// RestoreScreen restores the original terminal state
109func RestoreScreen() {
110    fmt.Print("\033[?1049l") // Switch back to the main screen buffer
111}
112
113func ExitCurd() {
114	RestoreScreen()
115	fmt.Println("Have a great day!")
116	os.Exit(0)
117}
118
119func UpdateCurd(repo, fileName string) error {
120    // Get the path of the currently running executable
121    executablePath, err := os.Executable()
122    if err != nil {
123        return fmt.Errorf("unable to find current executable: %v", err)
124    }
125
126    // Adjust file name for Windows
127    if runtime.GOOS == "windows" {
128        fileName += ".exe"
129    }
130
131    // GitHub release URL for curd
132    url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, fileName)
133
134    // Temporary path for the downloaded curd executable
135    tmpPath := executablePath + ".tmp"
136
137    // Download the curd executable
138    resp, err := http.Get(url)
139    if err != nil {
140        return fmt.Errorf("failed to download file: %v", err)
141    }
142    defer resp.Body.Close()
143
144    // Check if the download was successful
145    if resp.StatusCode != http.StatusOK {
146        return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
147    }
148
149    // Create a new temporary file
150    out, err := os.Create(tmpPath)
151    if err != nil {
152        return fmt.Errorf("failed to create temporary file: %v", err)
153    }
154    defer out.Close()
155
156    // Write the downloaded content to the temporary file
157    _, err = io.Copy(out, resp.Body)
158    if err != nil {
159        return fmt.Errorf("failed to save downloaded file: %v", err)
160    }
161
162    // Close and rename the temporary file to replace the current executable
163    out.Close()
164
165    // Replace the current executable with the downloaded curd
166    if err := os.Rename(tmpPath, executablePath); err != nil {
167        return fmt.Errorf("failed to replace the current executable: %v", err)
168    }
169    fmt.Println("Downloaded curd executable to", executablePath)
170
171	if runtime.GOOS != "windows" {
172		// Ensure the new file has executable permissions
173		if err := os.Chmod(executablePath, 0755); err != nil {
174			return fmt.Errorf("failed to set permissions on the new file: %v", err)
175		}
176	}
177	
178    return nil
179}
180
181func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
182	fmt.Println("Enter the anime name:")
183	var query string
184	fmt.Scanln(&query)
185	animeMap, err := SearchAnimeAnilist(query, user.Token)
186	if err != nil {
187		Log(fmt.Sprintf("Failed to search anime: %v", err), logFile)
188		ExitCurd()
189	}
190	anilistSelectedOption, err := DynamicSelect(animeMap)
191	if err != nil {
192		Log(fmt.Sprintf("No anime available: %v", err), logFile)
193		ExitCurd()
194	}
195	animeID, err := strconv.Atoi(anilistSelectedOption.Key)
196	if err != nil {
197		Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err), logFile)
198		ExitCurd()
199	}
200	err = AddAnimeToWatchingList(animeID, user.Token)
201	if err != nil {
202		Log(fmt.Sprintf("Failed to add anime to watching list: %v", err), logFile)
203		ExitCurd()
204	}
205	anilistUserData, err := GetUserData(user.Token, user.Id)
206	if err != nil {
207		Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
208		ExitCurd()
209	}
210	user.AnimeList = ParseAnimeList(anilistUserData)
211}
212
213func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
214	var err error
215
216	// Get user id, username and Anime list
217	user.Id, user.Username, err = GetAnilistUserID(user.Token)
218	if err != nil {
219		Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
220		ExitCurd()
221	}
222	anilistUserData, err := GetUserData(user.Token, user.Id)
223	if err != nil {
224		Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
225		ExitCurd()
226	}
227	user.AnimeList = ParseAnimeList(anilistUserData)
228	animeListMap := GetAnimeMap(user.AnimeList)
229	var anilistSelectedOption SelectionOption
230	var selectedAllanimeAnime SelectionOption
231	var userQuery string
232
233	if anime.Ep.ContinueLast {
234		// Get the last watched anime ID from the curd_id file
235		curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
236		curdIDBytes, err := os.ReadFile(curdIDPath)
237		if err != nil {
238			Log(fmt.Sprintf("Error reading curd_id file: %v", err), logFile)
239			ExitCurd()
240		}
241
242		lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
243		if err != nil {
244			Log(fmt.Sprintf("Error converting curd_id to integer: %v", err), logFile)
245			ExitCurd()
246		}
247
248		anime.AnilistId = lastWatchedID
249		anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
250	} else {
251		// Select anime to watch (Anilist)
252		var err error
253		anilistSelectedOption, err = DynamicSelect(animeListMap)
254		if err != nil {
255			Log(fmt.Sprintf("Error selecting anime: %v", err), logFile)
256			ExitCurd()
257		}
258
259		if anilistSelectedOption.Key == "-1" || anilistSelectedOption.Label == "quit" {
260			ExitCurd()
261		}
262
263		if anilistSelectedOption.Label == "add_new" {
264			AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile)
265		}
266
267		userQuery = anilistSelectedOption.Label
268		anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
269		if err != nil {
270			Log(fmt.Sprintf("Error converting Anilist ID: %v", err), logFile)
271			ExitCurd()
272		}
273	}
274	// Find anime in Local history
275	animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")	
276	
277	// Get anime entry
278	selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
279	if err != nil {
280		fmt.Println("Can not find the anime in anilist animelist")
281	}
282
283	// Set anime entry
284	anime.Title = selectedAnilistAnime.Media.Title
285	anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
286	anime.Ep.Number = selectedAnilistAnime.Progress+1
287
288	// if anime not found in database, find it in animeList
289	if animePointer == nil {
290		// Get Anime list (All anime)
291		animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
292		if err != nil {
293			fmt.Println("Failed to select anime", logFile)
294			os.Exit(1)
295		}
296		if len(animeList) == 0 {
297			fmt.Println("No results found.")
298			ExitCurd()
299		}
300
301		// find anime in animeList
302		anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
303		if err != nil {
304			Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile)
305		}
306			
307		// If unable to get Allanime id automatically get manually
308		if anime.AllanimeId == "" {
309			fmt.Println("Failed to automatically select anime")
310			selectedAllanimeAnime, err := DynamicSelect(animeList)
311			if err != nil {
312				fmt.Println("No anime available")
313				ExitCurd()
314			}
315			anime.AllanimeId = selectedAllanimeAnime.Key
316		}
317	} else {
318		// if anime found in database, use it
319		anime.AllanimeId = animePointer.AllanimeId
320		anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
321		anime.Ep.Resume = true
322		anime.Ep.Number = animePointer.Ep.Number
323	}
324
325	// If upstream is ahead, update the episode number
326	if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
327		if temp_anime.Progress > anime.Ep.Number {
328			anime.Ep.Number = temp_anime.Progress
329			anime.Ep.Player.PlaybackTime = 0
330			anime.Ep.Resume = false
331		}
332	}
333
334	if anime.TotalEpisodes == 0 {
335		// Get updated anime data
336		Log(selectedAllanimeAnime, logFile)
337		updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
338		Log(updatedAnime, logFile)
339		if err != nil {
340			Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile)
341		} else {
342			anime.TotalEpisodes = updatedAnime.TotalEpisodes
343			Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile)
344		}
345	}
346
347	if anime.TotalEpisodes == 0 { // If failed to get anime data
348		fmt.Println("Failed to get anime data. Attempting to retrieve from anime list.")
349		animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
350		if err != nil {
351			fmt.Println("Failed to retrieve anime list:", err)
352		} else {
353			for allanimeId, label := range animeList {
354				if allanimeId == anime.AllanimeId {
355					// Extract total episodes from the label
356					if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
357						anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
358						fmt.Printf("Retrieved total episodes: %d\n", anime.TotalEpisodes)
359						break
360					}
361				}
362			}
363		}
364		
365		if anime.TotalEpisodes == 0 {
366			fmt.Println("Still unable to determine total episodes.")
367			fmt.Println("Your AniList progress:", selectedAnilistAnime.Progress)
368			fmt.Print("Enter the episode you want to start from: ")
369			var episodeNumber int
370			fmt.Scanln(&episodeNumber)
371			anime.Ep.Number = episodeNumber
372		} else {
373			anime.Ep.Number = selectedAnilistAnime.Progress + 1
374		}
375	} else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
376		Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
377		fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
378		var answer string
379		fmt.Scanln(&answer)
380		if answer == "y" {
381			anime.Ep.Number = 1
382		} else {
383			anime.Ep.Number = anime.TotalEpisodes
384		}
385	}
386
387}
388
389// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
390func WriteTokenToFile(token string, filePath string) error {
391    // Extract the directory path
392    dir := filepath.Dir(filePath)
393
394    // Create all necessary parent directories
395    if err := os.MkdirAll(dir, 0755); err != nil {
396        return fmt.Errorf("failed to create directories: %v", err)
397    }
398
399    // Write the token to the file, creating it if it doesn't exist
400    err := os.WriteFile(filePath, []byte(token), 0644)
401    if err != nil {
402        return fmt.Errorf("failed to write token to file: %v", err)
403    }
404
405    return nil
406}
407
408func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
409
410	// Get episode link
411	link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
412	if err != nil {
413		// If unable to get episode link automatically get manually
414		episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
415		if err != nil {
416			fmt.Println("No episode list found")
417			RestoreScreen()
418			os.Exit(1)
419		}
420		fmt.Printf("Enter the episode (%v episodes)\n", episodeList[len(episodeList)-1])
421		fmt.Scanln(&anime.Ep.Number)
422		link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
423		if err != nil {
424			fmt.Println("Failed to get episode link")
425			os.Exit(1)
426		}
427		// anime.Ep.Links = link
428	}
429	anime.Ep.Links = link
430
431	if len(anime.Ep.Links) == 0 {
432		fmt.Println("No episode links found")
433		os.Exit(1)
434	}
435
436	Log(anime, logFile)
437
438	// Write anime.AnilistId to curd_id in the storage path
439	idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
440	Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile)
441	if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
442		Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
443	} else {
444		if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
445			Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
446		}
447	}
448
449	mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{})
450
451	if err != nil {
452		Log("Failed to start mpv", logFile)
453		os.Exit(1)
454	}
455
456	return mpvSocketPath
457}
458