internal/curd.go

1140 lines · 37746 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 anime is not in watching list, prompt user to add it into watching list
 827	isInWatchingList := false
 828	for _, entry := range user.AnimeList.Watching {
 829		if entry.Media.ID == anime.AnilistId {
 830			isInWatchingList = true
 831			break
 832		}
 833	}
 834
 835	if !isInWatchingList {
 836		// Create options for the prompt
 837		options := map[string]string{
 838			"yes": "Add to watching list",
 839			"no":  "Continue without adding",
 840		}
 841
 842		var selectedOption SelectionOption
 843		var err error
 844
 845		if userCurdConfig.RofiSelection {
 846			// Use rofi for selection
 847			selectedOption, err = DynamicSelect(options, false)
 848			if err != nil {
 849				Log("Error in selection: "+err.Error(), logFile)
 850				ExitCurd(err)
 851			}
 852		} else {
 853			// Use terminal selection
 854			selectedOption, err = DynamicSelect(options, false)
 855			if err != nil {
 856				Log("Error in selection: "+err.Error(), logFile)
 857				ExitCurd(err)
 858			}
 859		}
 860
 861		if selectedOption.Key == "yes" {
 862			err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
 863			if err != nil {
 864				Log("Error adding anime to watching list: "+err.Error(), logFile)
 865				ExitCurd(err)
 866			}
 867			// Refresh user's anime list after adding
 868			if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 869				anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id)
 870				if err != nil {
 871					Log("Error refreshing anime list: "+err.Error(), logFile)
 872					ExitCurd(err)
 873				}
 874				user.AnimeList = ParseAnimeList(anilistUserDataPreview)
 875			} else {
 876				anilistUserData, err := GetUserData(user.Token, user.Id)
 877				if err != nil {
 878					Log("Error refreshing anime list: "+err.Error(), logFile)
 879					ExitCurd(err)
 880				}
 881				user.AnimeList = ParseAnimeList(anilistUserData)
 882			}
 883		} else if selectedOption.Key == "-1" {
 884			ExitCurd(nil)
 885		}
 886	}
 887
 888    // If upstream is ahead, update the episode number
 889    if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
 890        if temp_anime.Progress > anime.Ep.Number {
 891            anime.Ep.Number = temp_anime.Progress
 892            anime.Ep.Player.PlaybackTime = 0
 893            anime.Ep.Resume = false
 894        }
 895    }
 896
 897    if anime.TotalEpisodes == 0 {
 898        // Get updated anime data
 899        Log(selectedAllanimeAnime, logFile)
 900        updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
 901        Log(updatedAnime, logFile)
 902        if err != nil {
 903            Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile)
 904        } else {
 905            anime.TotalEpisodes = updatedAnime.TotalEpisodes
 906            Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile)
 907        }
 908    }
 909
 910    if anime.TotalEpisodes == 0 { // If failed to get anime data
 911        CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
 912        animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
 913        if err != nil {
 914            CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
 915        } else {
 916            for allanimeId, label := range animeList {
 917                if allanimeId == anime.AllanimeId {
 918                    // Extract total episodes from the label
 919                    if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
 920                        anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
 921                        CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
 922                        break
 923                    }
 924                }
 925            }
 926        }
 927        
 928        if anime.TotalEpisodes == 0 {
 929            CurdOut("Still unable to determine total episodes.")
 930            CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
 931            var episodeNumber int
 932            if userCurdConfig.RofiSelection {
 933                userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
 934                if err != nil {
 935                    Log("Error getting user input: "+err.Error(), logFile)
 936                    ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
 937                }
 938                episodeNumber, err = strconv.Atoi(userInput)
 939            } else {
 940                fmt.Print("Enter the episode you want to start from: ")
 941                fmt.Scanln(&episodeNumber)
 942            }
 943            anime.Ep.Number = episodeNumber
 944        } else {
 945            anime.Ep.Number = selectedAnilistAnime.Progress + 1
 946        }
 947    } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
 948        Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
 949        var answer string
 950        if userCurdConfig.RofiSelection {
 951            userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
 952            if err != nil {
 953                Log("Error getting user input: "+err.Error(), logFile)
 954                ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
 955            }
 956            answer = userInput
 957        } else {
 958            fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
 959            fmt.Scanln(&answer)
 960        }
 961        if answer == "y" {
 962            anime.Ep.Number = 1
 963        } else {
 964            anime.Ep.Number = anime.TotalEpisodes
 965        }
 966    }
 967
 968}
 969
 970// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
 971func WriteTokenToFile(token string, filePath string) error {
 972    // Extract the directory path
 973    dir := filepath.Dir(filePath)
 974
 975    // Create all necessary parent directories
 976    if err := os.MkdirAll(dir, 0755); err != nil {
 977        return fmt.Errorf("failed to create directories: %v", err)
 978    }
 979
 980    // Write the token to the file, creating it if it doesn't exist
 981    err := os.WriteFile(filePath, []byte(token), 0644)
 982    if err != nil {
 983        return fmt.Errorf("failed to write token to file: %v", err)
 984    }
 985
 986    return nil
 987}
 988
 989func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
 990
 991	// Get episode link
 992	link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
 993	if err != nil {
 994		// If unable to get episode link automatically get manually
 995		episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
 996		if err != nil {
 997			CurdOut("No episode list found")
 998			RestoreScreen()
 999			os.Exit(1)
1000		}
1001		if userCurdConfig.RofiSelection {
1002			userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1003			if err != nil {
1004				Log("Error getting user input: "+err.Error(), logFile)
1005				ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
1006			}
1007			anime.Ep.Number, err = strconv.Atoi(userInput)
1008		} else {
1009			CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1010			fmt.Scanln(&anime.Ep.Number)
1011		}
1012		link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1013		if err != nil {
1014			CurdOut("Failed to get episode link")
1015			os.Exit(1)
1016		}
1017		// anime.Ep.Links = link
1018	}
1019	anime.Ep.Links = link
1020
1021	if len(anime.Ep.Links) == 0 {
1022		CurdOut("No episode links found")
1023		os.Exit(1)
1024	}
1025
1026	Log(anime, logFile)
1027
1028	// Write anime.AnilistId to curd_id in the storage path
1029	idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1030	Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile)
1031	if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
1032		Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
1033	} else {
1034		if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
1035			Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
1036		}
1037	}
1038
1039	// Display starting message with cover image and episode info
1040	if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
1041		// Get the cached image path
1042		cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
1043		filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
1044		cachePath := filepath.Join(cacheDir, filename)
1045
1046		// Display the image if it exists in cache
1047		_, err := os.Stat(cachePath)
1048		if err == nil { 
1049			// File exists
1050			Log(fmt.Sprintf("Image found at %s", cachePath), logFile)
1051			CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
1052		} else {
1053			// File does not exist
1054			Log(fmt.Sprintf("Image does not exist at %s", cachePath), logFile)
1055			CurdOut(fmt.Sprintf("%s - Episode %d", 
1056				GetAnimeName(*anime), 
1057				anime.Ep.Number))
1058
1059		}
1060	} else {
1061		CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
1062	}
1063	mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
1064
1065	if err != nil {
1066		Log("Failed to start mpv", logFile)
1067		os.Exit(1)
1068	}
1069
1070	return mpvSocketPath
1071}
1072
1073func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1074	// Create storage directory if it doesn't exist
1075	storagePath = os.ExpandEnv(storagePath)
1076	if err := os.MkdirAll(storagePath, 0755); err != nil {
1077		return fmt.Errorf("failed to create storage directory: %v", err)
1078	}
1079
1080	// Base URL for downloading config files
1081	baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
1082
1083	// Check each file
1084	for _, fileName := range filesToCheck {
1085		filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
1086
1087		// Skip if file already exists
1088		if _, err := os.Stat(filePath); err == nil {
1089			continue
1090		}
1091
1092		// Download file if it doesn't exist
1093		resp, err := http.Get(baseURL + fileName)
1094		if err != nil {
1095			return fmt.Errorf("failed to download %s: %v", fileName, err)
1096		}
1097		defer resp.Body.Close()
1098
1099		// Create the file
1100		out, err := os.Create(filePath)
1101		if err != nil {
1102			return fmt.Errorf("failed to create file %s: %v", fileName, err)
1103		}
1104		defer out.Close()
1105
1106		// Write the content
1107		if _, err := io.Copy(out, resp.Body); err != nil {
1108			return fmt.Errorf("failed to write file %s: %v", fileName, err)
1109		}
1110	}
1111
1112	return nil
1113}
1114
1115func getEntriesByCategory(list AnimeList, category string) []Entry {
1116    switch category {
1117    case "ALL":
1118        // Combine all categories into one slice
1119        allEntries := make([]Entry, 0)
1120        allEntries = append(allEntries, list.Watching...)
1121        allEntries = append(allEntries, list.Completed...)
1122        allEntries = append(allEntries, list.Paused...)
1123        allEntries = append(allEntries, list.Dropped...)
1124        allEntries = append(allEntries, list.Planning...)
1125        return allEntries
1126    case "CURRENT":
1127        return list.Watching
1128    case "COMPLETED":
1129        return list.Completed
1130    case "PAUSED":
1131        return list.Paused
1132    case "DROPPED":
1133        return list.Dropped
1134    case "PLANNING":
1135        return list.Planning
1136    default:
1137        return []Entry{}
1138    }
1139}
1140