internal/curd.go

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