internal/curd.go

1023 lines · 34625 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    // Get user id, username and Anime list
 559    user.Id, user.Username, err = GetAnilistUserID(user.Token)
 560    if err != nil {
 561        Log(fmt.Sprintf("Failed to get user ID: %v", err), logFile)
 562        ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
 563    }
 564
 565    // Get the anime list data
 566    if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 567        anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
 568        if err != nil {
 569            Log(fmt.Sprintf("Failed to get user data preview: %v", err), logFile)
 570            ExitCurd(fmt.Errorf("Failed to get user data preview"))
 571        }
 572        user.AnimeList = ParseAnimeList(anilistUserDataPreview)
 573    } else {
 574        anilistUserData, err = GetUserData(user.Token, user.Id)
 575        if err != nil {
 576            Log(fmt.Sprintf("Failed to get user data: %v", err), logFile)
 577            ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
 578        }
 579        user.AnimeList = ParseAnimeList(anilistUserData)
 580    }
 581
 582    // Skip category selection if Current flag is set
 583    var categorySelection SelectionOption
 584    if userCurdConfig.CurrentCategory {
 585        categorySelection = SelectionOption{
 586            Key:   "CURRENT",
 587            Label: "Currently Watching",
 588        }
 589    } else {
 590        // Create category selection map
 591        categories := map[string]string{
 592            "ALL":       "Show All",
 593            "CURRENT":   "Currently Watching",
 594            "PAUSED":    "On Hold",
 595            "PLANNING":  "Plan to Watch",
 596            "COMPLETED": "Completed",
 597            "DROPPED":   "Dropped",
 598            "UPDATE":    "Update Anime Entry",
 599            "UNTRACKED": "Untracked Watching",
 600        }
 601
 602        // Select category using DynamicSelect
 603        var err error
 604        categorySelection, err = DynamicSelect(categories, false)
 605        if err != nil {
 606            Log(fmt.Sprintf("Failed to select category: %v", err), logFile)
 607            ExitCurd(fmt.Errorf("Failed to select category"))
 608        }
 609
 610        if categorySelection.Key == "-1" {
 611            ExitCurd(nil)
 612        }
 613
 614        // Handle UPDATE option
 615        if categorySelection.Key == "UPDATE" {
 616            ClearScreen()
 617            UpdateAnimeEntry(userCurdConfig, user, logFile)
 618            ExitCurd(nil)
 619        } else if categorySelection.Key == "UNTRACKED" {
 620            ClearScreen()
 621            WatchUntracked(userCurdConfig, logFile)
 622        }
 623
 624        ClearScreen()
 625    }
 626
 627    // Filter anime list based on selected category
 628    var animeListMap map[string]string
 629    var animeListMapPreview map[string]RofiSelectPreview
 630    
 631    if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 632        animeListMapPreview = make(map[string]RofiSelectPreview)
 633        for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
 634            title := entry.Media.Title.English
 635            if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 636                title = entry.Media.Title.Romaji
 637            }
 638            animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 639                Title:      title,
 640                CoverImage: entry.CoverImage,
 641            }
 642        }
 643    } else {
 644        animeListMap = make(map[string]string)
 645        for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
 646            title := entry.Media.Title.English
 647            if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 648                title = entry.Media.Title.Romaji
 649            }
 650            animeListMap[strconv.Itoa(entry.Media.ID)] = title
 651        }
 652    }
 653
 654    var anilistSelectedOption SelectionOption
 655    var selectedAllanimeAnime SelectionOption
 656    var userQuery string
 657
 658    if anime.Ep.ContinueLast {
 659        // Get the last watched anime ID from the curd_id file
 660        curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
 661        curdIDBytes, err := os.ReadFile(curdIDPath)
 662        if err != nil {
 663            Log(fmt.Sprintf("Error reading curd_id file: %v", err), logFile)
 664            ExitCurd(fmt.Errorf("Error reading curd_id file"))
 665        }
 666
 667        lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
 668        if err != nil {
 669            Log(fmt.Sprintf("Error converting curd_id to integer: %v", err), logFile)
 670            ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
 671        }
 672
 673        anime.AnilistId = lastWatchedID
 674        anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
 675    } else {
 676        // Select anime to watch (Anilist)
 677        var err error
 678        if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 679            anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
 680        } else {
 681            anilistSelectedOption, err = DynamicSelect(animeListMap, true)
 682        }
 683        if err != nil {
 684            Log(fmt.Sprintf("Error selecting anime: %v", err), logFile)
 685            ExitCurd(fmt.Errorf("Error selecting anime"))
 686        }
 687
 688        Log(anilistSelectedOption, logFile)
 689
 690        if anilistSelectedOption.Key == "-1" {
 691            ExitCurd(nil)
 692        }
 693        
 694        if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
 695            anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes, logFile)
 696        }
 697        
 698        anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
 699        if err != nil {
 700            Log(fmt.Sprintf("Error converting Anilist ID: %v", err), logFile)
 701            ExitCurd(fmt.Errorf("Error converting Anilist ID"))
 702        }
 703    }
 704    // Find anime in Local history
 705    animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")	
 706    
 707    // Get anime entry
 708    selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
 709    if err != nil {
 710        Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err), logFile)
 711        ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
 712    }
 713
 714    // Set anime entry
 715    anime.Title = selectedAnilistAnime.Media.Title
 716    anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
 717    anime.Ep.Number = selectedAnilistAnime.Progress+1
 718    var animeList map[string]string
 719    userQuery = anime.Title.Romaji
 720
 721    // if anime not found in database, find it in animeList
 722    if animePointer == nil {
 723        Log("Anime not found in database, searching in animeList...", logFile)
 724        // Get Anime list (All anime)
 725        Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub), logFile)
 726        
 727        animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
 728        Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err), logFile)
 729        if err != nil {
 730            Log(fmt.Sprintf("Failed to select anime: %v", err), logFile)
 731            ExitCurd(fmt.Errorf("Failed to select anime"))
 732        }
 733        if len(animeList) == 0 {
 734            ExitCurd(fmt.Errorf("No results found."))
 735        }
 736
 737        // find anime in animeList
 738        anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
 739        if err != nil {
 740            Log(fmt.Sprintf("Failed to find anime in animeList: %v", err), logFile)
 741        }
 742
 743        // If unable to get Allanime id automatically get manually
 744        if anime.AllanimeId == "" {
 745            CurdOut("Failed to automatically select anime")
 746            selectedAllanimeAnime, err := DynamicSelect(animeList, false)
 747
 748			if selectedAllanimeAnime.Key == "-1" {
 749				ExitCurd(nil)
 750			}
 751
 752            if err != nil {
 753                // fmt.Println("No anime available")
 754                ExitCurd(fmt.Errorf("No anime available"))
 755            }
 756            anime.AllanimeId = selectedAllanimeAnime.Key
 757        }
 758    } else {
 759        // if anime found in database, use it
 760		anime.AllanimeId = animePointer.AllanimeId
 761		anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
 762		if anime.Ep.Number == animePointer.Ep.Number {
 763			anime.Ep.Resume = true
 764		}
 765    }
 766
 767    if selectedAllanimeAnime.Key == "-1" {
 768        ExitCurd(nil)
 769    }
 770
 771    // If upstream is ahead, update the episode number
 772    if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
 773        if temp_anime.Progress > anime.Ep.Number {
 774            anime.Ep.Number = temp_anime.Progress
 775            anime.Ep.Player.PlaybackTime = 0
 776            anime.Ep.Resume = false
 777        }
 778    }
 779
 780    if anime.TotalEpisodes == 0 {
 781        // Get updated anime data
 782        Log(selectedAllanimeAnime, logFile)
 783        updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
 784        Log(updatedAnime, logFile)
 785        if err != nil {
 786            Log(fmt.Sprintf("Error getting updated anime data: %v", err), logFile)
 787        } else {
 788            anime.TotalEpisodes = updatedAnime.TotalEpisodes
 789            Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes), logFile)
 790        }
 791    }
 792
 793    if anime.TotalEpisodes == 0 { // If failed to get anime data
 794        CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
 795        animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
 796        if err != nil {
 797            CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
 798        } else {
 799            for allanimeId, label := range animeList {
 800                if allanimeId == anime.AllanimeId {
 801                    // Extract total episodes from the label
 802                    if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
 803                        anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
 804                        CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
 805                        break
 806                    }
 807                }
 808            }
 809        }
 810        
 811        if anime.TotalEpisodes == 0 {
 812            CurdOut("Still unable to determine total episodes.")
 813            CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
 814            var episodeNumber int
 815            if userCurdConfig.RofiSelection {
 816                userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
 817                if err != nil {
 818                    Log("Error getting user input: "+err.Error(), logFile)
 819                    ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
 820                }
 821                episodeNumber, err = strconv.Atoi(userInput)
 822            } else {
 823                fmt.Print("Enter the episode you want to start from: ")
 824                fmt.Scanln(&episodeNumber)
 825            }
 826            anime.Ep.Number = episodeNumber
 827        } else {
 828            anime.Ep.Number = selectedAnilistAnime.Progress + 1
 829        }
 830    } else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
 831        Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number), logFile)
 832        var answer string
 833        if userCurdConfig.RofiSelection {
 834            userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
 835            if err != nil {
 836                Log("Error getting user input: "+err.Error(), logFile)
 837                ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
 838            }
 839            answer = userInput
 840        } else {
 841            fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
 842            fmt.Scanln(&answer)
 843        }
 844        if answer == "y" {
 845            anime.Ep.Number = 1
 846        } else {
 847            anime.Ep.Number = anime.TotalEpisodes
 848        }
 849    }
 850
 851}
 852
 853// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
 854func WriteTokenToFile(token string, filePath string) error {
 855    // Extract the directory path
 856    dir := filepath.Dir(filePath)
 857
 858    // Create all necessary parent directories
 859    if err := os.MkdirAll(dir, 0755); err != nil {
 860        return fmt.Errorf("failed to create directories: %v", err)
 861    }
 862
 863    // Write the token to the file, creating it if it doesn't exist
 864    err := os.WriteFile(filePath, []byte(token), 0644)
 865    if err != nil {
 866        return fmt.Errorf("failed to write token to file: %v", err)
 867    }
 868
 869    return nil
 870}
 871
 872func StartCurd(userCurdConfig *CurdConfig, anime *Anime, logFile string) string {
 873
 874	// Get episode link
 875	link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
 876	if err != nil {
 877		// If unable to get episode link automatically get manually
 878		episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
 879		if err != nil {
 880			CurdOut("No episode list found")
 881			RestoreScreen()
 882			os.Exit(1)
 883		}
 884		if userCurdConfig.RofiSelection {
 885			userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
 886			if err != nil {
 887				Log("Error getting user input: "+err.Error(), logFile)
 888				ExitCurd(fmt.Errorf("Error getting user input: "+err.Error()))
 889			}
 890			anime.Ep.Number, err = strconv.Atoi(userInput)
 891		} else {
 892			CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
 893			fmt.Scanln(&anime.Ep.Number)
 894		}
 895		link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
 896		if err != nil {
 897			CurdOut("Failed to get episode link")
 898			os.Exit(1)
 899		}
 900		// anime.Ep.Links = link
 901	}
 902	anime.Ep.Links = link
 903
 904	if len(anime.Ep.Links) == 0 {
 905		CurdOut("No episode links found")
 906		os.Exit(1)
 907	}
 908
 909	Log(anime, logFile)
 910
 911	// Write anime.AnilistId to curd_id in the storage path
 912	idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
 913	Log(fmt.Sprintf("idFilePath: %v", idFilePath), logFile)
 914	if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
 915		Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err), logFile)
 916	} else {
 917		if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
 918			Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err), logFile)
 919		}
 920	}
 921
 922	// Display starting message with cover image and episode info
 923	if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
 924		// Get the cached image path
 925		cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
 926		filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
 927		cachePath := filepath.Join(cacheDir, filename)
 928
 929		// Display the image if it exists in cache
 930		_, err := os.Stat(cachePath)
 931		if err == nil { 
 932			// File exists
 933			Log(fmt.Sprintf("Image found at %s", cachePath), logFile)
 934			CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
 935		} else {
 936			// File does not exist
 937			Log(fmt.Sprintf("Image does not exist at %s", cachePath), logFile)
 938			CurdOut(fmt.Sprintf("%s - Episode %d", 
 939				GetAnimeName(*anime), 
 940				anime.Ep.Number))
 941
 942		}
 943	} else {
 944		CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
 945	}
 946	mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
 947
 948	if err != nil {
 949		Log("Failed to start mpv", logFile)
 950		os.Exit(1)
 951	}
 952
 953	return mpvSocketPath
 954}
 955
 956func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
 957	// Create storage directory if it doesn't exist
 958	storagePath = os.ExpandEnv(storagePath)
 959	if err := os.MkdirAll(storagePath, 0755); err != nil {
 960		return fmt.Errorf("failed to create storage directory: %v", err)
 961	}
 962
 963	// Base URL for downloading config files
 964	baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
 965
 966	// Check each file
 967	for _, fileName := range filesToCheck {
 968		filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
 969
 970		// Skip if file already exists
 971		if _, err := os.Stat(filePath); err == nil {
 972			continue
 973		}
 974
 975		// Download file if it doesn't exist
 976		resp, err := http.Get(baseURL + fileName)
 977		if err != nil {
 978			return fmt.Errorf("failed to download %s: %v", fileName, err)
 979		}
 980		defer resp.Body.Close()
 981
 982		// Create the file
 983		out, err := os.Create(filePath)
 984		if err != nil {
 985			return fmt.Errorf("failed to create file %s: %v", fileName, err)
 986		}
 987		defer out.Close()
 988
 989		// Write the content
 990		if _, err := io.Copy(out, resp.Body); err != nil {
 991			return fmt.Errorf("failed to write file %s: %v", fileName, err)
 992		}
 993	}
 994
 995	return nil
 996}
 997
 998func getEntriesByCategory(list AnimeList, category string) []Entry {
 999    switch category {
1000    case "ALL":
1001        // Combine all categories into one slice
1002        allEntries := make([]Entry, 0)
1003        allEntries = append(allEntries, list.Watching...)
1004        allEntries = append(allEntries, list.Completed...)
1005        allEntries = append(allEntries, list.Paused...)
1006        allEntries = append(allEntries, list.Dropped...)
1007        allEntries = append(allEntries, list.Planning...)
1008        return allEntries
1009    case "CURRENT":
1010        return list.Watching
1011    case "COMPLETED":
1012        return list.Completed
1013    case "PAUSED":
1014        return list.Paused
1015    case "DROPPED":
1016        return list.Dropped
1017    case "PLANNING":
1018        return list.Planning
1019    default:
1020        return []Entry{}
1021    }
1022}
1023