Commit 2f65b88fc2

2f65b88fc2a05e577a63bba0bd2d539ee743ccb6

parent: 60ab61d418

Unsigned

Wraient <wraient.911@gmail.com> · 2026-04-15 17:52 UTC

feat: Anilist Caching

Layout: unified · split

internal/anilist.go +2 −3
@@ -804,7 +804,6 @@ func makePostRequest(url, query string, variables map[string]interface{}, header
804 804
805func ParseAnimeList(input map[string]interface{}) AnimeList { 805func ParseAnimeList(input map[string]interface{}) AnimeList {
806 var animeList AnimeList 806 var animeList AnimeList
807 userCurdConfig := GetGlobalConfig()
808 807
809 toInt := func(value interface{}) int { 808 toInt := func(value interface{}) int {
810 switch v := value.(type) { 809 switch v := value.(type) {
@@ -880,8 +879,8 @@ func ParseAnimeList(input map[string]interface{}) AnimeList {
880 CompletedAt: parseFuzzyDate(entryData["completedAt"]), 879 CompletedAt: parseFuzzyDate(entryData["completedAt"]),
881 } 880 }
882 881
883 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 882 if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
884 animeEntry.CoverImage = safeString(media["coverImage"].(map[string]interface{})["large"]) 883 animeEntry.CoverImage = safeString(coverImage["large"])
885 } 884 }
886 885
887 // Append entries based on their status 886 // Append entries based on their status
internal/anilist_cache.go added +301
@@ -0,0 +1,301 @@
1package internal
2
3import (
4 "encoding/json"
5 "fmt"
6 "os"
7 "path/filepath"
8 "strconv"
9 "sync"
10 "time"
11)
12
13const animeListCacheFileName = "anilist_list_cache.json"
14
15type animeListCachePayload struct {
16 AnimeList AnimeList `json:"anime_list"`
17 UpdatedAt time.Time `json:"updated_at"`
18 UserID int `json:"user_id"`
19}
20
21type AnimeListSync struct {
22 mu sync.RWMutex
23 current AnimeList
24 updates chan AnimeList
25 refreshDone chan struct{} // closed exactly once when the background refresh finishes
26 closeOnce sync.Once
27}
28
29func NewAnimeListSync(initial AnimeList) *AnimeListSync {
30 return &AnimeListSync{
31 current: initial,
32 updates: make(chan AnimeList, 1),
33 refreshDone: make(chan struct{}),
34 }
35}
36
37// MarkRefreshDone closes the refreshDone channel exactly once.
38func (s *AnimeListSync) MarkRefreshDone() {
39 s.closeOnce.Do(func() { close(s.refreshDone) })
40}
41
42// RefreshDone returns a channel that is closed when the background refresh finishes.
43func (s *AnimeListSync) RefreshDone() <-chan struct{} {
44 return s.refreshDone
45}
46
47func (s *AnimeListSync) Current() AnimeList {
48 s.mu.RLock()
49 defer s.mu.RUnlock()
50 return s.current
51}
52
53func (s *AnimeListSync) Replace(list AnimeList, notify bool) bool {
54 s.mu.Lock()
55 changed := !animeListEqual(s.current, list)
56 s.current = list
57 s.mu.Unlock()
58
59 if changed && notify {
60 select {
61 case s.updates <- list:
62 default:
63 select {
64 case <-s.updates:
65 default:
66 }
67 s.updates <- list
68 }
69 }
70
71 return changed
72}
73
74func (s *AnimeListSync) Updates() <-chan AnimeList {
75 return s.updates
76}
77
78func animeListCachePath(storagePath string) string {
79 return filepath.Join(os.ExpandEnv(storagePath), animeListCacheFileName)
80}
81
82func loadAnimeListCache(storagePath string, userID int) (animeListCachePayload, error) {
83 cacheFilePath := animeListCachePath(storagePath)
84 data, err := os.ReadFile(cacheFilePath)
85 if err != nil {
86 return animeListCachePayload{}, err
87 }
88
89 var payload animeListCachePayload
90 if err := json.Unmarshal(data, &payload); err != nil {
91 return animeListCachePayload{}, fmt.Errorf("failed to parse anime list cache: %w", err)
92 }
93
94 if payload.UserID != 0 && userID != 0 && payload.UserID != userID {
95 return animeListCachePayload{}, fmt.Errorf("anime list cache belongs to a different AniList user")
96 }
97
98 return payload, nil
99}
100
101func saveAnimeListCache(storagePath string, userID int, list AnimeList) error {
102 storagePath = os.ExpandEnv(storagePath)
103 if err := os.MkdirAll(storagePath, 0o755); err != nil {
104 return fmt.Errorf("failed to create storage directory: %w", err)
105 }
106
107 payload := animeListCachePayload{
108 AnimeList: list,
109 UpdatedAt: time.Now(),
110 UserID: userID,
111 }
112
113 data, err := json.MarshalIndent(payload, "", " ")
114 if err != nil {
115 return fmt.Errorf("failed to marshal anime list cache: %w", err)
116 }
117
118 cacheFilePath := animeListCachePath(storagePath)
119 tempFilePath := cacheFilePath + ".tmp"
120 if err := os.WriteFile(tempFilePath, data, 0o644); err != nil {
121 return fmt.Errorf("failed to write anime list cache: %w", err)
122 }
123
124 if err := os.Rename(tempFilePath, cacheFilePath); err != nil {
125 _ = os.Remove(tempFilePath)
126 return fmt.Errorf("failed to replace anime list cache: %w", err)
127 }
128
129 return nil
130}
131
132func animeListEqual(a, b AnimeList) bool {
133 left, err := json.Marshal(a)
134 if err != nil {
135 return false
136 }
137 right, err := json.Marshal(b)
138 if err != nil {
139 return false
140 }
141 return string(left) == string(right)
142}
143
144func FetchLatestAnimeList(token string, userID int) (AnimeList, error) {
145 userData, err := GetUserDataPreview(token, userID)
146 if err != nil {
147 return AnimeList{}, err
148 }
149
150 return ParseAnimeList(userData), nil
151}
152
153func refreshAnimeListInBackground(userCurdConfig *CurdConfig, user *User) {
154 if user == nil || user.ListSync == nil {
155 return
156 }
157
158 go func() {
159 // Signal done regardless of success/failure so callers never block forever.
160 defer user.ListSync.MarkRefreshDone()
161
162 // Only fetch the user ID when we don't already have it (first run, no cache).
163 // On cache hits user.Id is already seeded, so skip this extra round-trip.
164 if user.Id == 0 {
165 userID, username, err := GetAnilistUserID(user.Token)
166 if err != nil {
167 Log(fmt.Sprintf("Failed to refresh user ID in background: %v", err))
168 return
169 }
170 user.Id = userID
171 if user.Username == "" {
172 user.Username = username
173 }
174 }
175
176 latestList, err := FetchLatestAnimeList(user.Token, user.Id)
177 if err != nil {
178 Log(fmt.Sprintf("Failed to refresh anime list in background: %v", err))
179 return
180 }
181
182 if err := saveAnimeListCache(userCurdConfig.StoragePath, user.Id, latestList); err != nil {
183 Log(fmt.Sprintf("Failed to save refreshed anime list cache: %v", err))
184 }
185
186 user.ListSync.Replace(latestList, true)
187 }()
188}
189
190func InitializeUserAnimeList(userCurdConfig *CurdConfig, user *User) error {
191 cachedPayload, err := loadAnimeListCache(userCurdConfig.StoragePath, user.Id)
192 if err == nil {
193 // Seed user ID from cache so we skip the blocking GetAnilistUserID network call.
194 if user.Id == 0 && cachedPayload.UserID != 0 {
195 user.Id = cachedPayload.UserID
196 }
197 user.AnimeList = cachedPayload.AnimeList
198 user.ListSync = NewAnimeListSync(cachedPayload.AnimeList)
199 // Refresh user ID + anime list in the background (non-blocking).
200 refreshAnimeListInBackground(userCurdConfig, user)
201 return nil
202 }
203
204 if !os.IsNotExist(err) {
205 Log(fmt.Sprintf("Failed to load anime list cache, fetching latest instead: %v", err))
206 }
207
208 // No cache — blocking fetch is unavoidable on first run.
209 if user.Id == 0 {
210 userID, username, idErr := GetAnilistUserID(user.Token)
211 if idErr != nil {
212 return idErr
213 }
214 user.Id = userID
215 user.Username = username
216 }
217
218 latestList, err := FetchLatestAnimeList(user.Token, user.Id)
219 if err != nil {
220 return err
221 }
222
223 user.AnimeList = latestList
224 user.ListSync = NewAnimeListSync(latestList)
225 // Blocking fetch already has the freshest data — mark done immediately.
226 user.ListSync.MarkRefreshDone()
227 if err := saveAnimeListCache(userCurdConfig.StoragePath, user.Id, latestList); err != nil {
228 Log(fmt.Sprintf("Failed to save anime list cache: %v", err))
229 }
230
231 return nil
232}
233
234func RefreshUserAnimeList(userCurdConfig *CurdConfig, user *User) error {
235 if user.Id == 0 {
236 userID, username, err := GetAnilistUserID(user.Token)
237 if err != nil {
238 return err
239 }
240 user.Id = userID
241 if user.Username == "" {
242 user.Username = username
243 }
244 }
245
246 latestList, err := FetchLatestAnimeList(user.Token, user.Id)
247 if err != nil {
248 return err
249 }
250
251 user.AnimeList = latestList
252 if user.ListSync == nil {
253 user.ListSync = NewAnimeListSync(latestList)
254 } else {
255 user.ListSync.Replace(latestList, true)
256 }
257
258 if err := saveAnimeListCache(userCurdConfig.StoragePath, user.Id, latestList); err != nil {
259 Log(fmt.Sprintf("Failed to save anime list cache: %v", err))
260 }
261
262 return nil
263}
264
265func buildCategorySelectionOptions(list AnimeList, category string) []SelectionOption {
266 userCurdConfig := GetGlobalConfig()
267 options := make([]SelectionOption, 0)
268
269 for _, entry := range getEntriesByCategory(list, category) {
270 title := entry.Media.Title.English
271 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
272 title = entry.Media.Title.Romaji
273 }
274
275 options = append(options, SelectionOption{
276 Key: strconv.Itoa(entry.Media.ID),
277 Label: title,
278 })
279 }
280
281 return options
282}
283
284func buildCategoryPreviewOptions(list AnimeList, category string) map[string]RofiSelectPreview {
285 userCurdConfig := GetGlobalConfig()
286 options := make(map[string]RofiSelectPreview)
287
288 for _, entry := range getEntriesByCategory(list, category) {
289 title := entry.Media.Title.English
290 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
291 title = entry.Media.Title.Romaji
292 }
293
294 options[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
295 Title: title,
296 CoverImage: entry.CoverImage,
297 }
298 }
299
300 return options
301}
internal/curd.go +109 −246
@@ -242,132 +242,14 @@ updateOptionLoop:
242 var animeListOptions []SelectionOption 242 var animeListOptions []SelectionOption
243 var animeListMapPreview map[string]RofiSelectPreview 243 var animeListMapPreview map[string]RofiSelectPreview
244 244
245 if user.ListSync != nil {
246 user.AnimeList = user.ListSync.Current()
247 }
248
245 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 249 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
246 animeListMapPreview = make(map[string]RofiSelectPreview) 250 animeListMapPreview = buildCategoryPreviewOptions(user.AnimeList, "ALL")
247 // Include anime from all categories
248 for _, entry := range user.AnimeList.Watching {
249 title := entry.Media.Title.English
250 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
251 title = entry.Media.Title.Romaji
252 }
253 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
254 Title: title,
255 CoverImage: entry.CoverImage,
256 }
257 }
258 for _, entry := range user.AnimeList.Completed {
259 title := entry.Media.Title.English
260 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
261 title = entry.Media.Title.Romaji
262 }
263 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
264 Title: title,
265 CoverImage: entry.CoverImage,
266 }
267 }
268 for _, entry := range user.AnimeList.Paused {
269 title := entry.Media.Title.English
270 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
271 title = entry.Media.Title.Romaji
272 }
273 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
274 Title: title,
275 CoverImage: entry.CoverImage,
276 }
277 }
278 for _, entry := range user.AnimeList.Dropped {
279 title := entry.Media.Title.English
280 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
281 title = entry.Media.Title.Romaji
282 }
283 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
284 Title: title,
285 CoverImage: entry.CoverImage,
286 }
287 }
288 for _, entry := range user.AnimeList.Planning {
289 title := entry.Media.Title.English
290 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
291 title = entry.Media.Title.Romaji
292 }
293 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
294 Title: title,
295 CoverImage: entry.CoverImage,
296 }
297 }
298 for _, entry := range user.AnimeList.Rewatching {
299 title := entry.Media.Title.English
300 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
301 title = entry.Media.Title.Romaji
302 }
303 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
304 Title: title,
305 CoverImage: entry.CoverImage,
306 }
307 }
308 } else { 251 } else {
309 animeListOptions = make([]SelectionOption, 0) 252 animeListOptions = buildCategorySelectionOptions(user.AnimeList, "ALL")
310 // Include anime from all categories
311 for _, entry := range user.AnimeList.Watching {
312 title := entry.Media.Title.English
313 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
314 title = entry.Media.Title.Romaji
315 }
316 animeListOptions = append(animeListOptions, SelectionOption{
317 Key: strconv.Itoa(entry.Media.ID),
318 Label: title,
319 })
320 }
321 for _, entry := range user.AnimeList.Completed {
322 title := entry.Media.Title.English
323 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
324 title = entry.Media.Title.Romaji
325 }
326 animeListOptions = append(animeListOptions, SelectionOption{
327 Key: strconv.Itoa(entry.Media.ID),
328 Label: title,
329 })
330 }
331 for _, entry := range user.AnimeList.Paused {
332 title := entry.Media.Title.English
333 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
334 title = entry.Media.Title.Romaji
335 }
336 animeListOptions = append(animeListOptions, SelectionOption{
337 Key: strconv.Itoa(entry.Media.ID),
338 Label: title,
339 })
340 }
341 for _, entry := range user.AnimeList.Dropped {
342 title := entry.Media.Title.English
343 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
344 title = entry.Media.Title.Romaji
345 }
346 animeListOptions = append(animeListOptions, SelectionOption{
347 Key: strconv.Itoa(entry.Media.ID),
348 Label: title,
349 })
350 }
351 for _, entry := range user.AnimeList.Planning {
352 title := entry.Media.Title.English
353 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
354 title = entry.Media.Title.Romaji
355 }
356 animeListOptions = append(animeListOptions, SelectionOption{
357 Key: strconv.Itoa(entry.Media.ID),
358 Label: title,
359 })
360 }
361 for _, entry := range user.AnimeList.Rewatching {
362 title := entry.Media.Title.English
363 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
364 title = entry.Media.Title.Romaji
365 }
366 animeListOptions = append(animeListOptions, SelectionOption{
367 Key: strconv.Itoa(entry.Media.ID),
368 Label: title,
369 })
370 }
371 } 253 }
372 254
373 // Anime selection loop 255 // Anime selection loop
@@ -376,9 +258,19 @@ updateOptionLoop:
376 // Select anime to update 258 // Select anime to update
377 var selectedAnime SelectionOption 259 var selectedAnime SelectionOption
378 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 260 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
379 selectedAnime, err = DynamicSelectPreview(animeListMapPreview, false) 261 selectedAnime, err = DynamicSelectPreviewWithRefresh(animeListMapPreview, false, &PreviewSelectionRefreshConfig{
262 Updates: user.ListSync.Updates(),
263 BuildOptions: func(list AnimeList) map[string]RofiSelectPreview {
264 return buildCategoryPreviewOptions(list, "ALL")
265 },
266 })
380 } else { 267 } else {
381 selectedAnime, err = DynamicSelect(animeListOptions) 268 selectedAnime, err = DynamicSelectWithRefresh(animeListOptions, &SelectionRefreshConfig{
269 Updates: user.ListSync.Updates(),
270 BuildOptions: func(list AnimeList) []SelectionOption {
271 return buildCategorySelectionOptions(list, "ALL")
272 },
273 })
382 } 274 }
383 if err != nil { 275 if err != nil {
384 Log(fmt.Sprintf("Failed to select anime: %v", err)) 276 Log(fmt.Sprintf("Failed to select anime: %v", err))
@@ -401,6 +293,10 @@ updateOptionLoop:
401 ExitCurd(fmt.Errorf("Failed to convert anime ID")) 293 ExitCurd(fmt.Errorf("Failed to convert anime ID"))
402 } 294 }
403 295
296 if user.ListSync != nil {
297 user.AnimeList = user.ListSync.Current()
298 }
299
404 // After getting animeID, get the current anime entry 300 // After getting animeID, get the current anime entry
405 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key) 301 selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key)
406 if err != nil { 302 if err != nil {
@@ -501,6 +397,11 @@ updateOptionLoop:
501 } 397 }
502 } 398 }
503 399
400 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
401 Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
402 ExitCurd(fmt.Errorf("Failed to refresh anime list"))
403 }
404
504 CurdOut("Anime updated successfully!") 405 CurdOut("Anime updated successfully!")
505 return 406 return
506 } 407 }
@@ -702,21 +603,9 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
702 ExitCurd(fmt.Errorf("Failed to add anime to list")) 603 ExitCurd(fmt.Errorf("Failed to add anime to list"))
703 } 604 }
704 605
705 // Refresh user's anime list after adding 606 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
706 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 607 Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
707 anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id) 608 ExitCurd(fmt.Errorf("Failed to refresh anime list"))
708 if err != nil {
709 Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
710 ExitCurd(fmt.Errorf("Failed to refresh anime list"))
711 }
712 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
713 } else {
714 anilistUserData, err := GetUserData(user.Token, user.Id)
715 if err != nil {
716 Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
717 ExitCurd(fmt.Errorf("Failed to refresh anime list"))
718 }
719 user.AnimeList = ParseAnimeList(anilistUserData)
720 } 609 }
721 610
722 return anilistSelectedOption 611 return anilistSelectedOption
@@ -724,36 +613,19 @@ func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseA
724 613
725func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) { 614func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) {
726 var err error 615 var err error
727 var anilistUserData map[string]interface{}
728 var anilistUserDataPreview map[string]interface{}
729 var startingRewatch bool 616 var startingRewatch bool
730 617
731 // Filter anime list based on selected category 618 // Filter anime list based on selected category
732 var animeListOptions []SelectionOption 619 var animeListOptions []SelectionOption
733 var animeListMapPreview map[string]RofiSelectPreview 620 var animeListMapPreview map[string]RofiSelectPreview
734 621
735 // Get user id, username and Anime list 622 // Initialize anime list. On a cache hit this is instant (reads from disk) and
736 user.Id, user.Username, err = GetAnilistUserID(user.Token) 623 // the user ID is seeded from the cached payload, avoiding a blocking network
737 if err != nil { 624 // round-trip to AniList. The real user ID + latest list are refreshed in the
738 Log(fmt.Sprintf("Failed to get user ID: %v", err)) 625 // background goroutine inside InitializeUserAnimeList.
739 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`")) 626 if err := InitializeUserAnimeList(userCurdConfig, user); err != nil {
740 } 627 Log(fmt.Sprintf("Failed to initialize anime list: %v", err))
741 628 ExitCurd(fmt.Errorf("Failed to get user data\nYou can reset the token by running `curd -change-token`"))
742 // Get the anime list data
743 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
744 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
745 if err != nil {
746 Log(fmt.Sprintf("Failed to get user data preview: %v", err))
747 ExitCurd(fmt.Errorf("Failed to get user data preview"))
748 }
749 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
750 } else {
751 anilistUserData, err = GetUserData(user.Token, user.Id)
752 if err != nil {
753 Log(fmt.Sprintf("Failed to get user data: %v", err))
754 ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
755 }
756 user.AnimeList = ParseAnimeList(anilistUserData)
757 } 629 }
758 630
759 // Variables for selection results (used in both branches and after) 631 // Variables for selection results (used in both branches and after)
@@ -849,30 +721,14 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
849 ClearScreen() 721 ClearScreen()
850 } 722 }
851 723
724 if user.ListSync != nil {
725 user.AnimeList = user.ListSync.Current()
726 }
727
852 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 728 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
853 animeListMapPreview = make(map[string]RofiSelectPreview) 729 animeListMapPreview = buildCategoryPreviewOptions(user.AnimeList, categorySelection.Key)
854 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
855 title := entry.Media.Title.English
856 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
857 title = entry.Media.Title.Romaji
858 }
859 animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
860 Title: title,
861 CoverImage: entry.CoverImage,
862 }
863 }
864 } else { 730 } else {
865 animeListOptions = make([]SelectionOption, 0) 731 animeListOptions = buildCategorySelectionOptions(user.AnimeList, categorySelection.Key)
866 for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
867 title := entry.Media.Title.English
868 if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
869 title = entry.Media.Title.Romaji
870 }
871 animeListOptions = append(animeListOptions, SelectionOption{
872 Key: strconv.Itoa(entry.Media.ID),
873 Label: title,
874 })
875 }
876 } 732 }
877 733
878 // Anime selection loop (for back navigation) 734 // Anime selection loop (for back navigation)
@@ -901,7 +757,12 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
901 // Select anime to watch (Anilist) 757 // Select anime to watch (Anilist)
902 var err error 758 var err error
903 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 759 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
904 anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true) 760 anilistSelectedOption, err = DynamicSelectPreviewWithRefresh(animeListMapPreview, true, &PreviewSelectionRefreshConfig{
761 Updates: user.ListSync.Updates(),
762 BuildOptions: func(list AnimeList) map[string]RofiSelectPreview {
763 return buildCategoryPreviewOptions(list, categorySelection.Key)
764 },
765 })
905 } else { 766 } else {
906 // Add "Add new anime" option to the slice 767 // Add "Add new anime" option to the slice
907 tempOptions := make([]SelectionOption, len(animeListOptions)) 768 tempOptions := make([]SelectionOption, len(animeListOptions))
@@ -911,7 +772,17 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
911 Label: "Add new anime", 772 Label: "Add new anime",
912 }) 773 })
913 774
914 anilistSelectedOption, err = DynamicSelect(tempOptions) 775 anilistSelectedOption, err = DynamicSelectWithRefresh(tempOptions, &SelectionRefreshConfig{
776 Updates: user.ListSync.Updates(),
777 BuildOptions: func(list AnimeList) []SelectionOption {
778 updatedOptions := buildCategorySelectionOptions(list, categorySelection.Key)
779 updatedOptions = append(updatedOptions, SelectionOption{
780 Key: "add_new",
781 Label: "Add new anime",
782 })
783 return updatedOptions
784 },
785 })
915 } 786 }
916 if err != nil { 787 if err != nil {
917 Log(fmt.Sprintf("Error selecting anime: %v", err)) 788 Log(fmt.Sprintf("Error selecting anime: %v", err))
@@ -955,7 +826,20 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
955 } 826 }
956 } 827 }
957 } 828 }
958 // Find anime in Local history 829 // Wait for the background refresh goroutine to finish before reading
830 // progress+1. RefreshDone() is a channel that is closed (broadcast) the
831 // instant the goroutine completes — no polling, no race with the UI
832 // Updates consumer that already drained the updates channel.
833 if user.ListSync != nil {
834 select {
835 case <-user.ListSync.RefreshDone():
836 Log("Background refresh done, using latest anime list for playback")
837 case <-time.After(10 * time.Second):
838 Log("Timed out waiting for background anime list refresh; using cached list")
839 }
840 user.AnimeList = user.ListSync.Current()
841 }
842
959 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "") 843 animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
960 844
961 // Get anime entry 845 // Get anime entry
@@ -993,20 +877,9 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
993 startingRewatch = true 877 startingRewatch = true
994 CurdOut("Moved anime to Rewatching and restarting from episode 1.") 878 CurdOut("Moved anime to Rewatching and restarting from episode 1.")
995 879
996 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 880 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
997 anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id) 881 Log("Error refreshing anime list: " + err.Error())
998 if err != nil { 882 ExitCurd(err)
999 Log("Error refreshing anime list: " + err.Error())
1000 ExitCurd(err)
1001 }
1002 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
1003 } else {
1004 anilistUserData, err = GetUserData(user.Token, user.Id)
1005 if err != nil {
1006 Log("Error refreshing anime list: " + err.Error())
1007 ExitCurd(err)
1008 }
1009 user.AnimeList = ParseAnimeList(anilistUserData)
1010 } 883 }
1011 } 884 }
1012 885
@@ -1021,37 +894,39 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1021 Log(fmt.Sprintf("Failed to select anime: %v", err)) 894 Log(fmt.Sprintf("Failed to select anime: %v", err))
1022 ExitCurd(fmt.Errorf("Failed to select anime")) 895 ExitCurd(fmt.Errorf("Failed to select anime"))
1023 } 896 }
1024 // Prompt user for manual query when no results found 897 // Prompt user for manual query only when no results were found
1025 for { 898 if len(animeList) == 0 {
1026 var manualQuery string 899 for {
1027 if userCurdConfig.RofiSelection { 900 var manualQuery string
1028 userInput, err := GetUserInputFromRofi(fmt.Sprintf("No results found for '%s'. Press Enter to search with AniList name, or enter a custom name to search on AllAnime.", userQuery)) 901 if userCurdConfig.RofiSelection {
1029 if err != nil { 902 userInput, err := GetUserInputFromRofi(fmt.Sprintf("No results found for '%s'. Press Enter to search with AniList name, or enter a custom name to search on AllAnime.", userQuery))
1030 Log("Error getting user input: " + err.Error()) 903 if err != nil {
1031 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error())) 904 Log("Error getting user input: " + err.Error())
905 ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
906 }
907 manualQuery = userInput
908 } else {
909 CurdOut(fmt.Sprintf("No results found for '%s'.", userQuery))
910 CurdOut("Press Enter to search with AniList name, or enter a custom name to search on AllAnime:")
911 reader := bufio.NewReader(os.Stdin)
912 input, _ := reader.ReadString('\n')
913 manualQuery = strings.TrimSpace(input)
1032 } 914 }
1033 manualQuery = userInput
1034 } else {
1035 CurdOut(fmt.Sprintf("No results found for '%s'.", userQuery))
1036 CurdOut("Press Enter to search with AniList name, or enter a custom name to search on AllAnime:")
1037 reader := bufio.NewReader(os.Stdin)
1038 input, _ := reader.ReadString('\n')
1039 manualQuery = strings.TrimSpace(input)
1040 }
1041 915
1042 // If empty, use original AniList name 916 // If empty, use original AniList name
1043 if manualQuery == "" { 917 if manualQuery == "" {
1044 manualQuery = string(userQuery) 918 manualQuery = string(userQuery)
1045 } 919 }
1046 920
1047 animeList, err = SearchAnime(manualQuery, userCurdConfig.SubOrDub) 921 animeList, err = SearchAnime(manualQuery, userCurdConfig.SubOrDub)
1048 if err != nil { 922 if err != nil {
1049 Log(fmt.Sprintf("Failed to search anime with query '%s': %v", manualQuery, err)) 923 Log(fmt.Sprintf("Failed to search anime with query '%s': %v", manualQuery, err))
1050 ExitCurd(fmt.Errorf("Failed to search anime")) 924 ExitCurd(fmt.Errorf("Failed to search anime"))
1051 } 925 }
1052 926
1053 if len(animeList) > 0 { 927 if len(animeList) > 0 {
1054 break 928 break
929 }
1055 } 930 }
1056 } 931 }
1057 932
@@ -1216,21 +1091,9 @@ func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAni
1216 Log("Error adding anime to watching list: " + err.Error()) 1091 Log("Error adding anime to watching list: " + err.Error())
1217 ExitCurd(err) 1092 ExitCurd(err)
1218 } 1093 }
1219 // Refresh user's anime list after adding 1094 if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
1220 if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview { 1095 Log("Error refreshing anime list: " + err.Error())
1221 anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id) 1096 ExitCurd(err)
1222 if err != nil {
1223 Log("Error refreshing anime list: " + err.Error())
1224 ExitCurd(err)
1225 }
1226 user.AnimeList = ParseAnimeList(anilistUserDataPreview)
1227 } else {
1228 anilistUserData, err := GetUserData(user.Token, user.Id)
1229 if err != nil {
1230 Log("Error refreshing anime list: " + err.Error())
1231 ExitCurd(err)
1232 }
1233 user.AnimeList = ParseAnimeList(anilistUserData)
1234 } 1097 }
1235 } else if selectedOption.Key == "-1" { 1098 } else if selectedOption.Key == "-1" {
1236 ExitCurd(nil) 1099 ExitCurd(nil)
internal/selection_menu.go +390 −161
@@ -9,6 +9,7 @@ import (
9 "os" 9 "os"
10 "os/exec" 10 "os/exec"
11 "path/filepath" 11 "path/filepath"
12 "reflect"
12 "sort" 13 "sort"
13 "strings" 14 "strings"
14 "time" 15 "time"
@@ -30,6 +31,20 @@ type Model struct {
30 isHomeMenu bool // If true, ESC quits; if false, ESC goes back 31 isHomeMenu bool // If true, ESC quits; if false, ESC goes back
31} 32}
32 33
34type optionsRefreshedMsg struct {
35 options []SelectionOption
36}
37
38type SelectionRefreshConfig struct {
39 Updates <-chan AnimeList
40 BuildOptions func(AnimeList) []SelectionOption
41}
42
43type PreviewSelectionRefreshConfig struct {
44 Updates <-chan AnimeList
45 BuildOptions func(AnimeList) map[string]RofiSelectPreview
46}
47
33var ( 48var (
34 // Style definitions 49 // Style definitions
35 titleStyle = lipgloss.NewStyle(). 50 titleStyle = lipgloss.NewStyle().
@@ -79,6 +94,9 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
79 updateFilter := false 94 updateFilter := false
80 95
81 switch msg := msg.(type) { 96 switch msg := msg.(type) {
97 case optionsRefreshedMsg:
98 m.replaceOptions(msg.options)
99 return m, nil
82 case tea.KeyMsg: 100 case tea.KeyMsg:
83 switch msg.String() { 101 switch msg.String() {
84 case "ctrl+c": 102 case "ctrl+c":
@@ -145,6 +163,48 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
145 return m, nil 163 return m, nil
146} 164}
147 165
166func (m *Model) replaceOptions(options []SelectionOption) {
167 previousIndex := m.selected
168 previousKey := ""
169 previousLabel := ""
170
171 if m.selected >= 0 && m.selected < len(m.filteredKeys) {
172 previousKey = m.filteredKeys[m.selected].Key
173 previousLabel = m.filteredKeys[m.selected].Label
174 }
175
176 m.allOptions = options
177 m.filterOptions()
178
179 if len(m.filteredKeys) == 0 {
180 m.selected = 0
181 m.scrollOffset = 0
182 return
183 }
184
185 m.selected = findSelectionIndex(m.filteredKeys, previousKey, previousLabel, previousIndex)
186 if m.selected < 0 {
187 m.selected = 0
188 }
189
190 if m.selected < m.scrollOffset {
191 m.scrollOffset = m.selected
192 }
193
194 visibleCount := m.visibleItemsCount()
195 if visibleCount <= 0 {
196 m.scrollOffset = 0
197 return
198 }
199
200 if m.selected >= m.scrollOffset+visibleCount {
201 m.scrollOffset = m.selected - visibleCount + 1
202 }
203 if m.scrollOffset < 0 {
204 m.scrollOffset = 0
205 }
206}
207
148// View renders the UI and only shows as many options as fit in the terminal 208// View renders the UI and only shows as many options as fit in the terminal
149func (m Model) View() string { 209func (m Model) View() string {
150 var b strings.Builder 210 var b strings.Builder
@@ -209,70 +269,219 @@ func (m *Model) filterOptions() {
209 }) 269 })
210 } 270 }
211 271
212 // Add "Add new anime" option if enabled 272 // Determine whether the current filter is a substring of the pinned labels.
273 // When the filter matches "back" (e.g. "b", "ba", "bac", "back"), Back should
274 // appear BEFORE "Add new anime" so it is easy to reach. Otherwise keep the
275 // default order: Add new anime → Back → Quit.
276 // All three pinned items are always shown regardless of filter text.
277 filterLower := strings.ToLower(m.filter)
278 backMatchesFilter := filterLower != "" && strings.Contains("back", filterLower)
279
280 // If filter targets "back", pin it above Add new anime
281 if !m.isHomeMenu && backMatchesFilter {
282 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Back", Key: "-2"})
283 }
284
285 // Add new anime is always shown (pinned)
213 if m.addNewOption { 286 if m.addNewOption {
214 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"}) 287 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"})
215 } 288 }
216 // Add Back option before Quit (only for non-home menus) 289
217 if !m.isHomeMenu { 290 // Back in its default position (after Add new anime) when filter doesn't target it
291 if !m.isHomeMenu && !backMatchesFilter {
218 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Back", Key: "-2"}) 292 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Back", Key: "-2"})
219 } 293 }
294
295 // Quit is always last
220 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Quit", Key: "-1"}) 296 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Quit", Key: "-1"})
221} 297}
222 298
223func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) { 299func detectHomeMenu(options []SelectionOption) bool {
224 go preDownloadImages(options, 14) 300 for _, opt := range options {
301 if opt.Key == "ALL" || opt.Key == "CURRENT" {
302 return true
303 }
304 }
305 return false
306}
225 307
226 userCurdConfig := GetGlobalConfig() 308func findSelectionIndex(options []SelectionOption, previousKey string, previousLabel string, fallbackIndex int) int {
227 if userCurdConfig.StoragePath == "" { 309 if previousKey != "" {
228 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd") 310 for idx, option := range options {
311 if option.Key == previousKey {
312 return idx
313 }
314 }
229 } 315 }
230 316
231 var rofiInput strings.Builder 317 if previousLabel != "" {
232 selectionOptions := make([]SelectionOption, 0, len(options)) 318 for idx, option := range options {
319 if option.Label == previousLabel {
320 return idx
321 }
322 }
323 }
233 324
234 // Prepare options and rofi input 325 if fallbackIndex >= 0 && fallbackIndex < len(options) {
235 for id, opt := range options { 326 return fallbackIndex
236 cachePath, err := downloadToCache(opt.CoverImage) 327 }
237 if err != nil { 328
238 Log(fmt.Sprintf("Error caching image: %v", err)) 329 if len(options) == 0 {
239 continue 330 return -1
331 }
332
333 return min(fallbackIndex, len(options)-1)
334}
335
336func sortHomeMenuOptions(options []SelectionOption) []SelectionOption {
337 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",")
338 optMap := make(map[string]SelectionOption)
339 for _, opt := range options {
340 optMap[opt.Key] = opt
341 }
342
343 sorted := make([]SelectionOption, 0, len(options))
344 for _, key := range menuOrder {
345 if opt, exists := optMap[key]; exists {
346 sorted = append(sorted, opt)
347 delete(optMap, key)
240 } 348 }
241 rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", opt.Title, cachePath)) 349 }
350
351 for _, opt := range options {
352 if _, exists := optMap[opt.Key]; exists {
353 sorted = append(sorted, opt)
354 delete(optMap, opt.Key)
355 }
356 }
357
358 return sorted
359}
360
361func previewOptionsToSortedSelection(options map[string]RofiSelectPreview) []SelectionOption {
362 selectionOptions := make([]SelectionOption, 0, len(options))
363 for id, opt := range options {
242 selectionOptions = append(selectionOptions, SelectionOption{ 364 selectionOptions = append(selectionOptions, SelectionOption{
243 Label: opt.Title, 365 Label: opt.Title,
244 Key: id, 366 Key: id,
245 }) 367 })
246 } 368 }
247 369
248 if addnewoption { 370 sort.Slice(selectionOptions, func(i, j int) bool {
249 rofiInput.WriteString("Add new anime\n") 371 return selectionOptions[i].Label < selectionOptions[j].Label
372 })
373
374 return selectionOptions
375}
376
377func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
378 return DynamicSelectPreviewWithRefresh(options, addnewoption, nil)
379}
380
381func DynamicSelectPreviewWithRefresh(options map[string]RofiSelectPreview, addnewoption bool, refreshConfig *PreviewSelectionRefreshConfig) (SelectionOption, error) {
382 go preDownloadImages(options, 14)
383
384 userCurdConfig := GetGlobalConfig()
385 if userCurdConfig.StoragePath == "" {
386 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
250 } 387 }
251 // Add Back option before Quit (this is always a sub-menu when using preview)
252 rofiInput.WriteString("Back\n")
253 rofiInput.WriteString("Quit\n")
254 388
255 // Run rofi 389 currentOptions := options
256 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi")
257 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-show-icons", "-p", "Select Anime", "-i", "-no-custom")
258 cmd.Stdin = strings.NewReader(rofiInput.String())
259 var stdout, stderr bytes.Buffer
260 cmd.Stdout = &stdout
261 cmd.Stderr = &stderr
262 390
263 if err := cmd.Run(); err != nil { 391 for {
264 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String())) 392 var rofiInput strings.Builder
265 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String())) 393 selectionOptions := previewOptionsToSortedSelection(currentOptions)
266 // ESC pressed or rofi closed - return back 394
267 return SelectionOption{Key: "-2", Label: "Back"}, nil 395 for _, opt := range selectionOptions {
396 cachePath, err := downloadToCache(currentOptions[opt.Key].CoverImage)
397 if err != nil {
398 Log(fmt.Sprintf("Error caching image: %v", err))
399 continue
400 }
401 rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", opt.Label, cachePath))
402 }
403
404 if addnewoption {
405 rofiInput.WriteString("Add new anime\n")
406 }
407 rofiInput.WriteString("Back\n")
408 rofiInput.WriteString("Quit\n")
409
410 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi")
411 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-show-icons", "-p", "Select Anime", "-i", "-no-custom")
412 cmd.Stdin = strings.NewReader(rofiInput.String())
413 var stdout, stderr bytes.Buffer
414 cmd.Stdout = &stdout
415 cmd.Stderr = &stderr
416
417 if refreshConfig == nil || refreshConfig.Updates == nil {
418 if err := cmd.Run(); err != nil {
419 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
420 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
421 return SelectionOption{Key: "-2", Label: "Back"}, nil
422 }
423 return parsePreviewSelection(stdout.String(), selectionOptions)
424 }
425
426 if err := cmd.Start(); err != nil {
427 return SelectionOption{}, fmt.Errorf("failed to run Rofi preview menu: %w", err)
428 }
429
430 waitCh := make(chan error, 1)
431 go func() {
432 waitCh <- cmd.Wait()
433 }()
434
435 restartMenu := false
436
437 for !restartMenu {
438 select {
439 case err := <-waitCh:
440 if err != nil {
441 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
442 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
443 return SelectionOption{Key: "-2", Label: "Back"}, nil
444 }
445 return parsePreviewSelection(stdout.String(), selectionOptions)
446 case updatedList, ok := <-refreshConfig.Updates:
447 if !ok {
448 refreshConfig = nil
449 continue
450 }
451
452 updatedOptions := refreshConfig.BuildOptions(updatedList)
453 if reflect.DeepEqual(currentOptions, updatedOptions) {
454 continue
455 }
456
457 currentOptions = updatedOptions
458 restartMenu = true
459
460 if cmd.Process != nil {
461 _ = cmd.Process.Kill()
462 }
463 <-waitCh
464 }
465 }
268 } 466 }
467}
269 468
270 selected := strings.TrimSpace(stdout.String()) 469func preDownloadImages(options map[string]RofiSelectPreview, count int) {
470 i := 0
471 for _, option := range options {
472 if i >= count {
473 break
474 }
475 downloadToCache(option.CoverImage)
476 i++
477 }
478}
479
480func parsePreviewSelection(rawSelection string, selectionOptions []SelectionOption) (SelectionOption, error) {
481 selected := strings.TrimSpace(rawSelection)
271 482
272 // Handle special cases
273 switch selected { 483 switch selected {
274 case "": 484 case "":
275 // Empty selection - go back
276 return SelectionOption{Key: "-2", Label: "Back"}, nil 485 return SelectionOption{Key: "-2", Label: "Back"}, nil
277 case "Add new anime": 486 case "Add new anime":
278 return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil 487 return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
@@ -282,7 +491,6 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
282 return SelectionOption{Label: "Quit", Key: "-1"}, nil 491 return SelectionOption{Label: "Quit", Key: "-1"}, nil
283 } 492 }
284 493
285 // Find matching option
286 for _, opt := range selectionOptions { 494 for _, opt := range selectionOptions {
287 if opt.Label == selected { 495 if opt.Label == selected {
288 return opt, nil 496 return opt, nil
@@ -292,17 +500,6 @@ func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption boo
292 return SelectionOption{}, fmt.Errorf("selection not found in options") 500 return SelectionOption{}, fmt.Errorf("selection not found in options")
293} 501}
294 502
295func preDownloadImages(options map[string]RofiSelectPreview, count int) {
296 i := 0
297 for _, option := range options {
298 if i >= count {
299 break
300 }
301 downloadToCache(option.CoverImage)
302 i++
303 }
304}
305
306func downloadToCache(imageURL string) (string, error) { 503func downloadToCache(imageURL string) (string, error) {
307 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images") 504 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
308 if err := os.MkdirAll(cacheDir, 0755); err != nil { 505 if err := os.MkdirAll(cacheDir, 0755); err != nil {
@@ -357,101 +554,150 @@ func showCachedImagePreview(imageURL string) error {
357} 554}
358 555
359func RofiSelect(options []SelectionOption, isHomeMenu bool) (SelectionOption, error) { 556func RofiSelect(options []SelectionOption, isHomeMenu bool) (SelectionOption, error) {
557 return RofiSelectWithRefresh(options, isHomeMenu, nil)
558}
559
560func RofiSelectWithRefresh(options []SelectionOption, isHomeMenu bool, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
360 userCurdConfig := GetGlobalConfig() 561 userCurdConfig := GetGlobalConfig()
361 if userCurdConfig.StoragePath == "" { 562 if userCurdConfig.StoragePath == "" {
362 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd") 563 userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
363 } 564 }
364 565
365 // Create ordered list of options 566 currentOptions := options
366 var optionsList []string
367 for _, opt := range options {
368 optionsList = append(optionsList, opt.Label)
369 }
370
371 // Add "Back" option before "Quit" (only for non-home menus)
372 if !isHomeMenu {
373 optionsList = append(optionsList, "Back")
374 }
375 // Add "Quit" option at the end
376 optionsList = append(optionsList, "Quit")
377 optionsString := strings.Join(optionsList, "\n")
378 567
379 // Prepare and run rofi 568 for {
380 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi") 569 optionsString := buildRofiOptionsString(currentOptions, isHomeMenu)
381 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-i", "-p", "Select") 570 configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi")
382 cmd.Stdin = strings.NewReader(optionsString) 571 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-i", "-p", "Select")
383 var stdout, stderr bytes.Buffer 572 cmd.Stdin = strings.NewReader(optionsString)
384 cmd.Stdout = &stdout 573 var stdout, stderr bytes.Buffer
385 cmd.Stderr = &stderr 574 cmd.Stdout = &stdout
575 cmd.Stderr = &stderr
386 576
387 err := cmd.Run() 577 if refreshConfig == nil || refreshConfig.Updates == nil {
388 if err != nil { 578 err := cmd.Run()
389 if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 { 579 return parseRofiSelection(err, stdout.String(), currentOptions, isHomeMenu)
390 // ESC pressed or rofi closed: go back on sub-menus, quit on home menu
391 if isHomeMenu {
392 return SelectionOption{Key: "-1", Label: "Quit"}, nil
393 }
394 return SelectionOption{Key: "-2", Label: "Back"}, nil
395 } 580 }
396 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
397 }
398
399 selected := strings.TrimSpace(stdout.String())
400 581
401 // Handle special cases 582 if err := cmd.Start(); err != nil {
402 switch selected { 583 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %w", err)
403 case "":
404 // Empty selection: go back on sub-menus, quit on home menu
405 if isHomeMenu {
406 return SelectionOption{Key: "-1", Label: "Quit"}, nil
407 } 584 }
408 return SelectionOption{Key: "-2", Label: "Back"}, nil
409 case "Back":
410 return SelectionOption{Label: "Back", Key: "-2"}, nil
411 case "Quit":
412 return SelectionOption{Label: "Quit", Key: "-1"}, nil
413 }
414 585
415 // Find the matching SelectionOption 586 waitCh := make(chan error, 1)
416 for _, opt := range options { 587 go func() {
417 if opt.Label == selected { 588 waitCh <- cmd.Wait()
418 return opt, nil 589 }()
590
591 restartMenu := false
592
593 for !restartMenu {
594 select {
595 case err := <-waitCh:
596 if err != nil {
597 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
598 }
599 return parseRofiSelection(err, stdout.String(), currentOptions, isHomeMenu)
600 case updatedList, ok := <-refreshConfig.Updates:
601 if !ok {
602 refreshConfig = nil
603 continue
604 }
605
606 updatedOptions := refreshConfig.BuildOptions(updatedList)
607 if reflect.DeepEqual(currentOptions, updatedOptions) {
608 continue
609 }
610
611 currentOptions = updatedOptions
612 restartMenu = true
613
614 if cmd.Process != nil {
615 _ = cmd.Process.Kill()
616 }
617 <-waitCh
618 }
419 } 619 }
420 } 620 }
421
422 return SelectionOption{}, fmt.Errorf("selected option not found in original list")
423} 621}
424 622
425func DynamicSelectFromSlice(options []SelectionOption) (SelectionOption, error) { 623func DynamicSelectFromSlice(options []SelectionOption) (SelectionOption, error) {
426 // Detect if this is a home menu by checking for category keys 624 return dynamicSelectInternal(options, nil)
427 isHomeMenu := false 625}
428 for _, opt := range options { 626
429 if opt.Key == "ALL" || opt.Key == "CURRENT" { 627// DynamicSelect displays a simple selection prompt without extra features
430 isHomeMenu = true 628func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
431 break 629 return dynamicSelectInternal(options, nil)
432 } 630}
631
632func DynamicSelectWithRefresh(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
633 return dynamicSelectInternal(options, refreshConfig)
634}
635
636func dynamicSelectInternal(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
637 isHomeMenu := detectHomeMenu(options)
638
639 if isHomeMenu {
640 options = sortHomeMenuOptions(options)
433 } 641 }
434 642
435 if GetGlobalConfig().RofiSelection { 643 if GetGlobalConfig().RofiSelection {
436 return RofiSelect(options, isHomeMenu) 644 return RofiSelectWithRefresh(options, isHomeMenu, refreshConfig)
645 }
646
647 // Separate out the "add_new" sentinel so it is never sorted alphabetically.
648 // The addNewOption flag causes filterOptions() to append it after the sort.
649 hasAddNew := false
650 cleanOptions := make([]SelectionOption, 0, len(options))
651 for _, opt := range options {
652 if opt.Key == "add_new" {
653 hasAddNew = true
654 } else {
655 cleanOptions = append(cleanOptions, opt)
656 }
437 } 657 }
438 658
439 model := &Model{ 659 model := &Model{
440 allOptions: options, 660 allOptions: cleanOptions,
441 isHomeMenu: isHomeMenu, 661 isHomeMenu: isHomeMenu,
662 addNewOption: hasAddNew,
442 } 663 }
443 model.filterOptions() // Initialize filtered options 664 model.filterOptions()
444 665
445 p := tea.NewProgram(model) 666 p := tea.NewProgram(model)
667 stopRefresh := make(chan struct{})
668
669 if refreshConfig != nil && refreshConfig.Updates != nil {
670 go func(lastOptions []SelectionOption) {
671 currentOptions := lastOptions
672 for {
673 select {
674 case <-stopRefresh:
675 return
676 case updatedList, ok := <-refreshConfig.Updates:
677 if !ok {
678 return
679 }
680
681 updatedOptions := refreshConfig.BuildOptions(updatedList)
682 if reflect.DeepEqual(currentOptions, updatedOptions) {
683 continue
684 }
685
686 currentOptions = updatedOptions
687 p.Send(optionsRefreshedMsg{options: updatedOptions})
688 }
689 }
690 }(append([]SelectionOption(nil), options...))
691 }
446 692
447 finalModel, err := p.Run() 693 finalModel, err := p.Run()
694 close(stopRefresh)
448 if err != nil { 695 if err != nil {
449 return SelectionOption{}, err 696 return SelectionOption{}, err
450 } 697 }
451 698
452 // resetting terminal state 699 fmt.Print("\033[?25h")
453 fmt.Print("\033[?25h") // show cursor 700 fmt.Print("\033[?7h")
454 fmt.Print("\033[?7h") // line wrapping
455 701
456 finalSelectionModel, ok := finalModel.(*Model) 702 finalSelectionModel, ok := finalModel.(*Model)
457 if !ok { 703 if !ok {
@@ -464,66 +710,49 @@ func DynamicSelectFromSlice(options []SelectionOption) (SelectionOption, error)
464 return SelectionOption{}, nil 710 return SelectionOption{}, nil
465} 711}
466 712
467// DynamicSelect displays a simple selection prompt without extra features 713func buildRofiOptionsString(options []SelectionOption, isHomeMenu bool) string {
468func DynamicSelect(options []SelectionOption) (SelectionOption, error) { 714 optionsList := make([]string, 0, len(options)+2)
469 // Detect if this is a home menu by checking for category keys
470 isHomeMenu := false
471 for _, opt := range options { 715 for _, opt := range options {
472 if opt.Key == "ALL" || opt.Key == "CURRENT" { 716 optionsList = append(optionsList, opt.Label)
473 isHomeMenu = true
474 break
475 }
476 } 717 }
477 718
478 if GetGlobalConfig().RofiSelection { 719 if !isHomeMenu {
479 return RofiSelect(options, isHomeMenu) 720 optionsList = append(optionsList, "Back")
480 } 721 }
722 optionsList = append(optionsList, "Quit")
481 723
482 // Sort options if this contains menu categories 724 return strings.Join(optionsList, "\n")
483 if isHomeMenu { 725}
484 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",")
485 optMap := make(map[string]SelectionOption)
486 for _, opt := range options {
487 optMap[opt.Key] = opt
488 }
489 726
490 sorted := make([]SelectionOption, 0, len(options)) 727func parseRofiSelection(err error, rawSelection string, options []SelectionOption, isHomeMenu bool) (SelectionOption, error) {
491 for _, key := range menuOrder { 728 if err != nil {
492 if opt, exists := optMap[key]; exists { 729 if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 {
493 sorted = append(sorted, opt) 730 if isHomeMenu {
731 return SelectionOption{Key: "-1", Label: "Quit"}, nil
494 } 732 }
733 return SelectionOption{Key: "-2", Label: "Back"}, nil
495 } 734 }
496 options = sorted 735 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
497 }
498
499 model := &Model{
500 allOptions: options,
501 isHomeMenu: isHomeMenu,
502 }
503 model.filterOptions() // Initialize filtered options
504
505 p := tea.NewProgram(model)
506 finalModel, err := p.Run()
507 if err != nil {
508 return SelectionOption{}, err
509 } 736 }
510 737
511 fmt.Print("\033[?25h") // Show cursor 738 selected := strings.TrimSpace(rawSelection)
512 fmt.Print("\033[?7h") // Enable line wrapping 739 switch selected {
513 740 case "":
514 finalSelectionModel, ok := finalModel.(*Model) 741 if isHomeMenu {
515 if !ok { 742 return SelectionOption{Key: "-1", Label: "Quit"}, nil
516 return SelectionOption{}, fmt.Errorf("unexpected model type") 743 }
744 return SelectionOption{Key: "-2", Label: "Back"}, nil
745 case "Back":
746 return SelectionOption{Label: "Back", Key: "-2"}, nil
747 case "Quit":
748 return SelectionOption{Label: "Quit", Key: "-1"}, nil
517 } 749 }
518 750
519 // Check if the program was quit with Ctrl+C 751 for _, opt := range options {
520 if err != nil { 752 if opt.Label == selected {
521 return SelectionOption{Key: "-1", Label: "Quit"}, nil 753 return opt, nil
754 }
522 } 755 }
523 756
524 if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) { 757 return SelectionOption{}, fmt.Errorf("selected option not found in original list")
525 return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
526 }
527 return SelectionOption{}, nil
528} 758}
529
internal/structs.go +1
@@ -74,6 +74,7 @@ type User struct {
74 Username string 74 Username string
75 Id int 75 Id int
76 AnimeList AnimeList 76 AnimeList AnimeList
77 ListSync *AnimeListSync
77} 78}
78 79
79// AniListAnime is the struct for the API response 80// AniListAnime is the struct for the API response