internal/curd.go

459 lines · 14079 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			ExitCurd()
306		}
307			
308		// If unable to get Allanime id automatically get manually
309		if anime.AllanimeId == "" {
310			fmt.Println("Failed to automatically select anime")
311			selectedAllanimeAnime, err := DynamicSelect(animeList)
312			if err != nil {
313				fmt.Println("No anime available")
314				ExitCurd()
315			}
316			anime.AllanimeId = selectedAllanimeAnime.Key
317		}
318	} else {
319		// if anime found in database, use it
320		anime.AllanimeId = animePointer.AllanimeId
321		anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
322		anime.Ep.Resume = true
323		anime.Ep.Number = animePointer.Ep.Number
324	}
325
326	// If upstream is ahead, update the episode number
327	if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
328		if temp_anime.Progress > anime.Ep.Number {
329			anime.Ep.Number = temp_anime.Progress
330			anime.Ep.Player.PlaybackTime = 0
331			anime.Ep.Resume = false
332		}
333	}
334
335	if anime.TotalEpisodes == 0 {
336		// Get updated anime data
337		Log(selectedAllanimeAnime, logFile)
338		updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
339		Log(updatedAnime, logFile)
340		if err != nil {
341			Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile)
342		} else {
343			anime.TotalEpisodes = updatedAnime.TotalEpisodes
344			Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile)
345		}
346	}
347
348	if anime.TotalEpisodes == 0 { // If failed to get anime data
349		fmt.Println("Failed to get anime data. Attempting to retrieve from anime list.")
350		animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
351		if err != nil {
352			fmt.Println("Failed to retrieve anime list:", err)
353		} else {
354			for allanimeId, label := range animeList {
355				if allanimeId == anime.AllanimeId {
356					// Extract total episodes from the label
357					if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
358						anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
359						fmt.Printf("Retrieved total episodes: %d\n", anime.TotalEpisodes)
360						break
361					}
362				}
363			}
364		}
365		
366		if anime.TotalEpisodes == 0 {
367			fmt.Println("Still unable to determine total episodes.")
368			fmt.Println("Your AniList progress:", selectedAnilistAnime.Progress)
369			fmt.Print("Enter the episode you want to start from: ")
370			var episodeNumber int
371			fmt.Scanln(&episodeNumber)
372			anime.Ep.Number = episodeNumber
373		} else {
374			anime.Ep.Number = selectedAnilistAnime.Progress + 1
375		}
376	} else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
377		Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
378		fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
379		var answer string
380		fmt.Scanln(&answer)
381		if answer == "y" {
382			anime.Ep.Number = 1
383		} else {
384			anime.Ep.Number = anime.TotalEpisodes
385		}
386	}
387
388}
389
390// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
391func WriteTokenToFile(token string, filePath string) error {
392    // Extract the directory path
393    dir := filepath.Dir(filePath)
394
395    // Create all necessary parent directories
396    if err := os.MkdirAll(dir, 0755); err != nil {
397        return fmt.Errorf("failed to create directories: %v", err)
398    }
399
400    // Write the token to the file, creating it if it doesn't exist
401    err := os.WriteFile(filePath, []byte(token), 0644)
402    if err != nil {
403        return fmt.Errorf("failed to write token to file: %v", err)
404    }
405
406    return nil
407}
408
409func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
410
411	// Get episode link
412	link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
413	if err != nil {
414		// If unable to get episode link automatically get manually
415		episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
416		if err != nil {
417			fmt.Println("No episode list found")
418			RestoreScreen()
419			os.Exit(1)
420		}
421		fmt.Printf("Enter the episode (%v episodes)\n", episodeList[len(episodeList)-1])
422		fmt.Scanln(&anime.Ep.Number)
423		link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
424		if err != nil {
425			fmt.Println("Failed to get episode link")
426			os.Exit(1)
427		}
428		// anime.Ep.Links = link
429	}
430	anime.Ep.Links = link
431
432	if len(anime.Ep.Links) == 0 {
433		fmt.Println("No episode links found")
434		os.Exit(1)
435	}
436
437	Log(anime, logFile)
438
439	// Write anime.AnilistId to curd_id in the storage path
440	idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
441	Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile)
442	if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
443		Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
444	} else {
445		if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
446			Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
447		}
448	}
449
450	mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{})
451
452	if err != nil {
453		Log("Failed to start mpv", logFile)
454		os.Exit(1)
455	}
456
457	return mpvSocketPath
458}
459