internal/curd.go

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