internal/curd.go

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