Commit 824b391c23

824b391c23847c23a673e99c5ab8f44512a95812

parent: 1309809bc9

Unregistered key

Rushikesh Gaikwad <81632222+Wraient@users.noreply.github.com> · 2025-07-23 18:28 UTC
committer: <noreply@github.com>

Fix bugs and new features (#64)

* Add: rewatching list in show all

* Mod: Change [string]string to SelectionOption for maintaining order and consistency

* Mod: Make functions public

* Fix: Handle last episode scoring and completion

* Fix: Next Episode Prompt

* Add: Logging and new implementation for selectionOption[]

* Remove: Redundant keywords

Layout: unified · split

internal/anilist.go +9 −4
@@ -47,6 +47,7 @@ func GetAnimeMap(animeList AnimeList) map[string]string {
47 populateMap(animeList.Paused) 47 populateMap(animeList.Paused)
48 populateMap(animeList.Dropped) 48 populateMap(animeList.Dropped)
49 populateMap(animeList.Planning) 49 populateMap(animeList.Planning)
50 populateMap(animeList.Rewatching) // Add Rewatching list
50 51
51 return animeMap 52 return animeMap
52} 53}
@@ -82,6 +83,7 @@ func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
82 populateMap(animeList.Paused) 83 populateMap(animeList.Paused)
83 populateMap(animeList.Dropped) 84 populateMap(animeList.Dropped)
84 populateMap(animeList.Planning) 85 populateMap(animeList.Planning)
86 populateMap(animeList.Rewatching) // Add Rewatching list
85 87
86 return animeMap 88 return animeMap
87} 89}
@@ -792,13 +794,15 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
792 case "CURRENT": 794 case "CURRENT":
793 animeList.Watching = append(animeList.Watching, animeEntry) 795 animeList.Watching = append(animeList.Watching, animeEntry)
794 case "COMPLETED": 796 case "COMPLETED":
795 animeList.Completed = append(animeList.Completed, animeEntry) // Fix: Ensure Completed list is used 797 animeList.Completed = append(animeList.Completed, animeEntry)
796 case "PAUSED": 798 case "PAUSED":
797 animeList.Paused = append(animeList.Paused, animeEntry) // Fix: Append to Paused list 799 animeList.Paused = append(animeList.Paused, animeEntry)
798 case "DROPPED": 800 case "DROPPED":
799 animeList.Dropped = append(animeList.Dropped, animeEntry) // Fix: Append to Dropped list 801 animeList.Dropped = append(animeList.Dropped, animeEntry)
800 case "PLANNING": 802 case "PLANNING":
801 animeList.Planning = append(animeList.Planning, animeEntry) // Fix: Append to Planning list 803 animeList.Planning = append(animeList.Planning, animeEntry)
804 case "REPEATING": // Anilist uses REPEATING for rewatching
805 animeList.Rewatching = append(animeList.Rewatching, animeEntry)
802 } 806 }
803 } 807 }
804 } 808 }
@@ -820,6 +824,7 @@ func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
820 list.Paused, 824 list.Paused,
821 list.Dropped, 825 list.Dropped,
822 list.Planning, 826 list.Planning,
827 list.Rewatching, // Add Rewatching list
823 } 828 }
824 829
825 // Iterate through each category 830 // Iterate through each category
internal/anime_list.go +6 −3
@@ -41,7 +41,7 @@ type response struct {
41// fmt.Println(animeList) 41// fmt.Println(animeList)
42// } 42// }
43 43
44func SearchAnime(query, mode string) (map[string]string, error) { 44func SearchAnime(query, mode string) ([]SelectionOption, error) {
45 userCurdConfig := GetGlobalConfig() 45 userCurdConfig := GetGlobalConfig()
46 if userCurdConfig == nil { 46 if userCurdConfig == nil {
47 logFile = os.ExpandEnv("$HOME/.local/share/curd/debug.log") 47 logFile = os.ExpandEnv("$HOME/.local/share/curd/debug.log")
@@ -56,7 +56,7 @@ func SearchAnime(query, mode string) (map[string]string, error) {
56 ) 56 )
57 57
58 // Prepare the anime list 58 // Prepare the anime list
59 animeList := make(map[string]string) 59 animeList := make([]SelectionOption, 0)
60 60
61 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) { 61 searchGql := `query($search: SearchInput, $limit: Int, $page: Int, $translationType: VaildTranslationTypeEnumType, $countryOrigin: VaildCountryOriginEnumType) {
62 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) { 62 shows(search: $search, limit: $limit, page: $page, translationType: $translationType, countryOrigin: $countryOrigin) {
@@ -146,7 +146,10 @@ func SearchAnime(query, mode string) (map[string]string, error) {
146 displayName = anime.EnglishName 146 displayName = anime.EnglishName
147 } 147 }
148 148
149 animeList[anime.ID] = fmt.Sprintf("%s (%s episodes)", displayName, episodesStr) 149 animeList = append(animeList, SelectionOption{
150 Key: anime.ID,
151 Label: fmt.Sprintf("%s (%s episodes)", displayName, episodesStr),
152 })
150 } 153 }
151 return animeList, nil 154 return animeList, nil
152} 155}
internal/config.go +18 −15
@@ -110,7 +110,7 @@ func LoadConfig(configPath string) (CurdConfig, error) {
110 } 110 }
111 111
112 // Load the config from file 112 // Load the config from file
113 configMap, err := loadConfigFromFile(configPath) 113 configMap, err := LoadConfigFromFile(configPath)
114 if err != nil { 114 if err != nil {
115 return CurdConfig{}, fmt.Errorf("error loading config file: %v", err) 115 return CurdConfig{}, fmt.Errorf("error loading config file: %v", err)
116 } 116 }
@@ -133,7 +133,7 @@ func LoadConfig(configPath string) (CurdConfig, error) {
133 133
134 // Write updated config back to file only if AddMissingOptions is true 134 // Write updated config back to file only if AddMissingOptions is true
135 if addMissing && updated { 135 if addMissing && updated {
136 if err := saveConfigToFile(configPath, configMap); err != nil { 136 if err := SaveConfigToFile(configPath, configMap); err != nil {
137 return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err) 137 return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err)
138 } 138 }
139 } 139 }
@@ -144,7 +144,7 @@ func LoadConfig(configPath string) (CurdConfig, error) {
144 } 144 }
145 145
146 // Populate the CurdConfig struct from the config map 146 // Populate the CurdConfig struct from the config map
147 config := populateConfig(configMap) 147 config := PopulateConfig(configMap)
148 148
149 return config, nil 149 return config, nil
150} 150}
@@ -249,8 +249,8 @@ func ChangeToken(config *CurdConfig, user *User) {
249 WriteTokenToFile(user.Token, tokenPath) 249 WriteTokenToFile(user.Token, tokenPath)
250} 250}
251 251
252// Load config file from disk into a map (key=value format) 252// LoadConfigFromFile loads config file from disk into a map (key=value format)
253func loadConfigFromFile(path string) (map[string]string, error) { 253func LoadConfigFromFile(path string) (map[string]string, error) {
254 file, err := os.Open(path) 254 file, err := os.Open(path)
255 if err != nil { 255 if err != nil {
256 return nil, err 256 return nil, err
@@ -281,8 +281,8 @@ func loadConfigFromFile(path string) (map[string]string, error) {
281 return configMap, nil 281 return configMap, nil
282} 282}
283 283
284// Save updated config map to file in key=value format 284// SaveConfigToFile saves updated config map to file in key=value format
285func saveConfigToFile(path string, configMap map[string]string) error { 285func SaveConfigToFile(path string, configMap map[string]string) error {
286 file, err := os.Create(path) 286 file, err := os.Create(path)
287 if err != nil { 287 if err != nil {
288 return err 288 return err
@@ -299,8 +299,8 @@ func saveConfigToFile(path string, configMap map[string]string) error {
299 return writer.Flush() 299 return writer.Flush()
300} 300}
301 301
302// Populate the CurdConfig struct from a map 302// PopulateConfig populates the CurdConfig struct from a map
303func populateConfig(configMap map[string]string) CurdConfig { 303func PopulateConfig(configMap map[string]string) CurdConfig {
304 config := CurdConfig{} 304 config := CurdConfig{}
305 configValue := reflect.ValueOf(&config).Elem() 305 configValue := reflect.ValueOf(&config).Elem()
306 306
@@ -334,7 +334,7 @@ func populateConfig(configMap map[string]string) CurdConfig {
334 return config 334 return config
335} 335}
336 336
337func getOrderedCategories(userCurdConfig *CurdConfig) map[string]string { 337func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption {
338 // Define the default categories and their labels 338 // Define the default categories and their labels
339 defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "CONTINUE_LAST"} 339 defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "CONTINUE_LAST"}
340 defaultLabels := map[string]string{ 340 defaultLabels := map[string]string{
@@ -345,7 +345,7 @@ func getOrderedCategories(userCurdConfig *CurdConfig) map[string]string {
345 "CONTINUE_LAST": "Continue Last Session", 345 "CONTINUE_LAST": "Continue Last Session",
346 } 346 }
347 347
348 // Create ordered map to store final result 348 // Create ordered list to store final result
349 finalOrder := make([]string, 0) 349 finalOrder := make([]string, 0)
350 seen := make(map[string]bool) 350 seen := make(map[string]bool)
351 351
@@ -372,11 +372,14 @@ func getOrderedCategories(userCurdConfig *CurdConfig) map[string]string {
372 } 372 }
373 } 373 }
374 374
375 // Create the final ordered map 375 // Create the final ordered slice of SelectionOptions
376 orderedMap := make(map[string]string) 376 orderedCategories := make([]SelectionOption, 0, len(finalOrder))
377 for _, key := range finalOrder { 377 for _, key := range finalOrder {
378 orderedMap[key] = defaultLabels[key] 378 orderedCategories = append(orderedCategories, SelectionOption{
379 Key: key,
380 Label: defaultLabels[key],
381 })
379 } 382 }
380 383
381 return orderedMap 384 return orderedCategories
382} 385}
internal/curd.go +286 −62
@@ -143,7 +143,7 @@ func ExitCurd(err error) {
143 RestoreScreen() 143 RestoreScreen()
144 144
145 anime := GetGlobalAnime() 145 anime := GetGlobalAnime()
146 if anime != nil && anime.Ep.Player.SocketPath != "" { 146 if (anime != nil) && (anime.Ep.Player.SocketPath != "") {
147 _, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"}) 147 _, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
148 if err != nil { 148 if err != nil {
149 Log("Error closing MPV: " + err.Error()) 149 Log("Error closing MPV: " + err.Error())
@@ -223,11 +223,11 @@ func CurdOut(data interface{}) {
223} 223}
224 224
225func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) { 225func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
226 // Create update options map 226 // Create update options
227 updateOptions := map[string]string{ 227 updateOptions := []SelectionOption{
228 "CATEGORY": "Change Anime Category", 228 {Key: "CATEGORY", Label: "Change Anime Category"},
229 "PROGRESS": "Change Progress", 229 {Key: "PROGRESS", Label: "Change Progress"},
230 "SCORE": "Add/Change Score", 230 {Key: "SCORE", Label: "Add/Change Score"},
231 } 231 }
232 232
233 // Select update option 233 // Select update option
@@ -242,7 +242,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
242 } 242 }
243 243
244 // Get user's anime list 244 // Get user's anime list
245 var animeListMap map[string]string 245 var animeListOptions []SelectionOption
246 var animeListMapPreview map[string]RofiSelectPreview 246 var animeListMapPreview map[string]RofiSelectPreview
247 247
248 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 248 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
@@ -298,43 +298,78 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
298 CoverImage: entry.CoverImage, 298 CoverImage: entry.CoverImage,
299 } 299 }
300 } 300 }
301 for _, entry := range user.AnimeList.Rewatching {
302 title := entry.Media.Title.English
303 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
304 title = entry.Media.Title.Romaji
305 }
306 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
307 Title: title,
308 CoverImage: entry.CoverImage,
309 }
310 }
301 } else { 311 } else {
302 animeListMap = make(map[string]string) 312 animeListOptions = make([]SelectionOption, 0)
303 // Include anime from all categories 313 // Include anime from all categories
304 for _, entry := range user.AnimeList.Watching { 314 for _, entry := range user.AnimeList.Watching {
305 title := entry.Media.Title.English 315 title := entry.Media.Title.English
306 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { 316 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
307 title = entry.Media.Title.Romaji 317 title = entry.Media.Title.Romaji
308 } 318 }
309 animeListMap[strconv.Itoa(entry.Media.ID)] = title 319 animeListOptions = append(animeListOptions, SelectionOption{
320 Key: strconv.Itoa(entry.Media.ID),
321 Label: title,
322 })
310 } 323 }
311 for _, entry := range user.AnimeList.Completed { 324 for _, entry := range user.AnimeList.Completed {
312 title := entry.Media.Title.English 325 title := entry.Media.Title.English
313 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { 326 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
314 title = entry.Media.Title.Romaji 327 title = entry.Media.Title.Romaji
315 } 328 }
316 animeListMap[strconv.Itoa(entry.Media.ID)] = title 329 animeListOptions = append(animeListOptions, SelectionOption{
330 Key: strconv.Itoa(entry.Media.ID),
331 Label: title,
332 })
317 } 333 }
318 for _, entry := range user.AnimeList.Paused { 334 for _, entry := range user.AnimeList.Paused {
319 title := entry.Media.Title.English 335 title := entry.Media.Title.English
320 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { 336 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
321 title = entry.Media.Title.Romaji 337 title = entry.Media.Title.Romaji
322 } 338 }
323 animeListMap[strconv.Itoa(entry.Media.ID)] = title 339 animeListOptions = append(animeListOptions, SelectionOption{
340 Key: strconv.Itoa(entry.Media.ID),
341 Label: title,
342 })
324 } 343 }
325 for _, entry := range user.AnimeList.Dropped { 344 for _, entry := range user.AnimeList.Dropped {
326 title := entry.Media.Title.English 345 title := entry.Media.Title.English
327 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { 346 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
328 title = entry.Media.Title.Romaji 347 title = entry.Media.Title.Romaji
329 } 348 }
330 animeListMap[strconv.Itoa(entry.Media.ID)] = title 349 animeListOptions = append(animeListOptions, SelectionOption{
350 Key: strconv.Itoa(entry.Media.ID),
351 Label: title,
352 })
331 } 353 }
332 for _, entry := range user.AnimeList.Planning { 354 for _, entry := range user.AnimeList.Planning {
333 title := entry.Media.Title.English 355 title := entry.Media.Title.English
334 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { 356 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
335 title = entry.Media.Title.Romaji 357 title = entry.Media.Title.Romaji
336 } 358 }
337 animeListMap[strconv.Itoa(entry.Media.ID)] = title 359 animeListOptions = append(animeListOptions, SelectionOption{
360 Key: strconv.Itoa(entry.Media.ID),
361 Label: title,
362 })
363 }
364 for _, entry := range user.AnimeList.Rewatching {
365 title := entry.Media.Title.English
366 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
367 title = entry.Media.Title.Romaji
368 }
369 animeListOptions = append(animeListOptions, SelectionOption{
370 Key: strconv.Itoa(entry.Media.ID),
371 Label: title,
372 })
338 } 373 }
339 } 374 }
340 375
@@ -343,7 +378,7 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
343 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 378 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
344 selectedAnime, err = DynamicSelectPreview(animeListMapPreview, false) 379 selectedAnime, err = DynamicSelectPreview(animeListMapPreview, false)
345 } else { 380 } else {
346 selectedAnime, err = DynamicSelect(animeListMap) 381 selectedAnime, err = DynamicSelect(animeListOptions)
347 } 382 }
348 if err != nil { 383 if err != nil {
349 Log(fmt.Sprintf("Failed to select anime: %v", err)) 384 Log(fmt.Sprintf("Failed to select anime: %v", err))
@@ -369,17 +404,24 @@ func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
369 ClearScreen() 404 ClearScreen()
370 switch updateSelection.Key { 405 switch updateSelection.Key {
371 case "CATEGORY": 406 case "CATEGORY":
372 categories := map[string]string{ 407 categories := []SelectionOption{
373 "CURRENT": "Currently Watching", 408 {Key: "CURRENT", Label: "Currently Watching"},
374 "COMPLETED": "Completed", 409 {Key: "COMPLETED", Label: "Completed"},
375 "PAUSED": "On Hold", 410 {Key: "PAUSED", Label: "On Hold"},
376 "DROPPED": "Dropped", 411 {Key: "DROPPED", Label: "Dropped"},
377 "PLANNING": "Plan to Watch", 412 {Key: "PLANNING", Label: "Plan to Watch"},
413 {Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
378 } 414 }
379 415
380 currentStatus := "None" 416 currentStatus := "None"
381 if selectedAnilistAnime.Status != "" { 417 if selectedAnilistAnime.Status != "" {
382 currentStatus = categories[selectedAnilistAnime.Status] 418 // Find the label for the current status
419 for _, cat := range categories {
420 if cat.Key == selectedAnilistAnime.Status {
421 currentStatus = cat.Label
422 break
423 }
424 }
383 } 425 }
384 CurdOut(fmt.Sprintf("Current category: %s", currentStatus)) 426 CurdOut(fmt.Sprintf("Current category: %s", currentStatus))
385 427
@@ -550,6 +592,7 @@ func UpdateCurd(repo, fileName string) error {
550 592
551func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption { 593func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
552 var query string 594 var query string
595 var animeOptions []SelectionOption
553 var animeMapPreview map[string]RofiSelectPreview 596 var animeMapPreview map[string]RofiSelectPreview
554 var animeOptions []SelectionOption 597 var animeOptions []SelectionOption
555 var err error 598 var err error
@@ -571,7 +614,19 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
571 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 614 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
572 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token) 615 animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
573 } else { 616 } else {
574 animeOptions, err = SearchAnimeAnilist(query, user.Token) 617 animeMap, err := SearchAnimeAnilist(query, user.Token)
618 if err != nil {
619 Log(fmt.Sprintf("Failed to search anime: %v", err))
620 ExitCurd(fmt.Errorf("Failed to search anime"))
621 }
622 // Convert map to []SelectionOption
623 animeOptions = make([]SelectionOption, 0, len(animeMap))
624 for key, label := range animeMap {
625 animeOptions = append(animeOptions, SelectionOption{
626 Key: key,
627 Label: label,
628 })
629 }
575 } 630 }
576 if err != nil { 631 if err != nil {
577 Log(fmt.Sprintf("Failed to search anime: %v", err)) 632 Log(fmt.Sprintf("Failed to search anime: %v", err))
@@ -580,7 +635,7 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
580 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 635 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
581 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false) 636 anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
582 } else { 637 } else {
583 anilistSelectedOption, err = DynamicSelectFromSlice(animeOptions) 638 anilistSelectedOption, err = DynamicSelect(animeOptions)
584 } 639 }
585 640
586 if anilistSelectedOption.Key == "-1" { 641 if anilistSelectedOption.Key == "-1" {
@@ -598,12 +653,13 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
598 } 653 }
599 654
600 // Add category selection before adding to list 655 // Add category selection before adding to list
601 categories := map[string]string{ 656 categories := []SelectionOption{
602 "CURRENT": "Currently Watching", 657 {Key: "CURRENT", Label: "Currently Watching"},
603 "COMPLETED": "Completed", 658 {Key: "COMPLETED", Label: "Completed"},
604 "PAUSED": "On Hold", 659 {Key: "PAUSED", Label: "On Hold"},
605 "DROPPED": "Dropped", 660 {Key: "DROPPED", Label: "Dropped"},
606 "PLANNING": "Plan to Watch", 661 {Key: "PLANNING", Label: "Plan to Watch"},
662 {Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
607 } 663 }
608 664
609 ClearScreen() 665 ClearScreen()
@@ -651,7 +707,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
651 var anilistUserDataPreview map[string]interface{} 707 var anilistUserDataPreview map[string]interface{}
652 708
653 // Filter anime list based on selected category 709 // Filter anime list based on selected category
654 var animeListMap map[string]string 710 var animeListOptions []SelectionOption
655 var animeListMapPreview map[string]RofiSelectPreview 711 var animeListMapPreview map[string]RofiSelectPreview
656 712
657 // Get user id, username and Anime list 713 // Get user id, username and Anime list
@@ -718,11 +774,12 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
718 } 774 }
719 } else { 775 } else {
720 // Create category selection map 776 // Create category selection map
721 categories := getOrderedCategories(userCurdConfig) 777 // Get ordered categories
778 orderedCategories := getOrderedCategories(userCurdConfig)
779
780 // Use DynamicSelect with ordered categories directly
781 categorySelection, err = DynamicSelect(orderedCategories)
722 782
723 // Select category using DynamicSelect
724 var err error
725 categorySelection, err = DynamicSelect(categories)
726 if err != nil { 783 if err != nil {
727 Log(fmt.Sprintf("Failed to select category: %v", err)) 784 Log(fmt.Sprintf("Failed to select category: %v", err))
728 ExitCurd(fmt.Errorf("Failed to select category")) 785 ExitCurd(fmt.Errorf("Failed to select category"))
@@ -760,13 +817,16 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
760 } 817 }
761 } 818 }
762 } else { 819 } else {
763 animeListMap = make(map[string]string) 820 animeListOptions = make([]SelectionOption, 0)
764 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) { 821 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
765 title := entry.Media.Title.English 822 title := entry.Media.Title.English
766 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" { 823 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
767 title = entry.Media.Title.Romaji 824 title = entry.Media.Title.Romaji
768 } 825 }
769 animeListMap[strconv.Itoa(entry.Media.ID)] = title 826 animeListOptions = append(animeListOptions, SelectionOption{
827 Key: strconv.Itoa(entry.Media.ID),
828 Label: title,
829 })
770 } 830 }
771 } 831 }
772 } 832 }
@@ -798,10 +858,13 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
798 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 858 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
799 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true) 859 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
800 } else { 860 } else {
801 // Add "Add new anime" option to the map 861 // Add "Add new anime" option to the slice
802 animeListMap["add_new"] = "Add new anime" 862 animeListOptions = append(animeListOptions, SelectionOption{
863 Key: "add_new",
864 Label: "Add new anime",
865 })
803 866
804 anilistSelectedOption, err = DynamicSelect(animeListMap) 867 anilistSelectedOption, err = DynamicSelect(animeListOptions)
805 } 868 }
806 if err != nil { 869 if err != nil {
807 Log(fmt.Sprintf("Error selecting anime: %v", err)) 870 Log(fmt.Sprintf("Error selecting anime: %v", err))
@@ -838,7 +901,7 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
838 anime.Title = selectedAnilistAnime.Media.Title 901 anime.Title = selectedAnilistAnime.Media.Title
839 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes 902 anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
840 anime.Ep.Number = selectedAnilistAnime.Progress + 1 903 anime.Ep.Number = selectedAnilistAnime.Progress + 1
841 var animeList map[string]string 904 var animeList []SelectionOption
842 userQuery = anime.Title.Romaji 905 userQuery = anime.Title.Romaji
843 906
844 // if anime not found in database, find it in animeList 907 // if anime not found in database, find it in animeList
@@ -848,7 +911,6 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
848 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub)) 911 Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
849 912
850 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub) 913 animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
851 Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err))
852 if err != nil { 914 if err != nil {
853 Log(fmt.Sprintf("Failed to select anime: %v", err)) 915 Log(fmt.Sprintf("Failed to select anime: %v", err))
854 ExitCurd(fmt.Errorf("Failed to select anime")) 916 ExitCurd(fmt.Errorf("Failed to select anime"))
@@ -857,10 +919,21 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
857 ExitCurd(fmt.Errorf("No results found.")) 919 ExitCurd(fmt.Errorf("No results found."))
858 } 920 }
859 921
860 // find anime in animeList 922 // find anime in animeList by searching through the options
861 anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes)) 923 targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes)
862 if err != nil { 924 found := false
863 Log(fmt.Sprintf("Failed to find anime in animeList: %v", err)) 925 for i, option := range animeList {
926 Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s'", i, option.Key, option.Label))
927 if option.Label == targetLabel {
928 anime.AllanimeId = option.Key
929 Log(fmt.Sprintf("Found exact match! Setting AllanimeId to: %s", anime.AllanimeId))
930 found = true
931 break
932 }
933 }
934
935 if !found {
936 Log(fmt.Sprintf("No exact match found for label '%s'. Will require manual selection.", targetLabel))
864 } 937 }
865 938
866 // If unable to get Allanime id automatically get manually 939 // If unable to get Allanime id automatically get manually
@@ -873,7 +946,6 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
873 } 946 }
874 947
875 if err != nil { 948 if err != nil {
876 // fmt.Println("No anime available")
877 ExitCurd(fmt.Errorf("No anime available")) 949 ExitCurd(fmt.Errorf("No anime available"))
878 } 950 }
879 anime.AllanimeId = selectedAllanimeAnime.Key 951 anime.AllanimeId = selectedAllanimeAnime.Key
@@ -902,9 +974,9 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
902 974
903 if !isInWatchingList { 975 if !isInWatchingList {
904 // Create options for the prompt 976 // Create options for the prompt
905 options := map[string]string{ 977 options := []SelectionOption{
906 "yes": "Add to watching list", 978 {Key: "yes", Label: "Add to watching list"},
907 "no": "Continue without adding", 979 {Key: "no", Label: "Continue without adding"},
908 } 980 }
909 981
910 var selectedOption SelectionOption 982 var selectedOption SelectionOption
@@ -972,10 +1044,10 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
972 if err != nil { 1044 if err != nil {
973 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err)) 1045 CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
974 } else { 1046 } else {
975 for allanimeId, label := range animeList { 1047 for _, option := range animeList {
976 if allanimeId == anime.AllanimeId { 1048 if option.Key == anime.AllanimeId {
977 // Extract total episodes from the label 1049 // Extract total episodes from the label
978 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 { 1050 if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 {
979 anime.TotalEpisodes, _ = strconv.Atoi(matches[1]) 1051 anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
980 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes)) 1052 CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
981 break 1053 break
@@ -1028,6 +1100,33 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1028 if userCurdConfig.NextEpisodePrompt && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !userCurdConfig.RofiSelection { 1100 if userCurdConfig.NextEpisodePrompt && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !userCurdConfig.RofiSelection {
1029 // Ensure the terminal state is clean for the prompt 1101 // Ensure the terminal state is clean for the prompt
1030 fmt.Print("\r\033[K") // Carriage return and clear line 1102 fmt.Print("\r\033[K") // Carriage return and clear line
1103 episodeNum := anime.Ep.Number
1104 if !userCurdConfig.RofiSelection {
1105 episodeNum++
1106 }
1107
1108 CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum))
1109
1110 // Create options for the selection
1111 options := []SelectionOption{
1112 {Key: "yes", Label: "Yes, start next episode"},
1113 // "no": "No, quit",
1114 }
1115
1116 // Use DynamicSelect for both CLI and Rofi modes
1117 selectedOption, err := DynamicSelect(options)
1118 if err != nil {
1119 ExitCurd(err)
1120 }
1121
1122 if selectedOption.Key == "-1" {
1123 // User selected to quit
1124 fmt.Print("\r\033[K") // Carriage return and clear line
1125 ExitMPV(anime.Ep.Player.SocketPath)
1126 CurdOut("Exiting without starting next episode")
1127 ExitCurd(nil)
1128 return
1129 }
1031 } 1130 }
1032} 1131}
1033 1132
@@ -1052,12 +1151,24 @@ func WriteTokenToFile(token string, filePath string) error {
1052 1151
1053func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string { 1152func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1054 1153
1055 if anime.Ep.NextEpisode.Number == anime.Ep.Number { 1154 // Validate inputs
1155 if anime.AllanimeId == "" {
1156 CurdOut("Error: No anime ID found")
1157 os.Exit(1)
1158 }
1159 if anime.Ep.Number <= 0 {
1160 CurdOut("Error: Invalid episode number")
1161 os.Exit(1)
1162 }
1163
1164 if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1056 anime.Ep.Links = anime.Ep.NextEpisode.Links 1165 anime.Ep.Links = anime.Ep.NextEpisode.Links
1057 Log("using prefetched next episode link")
1058 } else { 1166 } else {
1059 // Get episode link 1167 // Get episode link
1060 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number) 1168 link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1169 if len(link) > 0 {
1170 Log(fmt.Sprintf("Links details: %+v", link))
1171 }
1061 if err != nil { 1172 if err != nil {
1062 // If unable to get episode link automatically get manually 1173 // If unable to get episode link automatically get manually
1063 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub) 1174 episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
@@ -1082,7 +1193,8 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1082 CurdOut("Failed to get episode link") 1193 CurdOut("Failed to get episode link")
1083 os.Exit(1) 1194 os.Exit(1)
1084 } 1195 }
1085 // anime.Ep.Links = link 1196 } else {
1197 Log(fmt.Sprintf("Successfully retrieved episode link on first try. Links count: %d", len(link)))
1086 } 1198 }
1087 anime.Ep.Links = link 1199 anime.Ep.Links = link
1088 } 1200 }
@@ -1090,10 +1202,10 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1090 if len(anime.Ep.Links) == 0 { 1202 if len(anime.Ep.Links) == 0 {
1091 CurdOut("No episode links found") 1203 CurdOut("No episode links found")
1092 os.Exit(1) 1204 os.Exit(1)
1205 } else {
1206 Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links)))
1093 } 1207 }
1094 1208
1095 Log(anime)
1096
1097 // Modify the goroutine in main.go where next episode links are fetched 1209 // Modify the goroutine in main.go where next episode links are fetched
1098 // Get next episode link in parallel 1210 // Get next episode link in parallel
1099 go func() { 1211 go func() {
@@ -1105,14 +1217,15 @@ func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1105 } 1217 }
1106 nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum) 1218 nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum)
1107 if err != nil { 1219 if err != nil {
1108 Log("Error getting next episode link: " + err.Error()) 1220 Log(fmt.Sprintf("Error getting next episode link for ep %d: %v", nextEpNum, err))
1109 } else { 1221 } else {
1110 anime.Ep.NextEpisode = NextEpisode{ 1222 anime.Ep.NextEpisode = NextEpisode{
1111 Number: nextEpNum, 1223 Number: nextEpNum,
1112 Links: nextLinks, 1224 Links: nextLinks,
1113 } 1225 }
1114 Log(fmt.Sprintf("Next episode link fetched for ep %d", nextEpNum))
1115 } 1226 }
1227 } else {
1228 Log(fmt.Sprintf("Next episode %d exceeds total episodes %d, skipping prefetch", nextEpNum, anime.TotalEpisodes))
1116 } 1229 }
1117 }() 1230 }()
1118 1231
@@ -1213,6 +1326,7 @@ func getEntriesByCategory(list AnimeList, category string) []Entry {
1213 allEntries = append(allEntries, list.Paused...) 1326 allEntries = append(allEntries, list.Paused...)
1214 allEntries = append(allEntries, list.Dropped...) 1327 allEntries = append(allEntries, list.Dropped...)
1215 allEntries = append(allEntries, list.Planning...) 1328 allEntries = append(allEntries, list.Planning...)
1329 allEntries = append(allEntries, list.Rewatching...)
1216 return allEntries 1330 return allEntries
1217 case "CURRENT": 1331 case "CURRENT":
1218 return list.Watching 1332 return list.Watching
@@ -1224,6 +1338,8 @@ func getEntriesByCategory(list AnimeList, category string) []Entry {
1224 return list.Dropped 1338 return list.Dropped
1225 case "PLANNING": 1339 case "PLANNING":
1226 return list.Planning 1340 return list.Planning
1341 case "REWATCHING": // Added for completeness, though "ALL" covers it.
1342 return list.Rewatching
1227 default: 1343 default:
1228 return []Entry{} 1344 return []Entry{}
1229 } 1345 }
@@ -1231,6 +1347,20 @@ func getEntriesByCategory(list AnimeList, category string) []Entry {
1231 1347
1232func NextEpisodePrompt(userCurdConfig *CurdConfig) { 1348func NextEpisodePrompt(userCurdConfig *CurdConfig) {
1233 anime := GetGlobalAnime() 1349 anime := GetGlobalAnime()
1350
1351 // Check if we just completed the last episode
1352 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1353 // Handle scoring and completion for the last episode
1354 HandleLastEpisodeCompletion(userCurdConfig, anime)
1355
1356 // Exit after completing the series
1357 fmt.Print("\r\033[K") // Carriage return and clear line
1358 ExitMPV(anime.Ep.Player.SocketPath)
1359 CurdOut("Series completed!")
1360 ExitCurd(nil)
1361 return
1362 }
1363
1234 // If in CLI mode (not Rofi), we need to show the next episode number 1364 // If in CLI mode (not Rofi), we need to show the next episode number
1235 episodeNum := anime.Ep.Number 1365 episodeNum := anime.Ep.Number
1236 if !userCurdConfig.RofiSelection { 1366 if !userCurdConfig.RofiSelection {
@@ -1240,8 +1370,8 @@ func NextEpisodePrompt(userCurdConfig *CurdConfig) {
1240 CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum)) 1370 CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum))
1241 1371
1242 // Create options for the selection 1372 // Create options for the selection
1243 options := map[string]string{ 1373 options := []SelectionOption{
1244 "yes": "Yes, start next episode", 1374 {Key: "yes", Label: "Yes, start next episode"},
1245 // "no": "No, quit", 1375 // "no": "No, quit",
1246 } 1376 }
1247 1377
@@ -1364,6 +1494,35 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
1364 // Save previous episode number for progress update 1494 // Save previous episode number for progress update
1365 prevEpisode := anime.Ep.Number 1495 prevEpisode := anime.Ep.Number
1366 1496
1497 // Check if we just completed the last episode
1498 if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1499 // Handle scoring and completion for the last episode
1500 HandleLastEpisodeCompletion(userCurdConfig, anime)
1501
1502 // Update Anilist progress for the last episode if not rewatching
1503 if !anime.Rewatching {
1504 user := &User{}
1505 var err error
1506 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token"))
1507 if err != nil {
1508 Log("Error reading token for progress update: " + err.Error())
1509 } else {
1510 go func() {
1511 err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode)
1512 if err != nil {
1513 Log("Error updating Anilist progress: " + err.Error())
1514 } else {
1515 CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1516 }
1517 }()
1518 }
1519 }
1520
1521 CurdOut("Series completed!")
1522 ExitCurd(nil)
1523 return
1524 }
1525
1367 // Increment episode number 1526 // Increment episode number
1368 anime.Ep.Number++ 1527 anime.Ep.Number++
1369 1528
@@ -1381,7 +1540,7 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
1381 CurdOut(fmt.Sprintf("Last episode (%d). Are you sure you want to watch it?", anime.Ep.Number)) 1540 CurdOut(fmt.Sprintf("Last episode (%d). Are you sure you want to watch it?", anime.Ep.Number))
1382 1541
1383 // Simple yes/no selection for the last episode 1542 // Simple yes/no selection for the last episode
1384 selectedOption, err := DynamicSelect(map[string]string{"yes": "Yes"}) 1543 selectedOption, err := DynamicSelect([]SelectionOption{{Key: "yes", Label: "Yes"}})
1385 if err != nil { 1544 if err != nil {
1386 ExitCurd(err) 1545 ExitCurd(err)
1387 } 1546 }
@@ -1432,3 +1591,68 @@ func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile str
1432 // Output message to user 1591 // Output message to user
1433 CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number)) 1592 CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
1434} 1593}
1594
1595// HandleLastEpisodeCompletion handles scoring and completion for the last episode
1596func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime) {
1597 // Check if this is the last episode and scoring is enabled
1598 if userCurdConfig.ScoreOnCompletion && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1599 // Get user token for scoring
1600 user := &User{}
1601
1602 // Get config for storage path
1603 homeDir := ""
1604 if runtime.GOOS == "windows" {
1605 homeDir = os.Getenv("USERPROFILE")
1606 } else {
1607 homeDir = os.Getenv("HOME")
1608 }
1609 configFilePath := filepath.Join(homeDir, ".config", "curd", "curd.conf")
1610 config, err := LoadConfig(configFilePath)
1611 if err != nil {
1612 Log("Error loading config for scoring: " + err.Error())
1613 return
1614 }
1615
1616 user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "token"))
1617 if err != nil {
1618 Log("Error reading token for scoring: " + err.Error())
1619 return
1620 }
1621
1622 // Prompt user to score the anime
1623 CurdOut("You've completed this anime! Would you like to rate it?")
1624
1625 scoreOptions := []SelectionOption{
1626 {Key: "yes", Label: "Yes, rate this anime"},
1627 {Key: "no", Label: "No, skip rating"},
1628 }
1629
1630 selectedOption, err := DynamicSelect(scoreOptions)
1631 if err != nil {
1632 Log(fmt.Sprintf("Error in score prompt selection: %v", err))
1633 return
1634 }
1635
1636 if selectedOption.Key == "yes" {
1637 err = RateAnime(user.Token, anime.AnilistId)
1638 if err != nil {
1639 Log(fmt.Sprintf("Error rating anime: %v", err))
1640 CurdOut("Failed to rate anime")
1641 } else {
1642 CurdOut("Anime rated successfully!")
1643 }
1644 }
1645
1646 // Update anime status to completed on AniList
1647 if !anime.Rewatching {
1648 go func() {
1649 err = UpdateAnimeStatus(user.Token, anime.AnilistId, "COMPLETED")
1650 if err != nil {
1651 Log("Error updating anime status to completed: " + err.Error())
1652 } else {
1653 CurdOut("Anime status updated to completed!")
1654 }
1655 }()
1656 }
1657 }
1658}
internal/discord.go +2 −2
@@ -38,11 +38,11 @@ func DiscordPresence(anime Anime, IsPaused bool) error {
38 //SmallText: fmt.Sprintf("Episode: %s", anime.Ep.Title.English), // Text when hovering over the small image 38 //SmallText: fmt.Sprintf("Episode: %s", anime.Ep.Title.English), // Text when hovering over the small image
39 Buttons: []*client.Button{ 39 Buttons: []*client.Button{
40 { 40 {
41 Label: "View on AniList", // Button label 41 Label: "View on AniList", // Button label
42 Url: fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId), // Button link 42 Url: fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId), // Button link
43 }, 43 },
44 { 44 {
45 Label: "View on MAL", // Button label 45 Label: "View on MAL", // Button label
46 Url: fmt.Sprintf("https://myanimelist.net/anime/%d", anime.MalId), // Button link 46 Url: fmt.Sprintf("https://myanimelist.net/anime/%d", anime.MalId), // Button link
47 }, 47 },
48 }, 48 },
internal/localTracking.go +1 −1
@@ -250,7 +250,7 @@ func LocalFindAnime(animeList []Anime, anilistID int, allanimeID string) *Anime
250 250
251func WatchUntracked(userCurdConfig *CurdConfig) { 251func WatchUntracked(userCurdConfig *CurdConfig) {
252 var query string 252 var query string
253 var animeList map[string]string 253 var animeList []SelectionOption
254 var err error 254 var err error
255 var anime Anime 255 var anime Anime
256 256
internal/selection_menu.go +84 −149
@@ -17,24 +17,16 @@ import (
17 "github.com/charmbracelet/lipgloss" 17 "github.com/charmbracelet/lipgloss"
18) 18)
19 19
20// SelectionOption holds the label and the internal key
21type SelectionOption struct {
22 Label string
23 Key string
24}
25
26// Model represents the application state for the selection prompt 20// Model represents the application state for the selection prompt
27type Model struct { 21type Model struct {
28 options map[string]string 22 filter string
29 filter string 23 filteredKeys []SelectionOption
30 filteredKeys []SelectionOption 24 allOptions []SelectionOption
31 selected int 25 selected int
32 terminalWidth int 26 terminalWidth int
33 terminalHeight int 27 terminalHeight int
34 scrollOffset int // Track the topmost visible item 28 scrollOffset int
35 addNewOption bool 29 addNewOption bool
36 useSliceMode bool // Track if we're using slice-based filtering
37 originalOptions []SelectionOption // Store original options for slice-based filtering
38} 30}
39 31
40var ( 32var (
@@ -183,29 +175,23 @@ func (m Model) visibleItemsCount() int {
183 175
184// filterOptions filters and sorts options based on the search term 176// filterOptions filters and sorts options based on the search term
185func (m *Model) filterOptions() { 177func (m *Model) filterOptions() {
186 m.filteredKeys = []SelectionOption{} 178 m.filteredKeys = nil
187 179 for _, opt := range m.allOptions {
188 if m.useSliceMode { 180 if strings.Contains(strings.ToLower(opt.Label), strings.ToLower(m.filter)) {
189 // slice-based filtering, filter from the original options 181 m.filteredKeys = append(m.filteredKeys, opt)
190 for _, option := range m.originalOptions {
191 if strings.Contains(strings.ToLower(option.Label), strings.ToLower(m.filter)) {
192 m.filteredKeys = append(m.filteredKeys, option)
193 }
194 } 182 }
195 } else { 183 }
196 // map-based filtering 184
197 for key, value := range m.options { 185 // Sort the filtered options alphabetically unless this is a menu selection
198 // When the key is " ", compare and display using the value instead 186 isMenu := false
199 if key == " " { 187 for _, opt := range m.allOptions {
200 if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) { 188 if opt.Key == "ALL" || opt.Key == "CURRENT" {
201 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key}) 189 isMenu = true
202 } 190 break
203 } else if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
204 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
205 }
206 } 191 }
192 }
207 193
208 // Sort the filtered options alphabetically 194 if !isMenu {
209 sort.Slice(m.filteredKeys, func(i, j int) bool { 195 sort.Slice(m.filteredKeys, func(i, j int) bool {
210 return m.filteredKeys[i].Label < m.filteredKeys[j].Label 196 return m.filteredKeys[i].Label < m.filteredKeys[j].Label
211 }) 197 })
@@ -213,20 +199,12 @@ func (m *Model) filterOptions() {
213 199
214 // Add "Add new anime" option if enabled 200 // Add "Add new anime" option if enabled
215 if m.addNewOption { 201 if m.addNewOption {
216 m.filteredKeys = append(m.filteredKeys, SelectionOption{ 202 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"})
217 Label: "Add new anime",
218 Key: "add_new",
219 })
220 } 203 }
221 204 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Quit", Key: "-1"})
222 m.filteredKeys = append(m.filteredKeys, SelectionOption{
223 Label: "Quit",
224 Key: "-1",
225 })
226} 205}
227 206
228func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) { 207func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
229 // Pre-download first 14 images in background
230 go preDownloadImages(options, 14) 208 go preDownloadImages(options, 14)
231 209
232 userCurdConfig := GetGlobalConfig() 210 userCurdConfig := GetGlobalConfig()
@@ -234,62 +212,46 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
234 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd") 212 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
235 } 213 }
236 214
237 // Prepare Rofi input with anime titles and their cached image paths
238 var rofiInput strings.Builder 215 var rofiInput strings.Builder
239 for _, option := range options { 216 selectionOptions := make([]SelectionOption, 0, len(options))
240 // Download and get cache path for the image 217
241 cachePath, err := downloadToCache(option.CoverImage) 218 // Prepare options and rofi input
219 for id, opt := range options {
220 cachePath, err := downloadToCache(opt.CoverImage)
242 if err != nil { 221 if err != nil {
243 Log(fmt.Sprintf("Error caching image: %v", err)) 222 Log(fmt.Sprintf("Error caching image: %v", err))
244 continue 223 continue
245 } 224 }
246 225 rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", opt.Title, cachePath))
247 // Format: "Title\x00icon\x1f/path/to/cached/image\n" 226 selectionOptions = append(selectionOptions, SelectionOption{
248 // This tells Rofi to use the image as an icon for this entry 227 Label: opt.Title,
249 rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", option.Title, cachePath)) 228 Key: id,
229 })
250 } 230 }
251 231
252 // Add "Add new anime" and "Quit" options
253 if addnewoption { 232 if addnewoption {
254 rofiInput.WriteString("Add new anime\n") 233 rofiInput.WriteString("Add new anime\n")
255 } 234 }
256 rofiInput.WriteString("Quit\n") 235 rofiInput.WriteString("Quit\n")
257 236
258 // Get the absolute path to the rasi config 237 // Run rofi
259 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi") 238 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi")
260 239 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-show-icons", "-p", "Select Anime", "-i", "-no-custom")
261 // Create the command with explicit arguments 240 cmd.Stdin = strings.NewReader(rofiInput.String())
262 args := []string{
263 "-dmenu",
264 "-theme", configPath,
265 "-show-icons",
266 "-p", "Select Anime",
267 "-i", // Case-insensitive matching
268 "-no-custom", // Disable custom input
269 }
270
271 // Create the command
272 rofiCmd := exec.Command("rofi", args...)
273
274 // Set up pipes for input/output
275 rofiCmd.Stdin = strings.NewReader(rofiInput.String())
276 var stdout, stderr bytes.Buffer 241 var stdout, stderr bytes.Buffer
277 rofiCmd.Stdout = &stdout 242 cmd.Stdout = &stdout
278 rofiCmd.Stderr = &stderr 243 cmd.Stderr = &stderr
279 244
280 // Run the command 245 if err := cmd.Run(); err != nil {
281 err := rofiCmd.Run()
282 if err != nil {
283 // Log both stdout and stderr for debugging
284 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String())) 246 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
285 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String())) 247 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
286 return SelectionOption{}, fmt.Errorf("failed to execute rofi: %w", err) 248 return SelectionOption{}, fmt.Errorf("failed to execute rofi: %w", err)
287 } 249 }
288 250
289 selectedTitle := strings.TrimSpace(stdout.String()) 251 selected := strings.TrimSpace(stdout.String())
290 252
291 // Handle special cases 253 // Handle special cases
292 switch selectedTitle { 254 switch selected {
293 case "": 255 case "":
294 return SelectionOption{}, fmt.Errorf("no selection made") 256 return SelectionOption{}, fmt.Errorf("no selection made")
295 case "Add new anime": 257 case "Add new anime":
@@ -298,13 +260,10 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
298 return SelectionOption{Label: "Quit", Key: "-1"}, nil 260 return SelectionOption{Label: "Quit", Key: "-1"}, nil
299 } 261 }
300 262
301 // Find the selected anime in options 263 // Find matching option
302 for id, option := range options { 264 for _, opt := range selectionOptions {
303 if option.Title == selectedTitle { 265 if opt.Label == selected {
304 return SelectionOption{ 266 return opt, nil
305 Label: option.Title,
306 Key: id,
307 }, nil
308 } 267 }
309 } 268 }
310 269
@@ -375,60 +334,55 @@ func showCachedImagePreview(imageURL string) error {
375 return nil 334 return nil
376} 335}
377 336
378func RofiSelect(options map[string]string) (SelectionOption, error) { 337func RofiSelect(options []SelectionOption) (SelectionOption, error) {
379 userCurdConfig := GetGlobalConfig() 338 userCurdConfig := GetGlobalConfig()
380 if userCurdConfig.StoragePath == "" { 339 if userCurdConfig.StoragePath == "" {
381 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd") 340 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
382 } 341 }
383 342
384 // Create a slice to store the options in the order we want 343 // Create ordered list of options
385 var optionsList []string 344 var optionsList []string
386 for _, value := range options { 345 for _, opt := range options {
387 optionsList = append(optionsList, value) 346 optionsList = append(optionsList, opt.Label)
388 } 347 }
389 348
390 // Sort the options alphabetically 349 // Add "Quit" option at the end
391 sort.Strings(optionsList)
392
393 // Add "Quit" options
394 optionsList = append(optionsList, "Quit") 350 optionsList = append(optionsList, "Quit")
395
396 // Join all options into a single string, separated by newlines
397 optionsString := strings.Join(optionsList, "\n") 351 optionsString := strings.Join(optionsList, "\n")
398 352
399 // Prepare the Rofi command 353 // Prepare and run rofi
400 cmd := exec.Command("rofi", "-dmenu", "-theme", filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi"), "-i", "-p", "Select an anime") 354 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi")
401 355 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-i", "-p", "Select")
402 // Set up pipes for input and output
403 cmd.Stdin = strings.NewReader(optionsString) 356 cmd.Stdin = strings.NewReader(optionsString)
404 var out bytes.Buffer 357 var stdout, stderr bytes.Buffer
405 cmd.Stdout = &out 358 cmd.Stdout = &stdout
359 cmd.Stderr = &stderr
406 360
407 // Run the command
408 err := cmd.Run() 361 err := cmd.Run()
409 if err != nil { 362 if err != nil {
363 if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 {
364 return SelectionOption{Key: "-1", Label: ""}, nil
365 }
410 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err) 366 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
411 } 367 }
412 368
413 // Get the selected option 369 selected := strings.TrimSpace(stdout.String())
414 selected := strings.TrimSpace(out.String())
415 370
416 // Handle special cases 371 // Handle special cases
417 switch selected { 372 switch selected {
418 case "": 373 case "":
419 return SelectionOption{}, fmt.Errorf("no selection made") 374 return SelectionOption{Key: "-1", Label: ""}, nil
420 case "Quit": 375 case "Quit":
421 return SelectionOption{Label: "Quit", Key: "-1"}, nil 376 return SelectionOption{Label: "Quit", Key: "-1"}, nil
422 } 377 }
423 378
424 // Find the key for the selected value 379 // Find the matching SelectionOption
425 for key, value := range options { 380 for _, opt := range options {
426 if value == selected { 381 if opt.Label == selected {
427 return SelectionOption{Label: value, Key: key}, nil 382 return opt, nil
428 } 383 }
429 } 384 }
430 385
431 // If we get here, the selected option wasn't found in the original map
432 return SelectionOption{}, fmt.Errorf("selected option not found in original list") 386 return SelectionOption{}, fmt.Errorf("selected option not found in original list")
433} 387}
434 388
@@ -482,61 +436,42 @@ func DynamicSelectFromSlice(options []SelectionOption) (SelectionOption, error)
482} 436}
483 437
484// DynamicSelect displays a simple selection prompt without extra features 438// DynamicSelect displays a simple selection prompt without extra features
485func DynamicSelect(options map[string]string) (SelectionOption, error) { 439func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
486 if GetGlobalConfig().RofiSelection { 440 if GetGlobalConfig().RofiSelection {
487 return RofiSelect(options) 441 return RofiSelect(options)
488 } 442 }
489 443
490 // Create a slice to maintain order 444 // Sort options if this contains menu categories
491 var orderedOptions []SelectionOption 445 for _, opt := range options {
446 if opt.Key == "ALL" || opt.Key == "CURRENT" {
447 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",")
448 optMap := make(map[string]SelectionOption)
449 for _, opt := range options {
450 optMap[opt.Key] = opt
451 }
492 452
493 // If this is a category selection (contains menu items), use the ordered keys 453 sorted := make([]SelectionOption, 0, len(options))
494 if _, hasMenu := options["ALL"]; hasMenu { 454 for _, key := range menuOrder {
495 // Get the menu order from config 455 if opt, exists := optMap[key]; exists {
496 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",") 456 sorted = append(sorted, opt)
497 457 }
498 // Add options in the specified order
499 for _, key := range menuOrder {
500 if value, exists := options[key]; exists {
501 orderedOptions = append(orderedOptions, SelectionOption{
502 Key: key,
503 Label: value,
504 })
505 } 458 }
506 } 459 options = sorted
507 } else { 460 break
508 // For other selections, preserve the order as passed in
509 // Since Go maps don't preserve insertion order, we need to handle this differently
510 // For now, we'll use the order as it comes from the map iteration
511 // (This will be random, but it's better than alphabetical sorting for search results)
512 for key, value := range options {
513 orderedOptions = append(orderedOptions, SelectionOption{
514 Key: key,
515 Label: value,
516 })
517 } 461 }
518 } 462 }
519 463
520 model := &Model{ 464 model := &Model{
521 options: options, 465 allOptions: options,
522 filteredKeys: orderedOptions,
523 } 466 }
467 model.filterOptions() // Initialize filtered options
524 468
525 model.filteredKeys = append(model.filteredKeys, SelectionOption{
526 Label: "Quit",
527 Key: "-1",
528 })
529
530 // Create a program with altScreen option turned off to maintain the terminal state
531 // This prevents the terminal from switching to an alternate screen
532 p := tea.NewProgram(model) 469 p := tea.NewProgram(model)
533
534 finalModel, err := p.Run() 470 finalModel, err := p.Run()
535 if err != nil { 471 if err != nil {
536 return SelectionOption{}, err 472 return SelectionOption{}, err
537 } 473 }
538 474
539 // Explicitly reset the terminal state
540 fmt.Print("\033[?25h") // Show cursor 475 fmt.Print("\033[?25h") // Show cursor
541 fmt.Print("\033[?7h") // Enable line wrapping 476 fmt.Print("\033[?7h") // Enable line wrapping
542 477
internal/structs.go +18 −5
@@ -106,14 +106,27 @@ type Entry struct {
106} 106}
107 107
108type AnimeList struct { 108type AnimeList struct {
109 Watching []Entry `json:"watching"` 109 Watching []Entry `json:"watching"`
110 Completed []Entry `json:"completed"` 110 Completed []Entry `json:"completed"`
111 Paused []Entry `json:"paused"` 111 Paused []Entry `json:"paused"`
112 Dropped []Entry `json:"dropped"` 112 Dropped []Entry `json:"dropped"`
113 Planning []Entry `json:"planning"` 113 Planning []Entry `json:"planning"`
114 Rewatching []Entry `json:"rewatching"`
114} 115}
115 116
116type RofiSelectPreview struct { 117type RofiSelectPreview struct {
117 Title string `json:"title"` 118 Title string `json:"title"`
118 CoverImage string `json:"coverImage"` 119 CoverImage string `json:"coverImage"`
119} 120}
121
122type SelectionOptionImage struct {
123 Key string
124 Label string
125 CoverImage string
126}
127
128// SelectionOption holds the label and the internal key
129type SelectionOption struct {
130 Label string
131 Key string
132}\ No newline at end of file