internal/curd.go

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