internal/curd.go

470 lines · 14888 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(err error) {
114	RestoreScreen()
115	if err != nil {
116		fmt.Println(err)
117		if runtime.GOOS == "windows" {
118			fmt.Println("Press Enter to exit")
119			var wait string
120			fmt.Scanln(&wait)
121			os.Exit(1)
122		} else {
123			fmt.Println("Have a great day!")
124			os.Exit(1)
125		}
126	}
127	os.Exit(0)
128}
129
130func UpdateCurd(repo, fileName string) error {
131    // Get the path of the currently running executable
132    executablePath, err := os.Executable()
133    if err != nil {
134        return fmt.Errorf("unable to find current executable: %v", err)
135    }
136
137    // Adjust file name for Windows
138    if runtime.GOOS == "windows" {
139        fileName += ".exe"
140    }
141
142    // GitHub release URL for curd
143    url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, fileName)
144
145    // Temporary path for the downloaded curd executable
146    tmpPath := executablePath + ".tmp"
147
148    // Download the curd executable
149    resp, err := http.Get(url)
150    if err != nil {
151        return fmt.Errorf("failed to download file: %v", err)
152    }
153    defer resp.Body.Close()
154
155    // Check if the download was successful
156    if resp.StatusCode != http.StatusOK {
157        return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
158    }
159
160    // Create a new temporary file
161    out, err := os.Create(tmpPath)
162    if err != nil {
163        return fmt.Errorf("failed to create temporary file: %v", err)
164    }
165    defer out.Close()
166
167    // Write the downloaded content to the temporary file
168    _, err = io.Copy(out, resp.Body)
169    if err != nil {
170        return fmt.Errorf("failed to save downloaded file: %v", err)
171    }
172
173    // Close and rename the temporary file to replace the current executable
174    out.Close()
175
176    // Replace the current executable with the downloaded curd
177    if err := os.Rename(tmpPath, executablePath); err != nil {
178        return fmt.Errorf("failed to replace the current executable: %v", err)
179    }
180    fmt.Println("Downloaded curd executable to", executablePath)
181
182	if runtime.GOOS != "windows" {
183		// Ensure the new file has executable permissions
184		if err := os.Chmod(executablePath, 0755); err != nil {
185			return fmt.Errorf("failed to set permissions on the new file: %v", err)
186		}
187	}
188	
189    return nil
190}
191
192func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
193	fmt.Println("Enter the anime name:")
194	var query string
195	fmt.Scanln(&query)
196	animeMap, err := SearchAnimeAnilist(query, user.Token)
197	if err != nil {
198		Log(fmt.Sprintf("Failed to search anime: %v", err), logFile)
199		ExitCurd(fmt.Errorf("Failed to search anime"))
200	}
201	anilistSelectedOption, err := DynamicSelect(animeMap)
202	if err != nil {
203		Log(fmt.Sprintf("No anime available: %v", err), logFile)
204		ExitCurd(fmt.Errorf("No anime available"))
205	}
206	animeID, err := strconv.Atoi(anilistSelectedOption.Key)
207	if err != nil {
208		Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err), logFile)
209		ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
210	}
211	err = AddAnimeToWatchingList(animeID, user.Token)
212	if err != nil {
213		Log(fmt.Sprintf("Failed to add anime to watching list: %v", err), logFile)
214		ExitCurd(fmt.Errorf("Failed to add anime to watching list"))
215	}
216	anilistUserData, err := GetUserData(user.Token, user.Id)
217	if err != nil {
218		Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
219		ExitCurd(fmt.Errorf("Failed to get user data"))
220	}
221	user.AnimeList = ParseAnimeList(anilistUserData)
222}
223
224func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime, logFile string) {
225	var err error
226
227	// Get user id, username and Anime list
228	user.Id, user.Username, err = GetAnilistUserID(user.Token)
229	if err != nil {
230		Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
231		ExitCurd(fmt.Errorf("Failed to get user ID"))
232	}
233	anilistUserData, err := GetUserData(user.Token, user.Id)
234	if err != nil {
235		Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
236		ExitCurd(fmt.Errorf("Failed to get user data"))
237	}
238	user.AnimeList = ParseAnimeList(anilistUserData)
239	animeListMap := GetAnimeMap(user.AnimeList)
240	var anilistSelectedOption SelectionOption
241	var selectedAllanimeAnime SelectionOption
242	var userQuery string
243
244	if anime.Ep.ContinueLast {
245		// Get the last watched anime ID from the curd_id file
246		curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
247		curdIDBytes, err := os.ReadFile(curdIDPath)
248		if err != nil {
249			Log(fmt.Sprintf("Error reading curd_id file: %v", err), logFile)
250			ExitCurd(fmt.Errorf("Error reading curd_id file"))
251		}
252
253		lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
254		if err != nil {
255			Log(fmt.Sprintf("Error converting curd_id to integer: %v", err), logFile)
256			ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
257		}
258
259		anime.AnilistId = lastWatchedID
260		anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
261	} else {
262		// Select anime to watch (Anilist)
263		var err error
264		anilistSelectedOption, err = DynamicSelect(animeListMap)
265		if err != nil {
266			Log(fmt.Sprintf("Error selecting anime: %v", err), logFile)
267			ExitCurd(fmt.Errorf("Error selecting anime"))
268		}
269
270		if anilistSelectedOption.Key == "-1" {
271			ExitCurd(nil)
272		}
273
274		if anilistSelectedOption.Label == "add_new" {
275			AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile)
276		}
277		
278		userQuery = anilistSelectedOption.Label
279		anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
280		if err != nil {
281			Log(fmt.Sprintf("Error converting Anilist ID: %v", err), logFile)
282			ExitCurd(fmt.Errorf("Error converting Anilist ID"))
283		}
284	}
285	// Find anime in Local history
286	animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")	
287	
288	// Get anime entry
289	selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
290	if err != nil {
291		Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err), logFile)
292		ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
293	}
294
295	// Set anime entry
296	anime.Title = selectedAnilistAnime.Media.Title
297	anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
298	anime.Ep.Number = selectedAnilistAnime.Progress+1
299
300	// if anime not found in database, find it in animeList
301	if animePointer == nil {
302		// Get Anime list (All anime)
303		animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
304		if err != nil {
305			Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
306			ExitCurd(fmt.Errorf("Failed to select anime"))
307		}
308		if len(animeList) == 0 {
309			// fmt.Println("No results found.")
310			ExitCurd(fmt.Errorf("No results found."))
311		}
312
313		// find anime in animeList
314		anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
315		if err != nil {
316			Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile)
317		}
318			
319		// If unable to get Allanime id automatically get manually
320		if anime.AllanimeId == "" {
321			fmt.Println("Failed to automatically select anime")
322			selectedAllanimeAnime, err := DynamicSelect(animeList)
323			if err != nil {
324				// fmt.Println("No anime available")
325				ExitCurd(fmt.Errorf("No anime available"))
326			}
327			anime.AllanimeId = selectedAllanimeAnime.Key
328		}
329	} else {
330		// if anime found in database, use it
331		anime.AllanimeId = animePointer.AllanimeId
332		anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
333		anime.Ep.Resume = true
334		anime.Ep.Number = animePointer.Ep.Number
335	}
336
337	// If upstream is ahead, update the episode number
338	if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
339		if temp_anime.Progress > anime.Ep.Number {
340			anime.Ep.Number = temp_anime.Progress
341			anime.Ep.Player.PlaybackTime = 0
342			anime.Ep.Resume = false
343		}
344	}
345
346	if anime.TotalEpisodes == 0 {
347		// Get updated anime data
348		Log(selectedAllanimeAnime, logFile)
349		updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
350		Log(updatedAnime, logFile)
351		if err != nil {
352			Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile)
353		} else {
354			anime.TotalEpisodes = updatedAnime.TotalEpisodes
355			Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile)
356		}
357	}
358
359	if anime.TotalEpisodes == 0 { // If failed to get anime data
360		fmt.Println("Failed to get anime data. Attempting to retrieve from anime list.")
361		animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
362		if err != nil {
363			fmt.Println("Failed to retrieve anime list:", err)
364		} else {
365			for allanimeId, label := range animeList {
366				if allanimeId == anime.AllanimeId {
367					// Extract total episodes from the label
368					if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
369						anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
370						fmt.Printf("Retrieved total episodes: %d\n", anime.TotalEpisodes)
371						break
372					}
373				}
374			}
375		}
376		
377		if anime.TotalEpisodes == 0 {
378			fmt.Println("Still unable to determine total episodes.")
379			fmt.Println("Your AniList progress:", selectedAnilistAnime.Progress)
380			fmt.Print("Enter the episode you want to start from: ")
381			var episodeNumber int
382			fmt.Scanln(&episodeNumber)
383			anime.Ep.Number = episodeNumber
384		} else {
385			anime.Ep.Number = selectedAnilistAnime.Progress + 1
386		}
387	} else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
388		Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
389		fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
390		var answer string
391		fmt.Scanln(&answer)
392		if answer == "y" {
393			anime.Ep.Number = 1
394		} else {
395			anime.Ep.Number = anime.TotalEpisodes
396		}
397	}
398
399}
400
401// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
402func WriteTokenToFile(token string, filePath string) error {
403    // Extract the directory path
404    dir := filepath.Dir(filePath)
405
406    // Create all necessary parent directories
407    if err := os.MkdirAll(dir, 0755); err != nil {
408        return fmt.Errorf("failed to create directories: %v", err)
409    }
410
411    // Write the token to the file, creating it if it doesn't exist
412    err := os.WriteFile(filePath, []byte(token), 0644)
413    if err != nil {
414        return fmt.Errorf("failed to write token to file: %v", err)
415    }
416
417    return nil
418}
419
420func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
421
422	// Get episode link
423	link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
424	if err != nil {
425		// If unable to get episode link automatically get manually
426		episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
427		if err != nil {
428			fmt.Println("No episode list found")
429			RestoreScreen()
430			os.Exit(1)
431		}
432		fmt.Printf("Enter the episode (%v episodes)\n", episodeList[len(episodeList)-1])
433		fmt.Scanln(&anime.Ep.Number)
434		link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
435		if err != nil {
436			fmt.Println("Failed to get episode link")
437			os.Exit(1)
438		}
439		// anime.Ep.Links = link
440	}
441	anime.Ep.Links = link
442
443	if len(anime.Ep.Links) == 0 {
444		fmt.Println("No episode links found")
445		os.Exit(1)
446	}
447
448	Log(anime, logFile)
449
450	// Write anime.AnilistId to curd_id in the storage path
451	idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
452	Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile)
453	if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
454		Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
455	} else {
456		if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
457			Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
458		}
459	}
460
461	mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{})
462
463	if err != nil {
464		Log("Failed to start mpv", logFile)
465		os.Exit(1)
466	}
467
468	return mpvSocketPath
469}
470