internal/curd.go

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