internal/anilist_cache.go

301 lines · 7947 bytes

  1package internal
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"os"
  7	"path/filepath"
  8	"strconv"
  9	"sync"
 10	"time"
 11)
 12
 13const anilistAnimeListCacheFileName = "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 aniListCachePath(storagePath string) string {
 79	return filepath.Join(os.ExpandEnv(storagePath), anilistAnimeListCacheFileName)
 80}
 81
 82func loadAniListAnimeListCache(storagePath string, userID int) (animeListCachePayload, error) {
 83	cacheFilePath := aniListCachePath(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 saveAniListAnimeListCache(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 := aniListCachePath(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 FetchLatestAniListAnimeList(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 refreshAniListAnimeListInBackground(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 := FetchLatestAniListAnimeList(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 := saveAniListAnimeListCache(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 InitializeAniListUserAnimeList(userCurdConfig *CurdConfig, user *User) error {
191	cachedPayload, err := loadAniListAnimeListCache(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		refreshAniListAnimeListInBackground(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 := FetchLatestAniListAnimeList(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 := saveAniListAnimeListCache(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 RefreshAniListUserAnimeList(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 := FetchLatestAniListAnimeList(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 := saveAniListAnimeListCache(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}