internal/curd.go

500 lines · 15577 bytes

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