internal/curd.go

1078 lines · 36006 bytes

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