package handlers import ( "crypto/rand" "encoding/hex" "log" "sync" "time" "adam-french.co.uk/backend/services" "github.com/zmb3/spotify/v2" spotifyauth "github.com/zmb3/spotify/v2/auth" "gorm.io/gorm" ) // Store is the dependency container shared by every handler and resolver. // Cache fields are guarded by cacheMu: use the accessors, never the fields. type Store struct { DB *gorm.DB SpotifyAuth *spotifyauth.Authenticator SpotifyClient *spotify.Client Auth *services.Auth Notes *services.Notes LoginLimiter *services.RateLimiter // The Python service on the Docker network, no trailing slash. PythonURL string Uploads *services.Uploads cacheMu sync.RWMutex RecentSongs *[]spotify.RecentlyPlayedItem RecentSongsFetchedAt time.Time // 1 minute TTL. GiteaHost string GiteaPort string GiteaFeed *services.GiteaFeedResponse GiteaFeedFetchedAt time.Time // 5 minute TTL. SteamAPIKey string SteamID string SteamRecentGames []services.SteamRecentGame SteamOnline bool SteamFetchedAt time.Time // One-shot OAuth CSRF nonces. In memory: a lost nonce only restarts a // seconds-long flow. spotifyStatesMu sync.Mutex spotifyStates map[string]time.Time // Every page visit would otherwise log "Spotify not authenticated". spotifyNilLoggedMu sync.Mutex spotifyNilLoggedAt time.Time } const spotifyStateTTL = 10 * time.Minute // NewSpotifyState mints a nonce. Pruning here is the only cleanup; only an // admin can add entries. func (s *Store) NewSpotifyState() (string, error) { b := make([]byte, 32) if _, err := rand.Read(b); err != nil { return "", err } state := hex.EncodeToString(b) s.spotifyStatesMu.Lock() defer s.spotifyStatesMu.Unlock() if s.spotifyStates == nil { s.spotifyStates = make(map[string]time.Time) } for k, created := range s.spotifyStates { if time.Since(created) > spotifyStateTTL { delete(s.spotifyStates, k) } } s.spotifyStates[state] = time.Now() return state, nil } // ConsumeSpotifyState removes the nonce, so a replayed callback fails. func (s *Store) ConsumeSpotifyState(state string) bool { if state == "" { return false } s.spotifyStatesMu.Lock() defer s.spotifyStatesMu.Unlock() created, ok := s.spotifyStates[state] if !ok { return false } delete(s.spotifyStates, state) return time.Since(created) <= spotifyStateTTL } // LogSpotifyUnauthenticated logs at most once an hour. func (s *Store) LogSpotifyUnauthenticated(where string) { s.spotifyNilLoggedMu.Lock() defer s.spotifyNilLoggedMu.Unlock() if time.Since(s.spotifyNilLoggedAt) < time.Hour { return } s.spotifyNilLoggedAt = time.Now() log.Printf("[Spotify] not authenticated (seen in %s) — an admin can reconnect via GET /api/spotify/auth", where) } // CachedRecentSongs treats an empty list as stale. func (s *Store) CachedRecentSongs() ([]spotify.RecentlyPlayedItem, bool) { s.cacheMu.RLock() defer s.cacheMu.RUnlock() if s.RecentSongs == nil || len(*s.RecentSongs) == 0 { return nil, false } if time.Since(s.RecentSongsFetchedAt) >= time.Minute { return nil, false } return *s.RecentSongs, true } func (s *Store) SetRecentSongs(songs []spotify.RecentlyPlayedItem) { s.cacheMu.Lock() defer s.cacheMu.Unlock() s.RecentSongs = &songs s.RecentSongsFetchedAt = time.Now() } func (s *Store) CachedGiteaFeed() (*services.GiteaFeedResponse, bool) { s.cacheMu.RLock() defer s.cacheMu.RUnlock() if s.GiteaFeed == nil || time.Since(s.GiteaFeedFetchedAt) >= time.Minute { return nil, false } return s.GiteaFeed, true } func (s *Store) SetGiteaFeed(feed *services.GiteaFeedResponse) { s.cacheMu.Lock() defer s.cacheMu.Unlock() s.GiteaFeed = feed s.GiteaFeedFetchedAt = time.Now() } // CachedSteam judges freshness on the games list only, so an empty list is // always re-fetched. func (s *Store) CachedSteam() (games []services.SteamRecentGame, online bool, ok bool) { s.cacheMu.RLock() defer s.cacheMu.RUnlock() if s.SteamRecentGames == nil || time.Since(s.SteamFetchedAt) >= 5*time.Minute { return nil, false, false } return s.SteamRecentGames, s.SteamOnline, true } func (s *Store) SetSteam(games []services.SteamRecentGame, online bool) { s.cacheMu.Lock() defer s.cacheMu.Unlock() s.SteamRecentGames = games s.SteamOnline = online s.SteamFetchedAt = time.Now() }