internal/curd.go

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