internal/curd.go

1187 lines · 36742 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	var anilistUserData map[string]interface{}
 535	var anilistUserDataPreview map[string]interface{}
 536
 537	if userCurdConfig.RofiSelection {
 538		userInput, err := GetUserInputFromRofi("Enter the anime name")
 539		if err != nil {
 540			Log("Error getting user input: "+err.Error())
 541			ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
 542		}
 543		query = userInput
 544	} else {
 545		CurdOut("Enter the anime name:")
 546		fmt.Scanln(&query)
 547	}
 548	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 549		animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
 550	} else {
 551		animeMap, err = SearchAnimeAnilist(query, user.Token)
 552	}
 553	if err != nil {
 554		Log(fmt.Sprintf("Failed to search anime: %v", err))
 555		ExitCurd(fmt.Errorf("Failed to search anime"))
 556	}
 557	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 558		anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
 559	} else {
 560		anilistSelectedOption, err = DynamicSelect(animeMap, false)
 561	}
 562
 563	if anilistSelectedOption.Key == "-1" {
 564		ExitCurd(nil)
 565	}
 566
 567	if err != nil {
 568		Log(fmt.Sprintf("No anime available: %v", err))
 569		ExitCurd(fmt.Errorf("No anime available"))
 570	}
 571	animeID, err := strconv.Atoi(anilistSelectedOption.Key)
 572	if err != nil {
 573		Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err))
 574		ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
 575	}
 576	err = AddAnimeToWatchingList(animeID, user.Token)
 577	if err != nil {
 578		Log(fmt.Sprintf("Failed to add anime to watching list: %v", err))
 579		ExitCurd(fmt.Errorf("Failed to add anime to watching list"))
 580	}
 581	if user.Id == 0 {
 582		user.Id, user.Username, err = GetAnilistUserID(user.Token)
 583		if err != nil {
 584			Log(fmt.Sprintf("Failed to get user ID: %v", err))
 585			ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
 586		}
 587	}
 588	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 589		anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
 590	} else {
 591		anilistUserData, err = GetUserData(user.Token, user.Id)
 592	}
 593	if err != nil {
 594		Log(fmt.Sprintf("Failed to get user data: %v", err))
 595		ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
 596	}
 597	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 598		user.AnimeList = ParseAnimeList(anilistUserDataPreview)
 599	} else {
 600		user.AnimeList = ParseAnimeList(anilistUserData)
 601	}
 602
 603	return anilistSelectedOption
 604}
 605
 606func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) {
 607	var err error
 608	var anilistUserData map[string]interface{}
 609	var anilistUserDataPreview map[string]interface{}
 610
 611	// Filter anime list based on selected category
 612	var animeListMap map[string]string
 613	var animeListMapPreview map[string]RofiSelectPreview
 614
 615	// Get user id, username and Anime list
 616	user.Id, user.Username, err = GetAnilistUserID(user.Token)
 617	if err != nil {
 618		Log(fmt.Sprintf("Failed to get user ID: %v", err))
 619		ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
 620	}
 621
 622	// Get the anime list data
 623	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 624		anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
 625		if err != nil {
 626			Log(fmt.Sprintf("Failed to get user data preview: %v", err))
 627			ExitCurd(fmt.Errorf("Failed to get user data preview"))
 628		}
 629		user.AnimeList = ParseAnimeList(anilistUserDataPreview)
 630	} else {
 631		anilistUserData, err = GetUserData(user.Token, user.Id)
 632		if err != nil {
 633			Log(fmt.Sprintf("Failed to get user data: %v", err))
 634			ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
 635		}
 636		user.AnimeList = ParseAnimeList(anilistUserData)
 637	}
 638
 639	// If continueLast flag is set, directly get the last watched anime
 640	if anime.Ep.ContinueLast {
 641		// Get the last anime ID from the curd_id file
 642		idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
 643		idBytes, err := os.ReadFile(idFilePath)
 644		if err != nil {
 645			Log("Error reading curd_id file: "+err.Error())
 646			ExitCurd(fmt.Errorf("No last watched anime found"))
 647		}
 648
 649		anilistID, err := strconv.Atoi(string(idBytes))
 650		if err != nil {
 651			Log("Error converting anilist ID: "+err.Error())
 652			ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
 653		}
 654
 655		// Find the anime in database
 656		animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
 657		if animePointer == nil {
 658			ExitCurd(fmt.Errorf("Last watched anime not found in database"))
 659		}
 660
 661		// Set the anime details
 662		anime.AnilistId = animePointer.AnilistId
 663		// anime.AllanimeId = animePointer.AllanimeId
 664		// anime.Title = animePointer.Title
 665		// anime.Ep.Number = animePointer.Ep.Number
 666		// anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
 667		// anime.Ep.Resume = true
 668
 669	} else {
 670		// Skip category selection if Current flag is set
 671		var categorySelection SelectionOption
 672		if userCurdConfig.CurrentCategory {
 673			categorySelection = SelectionOption{
 674				Key:   "CURRENT",
 675				Label: "Currently Watching",
 676			}
 677		} else {
 678			// Create category selection map
 679			categories := map[string]string{
 680				"ALL":       "Show All",
 681				"CURRENT":   "Currently Watching",
 682				"PAUSED":    "On Hold",
 683				"PLANNING":  "Plan to Watch",
 684				"COMPLETED": "Completed",
 685				"DROPPED":   "Dropped",
 686				"UPDATE":    "Update Anime Entry",
 687				"UNTRACKED": "Untracked Watching",
 688			}
 689
 690			// Select category using DynamicSelect
 691			var err error
 692			categorySelection, err = DynamicSelect(categories, false)
 693			if err != nil {
 694				Log(fmt.Sprintf("Failed to select category: %v", err))
 695				ExitCurd(fmt.Errorf("Failed to select category"))
 696			}
 697
 698			if categorySelection.Key == "-1" {
 699				ExitCurd(nil)
 700			}
 701
 702			// Handle UPDATE option
 703			if categorySelection.Key == "UPDATE" {
 704				ClearScreen()
 705				UpdateAnimeEntry(userCurdConfig, user)
 706				ExitCurd(nil)
 707			} else if categorySelection.Key == "UNTRACKED" {
 708				ClearScreen()
 709				WatchUntracked(userCurdConfig)
 710			}
 711
 712			ClearScreen()
 713		}
 714
 715		if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 716			animeListMapPreview = make(map[string]RofiSelectPreview)
 717			for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
 718				title := entry.Media.Title.English
 719				if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 720					title = entry.Media.Title.Romaji
 721				}
 722				animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 723					Title:      title,
 724					CoverImage: entry.CoverImage,
 725				}
 726			}
 727		} else {
 728			animeListMap = make(map[string]string)
 729			for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
 730				title := entry.Media.Title.English
 731				if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 732					title = entry.Media.Title.Romaji
 733				}
 734				animeListMap[strconv.Itoa(entry.Media.ID)] = title
 735			}
 736		}
 737	}
 738
 739	var anilistSelectedOption SelectionOption
 740	var selectedAllanimeAnime SelectionOption
 741	var userQuery string
 742
 743	if anime.Ep.ContinueLast {
 744		// Get the last watched anime ID from the curd_id file
 745		curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
 746		curdIDBytes, err := os.ReadFile(curdIDPath)
 747		if err != nil {
 748			Log(fmt.Sprintf("Error reading curd_id file: %v", err))
 749			ExitCurd(fmt.Errorf("Error reading curd_id file"))
 750		}
 751
 752		lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
 753		if err != nil {
 754			Log(fmt.Sprintf("Error converting curd_id to integer: %v", err))
 755			ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
 756		}
 757
 758		anime.AnilistId = lastWatchedID
 759		anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
 760	} else {
 761		// Select anime to watch (Anilist)
 762		var err error
 763		if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 764			anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
 765		} else {
 766			anilistSelectedOption, err = DynamicSelect(animeListMap, true)
 767		}
 768		if err != nil {
 769			Log(fmt.Sprintf("Error selecting anime: %v", err))
 770			ExitCurd(fmt.Errorf("Error selecting anime"))
 771		}
 772
 773		Log(anilistSelectedOption)
 774
 775		if anilistSelectedOption.Key == "-1" {
 776			ExitCurd(nil)
 777		}
 778
 779		if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
 780			anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes)
 781		}
 782
 783		anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
 784		if err != nil {
 785			Log(fmt.Sprintf("Error converting Anilist ID: %v", err))
 786			ExitCurd(fmt.Errorf("Error converting Anilist ID"))
 787		}
 788	}
 789	// Find anime in Local history
 790	animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
 791
 792	// Get anime entry
 793	selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
 794	if err != nil {
 795		Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err))
 796		ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
 797	}
 798
 799	// Set anime entry
 800	anime.Title = selectedAnilistAnime.Media.Title
 801	anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
 802	anime.Ep.Number = selectedAnilistAnime.Progress + 1
 803	var animeList map[string]string
 804	userQuery = anime.Title.Romaji
 805
 806	// if anime not found in database, find it in animeList
 807	if animePointer == nil {
 808		Log("Anime not found in database, searching in animeList...")
 809		// Get Anime list (All anime)
 810		Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
 811
 812		animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
 813		Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err))
 814		if err != nil {
 815			Log(fmt.Sprintf("Failed to select anime: %v", err))
 816			ExitCurd(fmt.Errorf("Failed to select anime"))
 817		}
 818		if len(animeList) == 0 {
 819			ExitCurd(fmt.Errorf("No results found."))
 820		}
 821
 822		// find anime in animeList
 823		anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
 824		if err != nil {
 825			Log(fmt.Sprintf("Failed to find anime in animeList: %v", err))
 826		}
 827
 828		// If unable to get Allanime id automatically get manually
 829		if anime.AllanimeId == "" {
 830			CurdOut("Failed to automatically select anime")
 831			selectedAllanimeAnime, err := DynamicSelect(animeList, false)
 832
 833			if selectedAllanimeAnime.Key == "-1" {
 834				ExitCurd(nil)
 835			}
 836
 837			if err != nil {
 838				// fmt.Println("No anime available")
 839				ExitCurd(fmt.Errorf("No anime available"))
 840			}
 841			anime.AllanimeId = selectedAllanimeAnime.Key
 842		}
 843	} else {
 844		// if anime found in database, use it
 845		anime.AllanimeId = animePointer.AllanimeId
 846		anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
 847		if anime.Ep.Number == animePointer.Ep.Number {
 848			anime.Ep.Resume = true
 849		}
 850	}
 851
 852	if selectedAllanimeAnime.Key == "-1" {
 853		ExitCurd(nil)
 854	}
 855
 856	// If anime is not in watching list, prompt user to add it into watching list
 857	isInWatchingList := false
 858	for _, entry := range user.AnimeList.Watching {
 859		if entry.Media.ID == anime.AnilistId {
 860			isInWatchingList = true
 861			break
 862		}
 863	}
 864
 865	if !isInWatchingList {
 866		// Create options for the prompt
 867		options := map[string]string{
 868			"yes": "Add to watching list",
 869			"no":  "Continue without adding",
 870		}
 871
 872		var selectedOption SelectionOption
 873		var err error
 874
 875		// Use rofi for selection
 876		selectedOption, err = DynamicSelect(options, false)
 877		if err != nil {
 878			Log("Error in selection: "+err.Error())
 879			ExitCurd(err)
 880		}
 881
 882		if selectedOption.Key == "yes" {
 883			err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
 884			if err != nil {
 885				Log("Error adding anime to watching list: "+err.Error())
 886				ExitCurd(err)
 887			}
 888			// Refresh user's anime list after adding
 889			if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 890				anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id)
 891				if err != nil {
 892					Log("Error refreshing anime list: "+err.Error())
 893					ExitCurd(err)
 894				}
 895				user.AnimeList = ParseAnimeList(anilistUserDataPreview)
 896			} else {
 897				anilistUserData, err := GetUserData(user.Token, user.Id)
 898				if err != nil {
 899					Log("Error refreshing anime list: "+err.Error())
 900					ExitCurd(err)
 901				}
 902				user.AnimeList = ParseAnimeList(anilistUserData)
 903			}
 904		} else if selectedOption.Key == "-1" {
 905			ExitCurd(nil)
 906		}
 907	}
 908
 909	// If upstream is ahead, update the episode number
 910	if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
 911		if temp_anime.Progress > anime.Ep.Number {
 912			anime.Ep.Number = temp_anime.Progress
 913			anime.Ep.Player.PlaybackTime = 0
 914			anime.Ep.Resume = false
 915		}
 916	}
 917
 918	if anime.TotalEpisodes == 0 {
 919		// Get updated anime data
 920		Log(selectedAllanimeAnime)
 921		updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
 922		Log(updatedAnime)
 923		if err != nil {
 924			Log(fmt.Sprintf("Error getting updated anime data: %v", err))
 925		} else {
 926			anime.TotalEpisodes = updatedAnime.TotalEpisodes
 927			Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
 928		}
 929	}
 930
 931	if anime.TotalEpisodes == 0 { // If failed to get anime data
 932		CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
 933		animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
 934		if err != nil {
 935			CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
 936		} else {
 937			for allanimeId, label := range animeList {
 938				if allanimeId == anime.AllanimeId {
 939					// Extract total episodes from the label
 940					if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
 941						anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
 942						CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
 943						break
 944					}
 945				}
 946			}
 947		}
 948
 949		if anime.TotalEpisodes == 0 {
 950			CurdOut("Still unable to determine total episodes.")
 951			CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
 952			var episodeNumber int
 953			if userCurdConfig.RofiSelection {
 954				userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
 955				if err != nil {
 956					Log("Error getting user input: "+err.Error())
 957					ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
 958				}
 959				episodeNumber, err = strconv.Atoi(userInput)
 960			} else {
 961				fmt.Print("Enter the episode you want to start from: ")
 962				fmt.Scanln(&episodeNumber)
 963			}
 964			anime.Ep.Number = episodeNumber
 965		} else {
 966			anime.Ep.Number = selectedAnilistAnime.Progress + 1
 967		}
 968	} else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
 969		Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
 970		var answer string
 971		if userCurdConfig.RofiSelection {
 972			userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
 973			if err != nil {
 974				Log("Error getting user input: "+err.Error())
 975				ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
 976			}
 977			answer = userInput
 978		} else {
 979			fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
 980			fmt.Scanln(&answer)
 981		}
 982		if answer == "y" {
 983			anime.Ep.Number = 1
 984		} else {
 985			anime.Ep.Number = anime.TotalEpisodes
 986		}
 987	}
 988
 989}
 990
 991// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
 992func WriteTokenToFile(token string, filePath string) error {
 993	// Extract the directory path
 994	dir := filepath.Dir(filePath)
 995
 996	// Create all necessary parent directories
 997	if err := os.MkdirAll(dir, 0755); err != nil {
 998		return fmt.Errorf("failed to create directories: %v", err)
 999	}
1000
1001	// Write the token to the file, creating it if it doesn't exist
1002	err := os.WriteFile(filePath, []byte(token), 0644)
1003	if err != nil {
1004		return fmt.Errorf("failed to write token to file: %v", err)
1005	}
1006
1007	return nil
1008}
1009
1010func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1011
1012	if anime.Ep.NextEpisode.Number == anime.Ep.Number {
1013		anime.Ep.Links = anime.Ep.NextEpisode.Links
1014		fmt.Println("using prefetched next episode link")
1015	} else {
1016		// Get episode link
1017		link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1018		if err != nil {
1019			// If unable to get episode link automatically get manually
1020			episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
1021			if err != nil {
1022				CurdOut("No episode list found")
1023				RestoreScreen()
1024				os.Exit(1)
1025			}
1026			if userCurdConfig.RofiSelection {
1027				userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1028				if err != nil {
1029					Log("Error getting user input: "+err.Error())
1030					ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1031				}
1032				anime.Ep.Number, err = strconv.Atoi(userInput)
1033			} else {
1034				CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1035				fmt.Scanln(&anime.Ep.Number)
1036			}
1037			link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1038			if err != nil {
1039				CurdOut("Failed to get episode link")
1040				os.Exit(1)
1041			}
1042			// anime.Ep.Links = link
1043		}
1044		anime.Ep.Links = link
1045	}
1046
1047	if len(anime.Ep.Links) == 0 {
1048		CurdOut("No episode links found")
1049		os.Exit(1)
1050	}
1051
1052	Log(anime)
1053
1054	// Modify the goroutine in main.go where next episode links are fetched
1055	// Get next episode link in parallel
1056	go func() {
1057		nextEpNum := anime.Ep.Number + 1
1058		if nextEpNum <= anime.TotalEpisodes {
1059			// Get next canon episode number if filler skip is enabled
1060			if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) {
1061				nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum)
1062			}
1063			nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum)
1064			if err != nil {
1065				Log("Error getting next episode link: "+err.Error())
1066			} else {
1067				anime.Ep.NextEpisode = NextEpisode{
1068					Number: nextEpNum,
1069					Links:  nextLinks,
1070				}
1071				Log(fmt.Sprintf("Next episode link fetched for ep %d", nextEpNum))
1072			}
1073		}
1074	}()
1075
1076	// Write anime.AnilistId to curd_id in the storage path
1077	idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1078	Log(fmt.Sprintf("idFilePath: %v", idFilePath))
1079	if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
1080		Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err))
1081	} else {
1082		if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
1083			Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err))
1084		}
1085	}
1086
1087	// Display starting message with cover image and episode info
1088	if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
1089		// Get the cached image path
1090		cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
1091		filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
1092		cachePath := filepath.Join(cacheDir, filename)
1093
1094		// Display the image if it exists in cache
1095		_, err := os.Stat(cachePath)
1096		if err == nil {
1097			// File exists
1098			Log(fmt.Sprintf("Image found at %s", cachePath))
1099			CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
1100		} else {
1101			// File does not exist
1102			Log(fmt.Sprintf("Image does not exist at %s", cachePath))
1103			CurdOut(fmt.Sprintf("%s - Episode %d",
1104				GetAnimeName(*anime),
1105				anime.Ep.Number))
1106
1107		}
1108	} else {
1109		CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
1110	}
1111	mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number), anime)
1112
1113	if err != nil {
1114		Log("Failed to start mpv")
1115		os.Exit(1)
1116	}
1117
1118	return mpvSocketPath
1119}
1120
1121func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1122	// Create storage directory if it doesn't exist
1123	storagePath = os.ExpandEnv(storagePath)
1124	if err := os.MkdirAll(storagePath, 0755); err != nil {
1125		return fmt.Errorf("failed to create storage directory: %v", err)
1126	}
1127
1128	// Base URL for downloading config files
1129	baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
1130
1131	// Check each file
1132	for _, fileName := range filesToCheck {
1133		filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
1134
1135		// Skip if file already exists
1136		if _, err := os.Stat(filePath); err == nil {
1137			continue
1138		}
1139
1140		// Download file if it doesn't exist
1141		resp, err := http.Get(baseURL + fileName)
1142		if err != nil {
1143			return fmt.Errorf("failed to download %s: %v", fileName, err)
1144		}
1145		defer resp.Body.Close()
1146
1147		// Create the file
1148		out, err := os.Create(filePath)
1149		if err != nil {
1150			return fmt.Errorf("failed to create file %s: %v", fileName, err)
1151		}
1152		defer out.Close()
1153
1154		// Write the content
1155		if _, err := io.Copy(out, resp.Body); err != nil {
1156			return fmt.Errorf("failed to write file %s: %v", fileName, err)
1157		}
1158	}
1159
1160	return nil
1161}
1162
1163func getEntriesByCategory(list AnimeList, category string) []Entry {
1164	switch category {
1165	case "ALL":
1166		// Combine all categories into one slice
1167		allEntries := make([]Entry, 0)
1168		allEntries = append(allEntries, list.Watching...)
1169		allEntries = append(allEntries, list.Completed...)
1170		allEntries = append(allEntries, list.Paused...)
1171		allEntries = append(allEntries, list.Dropped...)
1172		allEntries = append(allEntries, list.Planning...)
1173		return allEntries
1174	case "CURRENT":
1175		return list.Watching
1176	case "COMPLETED":
1177		return list.Completed
1178	case "PAUSED":
1179		return list.Paused
1180	case "DROPPED":
1181		return list.Dropped
1182	case "PLANNING":
1183		return list.Planning
1184	default:
1185		return []Entry{}
1186	}
1187}