internal/curd.go

1203 lines · 37059 bytes

   1package internal
   2
   3import (
   4	"crypto/md5"
   5	"encoding/json"
   6	"fmt"
   7	"io"
   8	"net/http"
   9	"os"
  10	"os/exec"
  11	"path/filepath"
  12	"regexp"
  13	"runtime"
  14	"strconv"
  15	"strings"
  16	"time"
  17
  18	"github.com/gen2brain/beeep"
  19)
  20
  21func GetTokenFromFile(filePath string) (string, error) {
  22	// Read the token from the file
  23	data, err := os.ReadFile(filePath)
  24	if err != nil {
  25		return "", fmt.Errorf("failed to read token from file: %w", err)
  26	}
  27
  28	// Convert the byte slice to a string and remove any surrounding whitespace or newlines
  29	token := strings.TrimSpace(string(data))
  30
  31	return token, nil
  32}
  33
  34func EditConfig(configFilePath string) {
  35	// Get the user's preferred editor from the EDITOR environment variable
  36	editor := os.Getenv("EDITOR")
  37	if editor == "" {
  38		// If EDITOR is not set, use system-specific defaults
  39		if runtime.GOOS == "windows" {
  40			// Try Notepad++ first
  41			if _, err := exec.LookPath("notepad++"); err == nil {
  42				editor = "notepad++"
  43			} else {
  44				editor = "notepad.exe"
  45			}
  46		} else {
  47			editor = "vim"
  48		}
  49	}
  50
  51	// Construct the command to open the config file
  52	cmd := exec.Command(editor, configFilePath)
  53
  54	// Set the command to run in the current terminal
  55	cmd.Stdin = os.Stdin
  56	cmd.Stdout = os.Stdout
  57	cmd.Stderr = os.Stderr
  58
  59	// Run the editor command
  60	err := cmd.Run()
  61	if err != nil {
  62		CurdOut(fmt.Sprintf("Error opening config file: %v", err))
  63		return
  64	}
  65
  66	CurdOut("Config file edited successfully.")
  67}
  68
  69// ClearLogFile removes all contents from the specified log file
  70func ClearLogFile(logFile string) error {
  71	// Open the file with truncate flag to clear its contents
  72	file, err := os.OpenFile(logFile, os.O_WRONLY|os.O_TRUNC, 0666)
  73	if err != nil {
  74		return fmt.Errorf("failed to open log file: %w", err)
  75	}
  76	defer file.Close()
  77
  78	return nil
  79}
  80
  81// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
  82func Log(data interface{}) error {
  83	logFile := GetGlobalLogFile()
  84	// Open or create the log file
  85	file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
  86	if err != nil {
  87		return err
  88	}
  89	defer file.Close()
  90
  91	// Attempt to marshal the data into JSON
  92	jsonData, err := json.Marshal(data)
  93	if err != nil {
  94		return err
  95	}
  96
  97	// Get the caller information
  98	_, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
  99	if !ok {
 100		return fmt.Errorf("unable to get caller information")
 101	}
 102
 103	// Log the current time and the JSON representation along with caller info
 104	currentTime := time.Now().Format("2006/01/02 15:04:05")
 105	logMessage := fmt.Sprintf("[LOG] %s %s:%d: %s\n", currentTime, filename, lineNumber, jsonData)
 106	_, err = fmt.Fprint(file, logMessage) // Write to the file
 107	if err != nil {
 108		return err
 109	}
 110
 111	return nil
 112}
 113
 114// ClearScreen clears the terminal screen and saves the state
 115func ClearScreen() {
 116	userCurdConfig := GetGlobalConfig()
 117
 118	if userCurdConfig.AlternateScreen == false {
 119		return
 120	}
 121
 122	fmt.Print("\033[?1049h") // Switch to alternate screen buffer
 123	fmt.Print("\033[2J")     // Clear the entire screen
 124	fmt.Print("\033[H")      // Move cursor to the top left
 125}
 126
 127// RestoreScreen restores the original terminal state
 128func RestoreScreen() {
 129	userCurdConfig := GetGlobalConfig()
 130
 131	if userCurdConfig.AlternateScreen == false {
 132		return
 133	}
 134
 135	fmt.Print("\033[?1049l") // Switch back to the main screen buffer
 136}
 137
 138func ExitCurd(err error) {
 139	RestoreScreen()
 140
 141	anime := GetGlobalAnime()
 142	if anime != nil && anime.Ep.Player.SocketPath != "" {
 143		_, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
 144		if err != nil {
 145			Log("Error closing MPV: " + err.Error())
 146		}
 147	}
 148
 149	CurdOut("Have a great day!")
 150	if err != nil {
 151		CurdOut(err)
 152		if runtime.GOOS == "windows" {
 153			fmt.Println("Press Enter to exit")
 154			var wait string
 155			fmt.Scanln(&wait)
 156			os.Exit(1)
 157		} else {
 158			os.Exit(1)
 159		}
 160	}
 161	os.Exit(0)
 162}
 163
 164func CurdOut(data interface{}) {
 165	userCurdConfig := GetGlobalConfig()
 166	if userCurdConfig == nil {
 167		userCurdConfig = &CurdConfig{}
 168	}
 169	if !userCurdConfig.RofiSelection {
 170		fmt.Println(fmt.Sprintf("%v", data))
 171	} else {
 172		switch runtime.GOOS {
 173		case "windows":
 174			err := beeep.Notify(
 175				"Curd",
 176				fmt.Sprintf("%v", data),
 177				"",
 178			)
 179
 180			if err != nil {
 181				Log(fmt.Sprintf("Failed to send notification: %v", err))
 182			}
 183		case "linux":
 184			// Check if the input starts with "-i" for image notification
 185			dataStr := fmt.Sprintf("%v", data)
 186			if strings.HasPrefix(dataStr, "-i") && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
 187				// Split the string to get image path and message
 188				parts := strings.SplitN(dataStr, " ", 3)
 189				if len(parts) == 3 {
 190					// Remove quotes from the message
 191					message := strings.Trim(parts[2], "\"")
 192					cmd := exec.Command("notify-send",
 193						"-a", "Curd",
 194						"-h", "string:x-canonical-private-synchronous:curd-notification",
 195						"Curd",
 196						"-i", parts[1],
 197						message)
 198					err := cmd.Run()
 199					if err != nil {
 200						Log(fmt.Sprintf("%v", cmd))
 201						Log(fmt.Sprintf("Failed to send notification: %v", err))
 202					}
 203				}
 204			} else {
 205				cmd := exec.Command("notify-send",
 206					"-a", "Curd",
 207					"-h", "string:x-canonical-private-synchronous:curd-notification",
 208					"Curd",
 209					dataStr)
 210				err := cmd.Run()
 211				if err != nil {
 212					Log(fmt.Sprintf("%v", cmd))
 213					Log(fmt.Sprintf("Failed to send notification: %v", err))
 214				}
 215			}
 216		}
 217	}
 218}
 219
 220func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
 221	// Create update options map
 222	updateOptions := map[string]string{
 223		"CATEGORY": "Change Anime Category",
 224		"PROGRESS": "Change Progress",
 225		"SCORE":    "Add/Change Score",
 226	}
 227
 228	// Select update option
 229	updateSelection, err := DynamicSelect(updateOptions, false)
 230	if err != nil {
 231		Log(fmt.Sprintf("Failed to select update option: %v", err))
 232		ExitCurd(fmt.Errorf("Failed to select update option"))
 233	}
 234
 235	if updateSelection.Key == "-1" {
 236		ExitCurd(nil)
 237	}
 238
 239	// Get user's anime list
 240	var animeListMap map[string]string
 241	var animeListMapPreview map[string]RofiSelectPreview
 242
 243	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 244		animeListMapPreview = make(map[string]RofiSelectPreview)
 245		// Include anime from all categories
 246		for _, entry := range user.AnimeList.Watching {
 247			title := entry.Media.Title.English
 248			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 249				title = entry.Media.Title.Romaji
 250			}
 251			animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 252				Title:      title,
 253				CoverImage: entry.CoverImage,
 254			}
 255		}
 256		for _, entry := range user.AnimeList.Completed {
 257			title := entry.Media.Title.English
 258			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 259				title = entry.Media.Title.Romaji
 260			}
 261			animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 262				Title:      title,
 263				CoverImage: entry.CoverImage,
 264			}
 265		}
 266		for _, entry := range user.AnimeList.Paused {
 267			title := entry.Media.Title.English
 268			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 269				title = entry.Media.Title.Romaji
 270			}
 271			animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 272				Title:      title,
 273				CoverImage: entry.CoverImage,
 274			}
 275		}
 276		for _, entry := range user.AnimeList.Dropped {
 277			title := entry.Media.Title.English
 278			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 279				title = entry.Media.Title.Romaji
 280			}
 281			animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 282				Title:      title,
 283				CoverImage: entry.CoverImage,
 284			}
 285		}
 286		for _, entry := range user.AnimeList.Planning {
 287			title := entry.Media.Title.English
 288			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 289				title = entry.Media.Title.Romaji
 290			}
 291			animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 292				Title:      title,
 293				CoverImage: entry.CoverImage,
 294			}
 295		}
 296	} else {
 297		animeListMap = make(map[string]string)
 298		// Include anime from all categories
 299		for _, entry := range user.AnimeList.Watching {
 300			title := entry.Media.Title.English
 301			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 302				title = entry.Media.Title.Romaji
 303			}
 304			animeListMap[strconv.Itoa(entry.Media.ID)] = title
 305		}
 306		for _, entry := range user.AnimeList.Completed {
 307			title := entry.Media.Title.English
 308			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 309				title = entry.Media.Title.Romaji
 310			}
 311			animeListMap[strconv.Itoa(entry.Media.ID)] = title
 312		}
 313		for _, entry := range user.AnimeList.Paused {
 314			title := entry.Media.Title.English
 315			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 316				title = entry.Media.Title.Romaji
 317			}
 318			animeListMap[strconv.Itoa(entry.Media.ID)] = title
 319		}
 320		for _, entry := range user.AnimeList.Dropped {
 321			title := entry.Media.Title.English
 322			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 323				title = entry.Media.Title.Romaji
 324			}
 325			animeListMap[strconv.Itoa(entry.Media.ID)] = title
 326		}
 327		for _, entry := range user.AnimeList.Planning {
 328			title := entry.Media.Title.English
 329			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 330				title = entry.Media.Title.Romaji
 331			}
 332			animeListMap[strconv.Itoa(entry.Media.ID)] = title
 333		}
 334	}
 335
 336	// Select anime to update
 337	var selectedAnime SelectionOption
 338	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 339		selectedAnime, err = DynamicSelectPreview(animeListMapPreview, false)
 340	} else {
 341		selectedAnime, err = DynamicSelect(animeListMap, false)
 342	}
 343	if err != nil {
 344		Log(fmt.Sprintf("Failed to select anime: %v", err))
 345		ExitCurd(fmt.Errorf("Failed to select anime"))
 346	}
 347
 348	if selectedAnime.Key == "-1" {
 349		ExitCurd(nil)
 350	}
 351
 352	animeID, err := strconv.Atoi(selectedAnime.Key)
 353	if err != nil {
 354		Log(fmt.Sprintf("Failed to convert anime ID: %v", err))
 355		ExitCurd(fmt.Errorf("Failed to convert anime ID"))
 356	}
 357
 358	// After getting animeID, get the current anime entry
 359	selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key)
 360	if err != nil {
 361		Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err))
 362		ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
 363	}
 364	ClearScreen()
 365	switch updateSelection.Key {
 366	case "CATEGORY":
 367		categories := map[string]string{
 368			"CURRENT":   "Currently Watching",
 369			"COMPLETED": "Completed",
 370			"PAUSED":    "On Hold",
 371			"DROPPED":   "Dropped",
 372			"PLANNING":  "Plan to Watch",
 373		}
 374
 375		currentStatus := "None"
 376		if selectedAnilistAnime.Status != "" {
 377			currentStatus = categories[selectedAnilistAnime.Status]
 378		}
 379		CurdOut(fmt.Sprintf("Current category: %s", currentStatus))
 380
 381		categorySelection, err := DynamicSelect(categories, false)
 382		if err != nil {
 383			Log(fmt.Sprintf("Failed to select category: %v", err))
 384			ExitCurd(fmt.Errorf("Failed to select category"))
 385		}
 386
 387		if categorySelection.Key == "-1" {
 388			ExitCurd(nil)
 389		}
 390
 391		err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
 392		if err != nil {
 393			Log(fmt.Sprintf("Failed to update anime status: %v", err))
 394			ExitCurd(fmt.Errorf("Failed to update anime status"))
 395		}
 396
 397	case "PROGRESS":
 398		currentProgress := "None"
 399		if selectedAnilistAnime.Progress > 0 {
 400			currentProgress = strconv.Itoa(selectedAnilistAnime.Progress)
 401		}
 402
 403		var progress string
 404		if userCurdConfig.RofiSelection {
 405			progress, err = GetUserInputFromRofi(fmt.Sprintf("Current progress: %s\nEnter new progress (episode number)", currentProgress))
 406			if err != nil {
 407				Log(fmt.Sprintf("Failed to get progress input: %v", err))
 408				ExitCurd(fmt.Errorf("Failed to get progress input"))
 409			}
 410		} else {
 411			CurdOut(fmt.Sprintf("Current progress: %s", currentProgress))
 412			CurdOut("Enter new progress (episode number):")
 413			fmt.Scanln(&progress)
 414		}
 415
 416		progressNum, err := strconv.Atoi(progress)
 417		if err != nil {
 418			Log(fmt.Sprintf("Failed to convert progress to number: %v", err))
 419			ExitCurd(fmt.Errorf("Failed to convert progress to number"))
 420		}
 421
 422		err = UpdateAnimeProgress(user.Token, animeID, progressNum)
 423		if err != nil {
 424			Log(fmt.Sprintf("Failed to update anime progress: %v", err))
 425			ExitCurd(fmt.Errorf("Failed to update anime progress"))
 426		}
 427
 428	case "SCORE":
 429		currentScore := "None"
 430		if selectedAnilistAnime.Score > 0 {
 431			currentScore = strconv.Itoa(int(selectedAnilistAnime.Score))
 432		}
 433		CurdOut(fmt.Sprintf("Current score: %s", currentScore))
 434
 435		err = RateAnime(user.Token, animeID)
 436		if err != nil {
 437			Log(fmt.Sprintf("Failed to update anime score: %v", err))
 438			ExitCurd(fmt.Errorf("Failed to update anime score"))
 439		}
 440	}
 441
 442	CurdOut("Anime updated successfully!")
 443}
 444
 445func UpdateCurd(repo, fileName string) error {
 446	// Get the path of the currently running executable
 447	executablePath, err := os.Executable()
 448	if err != nil {
 449		return fmt.Errorf("unable to find current executable: %v", err)
 450	}
 451
 452	// Determine the correct binary name based on OS and architecture
 453	var binaryName string
 454	switch runtime.GOOS {
 455	case "windows":
 456		if strings.HasSuffix(executablePath, "curd.exe") {
 457			binaryName = "curd-windows.exe"
 458		}
 459	case "darwin": // macOS
 460		switch runtime.GOARCH {
 461		case "amd64":
 462			binaryName = "curd-macos-x86_64"
 463		case "arm64":
 464			binaryName = "curd-macos-arm64"
 465		default:
 466			binaryName = "curd-macos-universal"
 467		}
 468	case "linux":
 469		if runtime.GOARCH == "amd64" {
 470			binaryName = "curd-linux-x86_64"
 471		} else {
 472			return fmt.Errorf("unsupported Linux architecture: %s", runtime.GOARCH)
 473		}
 474	default:
 475		return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
 476	}
 477
 478	// GitHub release URL for curd
 479	url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName)
 480
 481	// Temporary path for the downloaded curd executable
 482	tmpPath := executablePath + ".tmp"
 483
 484	// Download the curd executable
 485	resp, err := http.Get(url)
 486	if err != nil {
 487		return fmt.Errorf("failed to download file: %v", err)
 488	}
 489	defer resp.Body.Close()
 490
 491	// Check if the download was successful
 492	if resp.StatusCode != http.StatusOK {
 493		return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
 494	}
 495
 496	// Create a new temporary file
 497	out, err := os.Create(tmpPath)
 498	if err != nil {
 499		return fmt.Errorf("failed to create temporary file: %v", err)
 500	}
 501	defer out.Close()
 502
 503	// Write the downloaded content to the temporary file
 504	_, err = io.Copy(out, resp.Body)
 505	if err != nil {
 506		return fmt.Errorf("failed to save downloaded file: %v", err)
 507	}
 508
 509	// Close and rename the temporary file to replace the current executable
 510	out.Close()
 511
 512	// Replace the current executable with the downloaded curd
 513	if err := os.Rename(tmpPath, executablePath); err != nil {
 514		return fmt.Errorf("failed to replace the current executable: %v", err)
 515	}
 516	CurdOut(fmt.Sprintf("Downloaded curd executable to %v", executablePath))
 517
 518	if runtime.GOOS != "windows" {
 519		// Ensure the new file has executable permissions
 520		if err := os.Chmod(executablePath, 0755); err != nil {
 521			return fmt.Errorf("failed to set permissions on the new file: %v", err)
 522		}
 523	}
 524
 525	return nil
 526}
 527
 528func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
 529	var query string
 530	var animeMap map[string]string
 531	var animeMapPreview map[string]RofiSelectPreview
 532	var err error
 533	var anilistSelectedOption SelectionOption
 534
 535	if userCurdConfig.RofiSelection {
 536		userInput, err := GetUserInputFromRofi("Enter the anime name")
 537		if err != nil {
 538			Log("Error getting user input: " + err.Error())
 539			ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
 540		}
 541		query = userInput
 542	} else {
 543		CurdOut("Enter the anime name:")
 544		fmt.Scanln(&query)
 545	}
 546	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 547		animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
 548	} else {
 549		animeMap, err = SearchAnimeAnilist(query, user.Token)
 550	}
 551	if err != nil {
 552		Log(fmt.Sprintf("Failed to search anime: %v", err))
 553		ExitCurd(fmt.Errorf("Failed to search anime"))
 554	}
 555	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 556		anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
 557	} else {
 558		anilistSelectedOption, err = DynamicSelect(animeMap, false)
 559	}
 560
 561	if anilistSelectedOption.Key == "-1" {
 562		ExitCurd(nil)
 563	}
 564
 565	if err != nil {
 566		Log(fmt.Sprintf("No anime available: %v", err))
 567		ExitCurd(fmt.Errorf("No anime available"))
 568	}
 569	animeID, err := strconv.Atoi(anilistSelectedOption.Key)
 570	if err != nil {
 571		Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err))
 572		ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
 573	}
 574
 575	// Add category selection before adding to list
 576	categories := map[string]string{
 577		"CURRENT":   "Currently Watching",
 578		"COMPLETED": "Completed",
 579		"PAUSED":    "On Hold",
 580		"DROPPED":   "Dropped",
 581		"PLANNING":  "Plan to Watch",
 582	}
 583
 584	ClearScreen()
 585	CurdOut("Select which list to add the anime to:")
 586
 587	categorySelection, err := DynamicSelect(categories, false)
 588	if err != nil {
 589		Log(fmt.Sprintf("Failed to select category: %v", err))
 590		ExitCurd(fmt.Errorf("Failed to select category"))
 591	}
 592
 593	if categorySelection.Key == "-1" {
 594		ExitCurd(nil)
 595	}
 596
 597	err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
 598	if err != nil {
 599		Log(fmt.Sprintf("Failed to add anime to list: %v", err))
 600		ExitCurd(fmt.Errorf("Failed to add anime to list"))
 601	}
 602
 603	// Refresh user's anime list after adding
 604	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 605		anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id)
 606		if err != nil {
 607			Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
 608			ExitCurd(fmt.Errorf("Failed to refresh anime list"))
 609		}
 610		user.AnimeList = ParseAnimeList(anilistUserDataPreview)
 611	} else {
 612		anilistUserData, err := GetUserData(user.Token, user.Id)
 613		if err != nil {
 614			Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
 615			ExitCurd(fmt.Errorf("Failed to refresh anime list"))
 616		}
 617		user.AnimeList = ParseAnimeList(anilistUserData)
 618	}
 619
 620	return anilistSelectedOption
 621}
 622
 623func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) {
 624	var err error
 625	var anilistUserData map[string]interface{}
 626	var anilistUserDataPreview map[string]interface{}
 627
 628	// Filter anime list based on selected category
 629	var animeListMap map[string]string
 630	var animeListMapPreview map[string]RofiSelectPreview
 631
 632	// Get user id, username and Anime list
 633	user.Id, user.Username, err = GetAnilistUserID(user.Token)
 634	if err != nil {
 635		Log(fmt.Sprintf("Failed to get user ID: %v", err))
 636		ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
 637	}
 638
 639	// Get the anime list data
 640	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 641		anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
 642		if err != nil {
 643			Log(fmt.Sprintf("Failed to get user data preview: %v", err))
 644			ExitCurd(fmt.Errorf("Failed to get user data preview"))
 645		}
 646		user.AnimeList = ParseAnimeList(anilistUserDataPreview)
 647	} else {
 648		anilistUserData, err = GetUserData(user.Token, user.Id)
 649		if err != nil {
 650			Log(fmt.Sprintf("Failed to get user data: %v", err))
 651			ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
 652		}
 653		user.AnimeList = ParseAnimeList(anilistUserData)
 654	}
 655
 656	// If continueLast flag is set, directly get the last watched anime
 657	if anime.Ep.ContinueLast {
 658		// Get the last anime ID from the curd_id file
 659		idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
 660		idBytes, err := os.ReadFile(idFilePath)
 661		if err != nil {
 662			Log("Error reading curd_id file: " + err.Error())
 663			ExitCurd(fmt.Errorf("No last watched anime found"))
 664		}
 665
 666		anilistID, err := strconv.Atoi(string(idBytes))
 667		if err != nil {
 668			Log("Error converting anilist ID: " + err.Error())
 669			ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
 670		}
 671
 672		// Find the anime in database
 673		animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
 674		if animePointer == nil {
 675			ExitCurd(fmt.Errorf("Last watched anime not found in database"))
 676		}
 677
 678		// Set the anime details
 679		anime.AnilistId = animePointer.AnilistId
 680		// anime.AllanimeId = animePointer.AllanimeId
 681		// anime.Title = animePointer.Title
 682		// anime.Ep.Number = animePointer.Ep.Number
 683		// anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
 684		// anime.Ep.Resume = true
 685
 686	} else {
 687		// Skip category selection if Current flag is set
 688		var categorySelection SelectionOption
 689		if userCurdConfig.CurrentCategory {
 690			categorySelection = SelectionOption{
 691				Key:   "CURRENT",
 692				Label: "Currently Watching",
 693			}
 694		} else {
 695			// Create category selection map
 696			categories := map[string]string{
 697				"CURRENT":       "Currently Watching",
 698				"ALL":           "Show All",
 699				"UNTRACKED":     "Untracked Watching",
 700				"UPDATE":        "Update (Episode, Status, Score)",
 701				"CONTINUE_LAST": "Continue Last Session",
 702			}
 703
 704			// Select category using DynamicSelect
 705			var err error
 706			categorySelection, err = DynamicSelect(categories, false)
 707			if err != nil {
 708				Log(fmt.Sprintf("Failed to select category: %v", err))
 709				ExitCurd(fmt.Errorf("Failed to select category"))
 710			}
 711
 712			if categorySelection.Key == "-1" {
 713				ExitCurd(nil)
 714			}
 715
 716			// Handle options
 717			if categorySelection.Key == "UPDATE" {
 718				ClearScreen()
 719				UpdateAnimeEntry(userCurdConfig, user)
 720				ExitCurd(nil)
 721			} else if categorySelection.Key == "UNTRACKED" {
 722				ClearScreen()
 723				WatchUntracked(userCurdConfig)
 724			} else if categorySelection.Key == "CONTINUE_LAST" {
 725				anime.Ep.ContinueLast = true
 726			}
 727
 728			ClearScreen()
 729		}
 730
 731		if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 732			animeListMapPreview = make(map[string]RofiSelectPreview)
 733			for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
 734				title := entry.Media.Title.English
 735				if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 736					title = entry.Media.Title.Romaji
 737				}
 738				animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 739					Title:      title,
 740					CoverImage: entry.CoverImage,
 741				}
 742			}
 743		} else {
 744			animeListMap = make(map[string]string)
 745			for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
 746				title := entry.Media.Title.English
 747				if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 748					title = entry.Media.Title.Romaji
 749				}
 750				animeListMap[strconv.Itoa(entry.Media.ID)] = title
 751			}
 752		}
 753	}
 754
 755	var anilistSelectedOption SelectionOption
 756	var selectedAllanimeAnime SelectionOption
 757	var userQuery string
 758
 759	if anime.Ep.ContinueLast {
 760		// Get the last watched anime ID from the curd_id file
 761		curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
 762		curdIDBytes, err := os.ReadFile(curdIDPath)
 763		if err != nil {
 764			Log(fmt.Sprintf("Error reading curd_id file: %v", err))
 765			ExitCurd(fmt.Errorf("Error reading curd_id file"))
 766		}
 767
 768		lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
 769		if err != nil {
 770			Log(fmt.Sprintf("Error converting curd_id to integer: %v", err))
 771			ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
 772		}
 773
 774		anime.AnilistId = lastWatchedID
 775		anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
 776	} else {
 777		// Select anime to watch (Anilist)
 778		var err error
 779		if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 780			anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
 781		} else {
 782			anilistSelectedOption, err = DynamicSelect(animeListMap, true)
 783		}
 784		if err != nil {
 785			Log(fmt.Sprintf("Error selecting anime: %v", err))
 786			ExitCurd(fmt.Errorf("Error selecting anime"))
 787		}
 788
 789		Log(anilistSelectedOption)
 790
 791		if anilistSelectedOption.Key == "-1" {
 792			ExitCurd(nil)
 793		}
 794
 795		if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
 796			anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes)
 797		}
 798
 799		anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
 800		if err != nil {
 801			Log(fmt.Sprintf("Error converting Anilist ID: %v", err))
 802			ExitCurd(fmt.Errorf("Error converting Anilist ID"))
 803		}
 804	}
 805	// Find anime in Local history
 806	animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
 807
 808	// Get anime entry
 809	selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
 810	if err != nil {
 811		Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err))
 812		ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
 813	}
 814
 815	// Set anime entry
 816	anime.Title = selectedAnilistAnime.Media.Title
 817	anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
 818	anime.Ep.Number = selectedAnilistAnime.Progress + 1
 819	var animeList map[string]string
 820	userQuery = anime.Title.Romaji
 821
 822	// if anime not found in database, find it in animeList
 823	if animePointer == nil {
 824		Log("Anime not found in database, searching in animeList...")
 825		// Get Anime list (All anime)
 826		Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
 827
 828		animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
 829		Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err))
 830		if err != nil {
 831			Log(fmt.Sprintf("Failed to select anime: %v", err))
 832			ExitCurd(fmt.Errorf("Failed to select anime"))
 833		}
 834		if len(animeList) == 0 {
 835			ExitCurd(fmt.Errorf("No results found."))
 836		}
 837
 838		// find anime in animeList
 839		anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
 840		if err != nil {
 841			Log(fmt.Sprintf("Failed to find anime in animeList: %v", err))
 842		}
 843
 844		// If unable to get Allanime id automatically get manually
 845		if anime.AllanimeId == "" {
 846			CurdOut("Failed to automatically select anime")
 847			selectedAllanimeAnime, err := DynamicSelect(animeList, false)
 848
 849			if selectedAllanimeAnime.Key == "-1" {
 850				ExitCurd(nil)
 851			}
 852
 853			if err != nil {
 854				// fmt.Println("No anime available")
 855				ExitCurd(fmt.Errorf("No anime available"))
 856			}
 857			anime.AllanimeId = selectedAllanimeAnime.Key
 858		}
 859	} else {
 860		// if anime found in database, use it
 861		anime.AllanimeId = animePointer.AllanimeId
 862		anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
 863		if anime.Ep.Number == animePointer.Ep.Number {
 864			anime.Ep.Resume = true
 865		}
 866	}
 867
 868	if selectedAllanimeAnime.Key == "-1" {
 869		ExitCurd(nil)
 870	}
 871
 872	// If anime is not in watching list, prompt user to add it into watching list
 873	isInWatchingList := false
 874	for _, entry := range user.AnimeList.Watching {
 875		if entry.Media.ID == anime.AnilistId {
 876			isInWatchingList = true
 877			break
 878		}
 879	}
 880
 881	if !isInWatchingList {
 882		// Create options for the prompt
 883		options := map[string]string{
 884			"yes": "Add to watching list",
 885			"no":  "Continue without adding",
 886		}
 887
 888		var selectedOption SelectionOption
 889		var err error
 890
 891		// Use rofi for selection
 892		selectedOption, err = DynamicSelect(options, false)
 893		if err != nil {
 894			Log("Error in selection: " + err.Error())
 895			ExitCurd(err)
 896		}
 897
 898		if selectedOption.Key == "yes" {
 899			err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
 900			if err != nil {
 901				Log("Error adding anime to watching list: " + err.Error())
 902				ExitCurd(err)
 903			}
 904			// Refresh user's anime list after adding
 905			if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 906				anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id)
 907				if err != nil {
 908					Log("Error refreshing anime list: " + err.Error())
 909					ExitCurd(err)
 910				}
 911				user.AnimeList = ParseAnimeList(anilistUserDataPreview)
 912			} else {
 913				anilistUserData, err := GetUserData(user.Token, user.Id)
 914				if err != nil {
 915					Log("Error refreshing anime list: " + err.Error())
 916					ExitCurd(err)
 917				}
 918				user.AnimeList = ParseAnimeList(anilistUserData)
 919			}
 920		} else if selectedOption.Key == "-1" {
 921			ExitCurd(nil)
 922		}
 923	}
 924
 925	// If upstream is ahead, update the episode number
 926	if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
 927		if temp_anime.Progress > anime.Ep.Number {
 928			anime.Ep.Number = temp_anime.Progress
 929			anime.Ep.Player.PlaybackTime = 0
 930			anime.Ep.Resume = false
 931		}
 932	}
 933
 934	if anime.TotalEpisodes == 0 {
 935		// Get updated anime data
 936		Log(selectedAllanimeAnime)
 937		updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
 938		Log(updatedAnime)
 939		if err != nil {
 940			Log(fmt.Sprintf("Error getting updated anime data: %v", err))
 941		} else {
 942			anime.TotalEpisodes = updatedAnime.TotalEpisodes
 943			Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
 944		}
 945	}
 946
 947	if anime.TotalEpisodes == 0 { // If failed to get anime data
 948		CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
 949		animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
 950		if err != nil {
 951			CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
 952		} else {
 953			for allanimeId, label := range animeList {
 954				if allanimeId == anime.AllanimeId {
 955					// Extract total episodes from the label
 956					if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
 957						anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
 958						CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
 959						break
 960					}
 961				}
 962			}
 963		}
 964
 965		if anime.TotalEpisodes == 0 {
 966			CurdOut("Still unable to determine total episodes.")
 967			CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
 968			var episodeNumber int
 969			if userCurdConfig.RofiSelection {
 970				userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
 971				if err != nil {
 972					Log("Error getting user input: " + err.Error())
 973					ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
 974				}
 975				episodeNumber, err = strconv.Atoi(userInput)
 976			} else {
 977				fmt.Print("Enter the episode you want to start from: ")
 978				fmt.Scanln(&episodeNumber)
 979			}
 980			anime.Ep.Number = episodeNumber
 981		} else {
 982			anime.Ep.Number = selectedAnilistAnime.Progress + 1
 983		}
 984	} else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
 985		Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
 986		var answer string
 987		if userCurdConfig.RofiSelection {
 988			userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
 989			if err != nil {
 990				Log("Error getting user input: " + err.Error())
 991				ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
 992			}
 993			answer = userInput
 994		} else {
 995			fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
 996			fmt.Scanln(&answer)
 997		}
 998		if answer == "y" {
 999			anime.Ep.Number = 1
1000		} else {
1001			anime.Ep.Number = anime.TotalEpisodes
1002		}
1003	}
1004
1005}
1006
1007// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
1008func WriteTokenToFile(token string, filePath string) error {
1009	// Extract the directory path
1010	dir := filepath.Dir(filePath)
1011
1012	// Create all necessary parent directories
1013	if err := os.MkdirAll(dir, 0755); err != nil {
1014		return fmt.Errorf("failed to create directories: %v", err)
1015	}
1016
1017	// Write the token to the file, creating it if it doesn't exist
1018	err := os.WriteFile(filePath, []byte(token), 0644)
1019	if err != nil {
1020		return fmt.Errorf("failed to write token to file: %v", err)
1021	}
1022
1023	return nil
1024}
1025
1026func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1027
1028	if anime.Ep.NextEpisode.Number == anime.Ep.Number {
1029		anime.Ep.Links = anime.Ep.NextEpisode.Links
1030		fmt.Println("using prefetched next episode link")
1031	} else {
1032		// Get episode link
1033		link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1034		if err != nil {
1035			// If unable to get episode link automatically get manually
1036			episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
1037			if err != nil {
1038				CurdOut("No episode list found")
1039				RestoreScreen()
1040				os.Exit(1)
1041			}
1042			if userCurdConfig.RofiSelection {
1043				userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1044				if err != nil {
1045					Log("Error getting user input: " + err.Error())
1046					ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1047				}
1048				anime.Ep.Number, err = strconv.Atoi(userInput)
1049			} else {
1050				CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1051				fmt.Scanln(&anime.Ep.Number)
1052			}
1053			link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1054			if err != nil {
1055				CurdOut("Failed to get episode link")
1056				os.Exit(1)
1057			}
1058			// anime.Ep.Links = link
1059		}
1060		anime.Ep.Links = link
1061	}
1062
1063	if len(anime.Ep.Links) == 0 {
1064		CurdOut("No episode links found")
1065		os.Exit(1)
1066	}
1067
1068	Log(anime)
1069
1070	// Modify the goroutine in main.go where next episode links are fetched
1071	// Get next episode link in parallel
1072	go func() {
1073		nextEpNum := anime.Ep.Number + 1
1074		if nextEpNum <= anime.TotalEpisodes {
1075			// Get next canon episode number if filler skip is enabled
1076			if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) {
1077				nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum)
1078			}
1079			nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum)
1080			if err != nil {
1081				Log("Error getting next episode link: " + err.Error())
1082			} else {
1083				anime.Ep.NextEpisode = NextEpisode{
1084					Number: nextEpNum,
1085					Links:  nextLinks,
1086				}
1087				Log(fmt.Sprintf("Next episode link fetched for ep %d", nextEpNum))
1088			}
1089		}
1090	}()
1091
1092	// Write anime.AnilistId to curd_id in the storage path
1093	idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1094	Log(fmt.Sprintf("idFilePath: %v", idFilePath))
1095	if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
1096		Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err))
1097	} else {
1098		if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
1099			Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err))
1100		}
1101	}
1102
1103	// Display starting message with cover image and episode info
1104	if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
1105		// Get the cached image path
1106		cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
1107		filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
1108		cachePath := filepath.Join(cacheDir, filename)
1109
1110		// Display the image if it exists in cache
1111		_, err := os.Stat(cachePath)
1112		if err == nil {
1113			// File exists
1114			Log(fmt.Sprintf("Image found at %s", cachePath))
1115			CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
1116		} else {
1117			// File does not exist
1118			Log(fmt.Sprintf("Image does not exist at %s", cachePath))
1119			CurdOut(fmt.Sprintf("%s - Episode %d",
1120				GetAnimeName(*anime),
1121				anime.Ep.Number))
1122
1123		}
1124	} else {
1125		CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
1126	}
1127	mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number), anime)
1128
1129	if err != nil {
1130		Log("Failed to start mpv")
1131		os.Exit(1)
1132	}
1133
1134	return mpvSocketPath
1135}
1136
1137func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1138	// Create storage directory if it doesn't exist
1139	storagePath = os.ExpandEnv(storagePath)
1140	if err := os.MkdirAll(storagePath, 0755); err != nil {
1141		return fmt.Errorf("failed to create storage directory: %v", err)
1142	}
1143
1144	// Base URL for downloading config files
1145	baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
1146
1147	// Check each file
1148	for _, fileName := range filesToCheck {
1149		filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
1150
1151		// Skip if file already exists
1152		if _, err := os.Stat(filePath); err == nil {
1153			continue
1154		}
1155
1156		// Download file if it doesn't exist
1157		resp, err := http.Get(baseURL + fileName)
1158		if err != nil {
1159			return fmt.Errorf("failed to download %s: %v", fileName, err)
1160		}
1161		defer resp.Body.Close()
1162
1163		// Create the file
1164		out, err := os.Create(filePath)
1165		if err != nil {
1166			return fmt.Errorf("failed to create file %s: %v", fileName, err)
1167		}
1168		defer out.Close()
1169
1170		// Write the content
1171		if _, err := io.Copy(out, resp.Body); err != nil {
1172			return fmt.Errorf("failed to write file %s: %v", fileName, err)
1173		}
1174	}
1175
1176	return nil
1177}
1178
1179func getEntriesByCategory(list AnimeList, category string) []Entry {
1180	switch category {
1181	case "ALL":
1182		// Combine all categories into one slice
1183		allEntries := make([]Entry, 0)
1184		allEntries = append(allEntries, list.Watching...)
1185		allEntries = append(allEntries, list.Completed...)
1186		allEntries = append(allEntries, list.Paused...)
1187		allEntries = append(allEntries, list.Dropped...)
1188		allEntries = append(allEntries, list.Planning...)
1189		return allEntries
1190	case "CURRENT":
1191		return list.Watching
1192	case "COMPLETED":
1193		return list.Completed
1194	case "PAUSED":
1195		return list.Paused
1196	case "DROPPED":
1197		return list.Dropped
1198	case "PLANNING":
1199		return list.Planning
1200	default:
1201		return []Entry{}
1202	}
1203}