Compare commits

...

272 Commits

Author SHA1 Message Date
bvandeusen 573aa4226d Merge pull request 'release v2026.05.13.2: artist covers + load-then-swap player transitions' (#45) from dev into main 2026-05-14 16:31:43 +00:00
bvandeusen 30fc7603d4 chore(flutter): bump versionCode to 3 for v2026.05.13.2 hotfix 2026-05-14 12:31:05 -04:00
bvandeusen 86d67f6fc6 fix(player): preload-then-swap cover transitions on both player surfaces
Previous fixes layered AnimatedSwitcher fades on top of a race: the
audio_handler broadcasts MediaItem twice on every track change
(bare metadata first, then with artUri once AlbumCoverCache resolves)
and the image bytes themselves decode asynchronously after the
widget mounts. The fades just smeared the resulting placeholder
flash without addressing the underlying ordering.

Rewrite the decision process around "load first, then swap":

**Mini player** (rapid change is acceptable per operator preference):
- Drop AnimatedSwitcher entirely
- PlayerBar becomes stateful, holds the most-recent non-null artUri
- Builds the child MediaItem with artUri = currentArtUri ?? _lastArtUri,
  so the previous cover stays visible across the null-artUri gap and
  the new cover snaps in the moment its artUri arrives

**Full player** (operator wants the image fully loaded before any
visible change):
- Introduce _displayedMedia + _displayedDominant state
- ref.listen on mediaItemProvider schedules a preload for each new
  track id (and for the artUri-bearing rebroadcast on the same id)
- _scheduleSwap awaits precacheImage on the file:// artUri AND
  awaits albumColorProvider's future for the dominant color
- Only then setState flips _displayedMedia + _displayedDominant in
  one frame — cover, title, gradient all advance atomically
- Drop the per-element AnimatedSwitcher wrappers; the backdrop
  AnimatedContainer still tweens between successive dominant
  colors so the gradient transition is smooth, not snap

Concurrency: rapid skips drop stale preload completions via
_pendingPreloadId. Decode/color failures fall through to the
previous dominant + the ServerImage/error-builder fallbacks.
2026-05-14 12:07:50 -04:00
bvandeusen 8cb9a8b797 fix(flutter): restore artist coverUrl on drift-cached ArtistRef
Multi-artist surfaces (home Rediscover, Library Artists tab, Liked
Artists carousel) were all rendering the music-notes placeholder
instead of real artist covers. Root cause:

CachedArtist.toRef() returned an ArtistRef with empty coverUrl —
the cache doesn't store the representative album id the server
derives at query time, and the adapter never reconstructed it.
The artist detail screen worked coincidentally because it derives
its header cover from `artist.albums[0].id` directly rather than
the ArtistRef's coverUrl field.

Fix:
* CachedArtistAdapter.toRef() now accepts an optional coverAlbumId
  and reconstructs `/api/albums/<id>/cover` when given. Matches the
  pattern AlbumRef uses (deterministic URL from entity id).
* artistTileProvider, libraryArtistsProvider, and artistProvider
  (single-artist) each LEFT JOIN cached_albums ordered by sort_title.
  First row per artist carries the alphabetically-first album id;
  toRef projects that into the cover URL.
* Multi-artist queries dedup in toResult since the join multiplies
  rows by album count.

Artists with no albums yet in drift come through with empty
coverUrl — UI falls back to the music-notes placeholder, same
behavior as before for that legitimately-coverless state.
2026-05-14 12:01:02 -04:00
bvandeusen 7339815ea9 Merge pull request 'release v2026.05.13.1: player + Discover hotfix' (#44) from dev into main 2026-05-14 15:17:45 +00:00
bvandeusen 2a18e91c39 feat(flutter): drift-first Library tabs + systemPlaylistsStatus + tab pre-warm
Four-part change to push more surfaces onto the drift cache and
eliminate cold-tab-visit latency on the Library screen.

* **Library Artists tab** — _libraryArtistsProvider migrates from
  REST-paginated AsyncNotifier with infinite-scroll loadMore to a
  drift-first StreamProvider over cached_artists ordered by
  sortName. Sync already populates the full set; cacheFirst's
  fetchAndPopulate covers the fresh-install + sync-not-yet-done
  cold case via /api/artists?limit=1000. SWR refresh on every
  visit. GridView.builder lazily realizes only visible cells so
  loading the full list up front is fine for typical libraries.
  loadMore + NotificationListener gone.

* **Library Albums tab** — same migration, drift-first over
  cached_albums joined with cached_artists for the artistName
  field.

* **systemPlaylistsStatusProvider** — new CachedSystemPlaylistsStatus
  single-row table (schema 6 → 7, JSON blob like CachedHomeSnapshot)
  for the home Playlists row's "building / pending / failed"
  placeholder logic. Drift-first means the row paints with the
  prior status instantly instead of flickering through
  SystemPlaylistsStatus.empty() while the REST call resolves.

* **Library screen tab pre-warm** — ref.listen on all 5 tab
  providers in _LibraryScreenState.build subscribes them upfront
  so swiping between tabs feels instant rather than each tab
  paying its own cold-cache cost on first visit. cacheFirst
  handles dedupe of concurrent fetchAndPopulate triggers.

Test mock updated for the StreamProvider type change on
systemPlaylistsStatusProvider.
2026-05-14 10:14:46 -04:00
bvandeusen 507c532f6d fix(flutter): drop redundant foundation import (debugPrint via material) 2026-05-14 08:42:50 -04:00
bvandeusen bf0ef5e0c3 fix(flutter): keep artist avatars round in the Library grid
ArtistCard hardcoded its avatar at Container(width: 124, height:
124) inside a ClipOval. In the Library Artists 3-column grid the
cell is narrower than the card's nominal 140dp width — on a typical
phone the cell is ~109dp, the padded inner content area ~93dp. The
parent constrained the Container's width to ~93dp but the explicit
height stayed 124dp, so ClipOval clipped a 93×124 rectangle and
the avatar rendered as a vertical ellipse.

Fix mirrors AlbumCard's pattern: ArtistCard takes an optional
`width` parameter (default 140 for horizontal carousels) and
derives coverSize = width - 16, so the Container is always square.
ArtistsTab now uses LayoutBuilder to compute cell width and passes
it through, same as AlbumsTab. Avatar stays a true circle at any
cell width.

mainAxisExtent on the grid replaces the previous fixed
childAspectRatio so cell height tracks cellW + name line, with
slack matching AlbumsTab's overflow guard.
2026-05-14 08:39:37 -04:00
bvandeusen 6efb3159d5 fix(flutter): silence 404 log noise from missing playlist covers
Playlist collages aren't generated until the build job runs over a
playlist with tracks — system playlists (For-You / Discover / Songs-
like) and any newly-created playlist hit a brief window where
/api/playlists/:id/cover returns 404. ServerImage's errorWidget
already renders the visual fallback (queue_music icon over slate);
this fix just keeps cached_network_image from spamming the dev
console with HttpExceptionWithStatus stack traces.

errorListener filters 404 specifically — auth (401/403) and any
5xx still log so real connectivity / permission issues stay visible.

User-visible behavior unchanged; this is a dev-mode log hygiene fix.
2026-05-14 08:32:35 -04:00
bvandeusen 8f1bc60757 chore(flutter): bump versionCode to 2 for v2026.05.13.1 hotfix 2026-05-14 08:30:23 -04:00
bvandeusen c29d25d1cb fix(playlists): dedup tracks across discover buckets
Discover playlists could surface the same track twice with the
duplicates landing back-to-back — a "first song plays, then plays
again, skip works" symptom user reported on v2026.05.13.0. Root
cause: interleaveBuckets rotates one track per pass per bucket but
never tracks which IDs it has already emitted, so a track that's
both a dormant-artist pick AND a random-unheard pick comes out
once from each bucket.

On a single-user server the crossUser bucket is empty, so the
redistribute step rolls its slots into dormant + random. Their
output then interleaves d0, r0, d1, r1, … — and when d0 == r0
(common: a dormant-artist track is also valid for random-unheard)
the result is [X, X, …] with adjacent duplicates.

Fix: track seen track IDs across all buckets while interleaving;
skip already-taken IDs and advance to the next index in that
bucket. Dedup priority is bucket order, so a track in both
dormant and random comes from dormant.

Regression test covers the single-user case directly. The existing
round-robin test still passes — no shared IDs in that fixture.

Note: stale duplicates already written to drift / served as cached
playlists will clear naturally on the next playlist rebuild (the
03:00-local refresh, or any manual /api/me/playlists/refresh).
2026-05-14 07:50:35 -04:00
bvandeusen 2ebe6229b7 fix(player): smooth full-player cover + backdrop on track change
Two related "snap in" effects on the now-playing screen:

1. **Album art snapped in after the fade.** AnimatedSwitcher cross-
   fades the new _AlbumArt over 300ms, but FileImage's bytes weren't
   decoded yet — the widget was visually empty during the fade and
   the cover landed abruptly after. precacheImage on the new file://
   artUri pre-decodes the bytes so by the time AnimatedSwitcher
   mounts the new tile, the cover paints synchronously inside it.
   The cross-fade now carries real content end-to-end.

2. **Backdrop color snapped in.** albumColorProvider.family is
   loading for the new id during the track-change moment, so
   dominant fell back to fs.obsidian; AnimatedContainer tweened to
   obsidian and then snapped to the resolved color a beat later.
   _NowPlayingScreenState now holds _lastDominant across builds:
   while extraction for the new id is loading, the gradient stays
   on the previous album's color, then animates straight to the
   new one once it resolves. No intermediate obsidian stop.

Net effect: track changes feel like a single smooth transition
instead of fade-out → blank → snap.
2026-05-14 07:41:27 -04:00
bvandeusen 6a08d94255 fix(player): smooth mini bar cover swap across track change
Audio handler broadcasts MediaItem twice on every track change:
once with artUri=null (the new track's bare metadata), then again
with artUri pointing at the AlbumCoverCache file once the cover
lands on disk. The mini player's cover element was rebuilding in
place: previous track's image → slate placeholder → new track's
image. That flash is the flicker reported on the v2026.05.13.0 build.

AnimatedSwitcher around the cover (180ms crossfade) keyed by the
artUri value makes the swap a smooth crossfade instead of a visible
snap. The Hero parent stays — its tag is stable across track changes
so the mini→full bar expansion animation keeps working unchanged.
2026-05-14 07:37:42 -04:00
bvandeusen 3e7b2582a2 fix(player): queue skip + cut over silence on track tap
Two bugs in the audio handler caused the playback issues seen on the
v2026.05.13.0 build:

1. **Queue button on the now-playing screen did nothing.** MinstrelAudio
   Handler never overrode skipToQueueItem, so taps in QueueScreen fell
   through to BaseAudioHandler's empty default. The queue UI updated
   nothing because the handler did nothing. Now overridden: rebuilds
   the source list via setQueueFromTracks(_lastTracks, initialIndex)
   so the targeted item plays cleanly even when its source hadn't been
   built yet by the background fill.

2. **Tapping a song in a playlist let the previous track bleed through
   until the new source finished building.** setQueueFromTracks awaits
   _buildAudioSource before swapping the player's source list, and
   that wait can be a few hundred ms on a cache miss. During the wait
   the old source kept playing while the mini player UI had already
   flipped to the new title/artist. Now pause()ing the player at the
   start of setQueueFromTracks silences the old source the moment the
   user taps.

Also stashes the most recent TrackRef list as _lastTracks so
skipToQueueItem can reconstruct sources without having to peek into
just_audio's internal source list.
2026-05-14 07:36:59 -04:00
bvandeusen baa601765e Merge pull request 'release v2026.05.13.0: SSE live updates + offline cache + per-item rendering' (#43) from dev into main 2026-05-14 02:36:47 +00:00
bvandeusen 3db90020d4 chore(flutter): bump version to 2026.5.13+1 for release 2026-05-13 22:29:11 -04:00
bvandeusen 7367595e71 feat(flutter): cosmetic reveal animations (Slice F)
Final slice of the per-item rendering pass. Wraps every tile widget
in an AnimatedSwitcher between the skeleton placeholder and the real
card. 220ms cross-fade with easeOut: tiles "settle into place"
rather than hard-cutting from shimmer to content. Since each tile
fades independently as its data lands — and the HydrationQueue's
concurrency cap drains in a natural cascade — the overall feel is
the staged "page builds piece by piece" effect we wanted, with no
per-tile position math required.

Bumps CachedNetworkImage fadeInDuration from zero to 120ms (server_
image.dart, discover_screen.dart). Imperceptible on cache hits since
the image decodes synchronously; on cache misses the bytes fade in
smoothly instead of popping. Slice 1's "zero fade" call was right
about the 500ms default being a regression, but 120ms threads the
needle.

Playlist detail wraps its body in the same AnimatedSwitcher so the
cold-load skeleton page cross-fades into the real track list.

Tiles affected: home _AlbumTile / _ArtistTile / _TrackTile + liked
_LikedAlbumTile / _LikedArtistTile / _LikedTrackRow + playlist
_SkeletonBody / _Body. All keyed via ValueKey so AnimatedSwitcher
detects the transition.

End of the per-item pass. Net behavior: cold visits paint shaped
pages instantly with skeletons, content cascades in as hydration
lands; warm visits paint fully from drift in the first frame.
2026-05-13 22:08:34 -04:00
bvandeusen 158a5d7506 fix(flutter): drop unused adapters import in library_screen
Slice E removed the bulk fetchAndPopulate paths that called toRef /
toDrift; the adapters.dart import is now unused.
2026-05-13 21:59:35 -04:00
bvandeusen f2fa441405 feat(flutter): liked tabs on per-item rendering (Slice E)
The three liked-tab providers now yield ordered lists of entity IDs
(read from cached_likes ORDER BY likedAt DESC). The UI renders
per-tile widgets that hydrate each entity individually via
albumTileProvider / artistTileProvider / trackTileProvider.

fetchAndPopulate dropped from the per-provider bulk endpoints to a
single shared call against /api/likes/ids — much cheaper, and the
tile providers handle entity hydration themselves. The bulk
/api/likes/{tracks,albums,artists} endpoints are no longer in the
Flutter cold path (server keeps serving them for web compat).

Cross-device SSE invalidate paths preserved so cross-device likes
still feel instant. Local LikesController mutations propagate via
cached_likes optimistic writes — same drift watch() route as before.

Tap-to-play on a track row uses currently-hydrated TrackRefs as the
play queue; still-loading tracks are skipped and join on next
rebuild as hydrations land.
2026-05-13 21:55:20 -04:00
bvandeusen a324454efe feat(flutter): skeleton rows during playlist cold-load (Slice D)
Cold-visit playlist detail used to render the header from the seed
and then a single CircularProgressIndicator while the bulk fetch
ran. Now it renders the header + seed.trackCount worth of skeleton
rows (capped at 8 when no seed is present). The real list swaps in
without a layout jump.

Slice D was originally scoped for per-track hydration through a new
discovery endpoint, but the unavailable-entries data model (playlist
rows that lost their underlying track to deletion / quarantine) make
that disproportionately expensive — would require a schema change to
support null trackIds on cached_playlist_tracks, a server endpoint,
and a screen rewrite. The skeleton-row approach captures ~80% of the
perceptual win at a fraction of the cost. True per-track hydration
remains a future opportunity if cold visits to very large playlists
still feel sluggish after Slice F polish lands.
2026-05-13 21:47:13 -04:00
bvandeusen 03c13d21c6 feat(flutter): home screen on per-item rendering (Slice C)
End-to-end pilot of the per-item architecture. Home now reads from
the new homeIndexProvider (drift-first over CachedHomeIndex with
/api/home/index discovery + SWR), then each tile is a small
ConsumerWidget watching its own albumTileProvider/artistTileProvider/
trackTileProvider. Tiles render a matched-dimension skeleton while
their entity is still hydrating, and swap in the real card once
drift emits the populated row.

Track hydration is wired up — /api/tracks/:id already existed so
the queue's case 'track' just calls api.getTrack(id) and persists.

The visible behavior:
* Cold visit: small /api/home/index round-trip (IDs only, ~10×
  smaller than /api/home), then sections appear shaped with
  skeleton tiles; each tile materializes as the hydration queue
  drains. No more "30s blank → everything pops in at once."
* Warm visit: drift index emits instantly, drift entity rows emit
  instantly, no network. Page paints fully in the first frame.
* Mid-state: scrolling through a partially-hydrated section sees
  real cards next to skeleton cards. Layout doesn't shift because
  skeletons match real-card dimensions exactly.

CachedHomeSnapshot (and the legacy homeProvider) stay in place but
unconsumed by Flutter — left in for now so revert is cheap if the
new path needs reworking. Cleanup follow-up in a later slice.

Old /api/home endpoint untouched, so the web client keeps working
unchanged.
2026-05-13 21:05:43 -04:00
bvandeusen 0119eacf14 feat(api): GET /api/home/index for per-item rendering (Slice B)
Sibling to /api/home that returns the same five sections (recently
added, rediscover albums, rediscover artists, most played, last
played) but as flat slices of entity ID strings instead of
denormalized objects. The Flutter client uses this to drive its
per-item rendering pass — small discovery response then per-tile
hydration via the existing /api/albums/:id, /api/artists/:id,
/api/tracks/:id endpoints.

Reuses recommendation.HomeData so the DB cost is identical to
/api/home. JSON payload shrinks roughly an order of magnitude on
populated libraries (no embedded title / artist / cover URL fields).

Old /api/home stays untouched so the web client and older Flutter
builds keep working — no min-client-version bump needed until both
clients have migrated.
2026-05-13 20:41:44 -04:00
bvandeusen 0504cae27c fix(flutter): drop unused imports flagged by analyze
Slice A landed with three transitive imports that the analyzer
correctly flagged as unused. AppDb / CachedAlbums table refs
propagate through audio_cache_manager.dart's `show appDbProvider`
re-export chain so the explicit db.dart import in the consumers
is redundant.
2026-05-13 20:30:33 -04:00
bvandeusen 64db364834 feat(flutter): per-item rendering infrastructure (Slice A)
Plumbing for the per-item rendering pass — no UI changes yet, just
the layers the home/playlist/liked migrations will sit on.

* CachedHomeIndex drift table (schema 5→6) — section/position →
  entity-id rows, populated by the upcoming /api/home/index endpoint.
* HydrationQueue (concurrency=4, in-flight dedup) — bounded request
  pump that takes (entityType, entityId) and persists the result to
  the right cached_<entity> table. Albums + artists wired today;
  tracks deferred until /api/tracks/:id exists.
* Per-entity tile providers (albumTileProvider, artistTileProvider,
  trackTileProvider as StreamProvider.family) — watch drift, enqueue
  hydration on miss, yield AsyncValue<EntityRef?>.
* Skeleton widgets (album/artist/track) matched to the real card
  dimensions with a 1.2s shimmer sweep using FabledSword tokens. No
  shimmer-package dep — single AnimationController per surface.

See docs/superpowers/specs/2026-05-13-per-item-rendering-design.md
for the full architecture rationale.
2026-05-13 20:25:40 -04:00
bvandeusen 99462185b4 feat(flutter): drift-first MyQuarantine
Final slice of the smooth-loading pass. Adds CachedQuarantineMine
(schema 5, columnar so flag/unflag can do row-level mutation) and
rewires MyQuarantineController to read from drift via watch() + SWR
refresh; flag/unflag write drift first and roll back on REST failure.

Public API (.flag / .unflag / .isHidden) unchanged so existing call
sites (library_screen Hidden tab, TrackActionsSheet) keep working.

Tests updated to match: bypassed-build-via-_StubController approach
no longer makes sense now that state lives in drift, so the suite is
rewritten against NativeDatabase.memory() with the same libsqlite3
skip the sync_controller suite uses on the CI runner.

The Hidden tab now paints from disk on cold open, the list is
queryable offline, and a flag from another device that arrived in
this user's quarantine via SSE-triggered invalidate lands the same
way as a local flag.
2026-05-13 18:41:18 -04:00
bvandeusen 395a6efb26 feat(flutter): drift-first History tab
Slice 4 of the smooth-loading pass. Adds CachedHistorySnapshot
(schema 4) and rewires _historyProvider through cacheFirst, mirroring
the homeProvider pattern: yield the last cached page immediately on
subscribe so the tab paints from disk on cold open, then SWR-refresh
in the background to surface fresh plays.

Also enables basic offline scrollback — the most recent History page
survives both app restart and connectivity loss.

JSON blob storage (vs columnar) because the page is small, always
read whole, and HistoryPage.fromJson already accepts the wire shape,
so server-side field additions don't force a migration.

History delta sync via library_changes is out of scope here; the next
visit's SWR pull is the source of freshness for now.
2026-05-13 18:31:36 -04:00
bvandeusen 1a2de0e738 feat(flutter): drift-first Liked tabs
Slice 3 of the smooth-loading pass. The three _likedTracksProvider /
_likedAlbumsProvider / _likedArtistsProvider entries on the Library
screen migrate from FutureProvider+REST to StreamProvider+cacheFirst.

Reads now flow from cached_likes joined against the metadata tables
SyncController already keeps fresh; LikesController's optimistic drift
write makes toggling a like re-emit these streams instantly without a
REST round-trip. Cold-cache fallback hits /api/likes/* when drift is
empty (fresh install pre-first-sync). SWR refresh on each visit catches
likes from other devices that haven't propagated via library_changes
yet.

The original FutureProvider versions fetched the first 50 rows. Drift
returns everything cached_likes knows about — for typical libraries
that's the full liked list. Pagination can come back when liked lists
are big enough to matter.

Like/unlike SSE invalidation paths preserved so cross-device updates
still feel real-time, even when the sender's library_changes hasn't
landed here yet.
2026-05-13 18:18:14 -04:00
bvandeusen 32c8d4f28f feat(flutter): pre-warm covers during library sync
Slice 2 of the cover-caching pass. SyncController now downloads cover
bytes for newly-upserted albums + playlists into the shared
flutter_cache_manager disk cache after each sync transaction commits.
A cold-start scroll through the home grid paints from disk on the very
first frame instead of firing one HTTP per visible tile.

Best-effort: fire-and-forget after commit, concurrency 3, per-URL
failures swallowed (404 for collages that haven't built yet, 401
during token-refresh races). Artist covers skipped — ArtistRef.coverUrl
is server-derived from "most-recent album" and not reconstructible
client-side; album pre-warm already covers the artist's primary visual.

Auth header reuses sessionTokenProvider for parity with ServerImage.
2026-05-13 18:06:53 -04:00
bvandeusen f732c49645 feat(flutter): disk-persistent cover cache via cached_network_image
Slice 1 of the cover-caching pass. The previous Image.network /
NetworkImage path only cached covers in memory, so a scroll-off + scroll-
back or an app restart re-downloaded every tile from the server. Swap
to cached_network_image so bytes land on disk (path_provider temp dir,
URL-keyed) and survive both.

Sites migrated:
  - ServerImage (all /api/*/cover usage — home grid, library, playlist,
    artist/album detail headers)
  - DiscoverScreen Lidarr suggestion thumbnails
  - PlayerBar mini cover (HTTPS branch; file:// branch unchanged since
    AlbumCoverCache files are already on disk)

Auth header forwarding preserved via httpHeaders. Fade-in disabled so
populated grids paint instantly on cache hit.

Slice 2 (pre-warm during sync) builds on this same cache manager.
2026-05-13 17:59:42 -04:00
bvandeusen ae5de91006 fix(flutter): tighten version-check cadence to 1m during active use
Drops the staleness gate from 1h to 1m and adds a Timer.periodic that
fires recheckIfStale every minute while the app is foregrounded. Net
effect: ~1 check per minute of active use, ~60 KB/hr data — trivially
affordable for the value of faster recovery when min_client_version
bumps server-side.

Timer is paired with the lifecycle observer: started in initState +
on resume, stopped in dispose + on pause/inactive/hidden/detached so
backgrounded apps don't burn battery on probes the user can't see.

Staleness gate still wraps the call so concurrent triggers (timer +
resume firing close together) dedupe to one network call. Manual
"Check now" still bypasses the gate via recheck().

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 16:30:40 -04:00
bvandeusen 369ed800b9 fix(flutter): non-blocking version check + 1h staleness throttle
Cold-start spinner was up to ~38s on slow / remote connections
because VersionGate blocked the entire ShellRoute on /healthz, with
the default dio's 8s connect + 30s receive timeouts. The /healthz
server handler itself is fine (microsecond JSON encode); the blocker
was client-side. Three issues fixed in one pass:

1. Optimistic render. VersionGate becomes a ConsumerStatefulWidget
   that always renders its child and just activates the version
   check controller on mount. The "you're too old" experience moves
   from a full-screen hard-block (_TooOldScreen, deleted) to a soft
   banner above the AppBar that lets the user keep playing cached
   content while they update.

2. 1h-throttled background check. New VersionCheckController
   (AsyncNotifier) hydrates from a secure-storage cache on boot,
   returning the cached result instantly. If the cache is missing
   or >1h old, fires a background recheck. AppLifecycleState.resumed
   triggers recheckIfStale so foregrounding after >1h re-checks
   without per-frame hammering. "Check now" button on the banner
   bypasses the staleness gate so dev iteration (push new APK, want
   to see banner clear) doesn't wait an hour.

3. Bounded health-check dio. The /healthz request uses a dedicated
   dio with connectTimeout: 3s + receiveTimeout: 2s rather than the
   default 8s / 30s. Health probes should fail fast — if the server
   can't ack in 5s, the user has bigger problems than a stale
   min_client_version and the cached value remains in effect.

Cache keys live alongside the existing tz cadence cache in
flutter_secure_storage (kResult + kAtMs). On any network error or
parse failure, _runCheck soft-fails without bumping the timestamp,
so the next staleness check will retry.

VersionTooOldBanner renders in _ShellWithPlayerBar's Column above
the existing UpdateBanner — the two coexist when both apply
(server rejects you AND an APK is queued).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 16:14:42 -04:00
bvandeusen 7cfaafd360 feat(#357): library_changes retention compactor
Closes the last deferred follow-up from #357. The library_changes
table is the append-only change log that drives /api/library/sync's
delta semantics — every mutation (scanner upsert, like, playlist
edit, track delete) writes one row. Without a retention policy the
table grows unbounded; the original migration (0025) called out the
follow-up explicitly.

New goroutine: sync.Compactor runs daily, deletes rows where
changed_at < now - 30 days. Logs a row count when non-zero so
operators can see compaction activity in the journal. First tick
fires on startup so a process that hasn't been compacted in a
while catches up immediately.

30-day retention matches the offline-mode spec
(docs/superpowers/specs/2026-05-09-flutter-offline-mode-design.md).
Clients with a cursor older than that hit the existing 410 fallback
path and resync from scratch.

Imported as syncpkg in main.go to follow the existing convention
(see internal/library/scanner.go).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 15:49:07 -04:00
bvandeusen 22bd06a578 feat(flutter): drift-first homeProvider (#357 deferred follow-up)
Home screen is the first surface on app open; without a local cache
the cold-start blocks on /api/home, which dominates felt latency on
slow or remote connections. This commit caches the last successful
HomeData as a single-row JSON blob in drift, so subsequent app opens
yield content immediately and revalidate in the background.

Schema:
  - New CachedHomeSnapshot table (single row: id=1, json TEXT,
    updated_at). schemaVersion bumped 2 → 3 with a forward migration
    that calls m.createTable(cachedHomeSnapshot). Codegen regenerated
    via build_runner; the *.g.dart files are gitignored and rebuilt
    by the CI Codegen step.

Provider rewrite:
  - homeProvider: FutureProvider<HomeData> → StreamProvider<HomeData>
    using the existing cacheFirst<CachedHomeSnapshotData, HomeData>
    pattern (alwaysRefresh: true for SWR). On cold cache the first
    /api/home fetch populates the row. On warm cache the cached
    HomeData is yielded immediately and a background REST fetch
    overwrites the row, which drift's watch() picks up.

  - Encoder helpers (_albumToJson / _artistToJson / _trackToJson) so
    HomeData survives the JSON round-trip into and out of drift.
    Field names match the server's /api/home wire shape exactly so
    HomeData.fromJson handles both fresh server responses and cached
    drift rows.

Callers untouched: home_screen.dart's ref.watch + ref.refresh +
metadata_prefetcher's ref.listen all keep working with the
StreamProvider shape (AsyncValue<HomeData> stays the surface type).

Test fix: 4 homeProvider.overrideWith sites in home_screen_test.dart
switched from `(ref) async => _emptyHome` (FutureProvider form) to
`(ref) => Stream.value(_emptyHome)` (StreamProvider form).

For #357. Completes the user-visible deferred follow-up. Remaining
deferred items: library_changes server-side retention.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 15:40:43 -04:00
bvandeusen efa52484d4 fix(web): add player stub to player-store mocks for TrackRow tests
#401 introduced player.current?.id reads into TrackRow.svelte and
PlaylistTrackRow.svelte, breaking 26 test cases across 6 files whose
existing vi.mock('$lib/player/store.svelte', ...) blocks only stubbed
the functions used by the original components.

Added player: { current: undefined } to each affected mock — keeps
the existing function spies and lets the new isCurrent derivation
read a defined (false-y) player.current without blowing up.

Only updated the 6 files that failed; 16 other player-store mocks
exist across the suite but their tests don't render Track/Playlist
rows so the derivation never fires. Future tests that render those
rows will need the same stub (visible at the failure point with a
clear error message).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 15:05:59 -04:00
bvandeusen 3e52ff7fa3 feat(#402): wire screen-scoped providers to liveEventsProvider
#392's dispatcher only invalidates publicly-importable providers
(myQuarantine + home). Screen-scoped providers (file-private in their
feature folders) get their own ref.listen(liveEventsProvider, ...) so
they go live without needing back-edge dependencies from /shared.

Five screens wired:

- library_screen.dart _LikedTab — invalidates _likedTracksProvider /
  _likedAlbumsProvider / _likedArtistsProvider on any of the six
  track/album/artist like/unlike kinds.

- playlist_detail_screen.dart — invalidates playlistDetailProvider(id)
  on playlist.updated / playlist.tracks_changed matching the visible
  playlist_id. On playlist.deleted matching the visible id, pops back
  so the user isn't left staring at a gone playlist.

- admin_requests_screen.dart — invalidates adminRequestsProvider on
  request.status_changed (covers user create/cancel + admin
  approve/reject + reconciler complete).

- admin_quarantine_screen.dart — invalidates adminQuarantineProvider
  on any quarantine.* event (flag from a user / admin resolve / file
  delete / lidarr delete).

- requests_screen.dart (own requests) — invalidates myRequestsProvider
  on request.status_changed. Server-side events are user-scoped via
  publishRequestStatusChanged's row.UserID, so admin actions on
  someone else's request route to the right stream.

History tab is NOT wired (no server-side play.scrobbled event yet —
documented in #402 body as deferred until that event ships).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 14:29:57 -04:00
bvandeusen 89ded7b46c feat(#402): publish album/artist like events on the SSE bus
#392 shipped track.liked / track.unliked but skipped the album +
artist symmetric pairs. Closes that gap so the Flutter Liked tab's
albums and artists sub-lists can listen for changes the same way
the tracks sub-list will (#402 wire-up lands next commit).

publishLikeEvent already handles the entity_type dispatch; the four
handler call sites just need the new lines.

For #402 follow-up to #392.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 14:27:23 -04:00
bvandeusen bb9e979876 feat(web,flutter): #401 — now-playing highlight on TrackRow + PlaylistTrackRow
Cross-platform consistency: when a track is currently playing, its row
on the album / liked / history / search / playlist detail surfaces
gets the same accent-border + bg-lift treatment that QueueTrackRow
applies on the queue panel. Closes the inconsistency caught during
the #375 DRY audit (the queue row had a "you are here" indicator;
other track-row surfaces did not).

Web — TrackRow.svelte + PlaylistTrackRow.svelte:
  isCurrent = player.current?.id === track.id
  → border-l-2 border-l-accent bg-surface-hover when true.
  PlaylistTrackRow additionally gates on !isUnavailable so deleted
  rows never match a phantom playing id.

Flutter — TrackRow + _PlaylistTrackRow:
  TrackRow becomes a ConsumerWidget, watches mediaItemProvider, and
  wraps its InkWell in a Container whose BoxDecoration carries the
  fs.iron background + 2px fs.accent left border when current. Title
  text also shifts to fs.accent and FontWeight.w500. Same pattern for
  _PlaylistTrackRow.

No "Now playing" pill on these surfaces — the player bar already
names the track, so the accent band alone reads as enough cue.

For #401 / #356 umbrella.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 14:05:33 -04:00
bvandeusen e282766268 fix(flutter): analyzer issues from #396 — unused import + AsyncValue API
Two issues caught by flutter analyze --fatal-infos:

- dart:ui import in album_color_extractor.dart was redundant because
  flutter/painting re-exports the Color it provides. Dropped.
- valueOrNull isn't on AsyncValue in this Riverpod version (the
  AsyncValue<Color?> nesting may also have confused the resolver).
  Switched to asData?.value which always returns the wrapped value
  on AsyncData and null on Loading/Error.

(palette_generator's "discontinued" warning is non-fatal informational
in pub; CI didn't fail on it. The package still works; alternative
swaps deferred until it actually breaks.)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 13:55:56 -04:00
bvandeusen 046ee8d576 feat(flutter): #396 — full-screen now-playing polish
Three of the four locked items (1, 2, 4); item 6 (swipe-tabs) stays
deferred until server-side lyrics ingestion exists.

1. Dominant-color gradient backdrop. New album_color_extractor.dart
   wraps the existing AlbumCoverCache: extracts the dominant color
   via PaletteGenerator over the local file, caches in-memory keyed
   by album_id. Top 55% of the screen carries the color (0.55 alpha
   → fs.obsidian) so controls below stay legible. AnimatedContainer
   tweens the gradient across track changes.

2. Hero transition for cover art (mini bar → full screen). Stable
   kPlayerCoverHeroTag (not media.id keyed) so the transition works
   regardless of what's playing and isn't racy if media swaps mid-tap.
   flightShuttleBuilder renders the destination's Hero widget for the
   whole flight, which reads as a clean grow rather than a swap.

4. Crossfade on track change. AnimatedSwitcher around the album art,
   title, and artist+album text block, all keyed by media.id so the
   switcher fades between old and new on each track-change rebuild.
   Pairs with the AnimatedContainer gradient so the whole "what's
   playing" zone changes in lockstep.

palette_generator: ^0.3.3 added.

For #396 / #356 umbrella.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 13:40:51 -04:00
bvandeusen b5c5dbbe76 fix(flutter): null-coalesce PlaylistTrack.streamUrl to TrackRef.streamUrl
PlaylistTrack.streamUrl is String? (nullable when track is unavailable
post-delete); TrackRef.streamUrl is required String. flutter analyze
caught the mismatch. Coalesce to empty string for unavailable rows —
they're already filtered out by the trackId != null check earlier in
the loop, so this branch is effectively unreachable but keeps the
type-checker happy.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 12:42:59 -04:00
bvandeusen 872b0de304 feat(flutter): #393 — always-visible play button on home cards
AlbumCard / ArtistCard / PlaylistCard gain a 44dp circular play
button overlaid bottom-right of the cover art. Mirrors the
hover-revealed .play-overlay on the web cards; always visible
because hover is not a real interaction on touch.

Per-card semantics match the web:

- AlbumCard: fetches /api/albums/{id}, starts playback from track 0.
- ArtistCard: fetches /api/artists/{id}/tracks, Fisher-Yates shuffles,
  plays from index 0 (matches web's playQueue(shuffle(tracks), 0)).
- PlaylistCard: fetches /api/playlists/{id}, materializes available
  rows into TrackRef, plays from index 0. Disabled state when
  trackCount == 0 — semi-transparent button, taps ignored.

Shared PlayCircleButton widget manages loading state (spinner during
fetch) so each card's onPressed can stay async without re-entrancy
guards. Cards become ConsumerWidget so they can reach the
playerActionsProvider + relevant API providers; constructor surface
unchanged so existing call sites (artist_detail, library_screen,
home_screen) keep working.

CompactTrackCard unchanged — its tap already plays-from-here.

For #393 / #356 umbrella.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 12:35:57 -04:00
bvandeusen 89d8b4b5a0 feat(flutter): send timezone on login + app-start + weekly
Flutter client posts FlutterTimezone.getLocalTimezone() to
PUT /api/me/timezone on every setSession (login / register success)
and on every AuthController.build (app cold-start with valid
session), when the locally-stored tz_last_sent_at is >7 days old.
Cadence tracked in flutter_secure_storage so it survives app
restarts.

Failures swallowed: the server's UTC default + last-known value
keep the scheduler functioning until the next attempt.

Completes the client side of #392 Half B (per-user timezone
scheduling).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 12:16:52 -04:00
bvandeusen 6b7e4f1dee feat(web): send timezone on login + bootstrap + weekly
Web client posts Intl.DateTimeFormat().resolvedOptions().timeZone to
PUT /api/me/timezone after every successful login, register, and
bootstrap when the locally-stored tz_last_sent_at is >7 days old.
Cadence tracked in localStorage keeps the server stateless on the
"is this stale?" check.

Failures swallowed: the server's UTC default + last-known value keep
the scheduler functioning until the next successful attempt. SSR-
safe via the typeof window guard.

For #392 Half B. Companion Flutter change in next commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 12:14:21 -04:00
bvandeusen c2168afbf0 fix(playlists): use CRON_TZ-prefixed cron expressions for per-job timezone
gocron v2's WithLocation is a SchedulerOption (process-wide), not a
JobOption — there's no per-job location knob. To get per-user
timezones we use a cron expression with the CRON_TZ= prefix, which
the underlying robfig/cron parser honors:

  CRON_TZ=America/New_York 0 3 * * *

Fires at 03:00 in the named zone every day. Same DST-correctness as
the original WithLocation approach.

Fall-back to UTC moves inline (was validateTimezoneOrUTC); kept the
helper because the test file still exercises it.

Caught by go vet on CI after slice 2 pushed:
"cannot use gocron.WithLocation(loc) (value of type
gocron.SchedulerOption) as gocron.JobOption value"

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 12:09:02 -04:00
bvandeusen 7fac264c73 feat(playlists): wire Refresh into PUT /api/me/timezone + registration
Completes the server side of #392 Half B.

PUT /api/me/timezone now calls scheduler.Refresh(ctx, userID) after
the DB write so the rescheduled daily-at-03:00-local job takes
effect synchronously. Failure to refresh is logged but doesn't
undo the DB write — the hourly reconciliation pass would pick it
up within an hour regardless.

POST /api/auth/register calls Refresh after successful user
insert so brand-new users get scheduled immediately rather than
waiting for the hourly pass to discover them.

system_cron.go deleted: the new scheduler subsumes its
responsibilities. The StartSystemPlaylistCron call in main.go is
also removed. Server restart now runs the new scheduler's startup
recovery + catch-up instead.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 11:58:24 -04:00
bvandeusen 46c8edfa82 feat(playlists): gocron-based per-user scheduler
Builds the per-user daily-at-03:00-local scheduler for #392 Half B.
Uses github.com/go-co-op/gocron/v2 with WithLocation(userTZ) for
each user's job. Hourly reconciliation pass keeps the in-memory
job set in sync with the active-users query.

Start sequence: clear stale in_flight rows; register a daily job
for every active user at their stored timezone; fire a one-shot
runOnce to catch up missed schedules during downtime; start gocron.

Stop drains and shuts down the gocron loop.

Refresh(ctx, userID) removes the user's existing job (if any) and
registers a fresh one at their current timezone — wired into the
PUT /api/me/timezone handler and new-user registration in the next
commit.

Server struct gains PlaylistScheduler; main.go constructs it after
the eventbus and threads it through to api.Mount. The existing
StartSystemPlaylistCron call stays for one more commit so we don't
have a window where no scheduler is running; Task 3 deletes it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 11:57:13 -04:00
bvandeusen 230da7bdcb feat(users): timezone column + PUT /api/me/timezone
Schema + endpoint scaffolding for #392 Half B (per-user timezone
scheduling). Adds two columns to the users table:

  - timezone text NOT NULL DEFAULT 'UTC' (IANA name)
  - timezone_updated_at timestamptz (nullable; populated on each PUT)

PUT /api/me/timezone validates the IANA value via time.LoadLocation
and writes the row. No scheduler integration yet — the scheduler
struct lands in the next commit and the handler-side Refresh call
in the commit after.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 11:54:45 -04:00
bvandeusen 5cd342d521 feat(playlists): daily seed rotation + jitter + 12+13 split for system playlists
Five diversity mechanics — applied to both For-You and Songs-Like-X.

1. For-You seed rotates daily across the user's top-5 most-played
   tracks. pickForYouSeedForDay uses userIDHash(user, day) mod
   len(seeds) so today's mix uses an entirely different similarity
   pool than tomorrow's. Within-day determinism preserved.
2. JitterMagnitude bumped 0.0 → 0.1. The scoring RNG is now seeded
   by userIDHash(user, day) rather than the no-op, so near-tied
   candidates shuffle daily without breaking within-day stability.
3. Head/tail split moves from 20+5 to 12+13. Roughly half the
   playlist comes from the tail now (daily-deterministic via
   tieBreakHash), giving the user substantially different content
   while a 12-track anchor of strong similarity matches keeps the
   mix recognizable.
4. Songs-Like-X seed artists shuffle daily across the user's top-5
   played artists. pickSeedArtistsForDay applies a userIDHash-seeded
   Fisher-Yates and takes 3.
5. scoreAndSortCandidates / pickTopN / pickHeadAndTail gain a userID
   parameter so the RNG can be seeded per-user; existing call sites
   updated; noopRNG removed.

Test fixtures widened similarity gaps (e.g. float64(50-i) instead of
(50-i)/50) so the new jitter (±0.1) doesn't perturb head ordering in
assertions about the head/tail mechanism. New seed_selection_test
coverage for userIDHash + pickForYouSeedForDay + pickSeedArtistsForDay
spans deterministic-within-day, varies-across-days, and graceful
degradation with small candidate pools.

PickTopPlayedTrackForUser replaced by PickTopPlayedTracksForUser
:many in the prior commit (b4801c2). The For-You seed lookup now
goes through pickForYouSeedForDay over the returned slice.
PickSeedArtists's LIMIT widened to 5 in the same prior commit.

For #392 Half A — system playlist content diversity. Half B
(per-user timezone scheduling) is a separate spec.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 10:19:49 -04:00
bvandeusen b4801c2dd3 refactor(playlists): SQL queries return top-5 candidate seeds
For-You + Songs-Like-X seed selection moves to Go-side daily rotation
(next commit). The SQL change just widens the candidate pool: top-5
played tracks instead of single top played track; top-5 artists
instead of top-3.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 10:04:39 -04:00
bvandeusen 90d8aae51a feat(#392): Flutter SSE consumer + dispatcher
Slice 4 — completes the #392 hybrid live-refresh loop.

live_events_provider.dart subscribes to /api/events/stream via dio's
streaming response mode, parses SSE frames (kind + JSON data + UserID
scope), and exposes them as a Riverpod StreamProvider. Heartbeat
comments are silently dropped; malformed JSON frames are skipped. The
provider auto-rebuilds when auth state changes (token rotation,
sign-out → sign-in), so reconnect is implicit.

live_events_dispatcher.dart listens to the stream and invalidates the
small set of publicly-importable providers we know about:

  - myQuarantineProvider + homeProvider on any quarantine.* event
  - homeProvider on any playlist.* event (Home renders the Playlists row)

Screen-private providers (library_screen.dart's _liked* /
_libraryAlbums / _history, admin screens, etc.) opt in to live-refresh
by themselves listening to liveEventsProvider in follow-up commits;
the dispatcher stays small and avoids back-edge dependencies on every
feature folder.

The dispatcher also installs an AppLifecycleState observer for
resume-time defensive invalidation. SSE will catch up on its own when
the app returns from background, but the invalidate flushes any stale
data immediately so the first frame back is fresh.

app.dart wires the dispatcher into the post-first-frame callback
alongside the other startup activations.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 22:25:15 -04:00
bvandeusen 15063ca0b4 fix(#392): simplify uuid formatter — gofmt-clean loop
The hand-unrolled byte-pair version in reconciler.go tripped gofmt -s
and goimports. Replaced with the same loop-based formatter that
internal/library/eventbus.go uses — same behaviour, fewer lines, lint
clean. Two copies of the helper still exist (one per package) to keep
the no-back-edge property for both internal/library and
internal/lidarrrequests, but they're now identical and the duplication
is tiny.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 22:21:38 -04:00
bvandeusen f7dfeff256 feat(#392): scan run lifecycle events on the SSE bus
Slice 3c — completes the server-side producer set.

Publishes scan.run_started when InsertScanRun succeeds and
scan.run_finished after FinishScanRun completes (success or with an
error_message payload). Per-file progress events are intentionally NOT
emitted — they'd flood the stream during large library scans without
giving the admin scan card anything actionable. The two-beat signal
gives the UI enough to invalidate scanStatusProvider at the right
moments.

Bus access uses a package-level setter on internal/library because
threading bus through RunScan + TryStartScan + Scheduler + all their
callers would touch ~10 sites without changing behavior at the boundaries
that don't publish. Per-process singleton, matches the log.SetDefault
idiom. cmd/minstrel/main.go calls library.SetEventBus(bus) once at
startup; test contexts that never call it skip publishing safely
(publishScanEvent is a no-op when bus is nil).

This completes the server side of #392. Slice 4 wires the Flutter
consumer: live_events_provider.dart (StreamProvider) +
live_events_dispatcher.dart (event-kind → provider invalidation)
+ AppLifecycleState cold-start invalidation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 21:52:06 -04:00
bvandeusen 84fc6b8d1b feat(#392): lidarr reconciler publishes request.status_changed on complete
Slice 3b — extends event publishing to background workers.

When the reconciler matches an approved Lidarr request against the
library and flips it to 'completed', it now publishes a
request.status_changed event scoped to the original requester so their
/requests page invalidates without polling. Three call sites — one per
kind (artist / album / track) — capture the completed row instead of
discarding it so the publish has the user_id.

Bus plumbing: the reconciler runs in cmd/minstrel/main.go which
constructs services before server.New is called. Moved bus
construction into main; the Server struct gained a Bus field that
Router() reads, falling back to a fresh local instance when nil
(test contexts). Result: one bus per process shared by every
publisher and the SSE subscriber endpoint.

reconciler.go inlines a uuid->string helper rather than reaching into
internal/api for one — avoids a back-edge dependency.

Test compat: 9 NewReconciler call sites in reconciler_integration_test.go
get `nil` for the new bus param. The reconciler's publishCompleted helper
is a no-op when the bus is nil so tests that don't care about events
keep passing.

Scanner producer (scan.progress) deferred to slice 3c — needs more
thought about which lifecycle transitions warrant events vs. flood the
stream.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 21:38:49 -04:00
bvandeusen ee7f0cdb42 feat(#392): publish quarantine + playlist mutation events
Slice 3a — extends the producer set onto the SSE bus.

quarantine events (5 producer sites):
- quarantine.flagged (user-side flag): broadcast so the flagger's other
  clients invalidate their Hidden tab and admins' clients invalidate
  their queue.
- quarantine.unflagged (user-side unflag): scoped to the user.
- quarantine.resolved / .file_deleted / .deleted_via_lidarr (admin
  actions): broadcast because a single admin action can affect every
  user who'd flagged that track.

playlist events (6 producer sites):
- playlist.created / .updated / .deleted: owner-scoped.
- playlist.tracks_changed: emitted for AppendTracks / RemoveTrack /
  Reorder. Owner-scoped. Single kind for all three mutations because
  the client invalidation logic is identical (refetch the detail).

Public-playlist subscribers (other users viewing someone else's public
playlist) intentionally left out — needs a separate broadcast kind, not
exercised yet at single-household scale.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 21:28:05 -04:00
bvandeusen 3ffa5608d8 feat(#392): publish track-like + request-status events to SSE bus
Slice 2 of #392 — wires the first producers onto the bus that slice 1
built. After this commit, an SSE subscriber sees real events fire:

- track.liked / track.unliked when the user toggles the heart on a track
  (handleLikeTrack / handleUnlikeTrack). Album + artist like events
  intentionally deferred — they're symmetric trivial follow-ups but the
  operator's primary like surface is tracks.
- request.status_changed when a Lidarr request is created, cancelled,
  approved, or rejected. Auto-approve will fire twice (pending then
  approved) in rapid succession, which is semantically correct; client
  invalidation handles that fine.

Events are user-scoped via row.UserID so admin approve/reject route to
the requester, not the admin acting. Helpers live in events_publish.go
so the wire shape (kind names, payload keys) stays in one place — future
producers in slice 3 reuse the same pattern.

events_publish.go is no-op when h.eventbus is nil so tests that
construct handlers without a bus continue to pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:55:33 -04:00
bvandeusen a5500aeeff fix(#392): update library_test.go for new Mount signature
go vet caught a missed test caller of api.Mount after slice 1's signature
change added the *eventbus.Bus parameter. Pass eventbus.New() in the test
— the TestRoutesRegisteredInMount test only walks the route table for
existence, never publishes or subscribes, so a throwaway bus is fine.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:49:55 -04:00
bvandeusen 170614baf1 feat(#392): SSE event stream foundation — eventbus + /api/events/stream
Slice 1 of the #392 hybrid live-refresh work. Ships the in-process pub/sub
bus and the SSE subscriber endpoint; no producers wired yet, so the stream
emits only heartbeats today. Verifiable in isolation by curl-ing the
endpoint with a valid Bearer token — the connection opens, ": heartbeat"
lines arrive every 15s, the connection closes cleanly on client disconnect.

eventbus.Bus is a small fan-out broadcaster: subscribers register through
Subscribe (returns a receive channel + an unsubscribe closure), writers
call Publish, and the bus drops events for any subscriber whose buffer is
full rather than blocking the writer. No persistence — clients are
expected to resync via normal /api/* fetches on (re)connect.

The SSE handler emits an initial ": connected" comment so the client sees
the connection open immediately, then forwards events whose UserID matches
the authenticated user (or is empty for broadcast). Heartbeat comments
keep proxy connections alive. Context cancellation cleanly tears down the
subscription on client disconnect.

Producers (likes, request status, quarantine, scanner, playlist mutations)
land in subsequent slices.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:44:37 -04:00
bvandeusen b466b6494a fix(flutter): unhide button + cover + timestamp on Library Hidden tab
Three small parity gaps in _HiddenTab vs the web /library/hidden page:

- No unhide affordance — once a track was flagged via the kebab, the only
  way to reverse it was to find the track in another surface and toggle
  via the kebab again. Added an Icons.restore IconButton on each tile that
  calls myQuarantineProvider.notifier.unflag(trackId) (the optimistic
  remove-with-rollback already lived on the notifier).
- No album cover art — added a 56px ServerImage thumb matching the web
  page's 14×14 thumb, with the same fs.slate fallback compact_track_card
  uses for missing covers.
- No relative timestamp — appended _relativeTime(row.createdAt) next to
  the reason pill so the user can tell "I hid this 3d ago" at a glance.

Also collapsed the duplicate provider: _HiddenTab was watching a local
FutureProvider that didn't see flag/unflag mutations, while the kebab's
HideTrackSheet flow goes through the canonical myQuarantineProvider
(AsyncNotifier). Switched _HiddenTab to watch myQuarantineProvider so
flag-from-anywhere and unhide-from-the-tab stay in sync. The local
_quarantineProvider was deleted; one source of truth now.

Caught during the #375 DRY audit cross-check against the #356 inventory.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 14:32:04 -04:00
bvandeusen 9acad5461e refactor(web): extract emptyPlaylistsMock + apiClientMock test helpers
The DRY pass audit (#375) found two inline mock patterns repeated across the
vitest suite: a default empty-playlists mock for $lib/api/playlists (4 exact
copies in menu/card tests) and an api-client spy mock for $lib/api/client
(9 callers split between get-only and full-RESTy shapes — unified into one
helper that always returns all four verb spies).

Mirrors the existing test-utils/mocks/likes.ts and test-utils/mocks/quarantine.ts
convention. Tests with intentionally divergent shapes (AddToPlaylistMenu's
richer createPlaylist payload, PlaylistCard's getPlaylist, route-specific
mocks, events.svelte's specific resolved value) stay inline.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 12:45:15 -04:00
bvandeusen 1f0f7eee1a fix(playlists): unblock Discover by removing SELECT DISTINCT + ORDER BY plan error
The cross-user bucket query combined SELECT DISTINCT with ORDER BY md5(...),
which Postgres rejects at plan time (SQLSTATE 42P10). buildDiscoverCandidates
returned that error on first bucket failure, so the whole Discover playlist
was skipped every nightly run — even though the random bucket pool was
healthy. Switched to GROUP BY so the md5 ordering expression no longer needs
to appear in the select list, and hardened the function so future single-
bucket failures degrade gracefully via slot redistribution instead of taking
out the whole playlist.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 09:50:01 -04:00
bvandeusen 0d009b34e2 Merge pull request 'release v2026.05.12.1: Discover surface + nav fixes + cache hygiene' (#42) from dev into main 2026-05-12 03:58:43 +00:00
bvandeusen 5fc04f14b7 fix(flutter): full-player kebab nav + restore artistAlbums SWR
Two unrelated issues, batched.

Full-player kebab → "Go to album/artist" still crashed with
_debugCheckDuplicatedPageKeys despite the prior onBeforeNavigate
fix. Cause: pop() and push() ran in the same frame, so go_router's
page-key reservation table briefly contained both /now-playing AND
the destination shell-child, tripping the duplicate-key assert.

Refactor: replace onBeforeNavigate with onNavigate(path), where the
host receives the path AFTER the sheet pops and owns the
navigation entirely. The full player wires:
  onNavigate: (path) async {
    await Navigator.of(context).maybePop();
    if (context.mounted) GoRouter.of(context).push(path);
  }
Awaiting the pop guarantees /now-playing is fully gone from the
navigator's page list before the push starts.

Mini player + track rows + everywhere else use the default (no
onNavigate) path that does context.push(path) inline — they're
already inside the ShellRoute, no race possible.

Restored alwaysRefresh: true on artistAlbumsProvider. Dropping it
in the cache-loop fix had a side effect: if drift's cachedAlbums
held only a subset of an artist's albums (user previously visited
just one album by them), the artist detail page rendered that
partial list forever — provider only fetched on empty drift, never
on partial drift. The metadata prefetcher only mass-warms
artistProvider (single row), so re-enabling SWR on artistAlbums
won't recreate the storm.
2026-05-11 23:54:11 -04:00
bvandeusen a09b636e1a fix(flutter): full player kebab Go to album/artist navigates cleanly
Same root cause as the /queue duplicate-page-key crash: /now-playing
is a top-level route (lives outside the ShellRoute), but
/artists/:id and /albums/:id are shell-children. Pushing a shell-
child from a top-level route makes go_router attempt to mount a
second ShellRoute on top of the active one, leaving navigation in a
broken state. The mini player works because it's already inside the
shell.

Add an optional onBeforeNavigate callback to TrackActionsSheet
(forwarded through TrackActionsButton). When set, fires after
sheet.pop() and before context.push() of the destination route.

Wire the full player's TrackActionsButton with onBeforeNavigate:
() => Navigator.of(context).maybePop() so /now-playing dismisses
itself before the detail route is pushed. Result: clean navigation
into the destination, mini player visible underneath as expected.

Mini player keeps the default (no callback) since it's already in
the shell.
2026-05-11 23:50:42 -04:00
bvandeusen 356f8f5d6c test(web): update home placeholder counts for new Discover slot
5-slot system row (For-You, Discover, 3× Songs-like) means:
- empty state: 5 placeholders (was 4)
- For-You only: 4 placeholders (was 3) — Discover + 3 songs-like
2026-05-11 23:46:07 -04:00
bvandeusen 96aa2407d9 feat(home): surface Discover system playlist as a tile (web + flutter)
Server has been generating system_variant='discover' playlists since
M6a (internal/playlists/system.go and POST
/api/playlists/system/discover/refresh) but neither client surfaced
it. The Flutter home filtered system playlists by exact match on
'for_you' and 'songs_like_artist', dropping Discover. The web home
did the same. Tiles were generated server-side and silently
discarded by both clients.

Add a Discover slot to the playlists row in both:
- Flutter: 5-slot row now (For You, Discover, 3× Songs-like) with
  matching placeholder state machine.
- Web: same shape, same placeholderVariant() call.

When the engine has built it, the real playlist tile renders;
otherwise a placeholder with the same building/pending/failed
status semantics as the other system tiles.
2026-05-11 23:41:01 -04:00
bvandeusen e856172d60 chore(flutter): drop success-path diagnostic prints
Cleanup pass on the noisy debugPrints we added during the recent
debugging sessions. Remaining prints are error-path only:
- AlbumCoverCache fetch failed
- album/playlist cold-cache fetch failed
- audio_handler playbackEventStream error
- audio_handler queue supersession (rare race)
- audio_handler forward/backward fill failed
- artist_detail play failed
- cacheFirst fetchAndPopulate failed (only when tag is set)

Removed per-event chatter:
- audio_handler player-state and processingState subscribers
- audio_handler timing measurements (built initial / setAudioSources
  / forward fill / backward fill)
- audio_handler cache hit/miss per-track (fired N times per play)
- audio_handler register stream cache (verifiable via Settings)
- audio_handler.configure log
- albumProvider step-by-step lines (drift miss / online / drift hit /
  album hit but no tracks)
- playlistDetailProvider step-by-step lines (calling get / drift
  write done / 404 evicted / drift hit / playlist hit but no tracks)
- playlistsListProvider wire returned + drift rows lines
- playTracks stage timings (serverUrl / token / configure / setQueue
  / play returned)
- metadataPrefetcher warming N artists
- artist_detail play tapped — N tracks success log
- cacheFirst step-by-step (drift hit / drift miss / online / done)

`tag` parameter on cacheFirst preserved for ad-hoc instrumentation.
2026-05-11 23:16:42 -04:00
bvandeusen ab62a3d118 fix(flutter): cancel stale background fills when queue changes
The lazy source-build commit (1ddde12) introduced a race: when the
user taps play on a new track while a previous queue's
_fillRemainingSources is still working, the stale fill keeps
calling _player.addAudioSource() on the new player state — appending
old-playlist tracks into the new queue and confusing the player into
the "locked to one song" symptom.

Fix: queue-generation counter. setQueueFromTracks bumps
_queueGeneration first thing; the background fill captures its gen
at start and aborts before any further player mutation if a newer
queue has taken over. The previous play() never gets to mutate the
new player state.

Also resets _suppressIndexUpdates at the start of every
setQueueFromTracks (defensive — covers the case where a prior
backward-fill bailed on its gen check before reaching `finally`)
and only releases the flag in finally if we're still the active
gen.

Symptoms this should resolve:
- "locked to one song" after rapid play taps
- Late `play() returned 73189ms` lines indicating a previous
  hung play() call finally resolving and stepping on current state
- Player stuck in odd processingState after queue swaps
2026-05-11 22:31:45 -04:00
bvandeusen a3c0aed63e feat(flutter): playlist detail nav hydration — header renders before fetch
Same pattern as album + artist detail. PlaylistDetailScreen accepts
optional Playlist seed via go_router extra. While
playlistDetailProvider is still resolving, render the header
(description if any + track count) plus a "loading tracks…" inline
spinner instead of an opaque full-screen CircularProgressIndicator.
The body fills in when tracks arrive via drift watch re-emit.

Routing reads s.extra as Playlist. PlaylistCard +
PlaylistsListScreen pass the playlist via extra. Surfaces with no
seed available (deep links etc.) fall back to the original full-
screen spinner.

Track row rendering already uses ListView.builder so visible row
count was never the bottleneck — the wait was for the detail fetch
itself. Header-on-tap is the win that makes the screen feel snappy.
2026-05-11 22:24:02 -04:00
bvandeusen 1ddde12959 perf: lazy player source build + Cache-Control on byte endpoints
Two unrelated wins as a single batch.

Flutter — lazy source building in setQueueFromTracks:
Today: Future.wait builds all N AudioSource objects (drift queries +
LockCaching ctor) before the player can call setAudioSources →
play(). Measured at 83ms for a 25-track playlist, on top of the
~285ms initial-source preload.

New flow: build only the initial source, hand it to setAudioSources
([initial], initialIndex: 0) so play() can start, then background-
fill the rest. Forward direction (skipNext targets) added via
addAudioSource. Backward direction (skipPrev) inserted at index 0..
initialIndex-1 with _suppressIndexUpdates true so the unavoidable
currentIndex shifts don't push the wrong MediaItem onto the stream.

Saves the up-front source-build wait — tap-to-audio for long queues
should drop by ~80-100ms even on cache hits.

Server — Cache-Control on the three byte-serving endpoints:
- /api/albums/{id}/cover: max-age=86400, must-revalidate. Covers
  change rarely (re-scan, MBID enrichment); a day of cache is safe
  and skips conditional GETs for the bulk of a session.
- /api/playlists/{id}/cover: max-age=300, must-revalidate. Collages
  recompute when contents change; short enough for edits to feel
  fresh, long enough to skip repeat fetches during a session.
- /api/tracks/{id}/stream: max-age=31536000, immutable. Track bytes
  are immutable for a given id (scanner re-indexes by file_path; new
  files get new ids). LockCachingAudioSource on the Flutter side
  already disk-caches, but proper headers let it skip even the
  conditional 304 on repeat plays.
2026-05-11 22:18:58 -04:00
bvandeusen f1b4652c77 Merge pull request 'release v2026.05.11.3: caching, perf, playlist polish' (#41) from dev into main 2026-05-12 00:35:48 +00:00
bvandeusen 261b44522d fix(flutter): bump album-grid cellH slack — silence 1px overflow warnings
Logs were spitting "RenderFlex overflowed by 1.00 pixels on the
bottom" from album_card.dart whenever the library Albums tab or
artist detail album grid rendered. Cell height was computed as
cover + gap + title + artist + 4px slack, which assumes pixel-perfect
14sp/12sp line heights — Flutter's actual rendering with ascent/
descent + line-height multipliers wants one more pixel.

Bump slack from 4 to 8 in both grids. AlbumCard layout unchanged;
the warnings stop.

Otherwise the log shape is healthy now: prefetcher fires once per
library page emit (expected, one batch per pagination), cache misses
fetch sequentially with clean drift-write → re-emit cycles, and
album taps are single-round-trip cold-fetches followed by drift hits.
No more cycles of duplicate fetches.
2026-05-11 20:27:54 -04:00
bvandeusen 6f20a75f9b feat(flutter): playlist cover art via deterministic /api/playlists/{id}/cover
Same fix shape as albums: drift's CachedPlaylistAdapter.toRef was
returning coverUrl: '' because the cache table doesn't persist the
server-derived URL. Set it to /api/playlists/<id>/cover in the
adapter — handleGetPlaylistCover serves the cached collage from
disk, so the URL is deterministic and the round-trip through drift
no longer drops it.

PlaylistCard + PlaylistsListScreen pass the existing queue_music
icon as ServerImage's fallback, so when the server hasn't built a
collage yet (system playlists with no tracks at build time), the
endpoint 404s and the icon shows over the slate background instead
of an empty box.
2026-05-11 20:15:38 -04:00
bvandeusen 2d5f0691c2 diag(flutter): surface player errors + state transitions
Tap→audio measured at ~370ms — that path's fast. Real symptom: a few
seconds of audio, then silence with no event surfaced to Flutter.
ExoPlayer is failing/completing somewhere and we have no log to act
on.

Three changes, all log-only:
- Add onError to playbackEventStream so stream failures (404, range-
  request bugs, decoder errors, network drops) print instead of
  silently halting playback.
- Subscribe to playerStateStream and log playing + processingState
  on every transition. Silent stops will now show as a state shift
  to completed / idle / buffering with no resumption.
- Subscribe to processingStateStream separately to catch fine-grained
  state transitions ExoPlayer reports between source advances.

After hot-restart, tap-then-go-quiet should produce a sequence we
can read — most likely either "processingState=completed" partway
through (server returning premature EOS or wrong Content-Length) or
a thrown error from ExoPlayer's source-loading path.
2026-05-11 19:43:37 -04:00
bvandeusen e8a515dac4 fix(flutter): import debugPrint in player_provider for the timing logs 2026-05-11 19:35:12 -04:00
bvandeusen acc7149537 diag(flutter): instrument playTracks + cache appdir; fix CI
CI fixes:
- artist_detail_screen.dart: drop unnecessary foundation import (debugPrint
  comes from material) and unused metadata_prefetcher import.

Playback timing visibility (so we can stop guessing where the lag
lives):
- playTracks now logs serverUrl / token / configure / setQueue /
  play() returned, each stage in milliseconds. The next time you
  tap play, we'll see exactly where the seconds go.
- setQueueFromTracks adds two more measurements: total source-build
  time across all tracks, and setAudioSources duration.

Small concrete win:
- audio_handler caches the application cache dir path on first use
  (already cached in _maybeRegisterStreamCache; now also used in
  _buildAudioSource for the LockCachingAudioSource path). One less
  platform channel hit per track on cache-miss queue builds.

Once we see real numbers we can decide whether the fix is to build
sources lazily (initial source first → play → background-add the
rest), pre-warm the audio handler at app start so playTracks skips
serverUrl + token reads entirely, or something else.
2026-05-11 19:11:44 -04:00
bvandeusen 4ede37d9ad fix(flutter): stop the cache feedback loop — playback no longer competes
The prefetcher + alwaysRefresh combination was creating a feedback
loop visible in the logs as repeated `metadataPrefetcher: warming N
albums` cycles, each kicking N parallel getAlbum fetches that then
triggered drift writes that triggered re-emits that re-ran the
prefetcher. Tap-to-play was queueing behind 14+ in-flight cache
fetches.

Three structural fixes:

1. Prefetcher hard-dedupes per session via _warmedArtists Set.
   Re-rendering a screen no longer re-fires fetches for ids we've
   already seen.

2. Prefetcher only warms artistProvider, not albumProvider. Albums
   carry track lists; pre-warming N albums fans out N parallel
   "fetch tracks" round trips for content the user may never visit.
   Artist rows are single-row lookups — cheap. Album detail loads
   on tap (still fast: server-side perf work makes it ~one round
   trip).

3. Drop alwaysRefresh from albumProvider, artistProvider,
   artistAlbumsProvider, artistTracksProvider. Each was kicking one
   silent background refresh per first cache hit. With the prefetcher
   creating many subscriptions in parallel, that meant every
   prewarmed id triggered an extra fetch even when drift was already
   populated. playlistsListProvider keeps alwaysRefresh — system
   playlists genuinely rotate UUIDs and need the catch-up. Pull-to-
   refresh remains the explicit invalidation path everywhere else.

Removed the warmAlbums calls from the library Albums tab and artist
detail album grid (the storm sources).

Net effect: cold app boot warms ~12-15 artist rows once, period.
Tapping a tile still fetches its detail on demand (one round trip,
fast). User-initiated playback isn't queued behind cache work.
2026-05-11 19:02:16 -04:00
bvandeusen 4bd069430b feat(flutter): extend metadata prefetch to library tabs + artist detail
MetadataPrefetcher gains warmAlbums(ids) / warmArtists(ids) public
methods so callers can fan out drift-cache warm-ups for whatever
collection just landed.

Wired into:
- Library Artists tab — warms first 8 artists from the page on every
  data emit (initial + paginate + refresh).
- Library Albums tab — same for first 8 albums.
- Artist detail album grid — warms first 8 albums from the artist's
  album list as soon as it loads, so tapping into any of them is a
  drift hit.

Hard-cap of 8 per call (same as the home prefetch). Set spans across
calls aren't deduped at this layer because providers themselves
short-circuit on cached values.

Also instrument the artist-detail play button: try/catch around the
artistTracksProvider read + playTracks call, snackbar on
empty-tracks or thrown-error so silent failures stop being silent.
The current behavior was an early return on tracks.isEmpty with no
visible feedback.
2026-05-11 18:52:37 -04:00
bvandeusen 22152b1ba3 feat(flutter): metadata prefetcher — pre-warm drift for likely tap targets
Across-the-board sluggishness was every cold-cache tap doing one
network round trip while the user waits. SWR helps on re-visits but
the first time you tap a tile from home you eat the latency.

MetadataPrefetcher listens to homeProvider. When /api/home returns,
it fires fire-and-forget reads on albumProvider + artistProvider for
the top-N items in each home section (recently added, rediscover,
most played, last played). Each provider read triggers the existing
cold-cache path, which writes to drift. By the time the user
actually taps a tile, it's already a drift hit and the detail
screen renders instantly.

Cap N=8 per section (covers what's visible on a typical phone
without scrolling). Set spans dedupe across sections so popular
artists don't get fetched five times. Errors are swallowed — a
failed prefetch is silent and the tile falls back to its on-tap
fetch behavior.

Wired alongside the existing audio prefetcher in app.dart's
postFrameCallback.
2026-05-11 18:44:09 -04:00
bvandeusen 572325e23f fix(flutter): write cachedTracks rows from playlist fetch (was the empty-rows bug)
Detail screen showed empty rows for system playlists because the
fetch batch wrote cachedPlaylists, cachedPlaylistTracks (positions),
cachedArtists, and cachedAlbums — but never cachedTracks themselves.
The detail screen's LEFT OUTER JOIN cachedTracks then returned null
on every row, so trackId was null and titles came back empty.

PlaylistTrack on the wire carries enough to populate cachedTracks
(id, title, albumId, artistId, durationSec). Adds a third dedup map
in fetchAndPopulate, batched with the existing artist + album writes.
track_number / disc_number aren't on the wire so they default to 0;
the detail screen doesn't surface them.

Reusing cachedTracks across albumProvider + playlistDetailProvider
also means tapping a playlist's track to play it now finds the row
in drift instead of triggering another fetch.
2026-05-11 18:38:21 -04:00
bvandeusen 8d466ebdd5 fix(flutter): reconcile stale playlists + recover from 404 on tap
The 404 on tapping the For-You tile traced to stale drift rows.
BuildSystemPlaylists rotates UUIDs on every rebuild, so old For-You
/ Songs-Like ids accumulate in cachedPlaylists. The list provider's
fetchAndPopulate was only doing insertOrReplace, which adds new rows
but never removes the obsolete ones — so the home tile renders 8
playlists when the server only knows 4, and 4 of those tiles 404 on
tap.

Two fixes:

playlistsListProvider.fetchAndPopulate now reconciles. After
fetching the fresh list, deleteWhere any user-owned drift row whose
id isn't in the fresh response, then upsert the fresh set in the
same batch. Public-from-others rows are left alone — they're not
keyed by ownership and we don't want to drop someone else's public
playlist just because the current user's response didn't enumerate
it. Operates inside the existing batch so it's atomic.

playlistDetailProvider.fetchAndPopulate now treats a DioException
404 as "this row is stale": delete the cachedPlaylists + any
cachedPlaylistTracks rows for this id, return false so the UI yields
emptyDetail. The next render of the home row sees the row gone and
the tile disappears, completing the cleanup.

Side note: every system-playlist rebuild discards drift rows for the
just-evicted UUIDs and writes the new ones. That cycle's been
silently churning since system playlists shipped — this is the
first time the cleanup actually runs.
2026-05-11 18:32:40 -04:00
bvandeusen af5744f8ab perf(home): aggregate-first rewrites for two scan-the-world queries
handleGetHome itself is well-architected (5 sections in parallel via
goroutines, latency-bound by the slowest single query). The cold-
start lag is two of those queries doing wider scans than necessary.

ListLastPlayedArtistsForUser was iterating FROM artists a with a
LATERAL play_events join per row — O(total_artists in library) plan
even for users who've only played a handful. Inverted: aggregate the
user's plays by artist_id first via the play_events → tracks join
(uses play_events_user_track_idx + tracks pkey), then attach the
artist row and lateral cover/count subqueries only for the artists
that actually appear. Cost now bounded by play history, not library
size.

ListMostPlayedTracksForUser was joining tracks/albums/artists for
every play_event row before grouping — O(total plays) work for
joins. Pre-aggregated play_events into a CTE keyed by track_id +
count(*), then joined to tracks/albums/artists only for the
distinct-tracks survivors. Order-by uses the pre-computed count.

No handler or generated-Go signature changes — both queries return
the same rowset shape, just much faster on libraries where total
artists/plays >> distinct-played-artists/distinct-played-tracks.
2026-05-11 18:26:20 -04:00
bvandeusen c7549bbe48 perf(api): collapse N+1 in /api/artists/{id} + 1 round-trip in /api/albums/{id}
Two new sqlc queries replace three sequential per-album round trips
that were dominating detail-screen latency.

GetAlbumWithArtist: handleGetAlbum was doing GetAlbumByID then
GetArtistByID — separate round trips for one logical lookup. The new
query joins albums + artists with sqlc.embed and returns both in one
SELECT. Detail-page DB cost: 3 trips → 2.

ListAlbumsByArtistWithTrackCount: handleGetArtist was loading the
artist's album list, then issuing one CountTracksByAlbum per album to
populate track_count. On a 30-album artist that's 32 sequential
queries — each ~5ms over a local DB, ~30ms over a remote one. The
new query embeds the album row + a correlated count(*) subquery, so
every album's track count comes back in one SELECT regardless of
album count. Detail-page DB cost: 1 + N → 1 + 1.

Together these account for the bulk of cold-cache navigation latency
on the Flutter client. Combined with the existing SWR + nav
hydration on the client side, detail screens should render their
header instantly and the body within one round trip instead of
N+constant.
2026-05-11 18:13:27 -04:00
bvandeusen 9cac664679 feat(flutter): register stream-cached files in the audio cache index
Closes the gap where LockCachingAudioSource wrote files to disk but
never told AudioCacheManager about them — meaning evict() couldn't
reclaim stream-cached files when usage exceeded the cap, only
explicitly-pinned downloads.

Wire just_audio's bufferedPositionStream as the "download complete"
signal: when bufferedPosition reaches duration (with 200ms slack for
header bytes), look up the on-disk file at the LockCaching path,
read its size, and insert an audio_cache_index row via the new
AudioCacheManager.registerStreamCache(). Source defaults to
incidental so stream-cached tracks are first to be evicted under
pressure.

Dedupe via _streamCacheRegistered Set so we don't hit drift on every
~200ms buffered-position emit. Cache the application cache dir path
on first use for the same reason.

Eviction now sees the full set of files on disk; usageBytes() (which
already walks the dir) and evict() (which reads the index) are
finally consistent for stream-cached tracks. Pinned tracks keep
their existing manual-download flow unchanged.
2026-05-11 17:46:32 -04:00
bvandeusen c08f4ace80 fix(flutter): cache usage display reflects actual disk, not just index
The Storage card has been showing "0 B" for users who only stream
(never explicitly pin or download an album). usageBytes() summed
SUM(size_bytes) from audio_cache_index — but the streaming path
through audio_handler writes files via LockCachingAudioSource without
ever inserting an index row, so the index undercounts (often to
zero) for normal use.

Walk the cache directory instead. Catches everything on disk:
manually pinned tracks (registered in the index), stream-cached
tracks (LockCaching), partial downloads. Falls back gracefully when
a file is racing against concurrent writes / deletes.

Eviction still operates on the index (it needs the source/recency
metadata to pick eviction order). Stream-cached files aren't subject
to eviction today — separate problem; addressed when we wire a
download-complete hook from LockCaching back into the index.
2026-05-11 17:41:07 -04:00
bvandeusen c1df2af992 fix(flutter): /queue at top level — fixes duplicate-key crash from player
Tapping the queue button from /now-playing crashed with
NavigatorState._debugCheckDuplicatedPageKeys. Root cause: when I
moved /now-playing out of the ShellRoute earlier, /queue was left
inside the shell. Pushing /queue while /now-playing was on top
made go_router try to mount a second ShellRoute instance under the
existing one — both shells got the same page key.

Move /queue out of the ShellRoute too, sibling to /now-playing.
Shell stays mounted (with whatever child it had) underneath both
top-level routes; pop from /queue returns to /now-playing or the
shell's previous child as appropriate.
2026-05-11 17:32:57 -04:00
bvandeusen a7f35a5d6d feat(flutter): full player — combined action row above seek
Move shuffle / repeat / queue out from below the play controls and
combine with the like + kebab into a single row sitting just above
the seek bar. Title row drops back to title-only (truly centered now,
no Stack needed since nothing competes for the row's right edge).

Layout order is now: art → title → artist → album → [shuffle, repeat,
queue, like, kebab] → seek → prev/play/next.

The "queue" icon in the top-right of the AppBar stays for now —
redundant with the new row but matches what users have already
muscle-memoried for opening the queue from any player state.
2026-05-11 17:25:27 -04:00
bvandeusen e610948307 Merge pull request 'release v2026.05.11.2: signing key + library infinite scroll' (#40) from dev into main 2026-05-11 19:51:41 +00:00
bvandeusen 8c00ee21c7 feat(flutter): infinite scroll on library Artists + Albums tabs
Both providers were FutureProvider<Paged<T>> returning a single page
of 50, so once the user scrolled past 50 items the list just ended.
Replace with AsyncNotifier<Paged<T>> that exposes loadMore(): fetches
the next page using items.length as the offset and appends to the
existing list. Idempotent guard via _loadingMore flag — concurrent
scroll events near the bottom collapse to a single fetch.

Both tabs now wrap the GridView in NotificationListener<ScrollNotification>
that fires loadMore() when within 800px of maxScrollExtent. The
lookahead is enough that the next page lands before the user hits
the visible bottom on a typical phone scroll.

Pull-to-refresh updated to invalidate + re-await the provider so a
manual refresh always starts from the first page.
2026-05-11 15:41:01 -04:00
bvandeusen 2500914498 fix(flutter): persistent release signing key via CI secret
Update installs were failing at the system scanner step because every
release APK was signed with a different signature: build.gradle.kts
fell back to signingConfigs.getByName("debug"), and the debug
keystore is generated per-machine — so every CI runner had a fresh
random key. Android refuses to upgrade an installed app when the
signature doesn't match, hence the "App not installed" failure
after the scan.

Two-part fix:

1. build.gradle.kts now defines a real "release" signing config when
   ANDROID_KEYSTORE_PATH is exported (with the matching password +
   alias env vars). Without those, falls through to the debug
   keystore so local `flutter run --release` still works.

2. flutter.yml decodes ANDROID_KEYSTORE_B64 (CI secret, base64 of the
   real release keystore) into a tmp path before the release-APK
   build step, then exports ANDROID_KEYSTORE_PATH + the three
   password/alias secrets as env vars. CI now hard-errors if the
   keystore secret is missing on a tagged build — we don't want
   another silent debug-keystore release.

OPERATOR ACTION REQUIRED before the next tag:

1. Generate a release keystore (one-time):
     keytool -genkey -v -keystore minstrel-release.keystore \
       -alias minstrel -keyalg RSA -keysize 2048 -validity 10000

2. Base64 it:
     base64 -w0 minstrel-release.keystore > keystore.b64

3. In Forgejo, add four repo secrets:
     ANDROID_KEYSTORE_B64    = contents of keystore.b64
     ANDROID_KEY_ALIAS       = minstrel
     ANDROID_STORE_PASSWORD  = the password you set
     ANDROID_KEY_PASSWORD    = same password (or different alias pwd)

4. Keep minstrel-release.keystore offline and backed up — losing it
   means you can never sign an upgrade for any existing install.

5. Existing installs from prior debug-keyed releases must be
   uninstalled before installing the first key-signed release. This
   is a one-time transition; future tagged builds will upgrade
   cleanly.
2026-05-11 14:22:32 -04:00
bvandeusen fb811804d2 Merge pull request 'release v2026.05.11.1: Flutter caching, navigation, and player polish' (#39) from dev into main 2026-05-11 17:47:41 +00:00
bvandeusen 0134281b8c fix(flutter): CI analyze + center title in full player
- artist_detail_screen.dart missed an `import '../models/artist.dart'`
  for the ArtistRef seed parameter; analyze flagged undefined_class.
- radio.dart + player_provider.dart doc comments wrapped URL
  parameters in <...> which lint reads as HTML. Switched to backticks.

Full player title is now centered absolutely via a Stack: title with
horizontal padding equal to the actions cluster width sits at the
optical center, while LikeButton + TrackActionsButton are pinned to
the right edge with Positioned. Fixed-height SizedBox(32) keeps the
row stable when the title wraps to a single ellipsized line.
2026-05-11 13:01:52 -04:00
bvandeusen 4dbb3190ff fix(flutter): player updates on track change + kebab artist nav + Start radio
Three issues, all related to the player surface:

1. Player UI didn't update on track change. audio_handler's
   _onCurrentIndexChanged only kicked off the cover load — it never
   pushed the new MediaItem onto the mediaItem stream. Title/artist/
   cover stayed pinned to whatever setQueueFromTracks(initialIndex:)
   set on first play. Now the listener pushes queue[idx] when the
   index changes.

2. Player kebab "Go to artist" 404'd while the same item from
   MostPlayed worked. Same TrackActionsSheet for both, but the
   player's _trackRefFromMediaItem was hardcoding artistId: ''
   because audio_handler's _toMediaItem never stashed it in extras.
   Stash artist_id alongside album_id; player_bar +
   now_playing_screen read it back. Both kebabs now navigate.

3. "Start radio" didn't exist on Flutter even though the server has
   /api/radio?seed_track=<id>. New RadioApi (lib/api/endpoints/
   radio.dart) wraps the endpoint; PlayerActions.startRadio(trackId)
   fetches + plays the result via the existing playTracks path.
   New menu item between "Add to playlist" and the divider above
   "Go to album", calls startRadio with a snackbar error fallback.
2026-05-11 12:32:43 -04:00
bvandeusen 2299824ad9 fix(flutter): system playlist tap loads tracks (mirror album refetch fix)
System playlists now show in the home row (good!) but tapping them
landed on an empty playlist. Same root cause as the earlier album
bug: playlistsListProvider wrote the playlist *row* to drift but
never the tracks. playlistDetailProvider only triggered cold-fetch
when the row was missing, so it yielded with an empty track list.

Refactor playlistDetailProvider to mirror albumProvider's approach:
- fetchAttempted guard (one-shot per subscription).
- Detect "playlist row exists but trackRows empty" and trigger the
  same fetchAndPopulate the cold-cache path uses. Drift watch
  re-emits with populated tracks.
- 10s timeout on the API fetch + diagnostic prints so any failure
  surfaces in logs.

While here, fix two adjacent issues:
- Wipe + re-insert this playlist's track positions on every fetch
  so server-side deletions actually propagate. Without the wipe,
  removed tracks would linger in drift forever.
- Write the artist + album rows referenced by the fetched tracks
  into cachedArtists / cachedAlbums (deduped). Without this, the
  joined artistName/albumTitle columns in the playlist track rows
  surface empty.

Cover art for system playlists is a separate issue — server emits
coverUrl but it may be empty for system mixes; PlaylistCard falls
back to the queue_music icon. Will tackle in a follow-up.
2026-05-11 12:26:17 -04:00
bvandeusen a77d4ceac0 fix(flutter): library Artists tab 404 + Albums tab 3-up grid
Artists tab 404: client called /api/library/artists, but the server
mounts the artists list at /api/artists (handleListArtists). Albums
sit at /api/library/albums for historical reasons — the paths aren't
symmetric. Switch listArtists() to /api/artists with sort=alpha.

Albums tab grid: matched the responsive 3-up layout we built for
artist detail. LayoutBuilder computes cellW from available width;
AlbumCard sized to the cell with titleMaxLines: 2; mainAxisExtent
matches actual content height (cover + 2-line title + artist line +
fudge). No more wide-aspect cells with empty space below the card.

Also wired `extra: ref` on the artists/albums grids and the Liked
tab so detail-screen nav hydration kicks in here too — taps from
library screens get the same instant header that home tiles do.
2026-05-11 12:21:24 -04:00
bvandeusen 11c40c6aca feat(flutter): SWR everywhere + nav hydration + cold-start home skeleton
Three changes addressing the cold-start spinner + stale-on-revisit pain.

A. SWR on remaining cacheFirst providers
- artistProvider, artistAlbumsProvider, artistTracksProvider all gain
  alwaysRefresh: true. Cache hit still renders instantly; one
  background refresh per subscription keeps the row from going stale
  forever.
- albumProvider (inline async*) and playlistDetailProvider (inline
  async*) now keep a `revalidated` flag and kick a one-shot
  background fetch on the first complete cache hit. Same effect as
  cacheFirst's alwaysRefresh, just inline.
- Three providers gained the connectivity timeout that
  album/artist/playlist already had.

B. Navigation hydration
- AlbumDetailScreen accepts `AlbumRef? seed`; ArtistDetailScreen
  accepts `ArtistRef? seed`. When the live provider is still loading,
  the seed populates cover/title/artist immediately so the page
  isn't blank.
- Routing wires `extra: AlbumRef|ArtistRef` from go_router into
  the seed parameter.
- Call sites updated: home (Recently added, Rediscover albums +
  artists, Last played), artist detail album grid. Where a ref isn't
  available (track actions sheet), the screen falls back to the
  spinner — no regression.

C. Cold-start home skeleton
- Replace the full-screen CircularProgressIndicator on /home with a
  layout-preserving skeleton: 5 section titles + 6 grey card-shaped
  placeholders per row. The page feels populated immediately;
  sections fill in independently as data arrives via the per-section
  providers.
- Drops the unused DelayedLoading import.

Net effect: re-visits to detail screens render instantly (cache hit
+ silent refresh); first visit from a tile shows the seed header
immediately while tracks load; cold-start home shows a layout
skeleton instead of a 30s blank spinner.
2026-05-11 12:12:44 -04:00
bvandeusen 37134950a5 Merge pull request 'release: M5-M7 server + web + Flutter, plus Flutter v1 polish' (#38) from dev into main 2026-05-11 15:21:58 +00:00
bvandeusen f4d07ef9a1 diag(flutter): trace playlist provider — wire vs drift vs filter
Web UI shows system playlists; Flutter shows placeholders. Wire shape,
adapters, drift schema, and filter constants all line up on inspection,
so adding instrumentation to pinpoint where the system rows fall out:

- Log what /api/playlists?kind=all actually returns (owned/public
  counts, including how many of owned are system).
- Log what cacheFirst sees on each drift emit: total rows, filtered,
  how many are system, how many landed in owned vs pub, plus the
  user.id used for the owned-vs-pub split.

Also add the 3s connectivity timeout that albumProvider/artistProvider
got — keeps the alwaysRefresh path from blocking on a stalled
connectivity stream.

Three log lines from one home-screen visit will tell us:
- Does the server emit system rows? (wire log: system=N)
- Do they land in drift? (drift log: filtered system=N)
- Do they survive the user-id filter? (drift log: owned system=N)
2026-05-11 11:07:24 -04:00
bvandeusen 74cc76b369 fix(flutter): preserve dev-version safety net + update version tests
Two test failures from the comparator rewrite:

1. "different unparseable strings → newer" was useful — branch-name
   builds (e.g. PackageInfo reports 'main' while server reports
   'dev') should still surface the banner so the operator sees that
   something is misaligned. Restore that fallback: if both sides
   parse to all-zero components (no numeric structure on either),
   compare as strings.

2. "honors prerelease ordering" tested pub_semver behavior we no
   longer use. Replaced with tests that cover what the new
   comparator actually does: zero-padding for length mismatch,
   leading-zero normalization, 4-part date+build comparisons, and
   month-rollover correctness without leading zeros.
2026-05-11 10:48:06 -04:00
bvandeusen a65474284a fix(flutter): satisfy curly_braces_in_flow_control_structures lint 2026-05-11 10:36:40 -04:00
bvandeusen 2f67c26a45 fix(flutter): pubspec version must be 3-part semver
flutter pub get rejects "2026.05.11.0+1" — it requires strict
MAJOR.MINOR.PATCH+BUILD with no leading zeros. Use 2026.5.11+1
as the local default; CI's --build-name="${TAG#v}" still injects
the full 4-part tag for release builds, so production APKs report
the tag verbatim while local dev builds get a sensible recent value.
2026-05-11 10:31:14 -04:00
bvandeusen ab8a86e794 fix(flutter): update banner false positive + lock-screen control routing
Update banner showing on identical versions:
- pubspec.yaml was stuck at the placeholder 0.1.0+1, so
  PackageInfo.version returned "0.1.0" while the server reported the
  actual release tag (e.g. "2026.05.10.1"). Comparison correctly said
  "newer" → banner always showed.
- Bump pubspec to 2026.05.11.0+1 so the local default matches the
  release cadence even before CI overrides it.
- Update flutter.yml release step to pass --build-name="${TAG#v}" so
  every tagged APK reports the tag as its PackageInfo.version. Future
  releases stop drifting from pubspec.
- Rewrite isVersionNewer to do component-wise int comparison with
  zero-padding: pub_semver.Version.parse rejects 4-part date versions
  like "2026.05.10.1", at which point the old code fell back to
  string inequality and treated "2026.05.10" as newer than itself
  vs "2026.05.10.0". Drop the pub_semver import (no longer used).

Lock-screen play/pause not responding:
- PlaybackState only listed MediaAction.seek in systemActions, which
  on Android 13+ means tapping the lock-screen play/pause button
  doesn't route back to the AudioHandler. Add play, pause,
  skipToNext, skipToPrevious to the set.
- Add androidCompactActionIndices: [0, 1, 2] so the compact
  notification view explicitly maps the three buttons.

Album art being smaller than the lock-screen frame is upstream of
this commit — the cover-cache writes whatever pixel dimensions the
server returns. If the server's /api/albums/<id>/cover returns small
thumbnails for these albums, the lock screen renders them at that
size. Worth a separate look at the server cover-emit path.
2026-05-11 10:27:04 -04:00
bvandeusen 727a0760da fix(flutter): refetch album when row exists but tracks don't
artistAlbumsProvider populates cachedAlbums (album rows only) without
ever fetching their tracks. When the user taps from the artist grid
into an album, albumProvider sees a drift hit on the album row, never
triggers cold-cache, and yields with an empty track list — visible as
the album header rendering above an empty body.

Refactor albumProvider's cold-cache logic into a helper closure that
either branch (no album row OR album row + no tracks) can call. Add a
fetchAttempted guard so a server response that legitimately returns
zero tracks doesn't loop forever.

Decision flow:
- albumRows empty: cold-fetch (existing path), yield empty on
  failure/offline
- albumRows hit but trackRows empty AND not yet attempted: same
  cold-fetch — drift watch re-emits with the populated tracks
- albumRows hit, trackRows hit (or attempted already): yield as-is
2026-05-11 08:52:45 -04:00
bvandeusen 983a9d92be fix(flutter): tighter track row + missing artist in mini player + hide redundant artist on artist page
Track row (album detail):
- Vertical padding 10→6 and only render the artist line when non-empty,
  so tracks without a populated artist row don't reserve a blank line.
- Number column 28→22 — visually tighter without making 3-digit
  numbers cramp.

Mini player missing artist:
- Symptom was an empty `artist` field on MediaItem after tapping a
  track in album detail; layout change wasn't the cause. Real cause:
  albumProvider's cold-cache only wrote cachedAlbums + cachedTracks,
  never cachedArtists. The drift JOINs that build the AlbumRef + each
  TrackRef returned null for the artist row, so artistName fell back
  to '' and the audio handler stamped MediaItem.artist=''.
- Cold-cache now collects every distinct (artistId, artistName) pair
  off the album header + each track, inserts them into cachedArtists
  alongside the album/tracks. Subsequent JOINs populate artistName,
  the audio handler stamps it on MediaItem, and the mini player picks
  it up via the existing artistName.isNotEmpty render.
- Existing cached albums won't get artist names until they're
  re-fetched (cache invalidation TBD). Future cold-cache hits will.

Artist detail album grid:
- AlbumCard gains showArtist (default true). Pass false in the artist
  detail grid since the page header already names the artist. cellH
  trimmed by the 16dp artist line.
2026-05-11 08:47:50 -04:00
bvandeusen 21ab0d78bb fix(flutter): artist albums grid — 3 per row, title wraps, no overflow
AlbumCard gains optional `width` (default 140 keeps horizontal lists
unchanged) and `titleMaxLines` (default 1) so callers can let the
title wrap to a second line. Cover sizes to width - 16 instead of a
hardcoded 124, so the card scales down cleanly when a narrower cell
width is passed in.

Artist detail grid: switch to 3 columns. LayoutBuilder computes the
cell width from the available width so AlbumCard sizes to the cell
exactly (no overflow). cellH = cover + gap + 2-line title + artist
line + small fudge — tight enough that there's no visible gap below
the card, tall enough to fit a wrapped title.
2026-05-11 08:43:58 -04:00
bvandeusen 107abda97e fix(flutter): album/artist covers in artist detail + tighter grid
Drift cache intentionally drops cover_url (server-derived). The
adapters comment says "REST cold-cache fallback briefly shows the real
values before drift takes over" — but once drift takes over, covers
are empty forever. Fix per source:

- Album cover: server constructs the URL deterministically as
  /api/albums/<id>/cover (internal/api/convert.go:69). Mirror that
  in CachedAlbumAdapter.toRef so AlbumRef.coverUrl is non-empty
  whether the row came from a fresh fetch or a drift hit. Restores
  cover art on the artist detail album grid (and any other surface
  reading albums from drift).

- Artist cover: server picks a representative album and reuses its
  cover (convert.go:98). Drift doesn't store the pointer, so derive
  client-side via the artist's first loaded album. New _ArtistAvatar
  prefers a non-empty server-emitted coverUrl and falls back to
  /api/albums/<firstAlbumId>/cover, then slate while the album list
  is still loading.

Album grid spacing was off because childAspectRatio: 0.8 inflated
each cell taller than the AlbumCard's actual ~160dp footprint,
leaving a visible gap below every card. Switch to mainAxisExtent: 168
with explicit 8dp main/cross spacing — cells now match the card and
sit on a clean grid.
2026-05-11 08:39:41 -04:00
bvandeusen 2b033131e0 fix(flutter): mini player heart/kebab span title+artist height
Move the like + kebab buttons out of the title row and place them as
siblings to the title/artist column. Row's default crossAxisAlignment
centers them against the row's full 48dp height (set by the album
art), so visually they sit at the vertical center of the title+artist
block instead of being pinned to the title baseline.

Width stays 32dp each — horizontal footprint matches what we had.
Bumped icon size 18→20 since they have more vertical space to occupy.
2026-05-11 08:36:39 -04:00
bvandeusen f88e82a777 fix(flutter): album/artist detail covers + cacheFirst tracing for hangs
Album detail screen rendered the cover slot as a bare slate Container
— no actual image. Wire ServerImage at /api/albums/<id>/cover (96dp,
rounded). Same for artist detail: ClipOval around ServerImage of the
artist's coverUrl, falling back to slate when empty.

Artist navigation hang: artistProvider goes through cacheFirst, which
had no logging — so we couldn't see whether the cold-cache fetch was
running. Add an optional `tag` parameter that, when set, debugPrints
each step (drift hit/miss, connectivity, fetch start/done/error).
Wire tags into artistProvider and artistAlbumsProvider, plus add the
3s connectivity timeout there too as belt-and-suspenders.

Next test pass should show cacheFirst[artist(<id>)]: lines that
pinpoint where the artist screen is sticking.
2026-05-11 08:35:02 -04:00
bvandeusen 3c0806d8fd diag(flutter): time-box connectivity check + trace album cold-cache path
Two changes to surface where detail-screen spinners hang:

1. Connectivity().checkConnectivity() goes over a platform channel
   that on some Android builds stalls. Wrap with a 2s timeout and
   default to "online" if it times out — being wrong about
   connectivity costs at most one failed fetch, but being stuck
   spins the UI forever.

2. albumProvider's cold-cache flow now debugPrints at every step:
   drift miss → connectivity result → API call → drift write → ack
   the re-emit. Also adds a 10s timeout on the API fetch and a 3s
   timeout on the connectivity await so a hang surfaces as an
   error-yielded empty AlbumRef instead of an infinite spinner.

Once the operator's next test produces logs we can pinpoint which
step is hanging. The diagnostic prints stay until the issue's root
cause is confirmed; will be removed in a follow-up.
2026-05-11 08:28:32 -04:00
bvandeusen 4621846ec4 fix(flutter): seed connectivityProvider with initial value (unhang detail screens)
Root cause for "only the first tile loads, others spin forever":

Connectivity().onConnectivityChanged only emits on connectivity
*changes*, not on subscription. Cold-cache code paths in albumProvider,
artistProvider, playlistsProvider, likes etc. all gate their fetches
on `await ref.read(connectivityProvider.future)`. Until the OS
happened to report the first connectivity flip, that future never
resolved — so any detail screen for an album/artist/playlist not
already in the drift cache hung indefinitely at the connectivity
check.

The "first tile" appeared to work because by the time the user
tapped it, a connectivity event had landed (or that album was already
cached from a prior session). Subsequent tiles whose data wasn't yet
cached blocked.

Switch the provider to async* and seed it with an immediate
checkConnectivity() before forwarding the change stream. .future
now resolves on first read regardless of whether the OS has reported
a change yet.
2026-05-11 08:21:55 -04:00
bvandeusen d4d936ee57 fix(flutter): mini player art fills its 48dp box (BoxFit.cover)
Image with width+height but no fit paints the source at its intrinsic
resolution inside the box. The cover-cache thumbnails are smaller
than 48dp, so the art rendered as a tiny inset in the slate box
instead of filling it. Cover stretches/crops uniformly to fill.
2026-05-11 08:17:17 -04:00
bvandeusen b6b73fdd0c fix(flutter): live seek bar (~200ms) + breathing room above controls
Why the seek bar appeared frozen: it was reading
PlaybackState.updatePosition, which audio_service only updates on
event transitions (play/pause/buffer/seek). Between events it sits
unchanged, so the bar only jumped at intervals.

Expose just_audio's positionStream (~200ms cadence) from the audio
handler, wrap as positionProvider, and read that in both the mini bar
and the full player. Now the bar advances continuously while playing.

While we're here: spread the full player's vertical layout per
operator — gap to seek 20→32, seek-to-primary 8→24, primary-to-
secondary 16→24, plus 24 below to match. The full player had visible
slack above the controls; this redistributes it.
2026-05-11 08:15:58 -04:00
bvandeusen 2a5b6970e9 feat(flutter): show album name beneath artist in full player
Title (22pt parchment) → artist (14pt ash) → album (12pt ash). Album
is conditional — drops out if MediaItem.album is empty rather than
leaving a blank line. Tightened the gap to the seek bar (24→20) to
absorb the new line on small screens.
2026-05-11 08:12:29 -04:00
bvandeusen 59427bcf2f fix(flutter): full player unmounts the shell — no doubled player UI
You correctly diagnosed: the mini bar was still visible underneath
the full player, and that's also why the bottom controls overflowed
by 45px (the shell's mini bar was eating the bottom 88dp).

Move /now-playing OUT of the ShellRoute and up to a top-level GoRoute.
Now pushing /now-playing unmounts the shell entirely — no mini bar
underneath, no fight for the bottom strip. The slide-up transition
still feels right because the shell stays painted for the duration of
the animation (so during the transition both are briefly visible, as
you noted is fine).

Drop the hideMini conditional in _ShellWithPlayerBar — no longer
needed since the shell isn't even built when the full player is on
top. Recovering the 88dp also resolves the bottom-controls overflow
without needing to shrink the layout.
2026-05-11 08:09:53 -04:00
bvandeusen 163c1174db feat(flutter): mini ↔ full player transition + flesh out NowPlayingScreen
Mini player simplifies to track-info + prev/play/next. The
shuffle/repeat/queue cluster moves to the full player, where it has
the room to breathe.

Full player (NowPlayingScreen) now has:
- Real album art (FileImage when artUri is file://, ServerImage from
  /api/albums/<id>/cover otherwise — same auth-aware loader as the
  rest of the app, with errorBuilder so a failed fetch falls back to
  a slate placeholder instead of a broken-image glyph).
- Title row with inline like + kebab.
- Full-width seek with start/end timestamps below.
- 36/72/36 prev/play/next.
- Secondary row: shuffle, repeat, queue.

Mini ↔ Full transition mechanics:
- Tap mini → push /now-playing with custom slide-up transition
  (CustomTransitionPage, 280ms easeOutCubic).
- Vertical drag-up flick on mini (>200 px/s) → same push.
- System back / leading expand-more icon → Navigator.pop, which the
  CustomTransitionPage replays as a slide-down (240ms easeInCubic).
- Drag-down on full player past 80px OR a >500 px/s downward flick
  → Navigator.pop. Buttons and the seek slider stay tappable since
  Flutter's gesture arena gives priority to the more-specific child
  recognizers.
- Mini player hides while /now-playing is the active route — the
  full player IS the player UI in that state, no need to fight over
  visual space.
2026-05-11 08:06:38 -04:00
bvandeusen 3162fedd3b fix(flutter): card taps via Material+InkWell, not GestureDetector
User reports only the first card in 'Recently added' navigates and the
HitTestBehavior.opaque fix in d703fc2 didn't fully resolve it.

Switch all three card widgets (album, artist, playlist) from
GestureDetector to Material(transparent) + InkWell. This is the more
idiomatic Flutter pattern for tap-to-navigate cards:

- InkWell registers via the Material ripple system instead of the
  raw gesture arena, sidestepping any subtle deferToChild edge cases
  inside horizontal ListViews.
- Visible ripple feedback on tap means a missed tap is now diagnosable
  visually — if the ripple shows but nothing navigates, the issue is
  on the route side; if no ripple, the tap never landed.

Material color is transparent so the existing dark page background
shows through unchanged.
2026-05-11 07:57:10 -04:00
bvandeusen a05a279508 fix(flutter): strip duplicate status-bar inset when update banner shows
You correctly diagnosed the symptom: the AppBar gets taller when the
banner is present. Why: the shell is [Banner, Expanded(child),
PlayerBar] and the banner uses SafeArea(bottom:false) to clear the
status bar. But MediaQuery.padding is screen-relative — the child's
Scaffold/AppBar reads MediaQuery.padding.top and applies its own
status-bar inset on top of the banner, doubling the gap.

Watch shouldShowUpdateBannerProvider in the shell. When it returns
non-null (banner visible), wrap the child in MediaQuery.removePadding
removeTop: true so the AppBar mounts directly under the banner. When
the banner is hidden, child gets its normal top inset.
2026-05-11 07:52:45 -04:00
bvandeusen a3985f1138 fix(flutter): cover images — wait for token, file:// loader, graceful errors
The 401s on /api/albums/<id>/cover were the root cause of "only the
first tile is navigable" — failed images leaving slate placeholders
that combined with the deferToChild hit-test (fixed in d703fc2) to
silently swallow taps.

ServerImage:
- sessionTokenProvider is a FutureProvider; .value is null after a
  hot restart until secure-storage resolves. Old code fired
  Image.network with headers:null at that moment, the network image
  cache locked in the 401 response, and never retried. Switch to
  AsyncValue.when so the widget waits for the token before mounting
  Image.network with the auth header attached.
- Add errorBuilder so a single failed image renders the parent
  fallback instead of leaking a stack trace + broken-icon glyph.

Player bar:
- media.artUri is set by AlbumCoverCache as Uri.file(path). Wrapping
  it in NetworkImage attempts HTTP on a file:// URI and fails. Use
  FileImage when the scheme is file, else NetworkImage.

Net effect: failed image loads no longer leak errors or block other
widgets from rendering / receiving taps.
2026-05-11 07:44:28 -04:00
bvandeusen 7cabe4efef fix(flutter): player bar — title visible, controls stacked, no overflow
Three issues from the screenshot:

1. Title invisible: LikeButton + TrackActionsButton were raw IconButtons
   with the default 48dp tap target, eating ~96dp of the title row.
   Wrap both in 32×32 SizedBox at the call site so the title actually
   gets enough room to render (still ellipsizes if needed).

2. Layout per operator's revised spec: track info gets a 2:1 share of
   the row vs the controls column. The controls column now stacks the
   shuffle/repeat/queue sub-row above the prev/play/next sub-row, both
   right-aligned.

3. Right-edge 2px overflow: previous play controls were 40+48+40=128dp
   in a flex-1 slot of ~110dp. Resize to 32+40+32=104dp matching the
   shuffle/repeat/queue row above (3×32=96dp), with the play button
   slightly larger to keep visual hierarchy.

Drop the volume provider import since the slider is gone (handled by
phone hardware buttons).
2026-05-11 07:34:11 -04:00
bvandeusen d703fc27f8 fix(flutter): album/artist card tap (HitTestBehavior.opaque)
Same root cause as the playlist card fix in f65650f — GestureDetector
defers to children by default, so taps over the cover image area
(ServerImage / SVG fallback) didn't reliably propagate. Mark the
detector opaque so the entire card surface is tappable, not just the
text below the cover.
2026-05-11 07:30:05 -04:00
bvandeusen f65650fb6d fix(flutter): player bar layout, system playlist tap, banner height
Player bar: drop the volume slider — phone hardware controls volume.
Right cluster collapses to a single row of shuffle/repeat/queue.

Playlist card: GestureDetector defers to children by default, so taps
over the cover image area didn't always register. Add HitTestBehavior.opaque
so the whole card surface is tappable.

Update banner: was 3-4× the height of its text — IconButton's default
48dp tap target plus generous vertical padding dominated. Tighten
padding (8→4), shrink dismiss button to 32×32 with iconSize 16, slim
the action button to 28dp height with shrinkWrap tap target.

Home screen: ClampingScrollPhysics + 140dp bottom padding (already
applied in working tree) so scroll stops just above the mini-player.
2026-05-11 07:27:14 -04:00
bvandeusen 51afc992d4 fix(web): apply data-testid attrs to PlayerBar that were dropped from a8e6e1c
The previous commit message said I added data-testid="player-bar-compact"
+ "player-bar-desktop" to PlayerBar.svelte but the edits actually
dropped silently — only the test file changes landed. Without the
testids, the test file's within(getByTestId(...)) calls all fail.

This adds the actual attributes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:07:52 -04:00
bvandeusen a8e6e1c2f7 fix(web,flutter): PlayerBar test scoping + system-playlists revalidate
Two bundled fixes:

### Web: PlayerBar test failures
PlayerBar renders both compact (md:hidden) and desktop (hidden md:flex)
blocks; jsdom doesn't apply CSS media queries so both DOM trees are
present in tests. screen.getByRole/getByText found duplicates →
14 test failures.

Added data-testid="player-bar-compact" + "player-bar-desktop"; tests
scope queries via within(getByTestId(...)). Compact is the focus of
#358, so most tests scope there. The "Up next" subgroup explicitly
scopes to desktop since that copy was dropped from compact.

### Flutter: system playlists not loading
cacheFirst was too conservative — when drift had user-created
playlists from sync but no system playlists (For-You / Discover),
fetchAndPopulate never fired (drift wasn't empty). Result: home
tile row showed user playlists but never the system ones.

Added cacheFirst alwaysRefresh option = stale-while-revalidate.
playlistsListProvider opts in: yields cache immediately, then kicks
off REST refresh in background. Drift watch() picks up the new rows
and re-emits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:07:22 -04:00
bvandeusen 19061cd10c feat(flutter): full parity for player bar — shuffle/repeat/volume + Like + kebab + 3-column layout (#356)
Mirrors web's compact PlayerBar both visually (3-column top + full-
width seek bottom) and functionally — closes parity gaps that had
been hidden because the prior mini-bar surfaced none of these
controls.

### audio_handler.dart

- Override `setShuffleMode` → delegates to just_audio's
  `setShuffleModeEnabled`.
- Override `setRepeatMode` → maps audio_service modes (none/one/all/
  group) to just_audio's LoopMode (off/one/all).
- New `setVolume(double)` + `volumeStream` getter (audio_service's
  PlaybackState doesn't carry volume — surface it separately).
- `_broadcastState` now populates PlaybackState's shuffleMode +
  repeatMode fields, and re-fires on shuffle/repeat/loop stream
  changes so UI subscribers stay in sync.

### player_provider.dart

- New `volumeProvider` (StreamProvider<double>).
- `PlayerActions` gains `toggleShuffle()`, `cycleRepeat()` (none →
  all → one → none), and `setVolume(double)`.

### player_bar.dart

Complete rebuild matching the operator-designed layout:

  ┌──────────┬───────────┬──────────────────┐
  │ art      │ ♥   ⋮     │ 🔀 🔁 ☰           │  ← short row
  │ title    │           │                  │
  │ artist   │ ⏮  ⏯  ⏭   │ volume slider    │  ← play row, full size
  ├──────────┴───────────┴──────────────────┤
  │ 0:42 ━━━━━●━━━━━━━━━━━━━━━━━━━━━ 3:21  │
  └─────────────────────────────────────────┘

- Column 1 (35%): cover + title + artist. Tap → /now-playing.
- Column 2 (intrinsic): like + kebab on top, play controls (40/48/40)
  on bottom.
- Column 3 (30%): shuffle/repeat/queue on top, volume slider on bottom.
- Bottom: full-width seek slider with mm:ss labels.

`TrackActionsButton` reused for the kebab; reconstructs a minimal
TrackRef from MediaItem extras (same pattern NowPlayingScreen
already uses).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 23:59:53 -04:00
bvandeusen b2d1a9ea10 fix(web): compact PlayerBar — 3-column top row, full-width seek bottom (#358)
Replaces the kebab-with-popover PlayerOverflowMenu approach with all
player controls visible inline. Operator's stated intent was "two-row
layout with all controls visible," not "kebab hides shuffle/repeat/
queue/volume" — restructured to match.

### Compact view (below md)

  ┌─────────┬───────────┬───────────────────┐
  │ art     │ ♥   ⋮     │ 🔀 🔁 ☰            │  ← short sub-row
  │ title   │           │                   │
  │ artist  │ ⏮  ⏯  ⏭   │ volume slider     │  ← play row at full size
  ├─────────┴───────────┴───────────────────┤
  │ 0:42 ━━━━━●━━━━━━━━━━━━━━━━━━━━━━ 3:21 │
  └─────────────────────────────────────────┘

- Column 1: cover + title/artist
- Column 2: like+kebab on top sub-row, play controls (40/48/40) below
- Column 3: shuffle/repeat/queue on top, volume slider below
- Bottom: full-width seek slider with time labels

### Desktop view (md+)

Existing 3-column layout preserved; only change is the redundant
PlayerOverflowMenu kebab (which had been mounting at all widths)
is no longer there. Volume + shuffle + repeat + queue stay inline
in the right cluster as before.

### Cleanup

- Deleted PlayerOverflowMenu.svelte + its test (no callers remain)
- The TrackMenu kebab (per-track actions) stays — it's a varying
  list of actions that doesn't fit inline

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 23:52:42 -04:00
bvandeusen fcded9294c Merge pull request 'fix(web): download button + server version display' (#37) from dev into main 2026-05-11 03:20:39 +00:00
bvandeusen c3ecd1bec8 fix: gofmt -s on version.go (tab-indent doc-comment code block) 2026-05-10 23:15:29 -04:00
bvandeusen 4c4399c9bb feat(server,web): expose server version via /healthz + display in Settings
Came up debugging the in-app update flow — wasn't obvious which image
the container was actually running without exec'ing in. New flow:

### Server
- internal/server/version.go: new `var ServerVersion = "dev"`,
  overridden via -ldflags at build time.
- /healthz response gains a "version" key alongside the existing
  "status" + "min_client_version". Backward-compat: existing clients
  ignore unknown JSON fields. Endpoint stays unauthenticated.

### Build
- Dockerfile: new `ARG MINSTREL_VERSION=dev`, threaded into the
  go build -ldflags so the binary's ServerVersion is stamped at
  link time. Default "dev" preserves local `docker build` ergonomics.
- .forgejo/workflows/release.yml: tags step also emits a `version`
  output (the git tag for tag pushes, "main" for branch pushes);
  build step passes it as `--build-arg MINSTREL_VERSION=...`.

### Web
- web/src/lib/components/ServerVersion.svelte: small understated
  text ("Server v2026.05.10.2") that fetches /healthz on mount.
  Renders nothing on parse failure or pre-version images.
- Mounted at the bottom of Settings.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 23:13:19 -04:00
bvandeusen e16bdd9546 fix(web): read snake_case keys in MobileAppDownload (#397)
Server's clientVersionResponse marshals to {version, apk_url,
size_bytes} but the component was reading body.apkUrl / body.sizeBytes
(camelCase). The !body.apkUrl guard was always true → early return →
download button never rendered even when /api/client/version returned
200 with valid data.

Verified directly: /api/client/version returns
  {"version":"v2026.05.10.1","apk_url":"/api/client/apk","size_bytes":65301242}
on the deployed v2026.05.10.1 image; the UI just wasn't reading those
keys.

Map wire (snake_case) → component (camelCase) explicitly via a
WireInfo type so the boundary is auditable.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 23:10:22 -04:00
bvandeusen 5054c46385 fix(web): collapse the entire Mobile app section when no APK bundled
When /api/client/version returns 404 (no APK in /app/client/, e.g.
v2026.05.10.0 which had a failed CI APK-attach step), the previous
shape rendered the section heading + intro paragraph with an empty
hole where the button should be. Confusing — looks like a broken
button.

Moved the section wrapper, heading, and intro paragraph INSIDE
MobileAppDownload so the whole block collapses together when info
is null. Settings page just mounts <MobileAppDownload />; nothing
visible if no APK is available.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 22:44:38 -04:00
bvandeusen 42abb7adff Merge pull request 'ci: unify REGISTRY_TOKEN + RELEASE_TOKEN into CI_TOKEN' (#36) from dev into main 2026-05-11 01:45:01 +00:00
bvandeusen e4578593d1 ci: unify REGISTRY_TOKEN + RELEASE_TOKEN into a single CI_TOKEN secret
Both prior secrets did related work (one for registry push, one for
release asset I/O) and required separate Forgejo PATs to manage.
Replacing with a single CI_TOKEN keyed off a single PAT with the
union of scopes (write:repository + write:package).

- flutter.yml: APK attach step → CI_TOKEN
- release.yml: docker login → CI_TOKEN; APK fetch step → CI_TOKEN

No behavior change — same calls, single secret name. Operator needs
to set CI_TOKEN in repo settings (Actions → Secrets) with a PAT that
has write:repository + write:package; the prior REGISTRY_TOKEN /
RELEASE_TOKEN secrets can be removed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 21:33:10 -04:00
bvandeusen 04933f2d9f Merge pull request 'M5–M7 sweep + offline cache + in-app updates + DRY pass' (#35) from dev into main 2026-05-11 01:09:36 +00:00
bvandeusen 154f415f92 fix(server,web): auth-gate client APK + version endpoints + per-user rate limit (#397)
Closes the bandwidth-abuse vector on the in-app update flow. Both
endpoints now sit inside the authed.Group; APK additionally gets a
60s/user rate limit to suppress accidental hammering or scripted
abuse.

### Server

- internal/api/client_assets.go:
  - clientAPKAllowDownload(): in-memory map[userID]time.Time under
    a mutex. Returns 0 (allow) or wait duration (block).
  - handleClientAPK reads user from context, checks the limit,
    returns 429 + Retry-After header if blocked.
  - testResetClientAPKRateLimit() lets tests start clean.
- internal/api/api.go: routes moved from the root /api group into
  the authed.Group block (alongside /quarantine, /requests, etc.).
- Tests: added TestClientAPK_401WhenUnauthenticated and
  TestClientAPK_RateLimit_429OnRapidSecondCall (also verifies
  different user gets a fresh slot). Existing tests updated to use
  authedRequest() helper.

### Web

- MobileAppDownload.svelte: switched from bare fetch (no credentials)
  to api.get<>() which carries the session cookie. 404 / 401 /
  network errors all silently hide the download row.
- Removed the login-page mount entirely — pre-auth surfaces should
  never show this. Settings → Mobile app section keeps it for
  logged-in users.

Flutter unaffected: dio's Bearer interceptor already attaches the
token, and the polling only fires once the post-login shell mounts
the banner widget.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 20:28:27 -04:00
bvandeusen 2435ef7961 feat(web): MobileAppDownload component on login + settings (#397 follow-up)
Closes the discoverability gap on the in-app update flow — the
/api/client/apk endpoint exists but had no web UI surface to find
it. User asked to be able to "visit the site on my phone and
download the apk from there."

- web/src/lib/components/MobileAppDownload.svelte — fetches
  /api/client/version once on mount; renders a download link with
  version + size when 200; renders nothing on 404 (no APK bundled,
  graceful degradation in dev environments and pre-CI-wiring images).
- Mounted on the login page (below the Register link) so the link
  is discoverable without authentication. The /api/client/* endpoints
  are themselves unauthed, so the flow works end-to-end for any
  visitor on a phone.
- Also mounted in Settings → Mobile app section for logged-in users
  who want to grab the matching APK for sideloading on a different
  device.

Browser handles the download via the server's existing
Content-Disposition: attachment; filename="minstrel.apk" header.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 20:23:56 -04:00
bvandeusen f6e27cd39a fix(flutter/test): isVersionNewer date-style assertion was wrong
pub_semver is permissive with leading zeros — '2026.05.10' parses as
2026.5.10, so date-style tags get strict semver ordering, not the
unparseable-fallback path. The test was asserting "any difference =
newer" for date strings, which is incorrect; the actual behavior
(and the right behavior) is proper ordering.

Split the test group into two:
- date-style (parses as semver): newer/older/equal assertions
- truly unparseable (e.g. branch names like 'main', 'dev'): the
  fallback's "any difference = newer" semantics still apply

Implementation in client_update_provider.dart unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 20:09:53 -04:00
bvandeusen f3378dd610 fix(flutter): apply Riverpod 3 NotifierProvider conversion missed in 14d7678
The previous fix-forward intended this change but the Edit didn't
make it into the commit (only the Go side landed). Re-applying the
StateProvider → NotifierProvider conversion so flutter analyze stops
failing on the undefined-function for StateProvider.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 20:02:29 -04:00
bvandeusen 14d7678624 fix: CI lint errors after #397 commits
- flutter analyze: Riverpod 3 dropped StateProvider; replaced
  _dismissedVersionsProvider with a small Notifier<Set<String>>
  + NotifierProvider, mutating via an `add(version)` method.
  Public API (shouldShowUpdateBannerProvider, dismissUpdateProvider)
  unchanged.
- golangci errcheck: defer f.Close() now wrapped in func() { _ = f.Close() }();
  os.Setenv calls in test helper switched to t.Setenv (cleaner — auto-restores
  on test cleanup, no manual Unsetenv needed).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 20:01:43 -04:00
bvandeusen e57a53a92e ci(server): bundle Android APK into image on tag releases (#397 phase 3)
Final phase of the in-app update flow. release.yml on tag pushes
fetches the APK that flutter.yml is attaching to the same release,
drops it into client/ in the build context, and the Dockerfile's
COPY client/ /app/client/ bakes it into the image.

### How it sequences

flutter.yml and release.yml both trigger on tag pushes and run in
parallel on different runners (flutter-ci vs go-ci). flutter.yml
typically finishes APK build + release attachment in 2-5 min.
release.yml polls the release page for up to 15 min for the APK to
appear, then proceeds. If the APK never lands (flutter.yml failure,
network hiccup), release.yml emits a warning and ships the image
without the bundled APK — server returns 404 from /api/client/version,
banner stays hidden, manual download from the release page still
works. Graceful degradation, not a blocker.

### Repo shape

- client/.gitkeep + client/README.md so the directory exists in git
  and the COPY in the Dockerfile always finds something to copy
- .gitignore excludes client/minstrel.apk + .version so accidental
  commits don't bloat the repo
- Dockerfile: COPY --chown=minstrel:minstrel client/ /app/client/

### Why polling vs cross-workflow trigger

Forgejo Actions' workflow_run support varies by runner version; the
polling approach is universally compatible. If/when we standardize on
a runner that handles workflow_run cleanly, the polling step can
become a `needs:` dependency.

Closes #397.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 19:44:08 -04:00
bvandeusen 02d9f39845 feat(flutter): in-app update banner + Android install intent (#397 phase 2)
Closes the operator-facing half of #397. Soft banner mounts at the
top of the shell when the server has a newer APK bundled at
/api/client/version; tap Install → APK downloads to cache → Android
PackageInstaller intent fires → user taps Install in the system
dialog → app restarts on the new version.

### Dart side

- lib/update/update_info.dart — wire shape for /api/client/version
- lib/update/client_update_provider.dart — Riverpod AsyncNotifier
  polling on app start + every 24h. Compares semver via pub_semver
  with non-semver string-equality fallback. Server 404 = "no update
  channel" = silent. Companion shouldShowUpdateBannerProvider gates
  on a per-version dismissed-set (in-memory; resets on restart).
- lib/update/installer.dart — UpdateInstaller wraps dio.download +
  the MethodChannel call to MainActivity.kt.
- lib/update/update_banner.dart — Material banner with idle /
  downloading (with progress) / error stages. Mounted in
  _ShellWithPlayerBar above the route content; SizedBox.shrink()
  when no update available so non-shell routes (login, server-url)
  see no banner anyway.
- isVersionNewer() extracted as a pure function and tested across
  semver, prerelease ordering, leading-v normalization, and
  non-semver fallback (date-tag style).

### Android side

- AndroidManifest.xml — REQUEST_INSTALL_PACKAGES permission;
  FileProvider with authorities ${applicationId}.fileprovider.
- res/xml/file_paths.xml — exposes the cache directory so the
  downloaded APK can be served via content:// URI (file:// is
  blocked since Android 7).
- MainActivity.kt — MethodChannel handler builds the FileProvider
  URI and fires Intent.ACTION_VIEW with FLAG_GRANT_READ_URI_PERMISSION
  so the system installer can read across the process boundary.

Phase 3 (CI sequencing — bake APK + version file into /app/client/
during release.yml's tag flow) is the remaining piece. Without it
the server returns 404 from /api/client/version and the banner
silently does nothing — graceful degradation, but no actual updates.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 19:42:04 -04:00
bvandeusen a2bea8601a feat(server): /api/client/version + /api/client/apk endpoints (#397 phase 1)
Phase 1 of the in-app update flow — server side. Endpoints serve the
bundled Android APK + sidecar version file from /app/client/.
Returns 404 gracefully when files aren't present, so dev environments
and pre-CI-wiring images degrade cleanly to "no update available."

- internal/api/client_assets.go: handleClientVersion + handleClientAPK.
  Both unauthenticated (matches /healthz) so install flow doesn't
  depend on a live session. APK served with proper
  application/vnd.android.package-archive Content-Type +
  http.ServeContent so Range requests work for resumable downloads
  on flaky networks.
- Path resolves to /app/client/ by default; MINSTREL_CLIENT_APK_DIR
  env var overrides for dev.
- Dockerfile creates /app/client/ + commented COPY hooks for the CI
  sequencing phase.
- Tests cover all four states: missing apk, apk-but-no-version,
  both present (200 with correct shape), apk stream (200 with
  correct Content-Type + body bytes).

Phases 2 (Flutter client provider + banner + install intent + Android
manifest changes) and 3 (CI sequencing to bake the APK into the image)
land in follow-up commits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 19:35:24 -04:00
bvandeusen 27f123f7d9 fix(server,flutter): sync wire format + systemVariant column (#357)
Two fixes in one commit because they're entangled — the systemVariant
work would have been theater otherwise.

## The wire-format bug

/api/library/sync was emitting PascalCase JSON for artist / album /
track / playlist upserts (raw json.Marshal of sqlc-generated structs
with no JSON tags — sqlc.yaml: emit_json_tags=false). Flutter's
sync_controller _*FromJson reads snake_case keys, so all metadata
sync rows landed in drift with empty strings / zero ints.

The like_track / like_album / like_artist / playlist_track entities
work because they're hand-built `map[string]string` payloads with
snake_case keys — they sidestepped the bug. The 4 raw-marshal
entities did not.

Existing sync test caught zero of this — it asserts on len(upserts)
not field shape.

Fix: server-side view structs in library_sync_views.go with proper
JSON tags + pgtype-flattening (UUID → 8-4-4-4-12 hex string,
Date → "2006-01-02"). Mirrors the playlistRowView pattern from
/api/playlists. New library_sync_views_test.go pins the wire keys
so future field-name drift breaks loud.

## systemVariant column (closes #357 plan C v1 limitation)

playlistSyncView now carries `system_variant` server → wire.

Flutter drift schema bumped from 1 → 2 with onUpgrade adding the
`systemVariant TEXT NULL` column to cached_playlists. Cursor reset
to 0 in the migration so existing rows refresh with the new field
on the next sync.

playlistsListProvider now filters locally by systemVariant:
- kind='user'   → systemVariant IS NULL  (the add-to-playlist sheet's intent)
- kind='system' → systemVariant IS NOT NULL
- kind='all'    → no filter

Closes the documented v1 limitation where the add-to-playlist sheet
showed system playlists alongside user-created ones.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 18:47:30 -04:00
bvandeusen 0db7054518 feat(flutter): user-facing requests view + cancel (#356)
Closes the cleanest remaining #356 gap — Discover submits Lidarr
requests but had no surface for users to view or cancel their own.
Admin had it; user didn't.

- RequestsApi at lib/api/endpoints/requests.dart — listMine() +
  cancel(id). Same /api/requests endpoint the web /requests page
  uses; identical AdminRequest wire shape so the existing model
  is reused (just augmented with matched_*_id fields for the
  "Listen" CTA on completed rows).
- MyRequestsController mirrors the web's auto-poll (#369 piece
  already shipped server-side / web-side): 12s refresh while any
  row is mid-ingest (status='approved'), stops on settle. Riverpod
  Timer in build() that's cancelled in onDispose.
- RequestsScreen with kind/status pills, ingest progress copy,
  Cancel (with confirm dialog) and Listen CTAs per row state.
- Route /requests under the shell. Entry point in settings between
  Profile and Appearance — "My requests".
- Widget tests cover empty / pending / completed / rejected states +
  the Cancel-confirm dialog.

Out of scope this slice: Discover-screen "View your requests" CTA
after submitting a new request. Reasonable follow-up but doesn't
block the management loop.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 18:08:23 -04:00
bvandeusen 861dd8ef17 feat(web): auto-poll request progress when ingests are in flight (#369)
Half of #369 — the auto-poll piece. Inbox deferred (separate task).

Both /requests (user) and /admin/requests (admin, 'approved' tab only)
now refetch every 12s while at least one row has status='approved'.
Stops automatically when all rows settle to pending/completed/rejected.
TanStack Query's default refetchIntervalInBackground=false handles
the visibility behavior — polling pauses when the tab is hidden and
resumes on focus.

Predicate hasInFlightRequest() is exported + tested so the polling
logic is auditable independent of TanStack Query's internals.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 17:59:38 -04:00
bvandeusen 7bc254e17e feat(web): stream resilience — preload=auto, stall recovery, next-track prefetch
Phases 1+2 of the background-play resilience work. Net effect on
desktop: gap-free track transitions on slow networks, automatic
recovery from transient stalls / network errors mid-track.

- preload="metadata" → "auto" on the main audio element so the
  browser pre-buffers more aggressively.
- attachStallRetry() — listens for stalled / waiting / network-error
  events. Schedules a reload-from-current-position after delayMs
  (3s default) if the buffer hasn't recovered. MEDIA_ERR_NETWORK
  triggers immediate retry. Bounded by maxRetries (3 default) to
  prevent tight loops on persistent failures.
- audioLoader seam — `lib/player/audioLoader.ts` exposes a
  resolve(track) → URL + optional prefetch(track) hint. Default
  returns track.stream_url; the planned Tauri shell can swap via
  setAudioLoader() to return blob URLs backed by a Rust cache,
  mirroring the Flutter drift+LockCachingAudioSource pattern.
- Hidden prefetch <audio> element. When current track passes 50%,
  start loading queue[index+1]. On track-end the swap is gap-free
  via browser HTTP cache + audio buffer warm-up.

Phase 3 (service worker chunk cache) deliberately deferred — that
work belongs in the Tauri shell as native Rust caching, not as a
web-only investment that would compete with it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 17:43:41 -04:00
bvandeusen 1daf0b7fdf feat(web): close #358 invites RowActionsMenu wiring
The mobile-responsive design called for all 4 admin tables to use
RowActionsMenu. Requests + Quarantine + Users users-section landed
in earlier commits; the invites section in the same users page was
still rendering inline Copy/Revoke buttons. Now uses RowActionsMenu
with primary Copy + secondary Revoke (danger).

Extend expiry from the design's secondary list deferred — no
server endpoint exists yet (lib/api/admin.ts has no
extendInviteExpiry).

Closes the in-code portion of #358. Real-device verification
walkthrough at 375/414/768 + grid/safe-area checks remain
operator-side.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 17:14:18 -04:00
bvandeusen 308202a1df refactor(web): extract CardActionCluster (#375 item #8 — narrowed scope)
The MediaCard consolidation in the discovery doc would have needed
~14 props to cover the differentiating bits (wrapping element a vs
button, art-shape, art-fallback strategy, click semantics, title
align/size, subtitle count). That's a god-prop blob that's harder to
reason about than three explicit cards.

Narrowed to the actually-drifted bit: the action cluster
(LikeButton + Plus + bottom-right menu slot, including the
stopPropagation defensive wrappers). One small component covers
AlbumCard / ArtistCard / CompactTrackCard so the focus-ring and
button-styling drift can't recur.

Each card keeps its own data-fetching, art container, and wrapping
element since those have load-bearing differences. The consolidation
addresses drift, not LOC for its own sake.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 16:58:17 -04:00
bvandeusen 9b4f907db6 refactor(web): sweep 24 test files to use makeTrack/makeTracks fixtures (#375)
Replaces inline TrackRef literal redefinitions with calls to the
test-utils helper. Tests that asserted on default field values
(e.g. track titles, artist names rendered in the DOM) keep explicit
overrides; tests that only need a stub for shape now use makeTrack()
with no overrides.

PlaylistCard.test.ts, PlaylistTrackRow.test.ts, and playlist.test.ts
SKIPPED — they use PlaylistTrack (with track_id/added_at), not TrackRef.
ArtistCard.svelte and +page.svelte route files (matched by initial grep)
SKIPPED — live code, not test files.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 15:58:14 -04:00
bvandeusen 993bcc6a14 fix(web/test): update playlist API tests for api.* call surface (#375)
After e8eff1b migrated playlists.ts from raw apiFetch to the api.*
wrapper, three test files mocked the wrong surface:

- playlists.test.ts: GET case asserted init.method === 'GET' but
  api.get omits init.method entirely (fetch defaults to GET). Fall
  back to 'GET' when init.method is undefined.
- playlists.refresh-discover.test.ts: re-mock ./client to expose
  `api: { post: vi.fn() }` instead of `apiFetch`; assertions check
  api.post call args.
- playlists.refresh-foryou.test.ts: same.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 15:48:04 -04:00
bvandeusen 2ec54bc429 refactor(web): sweep playlist.test.ts to use emptyQuarantineMock() (#375)
Replaces the hand-rolled { subscribe, data } quarantine stub with the
emptyQuarantineMock() helper. readable() satisfies the same store
contract the page actually uses (subscription via $store), and the
playlist tests don't assert on quarantine state — the mock is purely
a transitive module-load satisfier (PlaylistTrackRow → TrackMenu).

Companion to commit 7e8d196 (likes sweep), which initially skipped
this file because it shared the hand-rolled stub shape with the likes
mock; the quarantine half can safely move to the helper.

Five other files in the original 8-file batch (PlaylistTrackRow,
TrackMenu, TrackRow, PlayerBar, CompactTrackCard) were absorbed into
that likes-sweep commit; search/tracks was absorbed into commit
dd67f28 (pageUrl sweep). hidden.test.ts SKIPPED — it imports
createMyQuarantineQuery as a vi.fn() to mockReturnValue per-test and
asserts on unflagTrack call args; the helper would defeat both.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 15:42:57 -04:00
bvandeusen 7e8d19606a refactor(web): sweep test files to use empty likes/quarantine mocks (#375)
Replaces duplicated inline vi.mock('$lib/api/likes', ...) blocks with
the emptyLikesMock() helper, and (where previously left in working
tree by a parallel quarantine sweep) rolls in the matching
emptyQuarantineMock() switchovers in the same files.

Together with commit dd67f28 — which already swept the four search/*
test files for likes — this completes the 18 likes-mock conversions
called out in #375.

LikeButton.test.ts kept inline — it uses a state-driven mock to
assert the toggle behavior.

SKIPPED:
- liked.test.ts: re-exports createLikedTracksInfiniteQuery and the
  album/artist variants that emptyLikesMock() doesn't provide.
- playlist.test.ts: hand-rolled { subscribe, data } stub instead of
  readable(...) — different store contract.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 15:41:15 -04:00
bvandeusen dd67f28745 refactor(web): sweep 8 test files to use pageUrlModule() (#375)
Centralizes the inline { page: { get url() { return state.pageUrl } } }
mock shape via test-utils/mocks/appState.ts. The vi.hoisted state
declaration remains per-file (vitest mock-hoisting requires module-
level declaration). Adds a $test-utils alias to svelte.config.js so
the helper can be imported without ../../../ chains.

SKIPPED (mock exposes more than url):
- Shell.test.ts, MobileNavDrawer.test.ts, admin.test.ts: static
  page: { url: ... } shape, no hoisted state to centralize.
- album.test.ts, artist.test.ts: page exposes both params and url.
- playlist.test.ts, reset-password.test.ts: page exposes params only.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 15:39:25 -04:00
bvandeusen 6e0223a9b1 refactor(web): runMutation helper for generic-toast admin handlers (#375)
Wraps the dominant pattern (try { await fn } catch { pushToast(errMessage,
'error') }) for the 5 admin/+page.svelte handlers that surface errMessage
directly: onApprove, onReject, onResolve, onDeleteFile, onDeleteLidarr.

Tighter scope than originally planned — the 3 handlers in
admin/users/+page.svelte (onToggleAutoApprove, onGenerateInvite,
onRevokeInvite) use errCode + verb prefix ("Generate failed: ${code}")
which is structurally different and would change UX wire output if
forced through the helper. Skipping them keeps behavior identical.

The helper SWALLOWS errors so callers no longer need try/finally for
busy-state — `saving = true; await runMutation(...); saving = false;`
is correct because runMutation can't throw.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 15:39:00 -04:00
bvandeusen 0eaaf66748 refactor(web): playlistTrackToRef helper to dedupe TrackRef
reconstruction (#375)

PlaylistTrackRow.svelte and PlaylistCard.toTrackRefs both rebuilt
TrackRef from PlaylistTrack with the same field-by-field literal.
Server adding a new TrackRef field would have needed both sites
updated; now one helper owns the mapping.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 15:37:11 -04:00
bvandeusen 633406c05b refactor(web): safeLocalStorage helper for store persistence (#375)
Three nearly-identical try/catch wrappers across theme + player stores
collapse to read()/write()/remove() in lib/util/safeLocalStorage.ts.
Sets the pattern for future stores. Caller still does parse/serialize
since the existing call sites store strings (theme preference, volume
number) — no JSON wrapper needed yet.

persisted.ts left alone — its JSON-payload + per-key-suffix shape is
distinct enough to keep self-contained.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 15:36:45 -04:00
bvandeusen 2357df83be refactor(web): add test-utils helpers for likes/quarantine/track/appState mocks (#375)
Pre-sweep checkpoint. Adds:
- fixtures/track.ts        — makeTrack() / makeTracks(n) (18 files duplicate today)
- mocks/likes.ts           — emptyLikesMock() (19 files duplicate today)
- mocks/quarantine.ts      — emptyQuarantineMock() (9 files duplicate today)
- mocks/appState.ts        — pageUrlModule(state) (8 files duplicate today)

The sweep commits that follow update test files to use these helpers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 15:31:53 -04:00
bvandeusen e8eff1baa1 refactor(web): migrate playlists.ts to api.* wrapper (#375)
Drop 9 hand-rolled apiFetch calls with redundant Content-Type
headers + manual JSON.stringify. The api.* wrapper in client.ts
already handles both. Identical wire shape; existing tests cover
all endpoints.

Also makes api.del generic so DELETE endpoints with typed returns
(playlist track removal) can use the wrapper instead of raw
apiFetch. Default `T = null` preserves existing callers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 15:30:34 -04:00
bvandeusen 714039bae5 refactor(web): drive vite-injected theme-color from tokens.json (#375)
Closes the last theme-color hardcode. Runtime side already imports
tokens.colors.{dark,light}.obsidian via applyMetaThemeColor; build
side now matches via JSON import-attributes. Drops the // TODO(#375)
tripwire.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 15:29:48 -04:00
bvandeusen 65057473c6 refactor(web): break auth ↔ player import cycle via session-end signal (#375)
auth/store.svelte.ts no longer imports from $lib/player. Logout
broadcasts via auth/sessionEnd.svelte.ts (a tiny tick + outgoing
userId pair); player subscribes through $effect.root and owns the
player-specific teardown (clearPersistedQueue + playQueue([]) +
closeQueueDrawer()).

Cycle fully inverted — auth is now a pure leaf for player; future
session-end consumers (download cache, recent-search history) plug
in by adding their own effect on the same signal.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 15:29:30 -04:00
bvandeusen 94727f40bb fix(flutter): analyze errors after Plan C provider migrations
- cache_first.dart: backtick-fence List<T> doc comment to dodge
  unintended_html_in_doc_comment.
- library_providers.dart:163: switch single-row insert to
  insertAllOnConflictUpdate; Batch only exposes the *AllOnConflict*
  variant.
- 5 test files: StreamProvider.overrideWith takes Create<Stream<T>>,
  not Create<Future<T>>. Wrap data emissions in Stream.value(...).
- artist_detail_screen_test: add models/album.dart import for AlbumRef
  type annotation.
- track_actions_sheet_test: drop _StubLiked extends LikedIdsController
  (notifier no longer exists post-migration); override with
  Stream.value(LikedIds(...)) instead.
- like_button_test: rollback assertion now requires drift writes via
  LikesController. Skip under _skipDrift until libsqlite3-dev lands on
  the runner image (Fable #399). Replace stale .notifier reference
  with likesControllerProvider for completeness.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 13:04:27 -04:00
bvandeusen 98fdd9dcdf feat(flutter/cache): migrate playlist providers to drift-first (#357 plan C)
playlistsListProvider — StreamProvider over cached_playlists. Returns
all user-owned + others' public playlists. The 'kind' family arg only
affects the REST cold-cache fetch (server-side filter); drift can't
distinguish 'user' from 'system' kind because systemVariant isn't
persisted. v1 limitation: add-to-playlist sheet may briefly show
system playlists too. Follow-up: add systemVariant column + schema bump.

playlistDetailProvider — async* over the playlist watch stream + a
one-shot tracks query per emission (joins playlist_tracks → tracks →
artists → albums for snapshot fields). Cold-cache fallback inserts
playlist + playlist_tracks rows in one batch, then awaits re-emission.

Pull-to-refresh on these screens now triggers re-subscription rather
than forcing a REST fetch — drift is the source of truth and stays
fresh via SyncController's delta sync. Documented behaviour shift; if
operator wants force-refetch we can add it via a sync trigger later.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 11:27:49 -04:00
bvandeusen 08c16d6d86 fix(flutter): point like consumers at likesControllerProvider
Two consumer updates left out of 8a6c926: like_button.dart and
track_actions_sheet.dart still referenced the removed
likedIdsProvider.notifier API. Switched to the new
likesControllerProvider.toggle().

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 11:21:47 -04:00
bvandeusen 8a6c926ea7 feat(flutter/cache): migrate likedIdsProvider to drift-first; LikesController for mutations
Splits the previous LikedIdsController into two:

- likedIdsProvider — StreamProvider reading from cached_likes via
  drift watch(). Reactive: SyncController writes propagate
  automatically. Empty + online triggers REST cold-cache fallback
  that populates cached_likes via insertOrIgnore (sync may have
  already written some rows).

- likesControllerProvider (new) — exposes toggle(LikeKind, id).
  Optimistic: writes drift first (UI updates instantly via the
  watch stream), then REST. Rolls back drift on REST failure.

Two consumer updates: like_button.dart + track_actions_sheet.dart
switch from likedIdsProvider.notifier.toggle to
likesControllerProvider.toggle.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 11:20:59 -04:00
bvandeusen fc83c7b514 feat(flutter/cache): migrate artistAlbums/artistTracks/album to drift-first
Three providers all become StreamProviders driven by drift watch():

- artistAlbumsProvider: cacheFirst over the join of cached_albums +
  cached_artists for artist_name on each row.
- artistTracksProvider: cacheFirst over the join of cached_tracks +
  cached_artists + cached_albums for snapshot fields.
- albumProvider: composite ({album, tracks}) shape, so uses async*
  with two queries (album + tracks) for cleaner reactive behavior.
  Cold-cache fallback inlined; populates both album and tracks tables
  in one batch.

.future call site in artist_detail_screen.dart left as-is —
StreamProvider.future returns the next emission with the same
signature, so no consumer change needed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 11:19:47 -04:00
bvandeusen 947d4401a6 feat(flutter/cache): migrate artistProvider to drift-first (#357 plan C)
artistProvider becomes a StreamProvider backed by drift's cached_artists
watch(). Empty + online triggers REST fallback; populates drift; watch
re-emits. Empty + offline yields a sentinel ArtistRef(id: '', name: '');
surfaces should already check state.value?.id.isNotEmpty.

AsyncValue<ArtistRef> shape unchanged so .when callsites keep working.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 11:18:59 -04:00
bvandeusen 4eb9935f8e feat(flutter/cache): cacheFirst helper + drift↔model adapters (#357 plan C)
Foundation for the provider migrations. cacheFirst<D, T> wraps the
drift.watch() + REST cold-cache fallback pattern: yields cached rows
when present, kicks off REST fetch + drift populate when empty +
online, yields empty when offline. REST failures swallow to empty so
callers can surface errors via toast.

adapters.dart adds CachedX → XRef extension methods + reverse
XRef.toDrift() companions for Artist/Album/Track/Playlist. Adapters
accept some loss of server-derived fields (coverUrl, streamUrl,
ownerUsername) — UI already handles empty values; cold-cache fallback
briefly shows the real values before drift takes over.

cache_first_test covers all 4 branches (non-empty, empty+online,
empty+offline, REST failure). adapters_test covers basic round-trips.
Both safe to run on CI runner — no drift open required.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 11:18:29 -04:00
bvandeusen 2940e95b64 fix(flutter/test): skip TrackRow smoke test under the drift cohort
Pending-timer failure: CachedIndicator (now in TrackRow) reads
audioCacheManagerProvider, which constructs AppDb via drift_flutter's
driftDatabase(), which calls libsqlite3 — missing on the flutter-ci
runner. The async chain leaves a pending timer at test teardown.

Skip cohort matches sync_controller / audio_cache_manager / storage_section
tests; all re-enable once Fable #399 lands the runner image fix.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 10:49:03 -04:00
bvandeusen a3db6c9453 fix(flutter/test): testWidgets skip takes bool, not String
CI analyze flagged storage_section_test.dart's `skip: _skipDrift` calls.
testWidgets has signature `skip: bool?`; only test() takes `String?` as
the skip-reason. Changed _skipDrift in this file to `const bool = true`
and moved the rationale into a comment. The other two drift-cohort
files (sync_controller_test, audio_cache_manager_test) use test() so
their String const is fine.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 10:41:48 -04:00
bvandeusen 1b223d3891 fix(flutter/test): skip drift tests pending libsqlite3 in CI runner image
CI's flutter-ci runner doesn't ship libsqlite3.so. drift's NativeDatabase
fails at first use ("Failed to load dynamic library 'libsqlite3.so'").
Affected files:
  - test/cache/sync_controller_test.dart (4 tests)
  - test/cache/audio_cache_manager_test.dart (5 tests)
  - test/settings/storage_section_test.dart (2 tests, was silently
    succeeding because the drift call was best-effort but emitted
    multiple-AppDb warnings)

All 11 marked with skip: '...' + a top-level @Tags(['drift']) library
declaration so they can be re-enabled by tag once the runner image has
libsqlite3-dev installed (or once we move VM tests to sqlite3/wasm).
On-device verification covers the actual cache + sync logic.

Plus two collateral fixes:
  - test/cache/connectivity_provider_test.dart: connectivity_plus needs
    a platform channel that doesn't exist in unit tests; reduced to a
    non-null import smoke check.
  - test/library/widgets_smoke_test.dart: TrackRow now contains
    CachedIndicator (ConsumerWidget); wrapped TrackRow test in
    ProviderScope.

Filing follow-up for the runner image fix in next commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 10:27:49 -04:00
bvandeusen 0d171490c3 fix(flutter): analyze errors after Plan B push
Cleared 5 errors + 1 warning + 1 info from CI flutter analyze on 5114a81:

- prefetcher.dart: Riverpod listener callbacks used (_, _) for two
  placeholder params — Dart 3 enforces unique names. Changed to (_, __).
- prefetcher.dart: Riverpod 3's AsyncValue exposes `.value` (nullable)
  not `.valueOrNull`. Three call sites updated.
- sync_controller.dart: doc comment had `?since=<cursor>` → analyzer
  warned about unintended HTML. Wrapped in backticks with `{cursor}`.
- sync_controller.dart: delete loop over heterogeneous Table list
  inferred as List<Table>; drift's delete() expects TableInfo. Unrolled
  to explicit per-table deletes.
- audio_cache_manager_test.dart: db.into(...).insertAll([...]) doesn't
  exist on InsertStatement — only insert/insertOnConflictUpdate. Used
  db.batch((b) => b.insertAll(table, [...])) instead, in two test cases.
- audio_handler.dart: LockCachingAudioSource is marked experimental in
  just_audio. Added // ignore: experimental_member_use — operator
  acknowledged the experimental status during brainstorming and we're
  the project; CI's --fatal-infos would otherwise gate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 10:18:38 -04:00
bvandeusen 5114a8118c feat(flutter): CachedIndicator + Download buttons + app startup wiring
CachedIndicator (lib/library/widgets/cached_indicator.dart) — small
download glyph rendered next to a track row when AudioCacheManager
reports the track as cached. FutureBuilder one-shot.

Wiring:
  - track_row.dart: render CachedIndicator before the duration label
  - playlist_detail: 'Download' OutlinedButton next to Play; pins all
    playable tracks with source: autoPlaylist + SnackBar feedback
  - album_detail: 'Download' IconButton in the header; same pin pattern
  - app.dart: now ConsumerStatefulWidget — initState fires the initial
    sync + activates the prefetcher provider

Together these complete the operator-facing surfaces of the offline
slice: visible cache state, explicit download trigger, automatic
sync + queue-ahead prefetch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:23:26 -04:00
bvandeusen fd4ce402d7 feat(flutter/settings): Storage section UI — usage, cap, prefetch, controls
New StorageSection widget mounted in SettingsScreen between Appearance
and Password sections. Surfaces:

  - Cache usage display (live, refreshed on cap change + on Clear)
  - Cache size limit dropdown (1 / 5 / 10 / 25 GB / Unlimited)
  - Pre-fetch ahead dropdown (1 / 3 / 5 / 7 / 10 tracks)
  - Cache liked tracks switch
  - Clear cache button (confirm dialog, then clearAll)
  - Sync now button (triggers SyncController.sync(), spinner while inflight)

Cap change triggers immediate eviction. Clear cache wipes EVERYTHING
(manual-pinned tracks too) per the operator-facing copy.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:21:34 -04:00
bvandeusen 153e931490 feat(flutter/player): audio_handler reads from cache first; LockCaching fallback
_buildAudioSource is now async and cache-aware:
1. Cache hit  → AudioSource.uri(file://path)
2. Cache miss with manager → LockCachingAudioSource (cache-as-you-play)
3. No manager configured → plain AudioSource.uri (legacy fallback)

playerActionsProvider.playTracks now passes audioCacheManager into
configure() alongside coverCache. setQueueFromTracks awaits the source
build (Future.wait over the track list).

Out of scope: registering an index row when LockCachingAudioSource
finishes downloading (no clean hook from just_audio). Prefetcher /
Download buttons cover the index path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:20:24 -04:00
bvandeusen 536350380f feat(flutter/cache): Prefetcher — queue-ahead pre-download window
Listens to mediaItemProvider + cacheSettingsProvider. On track change
(or settings change), computes the [currentIdx, currentIdx + N] window
in the queue and pins each uncached track via AudioCacheManager with
source: autoPrefetch.

Window N comes from cacheSettingsProvider.prefetchWindow (default 5,
configurable in Settings → Storage card).

Smoke-test only at the unit level — real coverage via on-device pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:19:01 -04:00
bvandeusen ab58f3ffcb feat(flutter/cache): SyncController — token-based delta sync
Drives /api/library/sync against drift:
  - reads cursor from SyncMetadata (default 0 = full snapshot)
  - 204 → just bump lastSyncAt, return zeroes
  - 410 → wipe all cached entities + retry from cursor=0
  - 200 → apply upserts + deletes per entity type, advance cursor

Handles all 8 entity types (artist/album/track + like_track/like_album/
like_artist + playlist/playlist_track) for both upsert and delete paths.
Composite-key entities use the "<a>:<b>" string format the server emits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:18:15 -04:00
bvandeusen 16669a0365 feat(flutter/cache): AudioCacheManager — pin/unpin/evict + tiered LRU
API:
  - isCached(trackId), pathFor(trackId)
  - pin(trackId, source) — dio.download → drift index entry
  - unpin(trackId), clearAll()
  - usageBytes(), evict(targetBytes)

Eviction order: incidental → autoPrefetch → autoPlaylist → autoLiked.
'manual' never evicts via cap-driven eviction; only clearAll() removes
operator-pinned tracks.

Two providers:
  - appDbProvider — singleton AppDb per run
  - audioCacheManagerProvider — wraps the AppDb + dioProvider

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:17:14 -04:00
bvandeusen 2bcbb53c49 feat(flutter/cache): connectivityProvider + cacheSettingsProvider
connectivityProvider — StreamProvider<bool>; true when any connectivity
result is non-none. No Wi-Fi gate per operator decision.

cacheSettingsProvider — AsyncNotifier<CacheSettings> persisting
capBytes / prefetchWindow / cacheLikedTracks via flutter_secure_storage.
Defaults: 5 GB cap, 5-track prefetch, cache liked = on.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:15:17 -04:00
bvandeusen 326b7008a9 feat(flutter/cache): drift schema + new deps + CI codegen step (#357 plan B)
Adds the offline-mode foundation:
- pubspec deps: drift, drift_flutter, sqlite3_flutter_libs,
  connectivity_plus + drift_dev/build_runner (dev)
- lib/cache/db.dart with 8 tables: CachedArtists/Albums/Tracks/Likes/
  Playlists/PlaylistTracks + AudioCacheIndex + SyncMetadata
- *.g.dart added to .gitignore (build_runner regenerates per build)
- CI workflow gains a 'Codegen (drift)' step between pub get and
  analyze so the generated symbols exist when analyze runs

CacheSource enum drives tiered LRU eviction (manual/autoLiked/
autoPlaylist/autoPrefetch/incidental). Subsequent commits add the
sync controller, audio cache manager, prefetcher, settings UI.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:07:34 -04:00
bvandeusen 8d5c90e0ed fix(server): wrap defer tx.Rollback for errcheck + gofmt -s alignment
golangci-lint surfaced both on 9c7dec6:
- errcheck on bare 'defer tx.Rollback(ctx)' in 2 test files
- gofmt -s wanted tighter map-key alignment in library_sync.go +
  library_sync_test.go (auto-fixed by 'gofmt -s -w')

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:47:25 -04:00
bvandeusen 9c7dec60a9 fix(server): go mod tidy after sync_test brings testify direct
internal/sync/changes_test.go imports github.com/stretchr/testify/require,
moving testify from indirect to direct. Also pulled in testify's own
indirects (go-spew, go-difflib) and promoted pgerrcode to direct.

Caught by CI go vet on 6fb6729.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:45:15 -04:00
bvandeusen 6fb6729beb feat(server): playlists service writes library_changes
Five sites wired:

- Create / Update / Delete playlist: pool-bound LogChange after success
- AppendTracks: tx-bound LogChange per inserted playlist_track row
- RemoveTrack: tx-bound LogChange after the delete + lookup the
  track_id pre-delete so the composite key is still resolvable

The two tx-bound paths (AppendTracks, RemoveTrack) treat LogChange as
required — failure rolls back the playlist mutation too. The pool-bound
paths Warn on failure to match the scanner / likes pattern (mutation
already committed; missed log row recovers on next mutation).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:41:59 -04:00
bvandeusen e0c5789cee feat(server): like/unlike handlers write library_changes
All 6 like/unlike sites (track/album/artist × like/unlike) now emit a
library_changes row via the shared logLikeChange helper. Best-effort:
LogChange failures Warn but don't fail the HTTP response — a missed
log row is recovered at the next mutation on the same entity.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:40:56 -04:00
bvandeusen 0fa7dc7982 feat(server): scanner + DeleteTrackFile write library_changes
Wires sync.LogChange into the library mutation sites so /api/library/sync
reflects upserts and deletes.

Architectural pivot: LogChange's signature is now (ctx, dbq.DBTX, ...) so
it works with both *pgxpool.Pool and pgx.Tx. The scanner doesn't run
mutations in explicit transactions, so it pool-binds; delete.go matches.
Tx-bound callers (likes/playlists in subsequent commits) keep atomicity.

Also: sync.FormatUUID centralizes the pgtype.UUID → canonical string
conversion that both the scanner and the sync handler need; library_sync.go
now uses it instead of a local copy.

Best-effort logging on scanner failures (Warn, don't fail the scan): a
LogChange error after a successful upsert is rare and self-healing — the
next scan that touches the entity re-emits the change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:39:58 -04:00
bvandeusen 6bd8a15c7a feat(server): mount /api/library/sync route
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:36:46 -04:00
bvandeusen 9bf4b504b3 feat(server): GET /api/library/sync endpoint
Returns batched upserts + deletes since the supplied cursor. Empty cursor
returns full snapshot; subsequent calls pull deltas. Per-user entities
(likes, playlists) are scoped to the authed user. Composite-key entities
(likes, playlist_tracks) use stable string ids encoded by sync.EncodeLikeID
/ sync.EncodePlaylistTrackID.

Behavior:
  204 No Content - no changes since cursor
  200 OK         - JSON syncResponse {cursor, upserts, deletes}
  410 Gone       - cursor older than oldest log row; client must reset
  401 / 500      - standard envelope errors

Adds sqlc queries GetAlbumsByIDs, GetTracksByIDs, GetPlaylistsByIDs to
mirror the existing GetArtistsByIDs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:36:26 -04:00
bvandeusen 3959c85111 feat(server): sync.LogChange helper + EntityType/Op constants
New package internal/sync. LogChange writes a library_changes row inside
the supplied tx. Encode helpers produce stable composite ids for like_*
and playlist_track entries. Subsequent commits wire LogChange into the
scanner / likes / playlists services.

Also: dbtest.dataTables now includes library_changes so test isolation
holds across runs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:29:51 -04:00
bvandeusen cb35133843 feat(server): library_changes log table + sqlc queries
Append-only change log for library entities. Every mutation on
artists/albums/tracks/likes/playlists/playlist_tracks will write a row
in the same transaction as the mutation itself (wired in subsequent
commits). Powers the Flutter delta-sync endpoint (#357).

- 0025_library_changes migration (up + down)
- internal/db/queries/library_changes.sql (Insert, GetSince, MaxCursor, MinCursor)
- regenerated dbq from sqlc

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:28:26 -04:00
bvandeusen 084c202654 fix(web/test): MobileNavDrawer inert + integrations Save mocks Test first
MobileNavDrawer: Svelte 5 + jsdom binds `inert` as a property, not always
an attribute. Mirror the QueueDrawer.test.ts pattern that accepts either.

Integrations Save tests: Per commit bca8622 (Save runs Test first), the
two existing Save tests need to mock testLidarrConnection before clicking
Save — otherwise the Test step returns undefined, fails the ok check,
and putLidarrConfig is never reached. The newer 'Lidarr first-time
setup' suite already does this; just bringing the older two tests in
line. Also wrapped the assertions in waitFor since the put-config call
now resolves async after the test promise.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:21:04 -04:00
bvandeusen 3ffd9beca0 fix(web): preserve per-row aria-labels through RowActionsMenu + test fixes
CI vitest run on 3f8a2c5 surfaced 17 failures across 5 test files; this
commit addresses 15 that are this batch's responsibility.

1. RowActionsMenu now accepts ariaLabel on RowAction. Defaults to label.
   Admin pages (requests/quarantine/users) pass per-row aria-labels
   matching the pre-batch buttons ("Approve Geogaddi", "Resolve Roygbiv",
   "Make alice admin", etc.) so screen readers + tests find them.

2. PlayerBar.test.ts — anchored regex /^(play|pause)$/i so the new
   "Player options" overflow ⋮ doesn't also match /play|pause/i.

3. MobileNavDrawer.test.ts — added vi.mock for $app/state, $app/navigation,
   and $lib/auth/store.svelte (mirrors Shell.test.ts pattern). Without
   these, SvelteKit's notifiable_store helper isn't bootstrapped in
   vitest and the suite fails to load.

The 2 remaining vitest failures are in /admin/integrations Save flow
(putLidarrConfig spy not called). Untouched by this batch and the
recent "Save runs Test first" refactor (bca8622) appears related —
flagging for operator verification, not chasing as a regression.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:16:48 -04:00
bvandeusen 3f8a2c511a fix(web): MobileNavDrawer focus uses querySelector, not conditional bind:this
bind:this requires an Identifier or MemberExpression — a ternary
like {i === 0 ? firstNavLink : undefined} is invalid. Replaced
with a single bind on the <aside> root, then querySelector('nav a')
to locate the first nav link at focus time. Same behaviour, valid
Svelte.

Caught by CI svelte-check on 268e12a (failed before the @const
fix landed in 1536860):
  src/lib/components/MobileNavDrawer.svelte:91:13
  https://svelte.dev/e/bind_invalid_expression

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 20:26:44 -04:00
bvandeusen 1536860e59 fix(web): move {@const} blocks to immediate children of {#each}
Svelte 5 requires {@const} to be a direct child of certain blocks
({#snippet}, {#if}, {#each}, etc.). Placing them inside <li>
bodies broke the build with const_tag_invalid_placement. Moved
the RowAction const declarations up so they sit between {#each}
and the <li> opener; the each-binding (u/r) is in scope for the
entire each block body, so the consts behave identically.

Caught by local docker build on dev:
  src/routes/admin/users/+page.svelte:259:12
  https://svelte.dev/e/const_tag_invalid_placement

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 20:26:04 -04:00
bvandeusen 268e12a5eb feat(web): Modal overlay gets p-4 so max-w-md modals fit on phone
Without padding, max-w-md (448px) modals touch the viewport edges
on a 375px screen. p-4 on the overlay clamps them inside the safe
area. Covers all routes that use the shared <Modal> component
(discover track-confirm, quarantine typed-DELETE, users
password-reset, etc.).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 20:21:52 -04:00
bvandeusen 16e0e98943 feat(web): mobile mechanical sweep — pointer-aware arrows, h3 dividers, modal safe-area
- HorizontalScrollRow arrows bump 32px → 40px on coarse pointers
  (touch screens) for finger-friendly hits; mouse pointers unchanged.
- AlphabeticalGrid divider letter is now <h3> so screen readers
  announce it as a section heading. Margin reset to preserve layout.
- Modal overlay gets p-4 so max-w-md modals stay inside the safe
  area at 375px viewport. Covers all routes that use the shared
  <Modal> component (discover track-confirm, quarantine
  typed-DELETE, users password-reset, etc.).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 20:21:38 -04:00
bvandeusen f03a0042e8 feat(web): wire RowActionsMenu in users admin page
Primary: toggle admin (most semantically distinct per-user action).
Secondary: toggle auto-approve, reset password, delete (danger).
'Delete' was previously styled as a regular border button — now
correctly marked danger. No Edit action existed; not adding one.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 20:21:17 -04:00
bvandeusen e266a0f2dc feat(web): wire RowActionsMenu in requests + quarantine
Requests: primary Approve, secondary [Override, Reject].
Quarantine: primary Resolve, secondary [Play, Delete file]; the
Delete-via-Lidarr conditional stays inline above md (preserves the
disabled-with-tooltip semantics) and hides below md to avoid
crowding — the operator can still trigger it from the desktop view.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 20:20:43 -04:00
bvandeusen e0cf527304 feat(web): RowActionsMenu generic primary + ⋮ for admin tables
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 20:19:09 -04:00
bvandeusen ed6d0936ca feat(web): PlayerBar reflows to two-row layout below md
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 20:18:32 -04:00
bvandeusen d5983433c5 feat(web): PlayerOverflowMenu — shuffle/repeat/queue/volume in a menu
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 20:18:10 -04:00
bvandeusen df4cb434b2 feat(web): hamburger trigger + mobile drawer mount in Shell
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 20:17:35 -04:00
bvandeusen 857a8621ec feat(web): MobileNavDrawer off-canvas nav for <md viewport
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 20:17:17 -04:00
bvandeusen 7f395024a0 feat(web): mobileNav store for off-canvas drawer state
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 20:16:38 -04:00
bvandeusen 84a638a41f fix(flutter): clear analyze --fatal-infos issues
Three classes:

1. album_cover_cache.dart docstring used <applicationCacheDirectory>
   and <albumId> which the analyzer reads as unintended HTML. Wrapped
   the path in backticks and used {} placeholders.

2. settings AppearanceSection used RadioListTile.groupValue + onChanged,
   deprecated in Flutter 3.32+. Wrapped the radios in a RadioGroup
   ancestor (the new API) so individual tiles only declare value +
   activeColor. Test updated to read groupValue off the RadioGroup
   ancestor.

3. theme_extension.dart factories built FabledSwordTheme(...) without
   const, even though all args are static const tokens. Added const to
   the outer constructor calls in both .dark() and .light() — this
   propagates const to the inner TextStyle(...) calls automatically.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 16:16:35 -04:00
bvandeusen dd848e76e8 feat(flutter/playlists): empty-state hint on empty playlist detail
When a playlist has zero tracks, the detail screen previously showed
just the header with no indication of what to do next. Adds an inline
hint mirroring the web's copy: "No tracks yet. Add some via the
\"Add to playlist…\" entry on any track row."

Implementation: itemCount goes from tracks.length + 1 to
(tracks.isEmpty ? 2 : tracks.length + 1) and the builder emits the
hint at index 1 when tracks is empty. Header still renders at index 0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 16:07:41 -04:00
bvandeusen 0dbb662b4c feat(flutter): search no-results copy mirrors design-system voice
Follow-up to ccebd98 — the search_screen edit failed in that commit
because the file hadn't been read in the session. "No matches." →
"No matches for that query." Same scope as the larger sweep commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 16:07:19 -04:00
bvandeusen ccebd98735 feat(flutter): empty-state copy mirrors web design-system voice
Five terse "No X." strings replaced with the longer actionable forms
the web SPA uses on equivalent surfaces:

- Library Artists/Albums tabs: "No artists yet — scan a library folder
  via the server's config." (mirrors web /library/artists, /albums)
- Library Liked tab: "No liked artists, albums, or tracks yet."
  (consolidates web's per-section copy since Flutter shows all three
  in one tab)
- Search no-results: "No matches for that query." (web has per-section
  copy that doesn't fit Flutter's combined view)
- Discover no-results: "Nothing to add for that search yet." (mirrors
  web /discover)

Hidden tab keeps its current actionable hint (web's "Nothing hidden
yet." is terser but lacks the "use a track's menu to flag" guidance).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 16:06:58 -04:00
bvandeusen 231f1ddf9a test(flutter/theme): cover .dark()/.light() factories + back-compat alias
Four cases: dark factory pulls from FabledSwordDarkTokens, light from
FabledSwordLightTokens, flat tokens (accent / moss / etc.) are shared
between both, and the fromTokens() back-compat alias returns the dark
theme.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 15:50:51 -04:00
bvandeusen 143130eaae feat(flutter/settings): Appearance section with System/Light/Dark picker
Three RadioListTiles between Profile and Password sections. Tap →
themeModeProvider.notifier.set(...) → MaterialApp rebuilds with the
new theme via the existing themeMode wiring.

System has the only subtitle ("Match the device setting") — the
light/dark options are self-explanatory.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 15:50:29 -04:00
bvandeusen 56f0557d94 feat(flutter): MinstrelApp watches themeMode + offers darkTheme
MaterialApp now provides both light and dark themes plus a
themeMode bound to themeModeProvider. ThemeMode.system rebuilds
the tree automatically when the OS toggles brightness — no manual
listener needed.

While themeModeProvider is loading (storage read in flight), falls
back to AppThemeMode.system, which inherits the OS setting.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 15:47:41 -04:00
bvandeusen 6dc488652e feat(flutter/theme): themeModeProvider with secure-storage persistence
AsyncNotifier wrapping flutter_secure_storage's "theme_mode" key.
Returns AppThemeMode.system as the default. set(mode) writes the
value + updates state.

Used by MinstrelApp (next commit) to drive MaterialApp.themeMode and
by the Settings appearance section to persist the operator's pick.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 15:47:00 -04:00
bvandeusen caa19f2d91 feat(flutter/theme): buildDarkTheme + buildLightTheme
Both builders construct a ThemeData with the matching brightness +
ColorScheme.dark/.light + the corresponding FabledSwordTheme
extension. buildThemeData() stays as a back-compat alias returning
the dark theme so the existing widget-test suite keeps using it
without churn.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 15:46:37 -04:00
bvandeusen 66ddd3c366 feat(flutter/theme): FabledSwordTheme.dark() + .light() factories
Both factories produce the same field shape (semantic role-based
names like obsidian/iron/parchment) with palette values from the
new FabledSwordDarkTokens or FabledSwordLightTokens generated
classes. fromTokens() stays as a back-compat alias returning the
dark theme so existing call sites keep working.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 15:46:01 -04:00
bvandeusen b1f62a0733 feat(flutter/theme): codegen emits dark + light + flat token classes
gen_tokens.dart now produces FabledSwordDarkTokens (dark surface),
FabledSwordLightTokens (light surface), and FabledSwordFlatTokens
(colors that don't change + radii + fonts). The original
FabledSwordTokens class stays as a back-compat alias re-exporting
the dark surface + flat values; any code that reads
FabledSwordTokens.obsidian etc. continues to work during migration.

Source: shared/fabledsword.tokens.json (already had dark/light/flat
splits — this was the generator catching up).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 15:45:40 -04:00
bvandeusen 25ff7afc33 feat(flutter): TrackRow renders TrackActionsButton by default
Adds optional actions: bool = true param. When true (default), renders
the 3-dot menu trigger at the end of the row. Album detail / Search /
History / Liked tabs all consume TrackRow so they pick up the menu
transitively.

Pair with c8baaa5 which wired the button into the other 3 surfaces;
this commit completes the wire-up by including TrackRow itself (its
write was missed in the previous commit).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 13:43:40 -04:00
bvandeusen c8baaa5329 feat(flutter): wire TrackActionsButton into 4 surfaces
- TrackRow gains an actions: bool = true param; renders the button
  after duration. Album detail + Search + History/Liked tabs all
  consume TrackRow so they pick up the menu transitively.
- CompactTrackCard (home Most-played) gets the button at the end of
  its inner row.
- _PlaylistTrackRow in playlist_detail_screen gets the button next
  to duration; skipped for unavailable rows (no track id).
- NowPlayingScreen renders the button next to the title with
  hideQueueActions: true (Play next / Add to queue suppressed since
  the menu's track IS the playing one). artistId is left empty since
  it's not stashed in MediaItem.extras — Go-to-artist will route to
  /artists/ which is benign for v1; a follow-up could stash it.

Closes Tier 1 follow-up #2 (track-level actions menu).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 13:43:12 -04:00
bvandeusen 36006d703d feat(flutter/track-actions): AddToPlaylistSheet picker
Modal bottom sheet listing the caller's user-created playlists (system
playlists like For-You are filtered out — they're not user-mutable).
Tap a row to pop with the playlist id; consumer (TrackActionsSheet)
then calls PlaylistsApi.appendTracks.

Empty-state copy: "You haven't created any playlists yet."

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 13:42:19 -04:00
bvandeusen 2944288050 feat(flutter/track-actions): HideTrackSheet for reason + notes pick
Modal bottom sheet with five reason chips (mirroring server vocabulary
bad_rip / wrong_file / wrong_tags / duplicate / other) plus an optional
notes field. Returns (reason, notes) on Hide, null on Cancel. Default
selection is bad_rip.

Used by TrackActionsSheet's Hide action.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 13:41:48 -04:00
bvandeusen 5f239f05a5 feat(flutter/track-actions): TrackActionsButton + TrackActionsSheet
The 3-dot trigger and the modal-bottom-sheet menu it opens. 7 actions:
Play next, Add to queue, Like/Unlike, Add to playlist, Go to album,
Go to artist, Hide/Unhide. hideQueueActions: true suppresses the
first two for the Now Playing surface.

Sub-sheets (HideTrackSheet, AddToPlaylistSheet) land in subsequent
commits — this commit imports them speculatively, so CI between this
and the next two commits will fail. Resolved by Tasks 5 + 6.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 13:41:16 -04:00
bvandeusen 2499449c0b feat(flutter/player): playNext + enqueue + PlaylistsApi.appendTracks
Three small data-layer additions for the upcoming track-actions menu:

- PlaylistsApi.appendTracks(playlistId, trackIds) wraps
  POST /api/playlists/{id}/tracks for the "Add to playlist" action.
- audio_handler gains playNext (insertAudioSource at currentIndex+1)
  and enqueue (addAudioSource) — both also push the audio_service
  queue notifier so the queue-screen UI stays in sync.
- The AudioSource construction was extracted into a private
  _buildAudioSource helper so setQueueFromTracks / playNext / enqueue
  share one source-building path.
- PlayerActions exposes playNext / enqueue for menu use.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 13:40:17 -04:00
bvandeusen 5159bcd3f4 feat(flutter/quarantine): MyQuarantineController + provider
AsyncNotifier wrapping /api/quarantine/mine with optimistic flag /
unflag mutations and an isHidden(trackId) convenience for menu state.
Mirrors the LikedIdsController pattern: optimistic update, rollback
on server error.

Used by the next slice's TrackActionsSheet to power Hide / Unhide.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 13:39:32 -04:00
bvandeusen fdaa1a0472 feat(flutter/api): QuarantineApi for flag/unflag
Dio client for /api/quarantine — flag a track with a reason + optional
notes, unflag by track id. Mirrors the server's user-scoped quarantine
endpoints (separate from /admin/quarantine).

Used by the track-actions menu's Hide/Unhide action in the next slice
of commits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 13:38:52 -04:00
bvandeusen 534dafb044 feat(flutter/player): set MediaItem.artUri from local cover cache
Audio handler accepts an AlbumCoverCache via configure() and uses it
to populate MediaItem.artUri with a file:// URI to a locally cached
album cover. Lock screen, Bluetooth car displays, Wear OS, and CarPlay
now show the album cover for the currently playing track instead of
the system's generic music icon.

Flow:
- _toMediaItem stashes album_id in MediaItem.extras
- After setQueueFromTracks pushes the queue + initial mediaItem, fires
  _loadArtForCurrentItem async (doesn't block playback)
- Subscribes to _player.currentIndexStream so track advances trigger
  the same loader for the new current item
- _loadArtForCurrentItem early-returns if cache is null, no current
  item, no album_id, or artUri already set; otherwise calls
  cache.getOrFetch and pushes an updated MediaItem with artUri set
- Race guard: if the user skipped to another track while the fetch was
  in flight, the result is discarded

Closes the visible "generic music icon on lock screen" gap operator
flagged when first-testing on a real device.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 12:54:47 -04:00
bvandeusen d70075c426 feat(flutter/player): albumCoverCacheProvider + pass cache through configure
Adds the Riverpod provider (constructed with dioFactory pulling from
the authenticated dioProvider) and extends PlayerActions.playTracks
to forward the cache to audio_handler.configure(). The handler
signature change lands in the next commit.

Intentional intermediate-broken state: audio_handler.configure
doesn't yet accept coverCache. Resolved by the next task in the same
push.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 12:54:05 -04:00
bvandeusen b6d6f22598 feat(flutter/player): AlbumCoverCache for lock-screen artwork
Fetches album cover bytes via the authenticated dio and writes to
<applicationCacheDirectory>/album_covers/<albumId>.jpg. Returns the
local path so MediaItem.artUri can point at a file:// URI — Android's
MediaSession framework fetches artUri itself without our Bearer
header, so a pre-fetched local file is the workaround.

Concurrent callers for the same albumId dedupe to one fetch via an
in-flight Future map. Any failure (network / 4xx / 5xx / disk full /
empty id) returns null without throwing — playback continues with
the system's generic music icon, same UX as today.

No eviction — covers are tiny, OS clears cache when space is tight.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 12:53:20 -04:00
bvandeusen 78ad8a31e7 chore(flutter): promote path_provider to direct dep
Already a transitive dep via flutter_secure_storage and flutter_cache_manager.
Promoting to direct so we can import it from album_cover_cache (next
commit) for the lock-screen artwork cache directory.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 12:52:44 -04:00
bvandeusen d3a05520d3 fix(flutter): clear analyze --fatal-infos issues
Three info-level lints from CI:

- playlist_card.dart doc comment: "/playlists/<id>" → "/playlists/{id}"
  in backticks, since `<id>` was flagged as unintended HTML.
- compact_track_card_test.dart: home: Scaffold(...) is now const, which
  propagates const to CompactTrackCard and makes the inner [_track]
  implicitly const.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 12:05:02 -04:00
bvandeusen 17ff69780d test(flutter/home): cover new home parity layout
Expands the existing single test into four cases:
- 4 placeholder cards in Playlists row when no system playlists exist
- Empty-state copy for each section verbatim against the strings
  in HomeScreen
- Real For-You card renders with the system badge when present
- Existing rollups (Recently added / Rediscover) still render correctly
  alongside the new providers

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 11:40:46 -04:00
bvandeusen a2f6bdb44f feat(flutter/home): mirror web home structurally
Rewrites HomeScreen body to match the web home layout:
- Playlists row: For-You + 3 Songs-like + user playlists, with
  PlaylistPlaceholderCard for empty slots driven by
  systemPlaylistsStatusProvider
- Recently added: 50 albums in 2 rows of 25 sharing a scroll controller
- Rediscover: separate scrollers for albums (square) and artists
  (circular) — same condition as web's two-scroller branch
- Most played: 75 tracks in 3 rows of 25 using new CompactTrackCard
- Last played: existing single row layout preserved

Empty states use design-system understated-mythic copy mirrored
verbatim from web. Loading state uses DelayedLoading so brief network
blips don't flash a spinner.

Closes the visible parity gap the operator hit when first opening the
Flutter app on a real device.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 11:40:12 -04:00
bvandeusen 8fb82d473d feat(flutter/widgets): HorizontalScrollRow skips header when title empty
Lets multiple stacked HorizontalScrollRow instances render under a
single visible heading by passing title: "" to the second-row-onward
instances. Combined with the existing shared-controller support, this
gives us multi-row scrollers without a new widget.

Used in the next commit's home rewrite for Recently added (2 rows)
and Most played (3 rows).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 11:38:57 -04:00
bvandeusen a7fcafadda feat(flutter): DelayedLoading wrapper for skeleton-with-delay
Renders nothing for the first [delay] (default 200ms) of sustained
loading, then renders the [whileDelayed] child until loading completes.
Mirrors the web useDelayed hook so a fast network response doesn't
flash a skeleton.

Used in the next commit's home screen rewrite; otherwise unused this
slice.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 11:38:42 -04:00
bvandeusen 3ac8cc9363 feat(flutter/widgets): PlaylistCard + PlaylistPlaceholderCard
Mirrors the web equivalents at the same ~176dp width so the home
Playlists row keeps visual rhythm whether the slot is filled with a
real playlist or a placeholder.

PlaylistPlaceholderCard variants:
- building: spinner + "Building…"
- failed: warning + "Couldn't generate"
- seed-needed: muted icon + "Like more music"
- pending: muted icon + "Coming soon"

Used in the next commit's home Playlists row; otherwise unused this
slice.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 11:38:19 -04:00
bvandeusen dccdb00bce feat(flutter/widgets): CompactTrackCard for dense home Most-played row
Mirrors the web CompactTrackCard — small horizontal cell with cover
art (48dp), title, artist. Tap plays from this track in the section.
Width 176dp matches web's compact density so 25 tracks per row scroll
naturally on phone widths.

Cover URL is derived from track.albumId (/api/albums/<id>/cover) since
TrackRef itself doesn't carry a cover field — same pattern as web's
coverUrl() helper.

Used in the next commit's home Most-played section (3 rows × 25);
otherwise unused this slice.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 11:37:40 -04:00
bvandeusen 078520f504 feat(flutter): systemPlaylistsStatusProvider
Riverpod FutureProvider that reads the caller's system-playlists
build state. Consumed by the home Playlists row to decide between
real and placeholder cards.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 11:36:29 -04:00
bvandeusen d872a30506 feat(flutter): SystemPlaylistsStatus model + endpoint method
Adds the model + MeApi.systemPlaylistsStatus() for the home Playlists
row's placeholder-variant logic (building / failed / pending /
seed-needed). Mirrors GET /api/me/system-playlists-status which
returns the caller's most recent system_playlist_runs row.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 11:36:15 -04:00
bvandeusen 5613fec5ef fix(flutter): PlaylistsApi.list parses {owned, public} envelope
The server has always returned an enveloped response from GET
/api/playlists; the existing client decoded it as a flat List which
fails at runtime against the actual Map shape. Existing playlists
list screen would have been broken on any production instance.

list() now returns PlaylistsList { owned, public }. The existing
list screen consumes lists.all (owned + public flattened) — same
visible output as the previous flat-list assumption.

This unblocks the home parity slice which needs the same endpoint
for the new Playlists row.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 11:35:34 -04:00
bvandeusen 28b07c7ef4 fix(flutter/android): permit cleartext to 127.0.0.1 for just_audio loopback proxy
Audio playback failed against the prod HTTPS server with
"Cleartext HTTP traffic to 127.0.0.1 not permitted". Diagnostic
logging confirmed _baseUrl was correctly set to the prod URL — the
127.0.0.1 wasn't coming from the server or our URL construction.

Root cause: just_audio + audio_service spin up a local HTTP proxy on
loopback to inject the Authorization header, because Android's
MediaSession API can't pass headers down to ExoPlayer directly.
ExoPlayer connects to http://127.0.0.1:<random-port>; the proxy adds
the Bearer header and forwards to the real upstream HTTPS URL.
Loopback traffic doesn't leave the device.

This is the documented just_audio happy path — see
https://pub.dev/packages/just_audio#a-note-on-android-cleartext-traffic
— not a workaround for a plugin bug.

Adds network_security_config.xml that scopes cleartext permission to
127.0.0.1 ONLY. The base config keeps cleartextTrafficPermitted=false
so any actual remote endpoint must still be HTTPS.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 23:24:47 -04:00
bvandeusen 83df3773ae fix(flutter): cover URLs send Bearer auth + audio handler diag logging
Two issues from on-device testing against prod HTTPS:

1. ServerImage was resolving cover URLs correctly
   (https://minstrel.fabledsword.com/api/albums/.../cover) but the server
   returned 401 because Image.network doesn't carry the session token
   automatically the way the browser sends cookies. Forwards the stored
   session token as an Authorization: Bearer header. No-op when no token
   is present.

2. The "Cleartext HTTP traffic to 127.0.0.1" audio error reproduced even
   after the previous defensive check landed, which means the URL handed
   to ExoPlayer has a valid scheme+host (just the wrong host). The check
   only catches scheme-less URLs, so it didn't fire. Added debugPrint
   logging at configure() and setQueueFromTracks() time to show the
   actual baseUrl + per-track resolved URL on the next reproduction.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 23:15:56 -04:00
bvandeusen 088e8f4bf8 test(web/admin): align Lidarr bootstrap tests with file conventions
Refactors the new describe block to use the existing setupFresh()
helper pattern (mirrors setup() but with empty profile/folder lists
so we can verify the test response is what populates the dropdowns),
the lidarrSection() scoping helper (the cover-providers and SMTP
panels also have "Save changes" buttons that match unscoped queries),
and the correct mockQuery({ data: ... }) shape used elsewhere in the
file. Drops the duplicate afterEach (the file already has a global
one at line 131).

No behavior change in the tests themselves — same three cases.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 23:11:35 -04:00
bvandeusen c47ec6093f test(web/admin): cover Test-then-Save flow on /admin/integrations
Three new cases:
- Save on a fresh form calls test first, fills auto-defaults from the
  response, then put-config with non-zero defaults
- Save aborts when test fails and surfaces the error code
- An operator-picked default value survives the test → save sequence
  (auto-default $effect only fills when current value is 0/'')

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 23:10:37 -04:00
bvandeusen bca8622640 feat(web/admin): Save runs Test first, dropdowns honor test response
Click sequence on a fresh Lidarr config: enter URL + API key → click
Save. The page now calls testLidarrConnection first, stashes the
returned profiles/folders into local state, lets the existing
auto-default $effects pick first-of-each, then sends the put-config
request with non-zero defaults. If the test fails, the save aborts
and the error surfaces in saveError.

The explicit Test connection button keeps working and additionally
populates the dropdowns from the same response so an operator can
inspect/adjust before saving.

Each dropdown reads from its test-state array when present, falling
back to the existing query data (which only works after the first
successful save). list_errors entries surface as inline notes under
their respective dropdowns.

Closes the chicken-and-egg where saving required defaults that could
only be fetched after saving.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 23:08:58 -04:00
bvandeusen abb384f479 feat(web/admin): LidarrTestResult success branch carries profile + folder lists
Mirrors the server-side extension of POST /api/admin/lidarr/test. The
integrations page consumes these in the next commit to pre-fill the
quality/metadata/root-folder dropdowns on first-time Lidarr setup.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 23:08:02 -04:00
bvandeusen 22f03a5fe8 test(server/admin): cover new test endpoint response shape
- Updates the happy-path test stub to handle the three list endpoints
  Lidarr exposes (qualityprofile / metadataprofile / rootfolder) and
  asserts profiles + folders make it through to the response.
- Adds a partial-failure case where one list endpoint 5xxs; verifies
  ok=true, the failing list is omitted, and list_errors carries its
  bucket code.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 23:07:47 -04:00
bvandeusen 0bc17a85fb feat(server/admin): test endpoint returns profiles + folders on success
Extends POST /api/admin/lidarr/test response to include quality_profiles,
metadata_profiles, root_folders, and an optional list_errors map when the
Lidarr connection succeeds. The three list fetches run in parallel after
the ping; any per-list failure goes into list_errors so the response can
still report ok=true with whatever data did come back. Failed-ping
response shape is unchanged.

This lets /admin/integrations populate its dropdowns on a single
round-trip during first-time setup, fixing the chicken-and-egg where
the dropdowns previously gated on cfg.Enabled (which can't be true
until the first save, which itself needs non-zero defaults).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 23:07:15 -04:00
bvandeusen 602ef3bfdf fix(flutter): cover URLs resolve against server baseUrl + audio stream URL guard
Cover-art Image.network calls were passing server-relative URLs
(/api/albums/<id>/cover) straight to NetworkImage, which interprets
"no scheme" as file:/// and crashes with "No host specified in URI".
Same root cause regardless of HTTPS or HTTP server.

ServerImage wraps Image.network with a Riverpod read of
serverUrlProvider and prefixes the configured base URL. Absolute URLs
(e.g. discover screen's Lidarr image_urls) pass through unchanged.

Three call sites updated: album_card, artist_card, playlists_list_screen.
discover_screen left as-is — its row.imageUrl is already absolute (Lidarr
returns full URLs from MusicBrainz / Spotify metadata) and it has a
meaningful errorBuilder that ServerImage doesn't expose.

Also adds a defensive check in audio_handler.setQueueFromTracks: if
the constructed stream URL ends up scheme-less, throw a StateError
naming baseUrl + track.streamUrl + track.id instead of letting it
fall through to ExoPlayer which surfaces a confusing "Cleartext HTTP
traffic to 127.0.0.1 not permitted" error (Android's URL parser
defaults a scheme-less URI to localhost). User reported this exact
confusing error against an HTTPS prod server; the better message
will pinpoint where the empty baseUrl comes from on next reproduction.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 22:47:25 -04:00
bvandeusen 751c2878f7 fix(flutter/android): production manifest + AudioServiceActivity
Two related Android setup gaps caught when running on a clean Pixel 6
emulator:

1. MainActivity extended FlutterActivity, but the audio_service
   plugin requires AudioServiceActivity. AudioService.init() threw
   PlatformException("The Activity class declared in your
   AndroidManifest.xml is wrong"), and the partial-engine-reinit that
   followed cascaded into a flutter_cache_manager SQLite EXCLUSIVE
   lock crash. Both errors clear with the correct base class.

2. The main manifest was missing two production permissions:
   - POST_NOTIFICATIONS — Android 13+ runtime requirement for the
     media notification (now-playing tile in the system tray).
     audio_service auto-prompts at init() time once declared.
   - ACCESS_NETWORK_STATE — used by ConnectionErrorBanner +
     flutter_cache_manager for connectivity awareness.

Note for future contributors: src/main/AndroidManifest.xml IS the
production manifest. The src/debug and src/profile variants only add
dev-only entries (e.g. INTERNET re-declared in debug for hot-reload).
There is no separate "release" manifest in Flutter's convention.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 22:33:30 -04:00
bvandeusen 626fc7502c Merge pull request 'refactor(server): remove bootstrap admin path' (#34) from dev into main 2026-05-09 02:19:40 +00:00
bvandeusen c4cccea775 refactor(server): remove bootstrap admin path
The bootstrap-admin-from-env-vars flow was a holdover from before
self-registration could create the first admin. Now that handleRegister
+ CreateUserFirstAdminRace promotes the first user to register on an
empty users table (verified shipped in v2026.05.08.2 / #376), the
bootstrap path is just a second source of truth that confuses operators
(and leaves an "admin" account in the DB that nobody asked for).

Removes:
- internal/auth/bootstrap.go + its test
- The auth.Bootstrap call from cmd/minstrel/main.go
- AuthConfig + AdminBootstrapConfig structs from config
- MINSTREL_AUTH_ADMIN_USERNAME / _PASSWORD env reads + their test
- The auth: block from config.example.yaml
- Bootstrap-related comments in docker-compose.yml + README.md

The README quickstart now points operators at /register on first start
instead of "watch the logs for a one-time password."

Existing instances keep their bootstrap-admin row in the DB; operators
who want it gone can register a new admin via /register, promote them
in /admin/users, then delete the old bootstrap user (last-admin guard
will require the new admin to be promoted first). No migration needed.

Recovery story for forgotten admin passwords now hinges on Fable #321
(admin password reset CLI) — currently the only path back in if no
other admin exists.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 22:14:33 -04:00
bvandeusen 9bf3b8a2f2 Merge pull request 'feat(flutter): admin parity slice — requests, quarantine, users, invites' (#33) from dev into main 2026-05-09 02:07:59 +00:00
bvandeusen d5c8d316c5 fix(flutter): clear analyze --fatal-infos errors from admin parity slice
CI caught six issues against the new admin slice:

- AsyncValue<T> in this Riverpod 3.3.1 codebase exposes `.value`
  (returns T?), not `.valueOrNull`. Switched the three admin readers
  to match the established convention (player_bar, queue_screen,
  now_playing_screen all use `.value`).
- home_screen.dart still has ctx.push calls in _albumsRow / _artistsRow
  (carousel tap handlers) — restored the go_router import that
  Task 2 over-eagerly removed.
- admin_user_edit_sheet.dart had a single-line `if (!await ...) return;`
  that violated curly_braces_in_flow_control_structures. Wrapped in
  braces.
- admin_quarantine_item.dart doc comment had `<top>` placeholders that
  the analyzer flagged as unintended HTML. Rephrased without angle
  brackets.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 22:02:14 -04:00
bvandeusen 9f6ceb1731 feat(flutter/admin): users screen with users + invites sections
Single-scroll layout with two _SectionHeader-anchored blocks. Users
rows tap into AdminUserEditSheet. Invites row shows token (monospace)
with copy button, optional note, and a redeemed badge if applicable.

"Generate invite" opens a small dialog with an optional note field
(server hardcodes 24h TTL — admins can't customise expiry). On
success the new token is shown in a copy-once result dialog.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:57:53 -04:00
bvandeusen afcaf56b9c feat(flutter/admin): user row + edit sheet (toggles, reset, delete)
AdminUserRow shows username + admin/auto-approve badges; tap opens
AdminUserEditSheet bottom sheet.

Edit sheet: SwitchListTile pair for is_admin and auto_approve_requests
(both surface server errors via SnackBar, including the last-admin
guard). Reset password takes a typed-input dialog (>=8 chars enforced
client-side; admin supplies the new password). Delete routes through
TypedConfirmSheet ("DELETE") and pops the sheet on success.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:57:10 -04:00
bvandeusen 7d207e56f5 feat(flutter/admin): users + invites mutations
Extends AdminUsersController (build-only since slice 2) with setAdmin,
setAutoApprove, delete, resetPassword. is_admin/auto_approve toggles
optimistically swap the row and roll back on server error (including
the last-admin guard 4xx). resetPassword is admin-supplied; no
auto-generation mode exists server-side.

Adds AdminInvitesController + adminInvitesProvider with create
(prepends new invite to the list, returns it for the copy-once
dialog) and revoke (optimistic remove + rollback).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:56:34 -04:00
bvandeusen 3e905db906 feat(flutter/admin): quarantine screen + typed-confirm sheet
ExpansionTile per aggregated quarantine row — collapsed shows track,
artist · album, and "{N} reports: {top reason}". Expanded reveals the
nested per-user reports with their reasons + optional notes.

Three-dot menu offers Resolve / Delete file / Delete via Lidarr; both
deletes route through TypedConfirmSheet which requires the user to
type "DELETE" before the action button enables.

Adds AdminQuarantineController with optimistic-removal + rollback,
mirroring AdminRequestsController's pattern.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:56:00 -04:00
bvandeusen bd1bcab12b feat(flutter/admin): requests screen with approve/reject
AdminRequestsScreen renders rows from adminRequestsProvider, joining
requester user_id → username via adminUsersProvider for display
(falls back to UUID prefix when the users list hasn't loaded yet).
Approve fires immediately; Reject confirms via dialog. Both are
optimistic with rollback in the controller.

Adds AdminUsersController build-only (the read side) so the row join
works; mutation methods land in Slice 3 alongside the Users screen.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:54:58 -04:00
bvandeusen 8bb192fe54 feat(flutter/admin): adminRequestsProvider with optimistic approve/reject
AsyncNotifier removes the row optimistically on approve/reject; rolls
back to the pre-mutation list on server error. Invalidates
adminCountsProvider so the landing badge stays accurate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:54:05 -04:00
bvandeusen 408eed1f3d feat(flutter/settings): admin card visible to admins
Settings gains an _AdminSection that renders an "Admin" tile (Shield
icon → /admin) only when the current profile has is_admin = true.
Non-admins see the section as SizedBox.shrink() so the const ListView
children stay const.

Provides a discoverable second entry to the admin landing alongside
the kebab overflow shortcut.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:53:35 -04:00
bvandeusen 6b5d12f3a1 feat(flutter/admin): landing screen with section cards + counts
ListView of three AdminSectionCard tiles (Requests / Quarantine /
Users) showing live counts from adminCountsProvider. Pull-to-refresh
re-fans-out to the three list endpoints. Admin/Quarantine/Users
sub-routes will land in subsequent commits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:53:03 -04:00
bvandeusen 372e7eca86 feat(flutter/admin): API providers + adminCountsProvider
Single landing-screen provider fans out to requests/quarantine/users
list endpoints in parallel and returns counts for the section-card
badges. Per-section AsyncNotifier controllers land alongside their
screens in subsequent commits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:52:12 -04:00
bvandeusen 79d00ba001 feat(flutter/api): admin endpoint clients
Four small Dio-backed API classes mirroring the server's actual
contract (verified against internal/api/admin_*.go):

- Requests/Quarantine return flat lists; Users/Invites are enveloped
  ({"users": [...]}, {"invites": [...]}) and unwrap here
- setAutoApprove sends {auto_approve: bool} — different from the
  response field name auto_approve_requests
- resetPassword takes admin-supplied {password: string}, returns 204
- Invite create takes optional {note: string}; expiry is server-fixed
  at 24h

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:52:00 -04:00
bvandeusen 2b595c40cd feat(flutter): admin DTOs (request, quarantine item, user, invite)
Hand-rolled to match the server's actual JSON shapes:
- AdminRequest carries user_id (UUID, not username); kind switches
  which title field is the display name
- AdminQuarantineItem aggregates reports per track with reason_counts
  and a nested reports[] list, mirroring adminQueueRowView
- AdminUser includes display_name + auto_approve_requests
- Invite uses invited_by UUID + note (server hardcodes 24h TTL)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:51:33 -04:00
bvandeusen dfc08650e7 feat(flutter): wire admin routes + isAdmin gate
Adds /admin, /admin/requests, /admin/quarantine, /admin/users routes to
the ShellRoute (so PlayerBar persists). Redirect closure refuses any
/admin path when user.isAdmin is false. Server-side RequireAdmin
middleware remains the actual authority — this is UX.

Screens land in subsequent commits; this intermediate state won't build
until task 8/9 lands the AdminLandingScreen and the missing siblings
are stubbed out by task 11/13/16.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:50:53 -04:00
bvandeusen fc0350cb96 feat(flutter): adopt MainAppBarActions in Search, Discover, Playlists, Settings
Search keeps its conditional clear-text button and gains the shared
nav widget after it. Discover/Playlists/Settings get an actions row
they didn't have before. The kebab is now reachable from every
top-level screen, which is the prerequisite for the Admin entry.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:50:29 -04:00
bvandeusen 5546787f78 feat(flutter): adopt MainAppBarActions in Home + Library
HomeScreen drops its 5 ad-hoc IconButton actions in favour of the shared
widget. LibraryScreen gains an actions row it didn't have before. Both
now consistent.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:49:30 -04:00
bvandeusen 6564d37a2a feat(flutter): MainAppBarActions widget with admin-gated overflow
Shared AppBar actions for top-level screens — three primary icons
(Home/Library/Search, current screen suppressed) plus a kebab containing
Playlists/Discover/Settings and (only when isAdmin) Admin. Replaces the
ad-hoc per-screen IconButton lists; centralises admin-gating logic in
one place so /admin entry can't accidentally leak to non-admins.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 21:48:52 -04:00
bvandeusen 492460cf4a Merge pull request 'fix(web): /register reachable for bootstrap admin (closes #376)' (#32) from dev into main 2026-05-08 22:01:37 +00:00
bvandeusen c5dc3bd256 fix(web): exempt /register from auth guard so bootstrap admin can self-register
The +layout.svelte auth guard only treated /login as public, so any
unauthenticated visit to /register bounced to /login?returnTo=%2Fregister.
The "Register" link on the login page therefore looped back to itself,
making the first-user-becomes-admin bootstrap path (handleRegister +
CreateUserFirstAdminRace) unreachable in production.

Extracted isPublicRoute() into web/src/lib/auth/publicRoutes.ts so the
public-route set has one source of truth and is unit-testable. Test file
explicitly comment-tags /register as a #376 regression guard.

Closes the last gap in user-mgmt umbrella #376.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 17:59:43 -04:00
bvandeusen 3f2822dfc6 feat(flutter): discover screen — search Lidarr + create requests
- models/lidarr.dart (LidarrSearchResult + LidarrRequestKind)
- api/endpoints/discover.dart (search + createRequest)
- discover/discover_screen.dart with TextField, kind toggle (Artists/Albums),
  results list with in_library / requested pills
- /discover route + explore icon on home AppBar (5 actions now: Library,
  Playlists, Search, Discover, Settings)
2026-05-08 14:53:06 -04:00
bvandeusen dfbeed01a6 feat(flutter): settings screen + 4-icon home AppBar
- models/my_profile.dart (MyProfile + ListenBrainzStatus)
- api/endpoints/settings.dart (profile / password / listenbrainz CRUD)
- settings/settings_screen.dart with three sections:
  - Profile: display_name + email, Save profile
  - Password: current + new + confirm, validates >=8 + match
  - ListenBrainz: token paste + scrobble-enabled toggle
- /settings route + Settings icon on home AppBar
- Home AppBar now: Library + Playlists + Search + Settings (was just Search)
2026-05-08 14:51:04 -04:00
bvandeusen 1ad67dbe59 fix(flutter/test): tolerate Riverpod 3's ProviderException wrapper 2026-05-08 14:43:31 -04:00
bvandeusen da1cb7b590 feat(flutter): queue screen + skipToQueueItem support
- audio_handler: override skipToQueueItem(index) -> _player.seek(zero, index: i)
- player/queue_screen.dart: list of MediaItems with current track highlighted
  (left accent border + Now Playing badge), tap-to-jump on non-current rows
- /queue route + queue_music icon on /now-playing AppBar

Reorder + remove deferred for v1.
2026-05-08 14:42:10 -04:00
bvandeusen 66545bf8c3 feat(flutter): library screen with 5 tabs (Artists/Albums/History/Liked/Hidden)
Models:
- history_event.dart (HistoryEvent + HistoryPage envelope)
- quarantine_mine.dart (QuarantineMineRow for /api/quarantine/mine)
- Renamed Page<T> -> Paged<T> to avoid collision with Material's Page

Endpoints:
- library_lists.dart: listArtists / listAlbums (paged)
- me.dart: history + quarantineMine
- likes.dart: extended with listTracks/Albums/Artists (paged)

UI:
- library_screen.dart: TabBar over 5 tabs
- Artists tab: 3-col grid
- Albums tab: 2-col grid
- History tab: list with relative-time formatting (matches HistoryRow.svelte)
- Liked tab: 3 stacked sections (artists scroll-row, albums scroll-row, tracks list)
- Hidden tab: list of quarantined tracks with reason pill
- /library route + library_music icon on home AppBar

First page only for v1 (limit 50). Infinite scroll deferred.
2026-05-08 14:40:26 -04:00
bvandeusen 5541171e94 feat(flutter): playlists list + detail screens
- models/playlist.dart (Playlist, PlaylistTrack, PlaylistDetail)
- api/endpoints/playlists.dart (list with kind=user|system|all, get detail)
- playlists/playlists_provider.dart (Riverpod family providers)
- playlists/playlists_list_screen.dart (with system-variant pill)
- playlists/playlist_detail_screen.dart (header + Play button + rows)
- /playlists + /playlists/:id routes wired
- Home AppBar: queue_music icon next to Search

Tracks with track_id=null render greyed-out + struck-through (matches
web's PlaylistTrackRow behavior). Tap a row plays from that position;
top-level Play button plays the full playable subset from track 0.
2026-05-08 14:33:53 -04:00
bvandeusen 147d6e280e feat(flutter): bump deps to latest + Search screen slice
Major version bumps (riverpod 2->3, go_router 14->17, just_audio 0.9->0.10,
flutter_secure_storage 9->10, google_fonts 6->8, flutter_lints 4->6).
package_info_plus held at 8.x due to win32 conflict with secure_storage 10.x.

Riverpod 3 breaks: AsyncValue.valueOrNull -> .value, StateProvider replaced
with Notifier subclass. just_audio 0.10: ConcatenatingAudioSource -> setAudioSources.

Search slice:
- models/page.dart (generic Page<T> envelope)
- models/search_response.dart (3-facet wrapper)
- api/endpoints/search.dart
- search/search_provider.dart (debounced 250ms)
- search/search_screen.dart (TextField + 3 horizontal/vertical sections)
- Wired /search route + search button on home AppBar
2026-05-08 14:30:01 -04:00
bvandeusen 1b3f2e254b docs(readme): use :latest in quickstart compose instead of pinned tag 2026-05-08 13:50:53 -04:00
334 changed files with 23048 additions and 2018 deletions
+48 -6
View File
@@ -56,6 +56,12 @@ jobs:
- name: Pub get
run: flutter pub get
- name: Codegen (drift, etc.)
# build_runner generates *.g.dart files (drift schemas, etc.)
# which are gitignored. Must run before analyze + test so the
# generated symbols exist.
run: dart run build_runner build --delete-conflicting-outputs
- name: Analyze
run: flutter analyze --fatal-infos
@@ -66,9 +72,44 @@ jobs:
if: github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')
run: flutter build apk --debug
- name: Decode signing keystore
if: startsWith(github.ref, 'refs/tags/v')
# Reconstructs the release keystore from a base64-encoded
# CI secret so every tagged build is signed with the same
# key. Without this, each CI runner would generate its own
# debug keystore and Android would refuse to upgrade an
# existing install (signature mismatch).
shell: bash
env:
ANDROID_KEYSTORE_B64: ${{ secrets.ANDROID_KEYSTORE_B64 }}
run: |
if [ -z "${ANDROID_KEYSTORE_B64}" ]; then
echo "::error::ANDROID_KEYSTORE_B64 secret is missing — release builds need a consistent signing key"
exit 1
fi
KEYSTORE_PATH="${RUNNER_TEMP}/minstrel-release.keystore"
echo "${ANDROID_KEYSTORE_B64}" | base64 -d > "${KEYSTORE_PATH}"
echo "ANDROID_KEYSTORE_PATH=${KEYSTORE_PATH}" >> "${GITHUB_ENV}"
- name: Build release APK
if: startsWith(github.ref, 'refs/tags/v')
run: flutter build apk --release
# Inject the tag (sans leading 'v') as the build's --build-name
# so PackageInfo.version matches what /api/client/version
# reports — otherwise the in-app update banner would always
# think the user is behind because pubspec.yaml's static
# version drifts from the actual release tag.
#
# ANDROID_KEYSTORE_PATH is set by the previous step;
# build.gradle.kts picks it up and signs the release APK with
# the operator's persistent keystore.
shell: bash
env:
ANDROID_STORE_PASSWORD: ${{ secrets.ANDROID_STORE_PASSWORD }}
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
run: |
TAG="${GITHUB_REF#refs/tags/v}"
flutter build apk --release --build-name="${TAG}"
- name: Upload debug APK artifact
if: github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')
@@ -81,14 +122,15 @@ jobs:
if: startsWith(github.ref, 'refs/tags/v')
shell: bash
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
CI_TOKEN: ${{ secrets.CI_TOKEN }}
run: |
TAG="${GITHUB_REF#refs/tags/}"
REPO="${GITHUB_REPOSITORY}"
# Look up the release ID for this tag (release must exist already;
# release.yml creates it as part of the server-side release flow).
# Look up the release ID for this tag. The release object must
# exist already — operator creates it (or release.yml will, in
# a future enhancement) before pushing the tag.
RELEASE_ID=$(curl -fsSL \
-H "Authorization: token ${RELEASE_TOKEN}" \
-H "Authorization: token ${CI_TOKEN}" \
"https://git.fabledsword.com/api/v1/repos/${REPO}/releases/tags/${TAG}" \
| grep -oP '"id":\s*\K[0-9]+' | head -1)
if [ -z "${RELEASE_ID}" ]; then
@@ -96,6 +138,6 @@ jobs:
exit 1
fi
curl -fsSL \
-H "Authorization: token ${RELEASE_TOKEN}" \
-H "Authorization: token ${CI_TOKEN}" \
-F "attachment=@build/app/outputs/flutter-apk/app-release.apk" \
"https://git.fabledsword.com/api/v1/repos/${REPO}/releases/${RELEASE_ID}/assets?name=minstrel-${TAG}.apk"
+35 -2
View File
@@ -50,9 +50,11 @@ jobs:
if [[ "${GITHUB_REF}" == refs/tags/v* ]]; then
VERSION="${GITHUB_REF#refs/tags/}"
echo "args=-t ${IMAGE}:${VERSION} -t ${IMAGE}:latest" >> "$GITHUB_OUTPUT"
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
echo "::notice::Release build: ${VERSION} + latest"
else
echo "args=-t ${IMAGE}:main" >> "$GITHUB_OUTPUT"
echo "version=main" >> "$GITHUB_OUTPUT"
echo "::notice::Main-branch build: :main"
fi
@@ -60,9 +62,40 @@ jobs:
if: steps.guard.outputs.ready == 'true'
shell: bash
run: |
echo "${{ secrets.REGISTRY_TOKEN }}" \
echo "${{ secrets.CI_TOKEN }}" \
| docker login git.fabledsword.com -u "${{ github.actor }}" --password-stdin
# In-app update flow (#397): on tag pushes only, fetch the APK
# that flutter.yml is attaching to this same release. flutter.yml
# runs in parallel; poll up to 15 min for the asset to appear.
# On main pushes (or if the APK never lands), client/ stays empty
# and the endpoints return 404 — graceful degradation.
- name: Fetch APK for bundled in-app update channel
if: steps.guard.outputs.ready == 'true' && startsWith(github.ref, 'refs/tags/v')
shell: bash
env:
CI_TOKEN: ${{ secrets.CI_TOKEN }}
run: |
TAG="${GITHUB_REF#refs/tags/}"
REPO="${GITHUB_REPOSITORY}"
APK_URL="https://git.fabledsword.com/${REPO}/releases/download/${TAG}/minstrel-${TAG}.apk"
echo "Polling ${APK_URL} (up to 15 min for flutter.yml to attach)..."
for i in $(seq 1 30); do
if curl -fsSL -H "Authorization: token ${CI_TOKEN}" \
-o client/minstrel.apk "$APK_URL"; then
echo "Got APK on attempt $i"
echo "${TAG}" > client/minstrel.apk.version
ls -lh client/
exit 0
fi
echo "APK not ready yet (attempt $i/30), sleeping 30s..."
sleep 30
done
echo "::warning::APK never appeared at ${APK_URL} after 15 min — image will ship without bundled update channel"
- name: Build and push
if: steps.guard.outputs.ready == 'true'
run: docker buildx build --push ${{ steps.tags.outputs.args }} .
run: |
docker buildx build \
--build-arg MINSTREL_VERSION="${{ steps.tags.outputs.version }}" \
--push ${{ steps.tags.outputs.args }} .
+5
View File
@@ -12,6 +12,11 @@
# Test binary, built with `go test -c`
*.test
# Bundled Android APK + version sidecar (#397). Populated by CI for
# tag releases; never committed. README in client/ explains the flow.
client/minstrel.apk
client/minstrel.apk.version
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
+14 -2
View File
@@ -15,7 +15,13 @@ COPY . .
# Overwrite the committed placeholder with the freshly-built SPA assets.
COPY --from=web /web/build ./web/build
ENV CGO_ENABLED=0
RUN go build -trimpath -ldflags="-s -w" -o /out/minstrel ./cmd/minstrel
# Version stamping: release.yml passes the git tag via MINSTREL_VERSION
# build-arg; local `docker build` falls back to "dev". Surfaced at
# /healthz for operator-side image-version verification.
ARG MINSTREL_VERSION=dev
RUN go build -trimpath \
-ldflags="-s -w -X 'git.fabledsword.com/bvandeusen/minstrel/internal/server.ServerVersion=${MINSTREL_VERSION}'" \
-o /out/minstrel ./cmd/minstrel
FROM debian:bookworm-slim
RUN apt-get update \
@@ -33,9 +39,15 @@ COPY config.example.yaml /etc/smartmusic/config.yaml
# A non-writable path at this location silently breaks every downstream
# cache, so we create + chown it once at image build. Operators mount a
# named volume on top to persist across container recreates.
RUN mkdir -p /app/data && chown -R minstrel:minstrel /app
RUN mkdir -p /app/data /app/client && chown -R minstrel:minstrel /app
WORKDIR /app
# In-app update channel (#397). client/ in the build context holds
# minstrel.apk + minstrel.apk.version (populated by release.yml on tag
# pushes; .gitkeep + README otherwise). Endpoints return 404 when the
# APK files aren't present, so non-tag images degrade gracefully.
COPY --chown=minstrel:minstrel client/ /app/client/
USER minstrel
EXPOSE 4533
ENV MINSTREL_STORAGE_DATA_DIR=/app/data
+2 -3
View File
@@ -21,7 +21,7 @@ A self-hosted music server that thinks for you. Smart shuffle, contextual likes,
# compose.yaml
services:
minstrel:
image: git.fabledsword.com/bvandeusen/minstrel:v1.0.0
image: git.fabledsword.com/bvandeusen/minstrel:latest
ports: ['4533:4533']
volumes:
- ./music:/music:ro
@@ -48,7 +48,7 @@ volumes:
docker compose up -d
```
Watch `docker compose logs minstrel` on first start — a one-time admin password is printed to stderr. Sign in at `http://localhost:4533` with username `admin` and that password, then change it under Settings.
After the stack is up, visit `http://localhost:4533/register` and create your admin account. The first user to register on a fresh instance is automatically marked as the administrator; subsequent users can register through the same form (or via invite tokens generated from the admin Users panel, depending on how you configure registration).
For the full configuration surface, see [`config.example.yaml`](./config.example.yaml).
@@ -59,7 +59,6 @@ Most operators only need the env vars in the quickstart above. A few extras wort
- `MINSTREL_BRANDING_APP_NAME` — rename the instance ("Family Jukebox", "Office Music"). Surfaces in the header, browser tab, and OG share previews.
- `MINSTREL_STORAGE_DATA_DIR` — defaults to `./data`. Holds playlist cover collages and other generated artefacts.
- `MINSTREL_LIBRARY_SCAN_PATHS` — colon-separated list of music library roots to scan. Supports multiple roots (`/music:/podcasts`).
- `MINSTREL_AUTH_ADMIN_USERNAME` / `MINSTREL_AUTH_ADMIN_PASSWORD` — bootstrap admin credentials. Username defaults to `admin`; leave the password unset to have the server generate one and print it to stderr on first start.
ListenBrainz integration (per-user scrobble + similarity tokens) and Lidarr integration (URL + API key) are configured through the admin Settings UI rather than env vars or yaml — per Minstrel's "config in UI" rule, integration settings live where operators can edit them without restarting.
View File
+35
View File
@@ -0,0 +1,35 @@
# Bundled client assets
Holds the Android APK (`minstrel.apk` + `minstrel.apk.version`) that the
server serves via `/api/client/version` and `/api/client/apk` for the
in-app update flow (#397).
## Production
CI populates this directory on tag releases:
1. `flutter.yml` builds `app-release.apk` and attaches it to the
Forgejo release as `minstrel-<TAG>.apk`.
2. `release.yml` waits for that asset to appear, downloads it into
this directory as `minstrel.apk`, writes the tag string to
`minstrel.apk.version`, and `docker buildx build` includes both
via `COPY client/ /app/client/`.
## Development
Empty directory works fine — the endpoints return 404 and the Flutter
update banner stays hidden ("no update channel" graceful degradation).
To smoke-test the update flow locally, drop a real APK + a version
file into this directory:
```sh
cp /path/to/app-release.apk client/minstrel.apk
echo "v0.2.0" > client/minstrel.apk.version
```
## Why a directory and not embed.FS?
The APK is 30-60 MB. Embedding bloats the Go binary and slows
`go build` for everyone, even when the APK isn't being changed.
File-on-disk also lets operators override at runtime via volume
mount on `/app/client/` if they want to ship their own build.
+34 -7
View File
@@ -11,10 +11,10 @@ import (
"syscall"
"time"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/config"
"git.fabledsword.com/bvandeusen/minstrel/internal/coverart"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
"git.fabledsword.com/bvandeusen/minstrel/internal/lidarrconfig"
"git.fabledsword.com/bvandeusen/minstrel/internal/lidarrrequests"
@@ -25,6 +25,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/server"
"git.fabledsword.com/bvandeusen/minstrel/internal/similarity"
"git.fabledsword.com/bvandeusen/minstrel/internal/subsonic"
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
)
func main() {
@@ -67,10 +68,6 @@ func run() error {
}
defer pool.Close()
if err := auth.Bootstrap(ctx, pool, cfg.Auth.AdminBootstrap, logger); err != nil {
return fmt.Errorf("bootstrap admin: %w", err)
}
scanner := library.New(pool, logger, cfg.Library.ScanPaths)
contact := cfg.Library.ContactEmail
@@ -151,9 +148,38 @@ func run() error {
// import requests and reconciles them against the library. Short-circuits
// to no-op when lidarr_config.enabled = false.
lidarrCfg := lidarrconfig.New(pool)
lidarrReconciler := lidarrrequests.NewReconciler(pool, lidarrCfg, logger.With("component", "lidarr"))
// Live-event bus shared between SSE subscribers (api.Mount) and
// background workers that publish (reconciler today; scanner later).
// Constructed before any service that publishes so they all share the
// same instance.
bus := eventbus.New()
// Scan-run lifecycle events use a package-level setter rather than
// threading the bus through RunScan + TryStartScan + the Scheduler
// + every test caller. Per-process singleton, set once at startup.
library.SetEventBus(bus)
lidarrReconciler := lidarrrequests.NewReconciler(pool, lidarrCfg, logger.With("component", "lidarr"), bus)
go lidarrReconciler.Run(ctx)
// library_changes compactor (#357 follow-up). Daily tick; deletes
// rows older than the configured retention so the change-log table
// doesn't grow unbounded. Clients that drop offline longer than
// retention hit the /api/library/sync 410 fallback and resync.
libraryChangesCompactor := syncpkg.NewCompactor(pool, logger.With("component", "library_changes_compactor"))
go libraryChangesCompactor.Run(ctx)
// Per-user system-playlist scheduler (#392 Half B). Fires each
// active user's daily build at 03:00 in their stored timezone.
// Replaces the 24h-anchored cron loop (removed in the next commit
// of this arc).
playlistScheduler, err := playlists.NewScheduler(pool, logger.With("component", "playlist_scheduler"), cfg.Storage.DataDir)
if err != nil {
return fmt.Errorf("init playlist scheduler: %w", err)
}
if err := playlistScheduler.Start(ctx); err != nil {
return fmt.Errorf("start playlist scheduler: %w", err)
}
defer playlistScheduler.Stop()
// Ensure DataDir exists before any service tries to write into it.
// Fatal on failure: a non-writable data_dir silently breaks every
// downstream cache (playlist covers, artist art, album-cover fallback)
@@ -178,7 +204,8 @@ func run() error {
srv := server.New(logger, pool, scanner, subsonic.Config{
AllowPlaintextPassword: cfg.Subsonic.AllowPlaintextPassword,
}, cfg.Events, cfg.Recommendation, cfg.Storage.DataDir, cfg.Branding, coverEnricher, cfg.Library.CoverArtBackfillCap, coverSettings, scanner, scanCfg, scheduler)
playlists.StartSystemPlaylistCron(ctx, pool, logger.With("component", "system_playlist_cron"), cfg.Storage.DataDir)
srv.Bus = bus
srv.PlaylistScheduler = playlistScheduler
httpServer := &http.Server{
Addr: cfg.Server.Address,
Handler: srv.Router(),
-10
View File
@@ -22,16 +22,6 @@ log:
level: "info" # debug | info | warn | error
format: "text" # text | json
auth:
# One-shot admin bootstrap. Applied only when the users table is empty.
# Username defaults to "admin" when unset — you can omit this section
# entirely for a working bootstrap. Leave password blank to have the server
# generate one and log it to stderr on first start.
# Env: MINSTREL_AUTH_ADMIN_USERNAME, MINSTREL_AUTH_ADMIN_PASSWORD
admin_bootstrap:
username: "admin"
password: ""
library:
# Filesystem roots to scan for music. Each path is walked recursively.
# Env: MINSTREL_LIBRARY_SCAN_PATHS (colon-separated, PATH-style)
-3
View File
@@ -39,9 +39,6 @@ services:
MINSTREL_LIBRARY_SCAN_PATHS: /music
MINSTREL_LIBRARY_SCAN_ON_STARTUP: "true"
MINSTREL_STORAGE_DATA_DIR: /app/data
# MINSTREL_AUTH_ADMIN_PASSWORD left unset on purpose — bootstrap
# generates one and prints it to stderr on first boot. Watch the logs
# of the minstrel service the first time you bring the stack up.
networks:
- minstrel
ports:
+4
View File
@@ -43,3 +43,7 @@ app.*.map.json
/android/app/debug
/android/app/profile
/android/app/release
# drift codegen output (regenerated by build_runner; CI runs build_runner)
*.g.dart
+30 -3
View File
@@ -30,11 +30,38 @@ android {
versionName = flutter.versionName
}
// Real release signing config — populated only when CI exports
// ANDROID_KEYSTORE_PATH (decoded from a base64 secret) plus the
// matching password/alias env vars. Without these (local
// `flutter build apk --release` runs), the release build falls
// through to the debug keystore so local builds still work.
//
// Why this matters: Flutter's default `flutter run --release` and
// CI's earlier setup both signed with the per-machine debug
// keystore (~/.android/debug.keystore). Every CI runner generated
// its own debug key, so consecutive release APKs had different
// signatures and Android refused to upgrade an existing install.
val keystorePath: String? = System.getenv("ANDROID_KEYSTORE_PATH")
if (keystorePath != null && keystorePath.isNotEmpty()) {
signingConfigs {
create("release") {
storeFile = file(keystorePath)
storePassword = System.getenv("ANDROID_STORE_PASSWORD")
keyAlias = System.getenv("ANDROID_KEY_ALIAS")
keyPassword = System.getenv("ANDROID_KEY_PASSWORD")
}
}
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig = signingConfigs.getByName("debug")
signingConfig = if (keystorePath != null && keystorePath.isNotEmpty()) {
signingConfigs.getByName("release")
} else {
// Local-only fallback so `flutter run --release` works
// without the keystore. CI must export ANDROID_KEYSTORE_PATH.
signingConfigs.getByName("debug")
}
}
}
}
@@ -1,12 +1,23 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Used in all build flavours (debug / profile / release). -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<!-- Android 13+ requires this to be declared AND prompted at runtime
for the media notification (now-playing tile) to appear. Audio
playback works without it; only the system-tray surface breaks. -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- In-app update flow (#397). First update attempt prompts the
user to enable "Install unknown apps" for Minstrel in
Settings → Apps → Special access. One-time grant; persists. -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<application
android:label="minstrel"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
android:icon="@mipmap/ic_launcher"
android:networkSecurityConfig="@xml/network_security_config">
<activity
android:name=".MainActivity"
android:exported="true"
@@ -49,6 +60,20 @@
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
<!-- FileProvider for the in-app update flow (#397). Maps the
cache directory (where dio.download writes the APK) to a
content:// URI so the PackageInstaller intent can read it
across the process boundary. file:// URIs are blocked
since Android 7. -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
@@ -1,5 +1,70 @@
package com.fabledsword.minstrel
import io.flutter.embedding.android.FlutterActivity
import android.content.Intent
import androidx.core.content.FileProvider
import com.ryanheise.audioservice.AudioServiceActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File
class MainActivity : FlutterActivity()
// Must extend AudioServiceActivity (not FlutterActivity) so the
// audio_service plugin can wire its FlutterEngine through. Without this
// the platform call from AudioService.init() throws PlatformException
// "The Activity class declared in your AndroidManifest.xml is wrong",
// which on first start cascades into a flutter_cache_manager sqlite
// EXCLUSIVE-lock crash because the engine partially re-initialises.
class MainActivity : AudioServiceActivity() {
companion object {
private const val INSTALLER_CHANNEL = "com.fabledsword.minstrel/installer"
}
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
// In-app update channel (#397). Dart calls install(path) with
// the cache-dir APK path; we hand it to Android's
// PackageInstaller via FileProvider + ACTION_VIEW.
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, INSTALLER_CHANNEL)
.setMethodCallHandler { call, result ->
when (call.method) {
"install" -> {
val path = call.argument<String>("path")
if (path == null) {
result.error("missing_path", "path argument required", null)
return@setMethodCallHandler
}
try {
installApk(path)
result.success(null)
} catch (e: Exception) {
result.error("install_failed", e.message, null)
}
}
else -> result.notImplemented()
}
}
}
private fun installApk(path: String) {
val file = File(path)
if (!file.exists()) {
throw IllegalStateException("apk not found at $path")
}
val uri = FileProvider.getUriForFile(
this,
"${packageName}.fileprovider",
file
)
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "application/vnd.android.package-archive")
// NEW_TASK: PackageInstaller runs in its own task.
// GRANT_READ_URI_PERMISSION: hands the content:// URI to
// the installer process, which lacks our app's read perms
// by default.
flags = Intent.FLAG_ACTIVITY_NEW_TASK or
Intent.FLAG_GRANT_READ_URI_PERMISSION
}
startActivity(intent)
}
}
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
FileProvider mappings for the in-app update flow (#397).
- cache-path/. exposes the app's getCacheDir() so the downloaded
APK at <cache>/minstrel-update.apk can be read by the
PackageInstaller via the content:// URI built in MainActivity.kt.
-->
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="updates" path="." />
</paths>
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Permits cleartext HTTP to 127.0.0.1 ONLY. Required because just_audio +
audio_service spin up a local HTTP proxy on loopback to inject the
Authorization header (Android's MediaSession API can't pass headers down
to ExoPlayer directly). Without this exemption, ExoPlayer hits Android's
cleartext block when connecting to the local proxy and audio playback
fails with "Cleartext HTTP traffic to 127.0.0.1 not permitted".
All other hosts inherit cleartextTrafficPermitted="false" — actual
remote traffic (to your Minstrel server) must still be HTTPS.
Loopback traffic doesn't leave the device, so this exemption doesn't
reduce security for real network endpoints.
-->
<network-security-config>
<base-config cleartextTrafficPermitted="false" />
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">127.0.0.1</domain>
</domain-config>
</network-security-config>
@@ -0,0 +1,66 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../shared/widgets/main_app_bar_actions.dart';
import '../theme/theme_extension.dart';
import 'admin_providers.dart';
import 'widgets/admin_section_card.dart';
class AdminLandingScreen extends ConsumerWidget {
const AdminLandingScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final counts = ref.watch(adminCountsProvider);
return Scaffold(
backgroundColor: fs.obsidian,
appBar: AppBar(
backgroundColor: fs.obsidian,
elevation: 0,
title: Text('Admin', style: TextStyle(color: fs.parchment)),
actions: const [MainAppBarActions(currentRoute: '/admin')],
),
body: SafeArea(
child: counts.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => Center(
child: Text('$e', style: TextStyle(color: fs.error)),
),
data: (c) => RefreshIndicator(
onRefresh: () async => ref.refresh(adminCountsProvider.future),
child: ListView(
children: [
AdminSectionCard(
key: const Key('admin_card_requests'),
icon: Icons.inbox,
title: 'Requests',
subtitle: 'Approve or reject Lidarr requests',
count: c.requests,
onTap: () => context.push('/admin/requests'),
),
AdminSectionCard(
key: const Key('admin_card_quarantine'),
icon: Icons.warning_amber,
title: 'Quarantine',
subtitle: 'Resolve scan failures',
count: c.quarantine,
onTap: () => context.push('/admin/quarantine'),
),
AdminSectionCard(
key: const Key('admin_card_users'),
icon: Icons.people,
title: 'Users',
subtitle: 'Manage accounts and invites',
count: c.users,
onTap: () => context.push('/admin/users'),
),
],
),
),
),
),
);
}
}
@@ -0,0 +1,237 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/endpoints/admin_invites.dart';
import '../api/endpoints/admin_quarantine.dart';
import '../api/endpoints/admin_requests.dart';
import '../api/endpoints/admin_users.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/admin_quarantine_item.dart';
import '../models/admin_request.dart';
import '../models/admin_user.dart';
import '../models/invite.dart';
final adminRequestsApiProvider = FutureProvider<AdminRequestsApi>((ref) async {
return AdminRequestsApi(await ref.watch(dioProvider.future));
});
final adminQuarantineApiProvider =
FutureProvider<AdminQuarantineApi>((ref) async {
return AdminQuarantineApi(await ref.watch(dioProvider.future));
});
final adminUsersApiProvider = FutureProvider<AdminUsersApi>((ref) async {
return AdminUsersApi(await ref.watch(dioProvider.future));
});
final adminInvitesApiProvider = FutureProvider<AdminInvitesApi>((ref) async {
return AdminInvitesApi(await ref.watch(dioProvider.future));
});
class AdminCounts {
const AdminCounts({
required this.requests,
required this.quarantine,
required this.users,
});
final int requests;
final int quarantine;
final int users;
}
/// Fans out to the three list endpoints in parallel and rolls them up
/// into `{requests, quarantine, users}` for the landing screen badges.
final adminCountsProvider = FutureProvider<AdminCounts>((ref) async {
final requestsApi = await ref.watch(adminRequestsApiProvider.future);
final quarantineApi = await ref.watch(adminQuarantineApiProvider.future);
final usersApi = await ref.watch(adminUsersApiProvider.future);
final results = await Future.wait([
requestsApi.list(),
quarantineApi.list(),
usersApi.list(),
]);
return AdminCounts(
requests: (results[0] as List).length,
quarantine: (results[1] as List).length,
users: (results[2] as List).length,
);
});
class AdminRequestsController extends AsyncNotifier<List<AdminRequest>> {
@override
Future<List<AdminRequest>> build() async {
final api = await ref.watch(adminRequestsApiProvider.future);
return api.list();
}
Future<void> approve(String id) async {
await _decide(id, (api) => api.approve(id));
}
Future<void> reject(String id) async {
await _decide(id, (api) => api.reject(id));
}
Future<void> _decide(
String id,
Future<void> Function(AdminRequestsApi api) action,
) async {
final api = await ref.read(adminRequestsApiProvider.future);
final current = state.value ?? const <AdminRequest>[];
state = AsyncData(current.where((r) => r.id != id).toList());
try {
await action(api);
// Refresh landing badge.
ref.invalidate(adminCountsProvider);
} catch (e, st) {
state = AsyncData(current);
Error.throwWithStackTrace(e, st);
}
}
}
final adminRequestsProvider =
AsyncNotifierProvider<AdminRequestsController, List<AdminRequest>>(
AdminRequestsController.new);
/// Read side originally defined for the Requests screen's
/// requester-UUID → username join. Mutation methods (setAdmin,
/// setAutoApprove, resetPassword, delete) added alongside the Users
/// screen in Slice 3. resetPassword is admin-supplies; the server
/// has no auto-generation mode.
class AdminUsersController extends AsyncNotifier<List<AdminUser>> {
@override
Future<List<AdminUser>> build() async {
final api = await ref.watch(adminUsersApiProvider.future);
return api.list();
}
/// Optimistic flip of `is_admin` on the user row; rolls back on
/// server error (including the last-admin guard 4xx).
Future<void> setAdmin(String id, bool isAdmin) =>
_patch(id, (u) => _copy(u, isAdmin: isAdmin),
(api) => api.setAdmin(id, isAdmin));
Future<void> setAutoApprove(String id, bool autoApprove) =>
_patch(id, (u) => _copy(u, autoApproveRequests: autoApprove),
(api) => api.setAutoApprove(id, autoApprove));
Future<void> delete(String id) async {
final api = await ref.read(adminUsersApiProvider.future);
final current = state.value ?? const <AdminUser>[];
state = AsyncData(current.where((u) => u.id != id).toList());
try {
await api.delete(id);
ref.invalidate(adminCountsProvider);
} catch (e, st) {
state = AsyncData(current);
Error.throwWithStackTrace(e, st);
}
}
Future<void> resetPassword(String id, String newPassword) async {
final api = await ref.read(adminUsersApiProvider.future);
await api.resetPassword(id, newPassword);
}
Future<void> _patch(
String id,
AdminUser Function(AdminUser) mutate,
Future<void> Function(AdminUsersApi api) action,
) async {
final api = await ref.read(adminUsersApiProvider.future);
final current = state.value ?? const <AdminUser>[];
state = AsyncData([
for (final u in current) u.id == id ? mutate(u) : u,
]);
try {
await action(api);
} catch (e, st) {
state = AsyncData(current);
Error.throwWithStackTrace(e, st);
}
}
AdminUser _copy(AdminUser u, {bool? isAdmin, bool? autoApproveRequests}) =>
AdminUser(
id: u.id,
username: u.username,
displayName: u.displayName,
isAdmin: isAdmin ?? u.isAdmin,
autoApproveRequests: autoApproveRequests ?? u.autoApproveRequests,
createdAt: u.createdAt,
);
}
final adminUsersProvider =
AsyncNotifierProvider<AdminUsersController, List<AdminUser>>(
AdminUsersController.new);
class AdminQuarantineController
extends AsyncNotifier<List<AdminQuarantineItem>> {
@override
Future<List<AdminQuarantineItem>> build() async {
final api = await ref.watch(adminQuarantineApiProvider.future);
return api.list();
}
Future<void> resolve(String trackId) =>
_act(trackId, (api) => api.resolve(trackId));
Future<void> deleteFile(String trackId) =>
_act(trackId, (api) => api.deleteFile(trackId));
Future<void> deleteViaLidarr(String trackId) =>
_act(trackId, (api) => api.deleteViaLidarr(trackId));
Future<void> _act(
String trackId,
Future<void> Function(AdminQuarantineApi api) action,
) async {
final api = await ref.read(adminQuarantineApiProvider.future);
final current = state.value ?? const <AdminQuarantineItem>[];
state = AsyncData(current.where((q) => q.trackId != trackId).toList());
try {
await action(api);
ref.invalidate(adminCountsProvider);
} catch (e, st) {
state = AsyncData(current);
Error.throwWithStackTrace(e, st);
}
}
}
final adminQuarantineProvider = AsyncNotifierProvider<AdminQuarantineController,
List<AdminQuarantineItem>>(AdminQuarantineController.new);
class AdminInvitesController extends AsyncNotifier<List<Invite>> {
@override
Future<List<Invite>> build() async {
final api = await ref.watch(adminInvitesApiProvider.future);
return api.list();
}
/// Returns the freshly-minted invite so the screen can show the
/// token in a copy-once dialog. The new invite is also prepended
/// to the local list so it shows up without a refresh.
Future<Invite> create({String? note}) async {
final api = await ref.read(adminInvitesApiProvider.future);
final invite = await api.create(note: note);
final current = state.value ?? const <Invite>[];
state = AsyncData([invite, ...current]);
return invite;
}
Future<void> revoke(String token) async {
final api = await ref.read(adminInvitesApiProvider.future);
final current = state.value ?? const <Invite>[];
state = AsyncData(current.where((i) => i.token != token).toList());
try {
await api.revoke(token);
} catch (e, st) {
state = AsyncData(current);
Error.throwWithStackTrace(e, st);
}
}
}
final adminInvitesProvider =
AsyncNotifierProvider<AdminInvitesController, List<Invite>>(
AdminInvitesController.new);
@@ -0,0 +1,67 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../shared/live_events_provider.dart';
import '../shared/widgets/main_app_bar_actions.dart';
import '../theme/theme_extension.dart';
import 'admin_providers.dart';
import 'widgets/admin_quarantine_row.dart';
class AdminQuarantineScreen extends ConsumerWidget {
const AdminQuarantineScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
// #402 wire-up: any quarantine event (flag from a user / admin
// resolve / file delete / lidarr delete) refreshes the admin queue.
ref.listen<AsyncValue<LiveEvent>>(liveEventsProvider, (_, next) {
final e = next.asData?.value;
if (e == null) return;
if (e.kind.startsWith('quarantine.')) {
ref.invalidate(adminQuarantineProvider);
}
});
final items = ref.watch(adminQuarantineProvider);
return Scaffold(
backgroundColor: fs.obsidian,
appBar: AppBar(
backgroundColor: fs.obsidian,
elevation: 0,
title: Text('Quarantine', style: TextStyle(color: fs.parchment)),
actions: const [MainAppBarActions(currentRoute: '/admin/quarantine')],
),
body: SafeArea(
child: items.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) =>
Center(child: Text('$e', style: TextStyle(color: fs.error))),
data: (rows) {
if (rows.isEmpty) {
return Center(
child: Text('No quarantined tracks.',
style: TextStyle(color: fs.ash)),
);
}
final notifier = ref.read(adminQuarantineProvider.notifier);
return RefreshIndicator(
onRefresh: () async =>
ref.refresh(adminQuarantineProvider.future),
child: ListView.builder(
itemCount: rows.length,
itemBuilder: (_, i) => AdminQuarantineRow(
key: Key('admin_quarantine_row_${rows[i].trackId}'),
item: rows[i],
onResolve: () => notifier.resolve(rows[i].trackId),
onDeleteFile: () => notifier.deleteFile(rows[i].trackId),
onDeleteViaLidarr: () =>
notifier.deleteViaLidarr(rows[i].trackId),
),
),
);
},
),
),
);
}
}
@@ -0,0 +1,81 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/admin_user.dart';
import '../shared/live_events_provider.dart';
import '../shared/widgets/main_app_bar_actions.dart';
import '../theme/theme_extension.dart';
import 'admin_providers.dart';
import 'widgets/admin_request_row.dart';
class AdminRequestsScreen extends ConsumerWidget {
const AdminRequestsScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
// #402 wire-up: invalidate the admin requests list when a user
// creates/cancels/admin approves/rejects/reconciler completes —
// request.status_changed covers all of them.
ref.listen<AsyncValue<LiveEvent>>(liveEventsProvider, (_, next) {
final e = next.asData?.value;
if (e?.kind == 'request.status_changed') {
ref.invalidate(adminRequestsProvider);
}
});
final requests = ref.watch(adminRequestsProvider);
// Best-effort lookup for requester usernames. If the users provider
// hasn't loaded yet, valueOrNull is null and rows fall back to the
// UUID prefix; no blocking spinner.
final users = ref.watch(adminUsersProvider).value ?? const <AdminUser>[];
final usersById = {for (final u in users) u.id: u};
return Scaffold(
backgroundColor: fs.obsidian,
appBar: AppBar(
backgroundColor: fs.obsidian,
elevation: 0,
title: Text('Requests', style: TextStyle(color: fs.parchment)),
actions: const [MainAppBarActions(currentRoute: '/admin/requests')],
),
body: SafeArea(
child: requests.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) =>
Center(child: Text('$e', style: TextStyle(color: fs.error))),
data: (rows) {
if (rows.isEmpty) {
return Center(
child: Text('No pending requests.',
style: TextStyle(color: fs.ash)),
);
}
final notifier = ref.read(adminRequestsProvider.notifier);
return RefreshIndicator(
onRefresh: () async =>
ref.refresh(adminRequestsProvider.future),
child: ListView.builder(
itemCount: rows.length,
itemBuilder: (_, i) {
final req = rows[i];
final user = usersById[req.userId];
final display = user?.username ??
(req.userId.length >= 8
? req.userId.substring(0, 8)
: req.userId);
return AdminRequestRow(
key: Key('admin_request_row_${req.id}'),
request: req,
requesterDisplay: display,
onApprove: () => notifier.approve(req.id),
onReject: () => notifier.reject(req.id),
);
},
),
);
},
),
),
);
}
}
@@ -0,0 +1,200 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../shared/widgets/main_app_bar_actions.dart';
import '../theme/theme_extension.dart';
import 'admin_providers.dart';
import 'widgets/admin_user_edit_sheet.dart';
import 'widgets/admin_user_row.dart';
import 'widgets/invite_row.dart';
class AdminUsersScreen extends ConsumerWidget {
const AdminUsersScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final users = ref.watch(adminUsersProvider);
final invites = ref.watch(adminInvitesProvider);
return Scaffold(
backgroundColor: fs.obsidian,
appBar: AppBar(
backgroundColor: fs.obsidian,
elevation: 0,
title: Text('Users', style: TextStyle(color: fs.parchment)),
actions: const [MainAppBarActions(currentRoute: '/admin/users')],
),
body: SafeArea(
child: RefreshIndicator(
onRefresh: () async {
ref.invalidate(adminUsersProvider);
ref.invalidate(adminInvitesProvider);
},
child: ListView(
children: [
const _SectionHeader(text: 'Users'),
users.when(
loading: () => const Padding(
padding: EdgeInsets.all(16),
child: Center(child: CircularProgressIndicator()),
),
error: (e, _) => Padding(
padding: const EdgeInsets.all(16),
child: Text('$e', style: TextStyle(color: fs.error)),
),
data: (rows) => Column(
children: rows
.map((u) => AdminUserRow(
key: Key('admin_user_row_${u.id}'),
user: u,
onTap: () => AdminUserEditSheet.show(context, u),
))
.toList(),
),
),
const Divider(),
_SectionHeader(
text: 'Invites',
trailing: TextButton.icon(
key: const Key('invite_generate_button'),
onPressed: () => _showGenerateInvite(context, ref),
icon: Icon(Icons.add, color: fs.parchment),
label: Text('Generate',
style: TextStyle(color: fs.parchment)),
),
),
invites.when(
loading: () => const Padding(
padding: EdgeInsets.all(16),
child: Center(child: CircularProgressIndicator()),
),
error: (e, _) => Padding(
padding: const EdgeInsets.all(16),
child: Text('$e', style: TextStyle(color: fs.error)),
),
data: (rows) => Column(
children: rows
.map((i) => InviteRow(
key: Key('invite_row_${i.token}'),
invite: i,
onRevoke: () => ref
.read(adminInvitesProvider.notifier)
.revoke(i.token),
))
.toList(),
),
),
],
),
),
),
);
}
Future<void> _showGenerateInvite(BuildContext context, WidgetRef ref) async {
final controller = TextEditingController();
final note = await showDialog<String?>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Generate invite'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Token expires in 24 hours.'),
const SizedBox(height: 12),
TextField(
controller: controller,
decoration: const InputDecoration(
labelText: 'Note (optional)',
helperText: 'e.g. "for alice"',
),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(ctx, controller.text),
child: const Text('Generate'),
),
],
),
);
if (note == null || !context.mounted) return;
try {
final invite = await ref
.read(adminInvitesProvider.notifier)
.create(note: note.isEmpty ? null : note);
if (!context.mounted) return;
await showDialog<void>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Invite created'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Share this token with the new user:'),
const SizedBox(height: 8),
SelectableText(
invite.token,
style: const TextStyle(fontFamily: 'JetBrainsMono'),
),
],
),
actions: [
TextButton(
onPressed: () {
Clipboard.setData(ClipboardData(text: invite.token));
Navigator.pop(ctx);
},
child: const Text('Copy'),
),
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('Close'),
),
],
),
);
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('$e')));
}
}
}
}
class _SectionHeader extends StatelessWidget {
const _SectionHeader({required this.text, this.trailing});
final String text;
final Widget? trailing;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Row(
children: [
Text(
text,
style: TextStyle(
color: fs.parchment,
fontFamily: 'Fraunces',
fontSize: 18,
),
),
const Spacer(),
if (trailing != null) trailing!,
],
),
);
}
}
@@ -0,0 +1,101 @@
import 'package:flutter/material.dart';
import '../../models/admin_quarantine_item.dart';
import '../../theme/theme_extension.dart';
import 'typed_confirm_sheet.dart';
class AdminQuarantineRow extends StatelessWidget {
const AdminQuarantineRow({
super.key,
required this.item,
required this.onResolve,
required this.onDeleteFile,
required this.onDeleteViaLidarr,
});
final AdminQuarantineItem item;
final VoidCallback onResolve;
final VoidCallback onDeleteFile;
final VoidCallback onDeleteViaLidarr;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return ExpansionTile(
key: Key('admin_quarantine_tile_${item.trackId}'),
title: Text(
item.trackTitle,
style: TextStyle(
color: fs.parchment,
fontFamily: 'Fraunces',
fontSize: 16,
),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('${item.artistName} · ${item.albumTitle}',
style: TextStyle(color: fs.ash)),
Text(
'${item.reportCount} '
'${item.reportCount == 1 ? "report" : "reports"} · ${item.topReasonSummary}',
style: TextStyle(color: fs.error, fontSize: 12),
),
],
),
trailing: PopupMenuButton<String>(
key: Key('admin_quarantine_menu_${item.trackId}'),
icon: Icon(Icons.more_vert, color: fs.parchment),
onSelected: (action) async {
switch (action) {
case 'resolve':
onResolve();
break;
case 'delete_file':
if (await TypedConfirmSheet.show(
context,
title: 'Delete file?',
message:
'Permanently delete the local file for "${item.trackTitle}". '
'Cannot be undone.',
)) {
onDeleteFile();
}
break;
case 'delete_lidarr':
if (await TypedConfirmSheet.show(
context,
title: 'Delete via Lidarr?',
message:
'Ask Lidarr to delete the file for "${item.trackTitle}".',
)) {
onDeleteViaLidarr();
}
break;
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'resolve', child: Text('Resolve')),
PopupMenuItem(value: 'delete_file', child: Text('Delete file')),
PopupMenuItem(
value: 'delete_lidarr', child: Text('Delete via Lidarr')),
],
),
childrenPadding: const EdgeInsets.only(left: 16, right: 16, bottom: 8),
children: [
for (final report in item.reports)
ListTile(
dense: true,
title: Text(
'${report.username}${report.reason}',
style: TextStyle(color: fs.parchment, fontSize: 13),
),
subtitle: report.notes != null
? Text(report.notes!,
style: TextStyle(color: fs.ash, fontSize: 12))
: null,
),
],
);
}
}
@@ -0,0 +1,75 @@
import 'package:flutter/material.dart';
import '../../models/admin_request.dart';
import '../../theme/theme_extension.dart';
class AdminRequestRow extends StatelessWidget {
const AdminRequestRow({
super.key,
required this.request,
required this.requesterDisplay,
required this.onApprove,
required this.onReject,
});
final AdminRequest request;
/// Pre-resolved username (or UUID-prefix fallback) for the requester.
final String requesterDisplay;
final VoidCallback onApprove;
final VoidCallback onReject;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final subtitle =
'${request.kind} · ${request.artistName} · requested by $requesterDisplay';
return ListTile(
title: Text(
request.displayName,
style: TextStyle(
color: fs.parchment,
fontFamily: 'Fraunces',
fontSize: 16,
),
),
subtitle: Text(subtitle, style: TextStyle(color: fs.ash)),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
TextButton(
onPressed: onApprove,
style: TextButton.styleFrom(foregroundColor: fs.moss),
child: const Text('Approve'),
),
TextButton(
onPressed: () async {
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Reject request?'),
content: Text('Reject "${request.displayName}"?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(ctx, true),
style: TextButton.styleFrom(foregroundColor: fs.oxblood),
child: const Text('Reject'),
),
],
),
);
if (ok == true) onReject();
},
style: TextButton.styleFrom(foregroundColor: fs.oxblood),
child: const Text('Reject'),
),
],
),
);
}
}
@@ -0,0 +1,53 @@
import 'package:flutter/material.dart';
import '../../theme/theme_extension.dart';
class AdminSectionCard extends StatelessWidget {
const AdminSectionCard({
super.key,
required this.icon,
required this.title,
required this.subtitle,
required this.count,
required this.onTap,
});
final IconData icon;
final String title;
final String subtitle;
final int count;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return Card(
color: fs.iron,
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: ListTile(
leading: Icon(icon, color: fs.parchment),
title: Text(
title,
style: TextStyle(
color: fs.parchment,
fontFamily: 'Fraunces',
fontSize: 18,
),
),
subtitle: Text(subtitle, style: TextStyle(color: fs.ash)),
trailing: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: fs.bronze,
borderRadius: BorderRadius.circular(12),
),
child: Text(
'$count',
style: TextStyle(color: fs.obsidian, fontWeight: FontWeight.w500),
),
),
onTap: onTap,
),
);
}
}
@@ -0,0 +1,167 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../models/admin_user.dart';
import '../../theme/theme_extension.dart';
import '../admin_providers.dart';
import 'typed_confirm_sheet.dart';
class AdminUserEditSheet extends ConsumerWidget {
const AdminUserEditSheet({super.key, required this.user});
final AdminUser user;
static Future<void> show(BuildContext context, AdminUser user) =>
showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (_) => AdminUserEditSheet(user: user),
);
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final users = ref.read(adminUsersProvider.notifier);
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
child: Container(
color: fs.iron,
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
user.username,
style: TextStyle(
color: fs.parchment,
fontFamily: 'Fraunces',
fontSize: 20,
),
),
const SizedBox(height: 12),
SwitchListTile(
key: const Key('user_edit_is_admin'),
title: Text('Admin', style: TextStyle(color: fs.parchment)),
value: user.isAdmin,
onChanged: (v) async {
try {
await users.setAdmin(user.id, v);
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('$e')));
}
}
},
),
SwitchListTile(
key: const Key('user_edit_auto_approve'),
title: Text('Auto-approve requests',
style: TextStyle(color: fs.parchment)),
value: user.autoApproveRequests,
onChanged: (v) async {
try {
await users.setAutoApprove(user.id, v);
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('$e')));
}
}
},
),
const SizedBox(height: 12),
Row(
children: [
TextButton(
key: const Key('user_edit_reset_password'),
onPressed: () => _resetPassword(context, users),
child: const Text('Reset password'),
),
const Spacer(),
TextButton(
key: const Key('user_edit_delete'),
style: TextButton.styleFrom(foregroundColor: fs.oxblood),
onPressed: () => _deleteUser(context, users),
child: const Text('Delete'),
),
],
),
],
),
),
);
}
Future<void> _resetPassword(
BuildContext context, AdminUsersController users) async {
final controller = TextEditingController();
final newPw = await showDialog<String>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Reset password'),
content: TextField(
controller: controller,
obscureText: true,
decoration: const InputDecoration(
labelText: 'New password',
helperText: 'Minimum 8 characters',
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
if (controller.text.length >= 8) {
Navigator.pop(ctx, controller.text);
}
},
child: const Text('Reset'),
),
],
),
);
if (newPw == null || !context.mounted) return;
try {
await users.resetPassword(user.id, newPw);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Password reset.')),
);
}
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('$e')));
}
}
}
Future<void> _deleteUser(
BuildContext context, AdminUsersController users) async {
if (!await TypedConfirmSheet.show(
context,
title: 'Delete user?',
message:
'Permanently delete user "${user.username}" and all their data. '
'Cannot be undone.',
)) {
return;
}
try {
await users.delete(user.id);
if (context.mounted) Navigator.pop(context);
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('$e')));
}
}
}
}
@@ -0,0 +1,58 @@
import 'package:flutter/material.dart';
import '../../models/admin_user.dart';
import '../../theme/theme_extension.dart';
class AdminUserRow extends StatelessWidget {
const AdminUserRow({super.key, required this.user, required this.onTap});
final AdminUser user;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return ListTile(
title: Text(
user.username,
style: TextStyle(
color: fs.parchment,
fontFamily: 'Fraunces',
fontSize: 16,
),
),
subtitle: Wrap(
spacing: 6,
children: [
if (user.isAdmin) _Badge(label: 'admin', color: fs.bronze),
if (user.autoApproveRequests)
_Badge(label: 'auto-approve', color: fs.moss),
],
),
trailing: Icon(Icons.chevron_right, color: fs.ash),
onTap: onTap,
);
}
}
class _Badge extends StatelessWidget {
const _Badge({required this.label, required this.color});
final String label;
final Color color;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(8),
),
child: Text(
label,
style: TextStyle(color: fs.obsidian, fontSize: 11),
),
);
}
}
@@ -0,0 +1,72 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../models/invite.dart';
import '../../theme/theme_extension.dart';
class InviteRow extends StatelessWidget {
const InviteRow({
super.key,
required this.invite,
required this.onRevoke,
});
final Invite invite;
final VoidCallback onRevoke;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return ListTile(
title: Row(
children: [
Expanded(
child: SelectableText(
invite.token,
style: TextStyle(
color: fs.parchment,
fontFamily: 'JetBrainsMono',
fontSize: 13,
),
),
),
IconButton(
icon: Icon(Icons.copy, color: fs.ash, size: 18),
tooltip: 'Copy',
onPressed: () =>
Clipboard.setData(ClipboardData(text: invite.token)),
),
],
),
subtitle: Wrap(
spacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text('expires ${invite.expiresAt}',
style: TextStyle(color: fs.ash, fontSize: 12)),
if (invite.note != null)
Text('· ${invite.note}',
style: TextStyle(color: fs.ash, fontSize: 12)),
if (invite.isRedeemed)
Container(
padding:
const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
decoration: BoxDecoration(
color: fs.ash,
borderRadius: BorderRadius.circular(6),
),
child: Text(
'redeemed',
style: TextStyle(color: fs.obsidian, fontSize: 10),
),
),
],
),
trailing: IconButton(
icon: Icon(Icons.delete_outline, color: fs.oxblood),
tooltip: 'Revoke',
onPressed: onRevoke,
),
);
}
}
@@ -0,0 +1,124 @@
import 'package:flutter/material.dart';
import '../../theme/theme_extension.dart';
/// Modal bottom sheet that requires the user to type [confirmWord]
/// (default "DELETE") before the confirm button enables. Used for
/// destructive actions like quarantine delete-file / delete-via-Lidarr
/// and user delete.
///
/// Returns true if the user confirmed, false (or null → false) otherwise.
class TypedConfirmSheet extends StatefulWidget {
const TypedConfirmSheet({
super.key,
required this.title,
required this.message,
this.confirmWord = 'DELETE',
this.confirmLabel = 'Delete',
});
final String title;
final String message;
final String confirmWord;
final String confirmLabel;
static Future<bool> show(
BuildContext context, {
required String title,
required String message,
String confirmWord = 'DELETE',
String confirmLabel = 'Delete',
}) async {
final ok = await showModalBottomSheet<bool>(
context: context,
isScrollControlled: true,
builder: (_) => TypedConfirmSheet(
title: title,
message: message,
confirmWord: confirmWord,
confirmLabel: confirmLabel,
),
);
return ok ?? false;
}
@override
State<TypedConfirmSheet> createState() => _TypedConfirmSheetState();
}
class _TypedConfirmSheetState extends State<TypedConfirmSheet> {
final _controller = TextEditingController();
bool _enabled = false;
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
child: Container(
color: fs.iron,
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.title,
style: TextStyle(
color: fs.parchment,
fontFamily: 'Fraunces',
fontSize: 20,
),
),
const SizedBox(height: 12),
Text(widget.message, style: TextStyle(color: fs.ash)),
const SizedBox(height: 16),
Text(
'Type ${widget.confirmWord} to confirm:',
style: TextStyle(color: fs.ash),
),
const SizedBox(height: 8),
TextField(
key: const Key('typed_confirm_input'),
controller: _controller,
autofocus: true,
style: TextStyle(color: fs.parchment, fontFamily: 'JetBrainsMono'),
decoration: const InputDecoration(border: OutlineInputBorder()),
onChanged: (v) =>
setState(() => _enabled = v == widget.confirmWord),
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
const SizedBox(width: 8),
ElevatedButton(
key: const Key('typed_confirm_button'),
onPressed:
_enabled ? () => Navigator.pop(context, true) : null,
style: ElevatedButton.styleFrom(
backgroundColor: fs.oxblood,
foregroundColor: fs.parchment,
),
child: Text(widget.confirmLabel),
),
],
),
],
),
),
);
}
}
@@ -0,0 +1,32 @@
import 'package:dio/dio.dart';
import '../../models/invite.dart';
class AdminInvitesApi {
AdminInvitesApi(this._dio);
final Dio _dio;
/// GET /api/admin/invites → `{"invites": [...]}`. Envelope unwrapped.
Future<List<Invite>> list() async {
final r = await _dio.get<Map<String, dynamic>>('/api/admin/invites');
final raw = (r.data?['invites'] as List?) ?? const [];
return raw
.map((e) => Invite.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false);
}
/// POST /api/admin/invites — body is optional `{"note": "..."}`.
/// Server hardcodes the 24h TTL; admins cannot configure expiry.
/// Returns the bare invite (not enveloped).
Future<Invite> create({String? note}) async {
final r = await _dio.post<Map<String, dynamic>>(
'/api/admin/invites',
data: {if (note != null && note.isNotEmpty) 'note': note},
);
return Invite.fromJson(r.data ?? const {});
}
Future<void> revoke(String token) async {
await _dio.delete<void>('/api/admin/invites/$token');
}
}
@@ -0,0 +1,31 @@
import 'package:dio/dio.dart';
import '../../models/admin_quarantine_item.dart';
class AdminQuarantineApi {
AdminQuarantineApi(this._dio);
final Dio _dio;
/// GET /api/admin/quarantine — flat list (no envelope) of aggregated
/// quarantine rows.
Future<List<AdminQuarantineItem>> list() async {
final r = await _dio.get<List<dynamic>>('/api/admin/quarantine');
final raw = r.data ?? const [];
return raw
.map((e) =>
AdminQuarantineItem.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false);
}
Future<void> resolve(String trackId) async {
await _dio.post<void>('/api/admin/quarantine/$trackId/resolve');
}
Future<void> deleteFile(String trackId) async {
await _dio.post<void>('/api/admin/quarantine/$trackId/delete-file');
}
Future<void> deleteViaLidarr(String trackId) async {
await _dio.post<void>('/api/admin/quarantine/$trackId/delete-via-lidarr');
}
}
@@ -0,0 +1,26 @@
import 'package:dio/dio.dart';
import '../../models/admin_request.dart';
class AdminRequestsApi {
AdminRequestsApi(this._dio);
final Dio _dio;
/// GET /api/admin/requests — flat list of pending requests.
/// Server defaults to ?status=pending; we don't override.
Future<List<AdminRequest>> list() async {
final r = await _dio.get<List<dynamic>>('/api/admin/requests');
final raw = r.data ?? const [];
return raw
.map((e) => AdminRequest.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false);
}
Future<void> approve(String id) async {
await _dio.post<void>('/api/admin/requests/$id/approve');
}
Future<void> reject(String id) async {
await _dio.post<void>('/api/admin/requests/$id/reject');
}
}
@@ -0,0 +1,47 @@
import 'package:dio/dio.dart';
import '../../models/admin_user.dart';
class AdminUsersApi {
AdminUsersApi(this._dio);
final Dio _dio;
/// GET /api/admin/users → `{"users": [...]}`. Envelope unwrapped here.
Future<List<AdminUser>> list() async {
final r = await _dio.get<Map<String, dynamic>>('/api/admin/users');
final raw = (r.data?['users'] as List?) ?? const [];
return raw
.map((e) => AdminUser.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false);
}
Future<void> setAdmin(String id, bool isAdmin) async {
await _dio.put<void>(
'/api/admin/users/$id/admin',
data: {'is_admin': isAdmin},
);
}
/// Server's body field is `auto_approve` (NOT `auto_approve_requests`)
/// — different from the response field name. Verified against
/// internal/api/admin_users.go `adminAutoApproveReq` (May 2026).
Future<void> setAutoApprove(String id, bool autoApprove) async {
await _dio.put<void>(
'/api/admin/users/$id/auto-approve',
data: {'auto_approve': autoApprove},
);
}
/// Admin supplies the new password; server returns 204. There is no
/// server-generated-password mode.
Future<void> resetPassword(String id, String newPassword) async {
await _dio.post<void>(
'/api/admin/users/$id/reset-password',
data: {'password': newPassword},
);
}
Future<void> delete(String id) async {
await _dio.delete<void>('/api/admin/users/$id');
}
}
@@ -0,0 +1,59 @@
import 'package:dio/dio.dart';
import '../../models/lidarr.dart';
class DiscoverApi {
DiscoverApi(this._dio);
final Dio _dio;
/// GET /api/lidarr/search?q=...&kind=artist|album|track. Server has a
/// 60s LRU cache for repeat queries so re-typing the same string in
/// quick succession is cheap.
Future<List<LidarrSearchResult>> search(
String query,
LidarrRequestKind kind,
) async {
final r = await _dio.get<List<dynamic>>(
'/api/lidarr/search',
queryParameters: {'q': query, 'kind': kind.wire},
);
final raw = r.data ?? const [];
return raw
.map((e) =>
LidarrSearchResult.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false);
}
/// POST /api/requests. Returns the newly-created LidarrRequest body
/// — we don't expose a typed wrapper for that yet on mobile (admin
/// reviews requests; user just kicks them off), so we discard the
/// response and surface success/failure to the caller.
Future<void> createRequest({
required LidarrRequestKind kind,
required String artistMbid,
required String artistName,
String? albumMbid,
String? albumTitle,
String? trackMbid,
String? trackTitle,
}) async {
final body = <String, dynamic>{
'kind': kind.wire,
'lidarr_artist_mbid': artistMbid,
'artist_name': artistName,
};
if (albumMbid != null && albumMbid.isNotEmpty) {
body['lidarr_album_mbid'] = albumMbid;
}
if (trackMbid != null && trackMbid.isNotEmpty) {
body['lidarr_track_mbid'] = trackMbid;
}
if (albumTitle != null && albumTitle.isNotEmpty) {
body['album_title'] = albumTitle;
}
if (trackTitle != null && trackTitle.isNotEmpty) {
body['track_title'] = trackTitle;
}
await _dio.post<Map<String, dynamic>>('/api/requests', data: body);
}
}
@@ -3,6 +3,7 @@ import 'package:dio/dio.dart';
import '../../models/album.dart';
import '../../models/artist.dart';
import '../../models/home_data.dart';
import '../../models/home_index.dart';
import '../../models/track.dart';
/// LibraryApi wraps the server's native /api/* library surface.
@@ -27,6 +28,24 @@ class LibraryApi {
return HomeData.fromJson(r.data ?? const {});
}
/// GET /api/home/index — per-item rendering variant. Returns just IDs
/// per section; client hydrates each tile via the per-entity
/// endpoints. ~10× smaller than /api/home on populated libraries so
/// the cold-visit round-trip is correspondingly short.
Future<HomeIndex> getHomeIndex() async {
final r = await _dio.get<Map<String, dynamic>>('/api/home/index');
return HomeIndex.fromJson(r.data ?? const {});
}
/// GET /api/tracks/{id}. Returns the canonical TrackRef. Used by
/// the HydrationQueue to populate cached_tracks on a per-tile miss
/// — the existing endpoint already joins album + artist so the
/// response carries everything TrackRef needs.
Future<TrackRef> getTrack(String id) async {
final r = await _dio.get<Map<String, dynamic>>('/api/tracks/$id');
return TrackRef.fromJson(r.data ?? const {});
}
/// GET /api/artists/{id}. Server returns ArtistDetail which embeds
/// ArtistRef inline; ArtistRef.fromJson already reads only the fields
/// it cares about, so passing the whole body is correct.
@@ -0,0 +1,36 @@
import 'package:dio/dio.dart';
import '../../models/album.dart';
import '../../models/artist.dart';
import '../../models/page.dart';
/// Paged library browse endpoints. Distinct from LibraryApi (which
/// fetches Home + entity detail) so screens that just need a flat
/// list don't drag in detail-page providers.
class LibraryListsApi {
LibraryListsApi(this._dio);
final Dio _dio;
Future<Paged<ArtistRef>> listArtists({int limit = 50, int offset = 0}) async {
// Server mounts the artists list at /api/artists (handleListArtists),
// not /api/library/artists. Albums use /api/library/albums for
// historical reasons; the paths aren't symmetric.
final r = await _dio.get<Map<String, dynamic>>(
'/api/artists',
queryParameters: {
'limit': limit,
'offset': offset,
'sort': 'alpha',
},
);
return Paged.fromJson(r.data ?? const {}, ArtistRef.fromJson);
}
Future<Paged<AlbumRef>> listAlbums({int limit = 50, int offset = 0}) async {
final r = await _dio.get<Map<String, dynamic>>(
'/api/library/albums',
queryParameters: {'limit': limit, 'offset': offset},
);
return Paged.fromJson(r.data ?? const {}, AlbumRef.fromJson);
}
}
@@ -1,5 +1,10 @@
import 'package:dio/dio.dart';
import '../../models/album.dart';
import '../../models/artist.dart';
import '../../models/page.dart';
import '../../models/track.dart';
enum LikeKind { artist, album, track }
extension LikeKindPath on LikeKind {
@@ -22,6 +27,31 @@ class LikesApi {
await _dio.delete<void>('/api/likes/${kind.path}/$id');
}
/// GET /api/likes/tracks?limit=N&offset=N. Paged.
Future<Paged<TrackRef>> listTracks({int limit = 50, int offset = 0}) async {
final r = await _dio.get<Map<String, dynamic>>(
'/api/likes/tracks',
queryParameters: {'limit': limit, 'offset': offset},
);
return Paged.fromJson(r.data ?? const {}, TrackRef.fromJson);
}
Future<Paged<AlbumRef>> listAlbums({int limit = 50, int offset = 0}) async {
final r = await _dio.get<Map<String, dynamic>>(
'/api/likes/albums',
queryParameters: {'limit': limit, 'offset': offset},
);
return Paged.fromJson(r.data ?? const {}, AlbumRef.fromJson);
}
Future<Paged<ArtistRef>> listArtists({int limit = 50, int offset = 0}) async {
final r = await _dio.get<Map<String, dynamic>>(
'/api/likes/artists',
queryParameters: {'limit': limit, 'offset': offset},
);
return Paged.fromJson(r.data ?? const {}, ArtistRef.fromJson);
}
/// Returns sets of {artists, albums, tracks} the user has liked.
/// Server response keys (verified in internal/api/likes.go
/// `likedIDsResponse`): `artist_ids`, `album_ids`, `track_ids`.
+49
View File
@@ -0,0 +1,49 @@
import 'package:dio/dio.dart';
import '../../models/history_event.dart';
import '../../models/quarantine_mine.dart';
import '../../models/system_playlists_status.dart';
/// /api/me/* endpoints — caller-scoped data (history, profile, etc.).
class MeApi {
MeApi(this._dio);
final Dio _dio;
/// GET /api/me/history. Paginated via offset/limit; server emits
/// `{events, has_more}` rather than the standard `Page<T>` envelope.
Future<HistoryPage> history({int limit = 50, int offset = 0}) async {
final r = await _dio.get<Map<String, dynamic>>(
'/api/me/history',
queryParameters: {'limit': limit, 'offset': offset},
);
return HistoryPage.fromJson(r.data ?? const {});
}
/// GET /api/quarantine/mine — flat list (no envelope).
Future<List<QuarantineMineRow>> quarantineMine() async {
final r = await _dio.get<List<dynamic>>('/api/quarantine/mine');
final raw = r.data ?? const [];
return raw
.map((e) =>
QuarantineMineRow.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false);
}
/// GET /api/me/system-playlists-status. Returns the caller's most
/// recent system-playlist build state. Used by the home Playlists
/// row to choose between real and placeholder cards.
Future<SystemPlaylistsStatus> systemPlaylistsStatus() async {
final r = await _dio.get<Map<String, dynamic>>(
'/api/me/system-playlists-status',
);
return SystemPlaylistsStatus.fromJson(r.data ?? const {});
}
/// PUT /api/me/timezone — submit the device's IANA timezone. The
/// scheduler uses this to fire the user's daily playlist build at
/// 03:00 in their local time. See AuthController._sendTimezoneIfStale
/// for the weekly cadence trigger.
Future<void> putTimezone(String timezone) async {
await _dio.put<void>('/api/me/timezone', data: {'timezone': timezone});
}
}
@@ -0,0 +1,56 @@
import 'package:dio/dio.dart';
import '../../models/playlist.dart';
/// Wire shape for GET /api/playlists. Server splits owned vs. public so
/// the UI can present them as different sections; we preserve that split
/// to give the integrations page room to grow.
class PlaylistsList {
const PlaylistsList({required this.owned, required this.public});
final List<Playlist> owned;
final List<Playlist> public;
factory PlaylistsList.empty() =>
const PlaylistsList(owned: [], public: []);
/// Concatenated view for callers that don't care about the split.
List<Playlist> get all => [...owned, ...public];
}
class PlaylistsApi {
PlaylistsApi(this._dio);
final Dio _dio;
/// GET /api/playlists?kind=user|system|all. Server returns
/// `{"owned": [...], "public": [...]}`. Owned is the caller's own
/// playlists, filtered by the kind param (default "user"). Public
/// is other users' shared playlists; not filtered by kind.
Future<PlaylistsList> list({String kind = 'user'}) async {
final r = await _dio.get<Map<String, dynamic>>(
'/api/playlists',
queryParameters: {'kind': kind},
);
final body = r.data ?? const <String, dynamic>{};
List<Playlist> parse(String key) {
final raw = (body[key] as List?) ?? const [];
return raw
.map((e) => Playlist.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false);
}
return PlaylistsList(owned: parse('owned'), public: parse('public'));
}
Future<PlaylistDetail> get(String id) async {
final r = await _dio.get<Map<String, dynamic>>('/api/playlists/$id');
return PlaylistDetail.fromJson(r.data ?? const {});
}
/// POST /api/playlists/{id}/tracks. Owner only; server returns the
/// playlist detail with the new rows.
Future<void> appendTracks(String playlistId, List<String> trackIds) async {
await _dio.post<void>(
'/api/playlists/$playlistId/tracks',
data: {'track_ids': trackIds},
);
}
}
@@ -0,0 +1,25 @@
import 'package:dio/dio.dart';
/// /api/quarantine — flag a track (with reason + optional notes) and
/// unflag it. Both endpoints are user-scoped: callers can only flag
/// their own quarantine entries; admins use a separate /admin/quarantine
/// surface.
class QuarantineApi {
QuarantineApi(this._dio);
final Dio _dio;
/// POST /api/quarantine. Server returns 201 with the row.
/// Reason values: bad_rip | wrong_file | wrong_tags | duplicate | other.
Future<void> flag(String trackId, String reason, {String notes = ''}) async {
await _dio.post<void>('/api/quarantine', data: {
'track_id': trackId,
'reason': reason,
'notes': notes,
});
}
/// DELETE /api/quarantine/{track_id}. Server returns 204.
Future<void> unflag(String trackId) async {
await _dio.delete<void>('/api/quarantine/$trackId');
}
}
@@ -0,0 +1,27 @@
import 'package:dio/dio.dart';
import '../../models/track.dart';
/// `GET /api/radio?seed_track=<uuid>&limit=<int>`. Returns the seed
/// at index 0 followed by up to `limit-1` weighted-shuffle picks
/// scored by the server's recommendation engine. The shape matches
/// what `playerActions.playTracks` expects, so a radio start is just
/// one fetch + one playTracks call.
class RadioApi {
RadioApi(this._dio);
final Dio _dio;
Future<List<TrackRef>> seedTrack(String trackId, {int? limit}) async {
final r = await _dio.get<Map<String, dynamic>>(
'/api/radio',
queryParameters: {
'seed_track': trackId,
if (limit != null) 'limit': limit,
},
);
final raw = (r.data?['tracks'] as List?) ?? const [];
return raw
.map((e) => TrackRef.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false);
}
}
@@ -0,0 +1,31 @@
import 'package:dio/dio.dart';
import '../../models/admin_request.dart';
/// User-side requests API — `/api/requests`. Server scopes results to
/// the caller; admins see only their own here, not all users'. The
/// admin-cross-user view lives in `/api/admin/requests` (AdminRequestsApi).
///
/// Wire shape is identical to the admin endpoint, so the same
/// AdminRequest model is reused.
class RequestsApi {
RequestsApi(this._dio);
final Dio _dio;
/// GET /api/requests — caller's own requests, all statuses.
Future<List<AdminRequest>> listMine() async {
final r = await _dio.get<List<dynamic>>('/api/requests');
final raw = r.data ?? const [];
return raw
.map((e) => AdminRequest.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false);
}
/// DELETE /api/requests/{id} — cancel a pending request. Server
/// returns the cancelled row body (not 204) so the caller can patch
/// local state without a refetch.
Future<AdminRequest> cancel(String id) async {
final r = await _dio.delete<Map<String, dynamic>>('/api/requests/$id');
return AdminRequest.fromJson(r.data ?? const {});
}
}
@@ -0,0 +1,29 @@
import 'package:dio/dio.dart';
import '../../models/search_response.dart';
/// SearchApi wraps GET /api/search. The server runs three facets (artists,
/// albums, tracks) sharing one limit/offset pair. Each facet returns its
/// own total reflecting the full match count.
class SearchApi {
SearchApi(this._dio);
final Dio _dio;
/// Empty / whitespace-only query is the caller's responsibility to
/// guard against — the server returns 400 bad_request for it.
Future<SearchResponse> search(
String query, {
int limit = 20,
int offset = 0,
}) async {
final r = await _dio.get<Map<String, dynamic>>(
'/api/search',
queryParameters: {
'q': query,
'limit': limit,
'offset': offset,
},
);
return SearchResponse.fromJson(r.data ?? const {});
}
}
@@ -0,0 +1,57 @@
import 'package:dio/dio.dart';
import '../../models/my_profile.dart';
class SettingsApi {
SettingsApi(this._dio);
final Dio _dio;
Future<MyProfile> getProfile() async {
final r = await _dio.get<Map<String, dynamic>>('/api/me');
return MyProfile.fromJson(r.data ?? const {});
}
/// Pass only the fields you want to change; server merges. Empty
/// strings clear; null leaves the existing value alone.
Future<MyProfile> updateProfile({String? displayName, String? email}) async {
final body = <String, dynamic>{};
if (displayName != null) body['display_name'] = displayName;
if (email != null) body['email'] = email;
final r = await _dio.put<Map<String, dynamic>>(
'/api/me/profile',
data: body,
);
return MyProfile.fromJson(r.data ?? const {});
}
Future<void> changePassword({
required String current,
required String next,
}) async {
await _dio.put<void>('/api/me/password', data: {
'current_password': current,
'new_password': next,
});
}
Future<ListenBrainzStatus> getListenBrainz() async {
final r = await _dio.get<Map<String, dynamic>>('/api/me/listenbrainz');
return ListenBrainzStatus.fromJson(r.data ?? const {});
}
Future<ListenBrainzStatus> setListenBrainzToken(String token) async {
final r = await _dio.put<Map<String, dynamic>>(
'/api/me/listenbrainz',
data: {'token': token},
);
return ListenBrainzStatus.fromJson(r.data ?? const {});
}
Future<ListenBrainzStatus> setListenBrainzEnabled(bool enabled) async {
final r = await _dio.put<Map<String, dynamic>>(
'/api/me/listenbrainz',
data: {'enabled': enabled},
);
return ListenBrainzStatus.fromJson(r.data ?? const {});
}
}
+41 -3
View File
@@ -1,18 +1,56 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'cache/metadata_prefetcher.dart';
import 'cache/prefetcher.dart';
import 'cache/sync_controller.dart';
import 'shared/live_events_dispatcher.dart';
import 'shared/routing.dart';
import 'theme/theme_data.dart';
import 'theme/theme_mode_provider.dart';
class MinstrelApp extends ConsumerWidget {
class MinstrelApp extends ConsumerStatefulWidget {
const MinstrelApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ConsumerState<MinstrelApp> createState() => _MinstrelAppState();
}
class _MinstrelAppState extends ConsumerState<MinstrelApp> {
@override
void initState() {
super.initState();
// Activate offline-mode infrastructure once the first frame ships.
// SyncController.sync() is connectivity-aware (no-ops on no auth /
// no server URL), so calling it unconditionally is safe.
// Reading prefetcherProvider runs its constructor, which wires the
// queue + settings listeners.
WidgetsBinding.instance.addPostFrameCallback((_) {
// ignore: unawaited_futures
ref.read(syncControllerProvider.notifier).sync();
ref.read(prefetcherProvider);
// Metadata prefetcher: when /api/home returns, fire background
// albumProvider/artistProvider reads for the top-N items in
// each section so subsequent taps are drift hits, not network
// round trips.
ref.read(metadataPrefetcherProvider);
// Live events (#392): subscribes to /api/events/stream and
// invalidates publicly-scoped providers when relevant events
// arrive. Also installs an AppLifecycleState observer for
// resume-time defensive invalidation.
ref.read(liveEventsDispatcherProvider);
});
}
@override
Widget build(BuildContext context) {
final router = ref.watch(routerProvider);
final mode = ref.watch(themeModeProvider).value ?? AppThemeMode.system;
return MaterialApp.router(
title: 'Minstrel',
theme: buildThemeData(),
theme: buildLightTheme(),
darkTheme: buildDarkTheme(),
themeMode: mode.materialMode,
routerConfig: router,
);
}
+37 -4
View File
@@ -2,12 +2,17 @@ import 'dart:convert';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_timezone/flutter_timezone.dart';
import '../api/endpoints/me.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/user.dart';
const _kServerUrl = 'server_url';
const _kSessionToken = 'session_token';
const _kCurrentUser = 'current_user';
const _kServerUrl = 'server_url';
const _kSessionToken = 'session_token';
const _kCurrentUser = 'current_user';
const _kTzLastSentAt = 'tz_last_sent_at';
const _weeklyMs = 7 * 24 * 60 * 60 * 1000;
final secureStorageProvider = Provider<FlutterSecureStorage>(
(ref) => const FlutterSecureStorage(),
@@ -29,7 +34,12 @@ class AuthController extends AsyncNotifier<User?> {
_storage = ref.watch(secureStorageProvider);
final raw = await _storage.read(key: _kCurrentUser);
if (raw == null) return null;
return User.fromJson(jsonDecode(raw) as Map<String, dynamic>);
final user = User.fromJson(jsonDecode(raw) as Map<String, dynamic>);
// Fire-and-forget timezone send on app start with an existing
// session — no-op when last_sent_at is fresh.
// ignore: unawaited_futures
_sendTimezoneIfStale();
return user;
}
Future<void> setServerUrl(String url) async {
@@ -42,6 +52,8 @@ class AuthController extends AsyncNotifier<User?> {
await _storage.write(key: _kCurrentUser, value: userJson);
ref.invalidate(sessionTokenProvider);
state = AsyncData(User.fromJson(jsonDecode(userJson) as Map<String, dynamic>));
// ignore: unawaited_futures
_sendTimezoneIfStale();
}
Future<void> clearSession() async {
@@ -50,6 +62,27 @@ class AuthController extends AsyncNotifier<User?> {
ref.invalidate(sessionTokenProvider);
state = const AsyncData(null);
}
/// Sends the device's current IANA timezone to PUT /api/me/timezone
/// when the last successful send was >7 days ago (or never).
/// Cadence persists in flutter_secure_storage so it survives app
/// restarts. Failures are swallowed: the server keeps its previous
/// value (or 'UTC' default) until the next attempt.
Future<void> _sendTimezoneIfStale() async {
try {
final lastStr = await _storage.read(key: _kTzLastSentAt);
final lastMs = lastStr == null ? 0 : int.tryParse(lastStr) ?? 0;
final nowMs = DateTime.now().millisecondsSinceEpoch;
if (nowMs - lastMs < _weeklyMs) return;
final tz = await FlutterTimezone.getLocalTimezone();
if (tz.isEmpty) return;
final dio = await ref.read(dioProvider.future);
await MeApi(dio).putTimezone(tz);
await _storage.write(key: _kTzLastSentAt, value: nowMs.toString());
} catch (_) {
// Non-fatal — server falls back to UTC or last-known value.
}
}
}
final authControllerProvider =
+133
View File
@@ -0,0 +1,133 @@
// Drift row → model adapters and reverse-write adapters for populating
// drift from REST responses (#357 plan C).
//
// The cache loses some server-derived fields:
// - ArtistRef.coverUrl (server computes from most-recent album)
// - AlbumRef.coverUrl (server-emitted derived path)
// - TrackRef.streamUrl (could be reconstructed but kept empty for clarity)
// UI already handles empty coverUrl/streamUrl gracefully. REST cold-cache
// fallback briefly shows the real values before drift takes over.
import 'package:drift/drift.dart' as drift;
import '../models/album.dart';
import '../models/artist.dart';
import '../models/playlist.dart';
import '../models/track.dart';
import 'db.dart';
extension CachedArtistAdapter on CachedArtist {
/// `coverAlbumId` lets the caller pass a representative album id so
/// the ArtistRef carries a reconstructed `/api/albums/<id>/cover`
/// URL. cached_artists doesn't store this directly — the server
/// derives it from the most-recent album at query time — so drift
/// readers that want the cover URL join cached_albums and pass the
/// first album's id through. Empty string yields empty coverUrl,
/// matching the server's behavior for endpoints that don't carry
/// the lookup (artist detail, search, raw cached_artists row reads).
ArtistRef toRef({String coverAlbumId = ''}) => ArtistRef(
id: id,
name: name,
sortName: sortName,
coverUrl: coverAlbumId.isNotEmpty
? '/api/albums/$coverAlbumId/cover'
: '',
);
}
extension ArtistRefDriftWrite on ArtistRef {
CachedArtistsCompanion toDrift() => CachedArtistsCompanion.insert(
id: id,
name: name,
sortName: sortName.isNotEmpty ? sortName : name,
);
}
extension CachedAlbumAdapter on CachedAlbum {
/// `artistName` is supplied by the joined CachedArtists row at query time.
/// `coverUrl` is reconstructed deterministically from the album id —
/// the server emits the same shape (see internal/api/convert.go:69).
/// We don't need to persist it, so AlbumRef.coverUrl is non-empty
/// even when the row was populated from a sync that didn't carry the
/// derived URL.
AlbumRef toRef({String artistName = ''}) => AlbumRef(
id: id,
title: title,
sortTitle: sortTitle,
artistId: artistId,
artistName: artistName,
coverUrl: '/api/albums/$id/cover',
);
}
extension AlbumRefDriftWrite on AlbumRef {
CachedAlbumsCompanion toDrift() => CachedAlbumsCompanion.insert(
id: id,
artistId: artistId,
title: title,
sortTitle: sortTitle.isNotEmpty ? sortTitle : title,
);
}
extension CachedTrackAdapter on CachedTrack {
/// `artistName` and `albumTitle` come from joined rows.
TrackRef toRef({String artistName = '', String albumTitle = ''}) => TrackRef(
id: id,
title: title,
albumId: albumId,
albumTitle: albumTitle,
artistId: artistId,
artistName: artistName,
trackNumber: trackNumber,
discNumber: discNumber,
durationSec: durationMs ~/ 1000,
);
}
extension TrackRefDriftWrite on TrackRef {
CachedTracksCompanion toDrift() => CachedTracksCompanion.insert(
id: id,
albumId: albumId,
artistId: artistId,
title: title,
durationMs: drift.Value(durationSec * 1000),
trackNumber: drift.Value(trackNumber),
discNumber: drift.Value(discNumber),
);
}
extension CachedPlaylistAdapter on CachedPlaylist {
/// `ownerUsername` is server-derived; cache stores the userId only.
/// Pass empty unless a join supplies it.
/// `coverUrl` is reconstructed deterministically from the playlist
/// id — the server serves the cached collage at this path
/// (handleGetPlaylistCover). Mirrors the album-cover trick. When
/// the server hasn't built a collage yet (system playlists with no
/// tracks at build time), the endpoint 404s and PlaylistCard's
/// ServerImage falls back to its slate placeholder.
Playlist toRef({String ownerUsername = ''}) => Playlist(
id: id,
userId: userId,
name: name,
description: description,
isPublic: isPublic,
systemVariant: systemVariant,
trackCount: trackCount,
coverUrl: '/api/playlists/$id/cover',
ownerUsername: ownerUsername,
createdAt: '',
updatedAt: '',
);
}
extension PlaylistDriftWrite on Playlist {
CachedPlaylistsCompanion toDrift() => CachedPlaylistsCompanion.insert(
id: id,
userId: userId,
name: name,
description: drift.Value(description),
isPublic: drift.Value(isPublic),
trackCount: drift.Value(trackCount),
systemVariant: drift.Value(systemVariant),
);
}
+199
View File
@@ -0,0 +1,199 @@
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:drift/drift.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:path_provider/path_provider.dart';
import '../library/library_providers.dart' show dioProvider;
import 'db.dart';
/// Owns the audio cache directory + drift index.
/// API:
/// - isCached(trackId)
/// - pathFor(trackId)
/// - pin(trackId, source) — downloads + indexes
/// - unpin(trackId)
/// - evict(targetBytes) — tiered LRU
/// - usageBytes()
/// - clearAll()
class AudioCacheManager {
AudioCacheManager({
required AppDb db,
required Future<Dio> Function() dioFactory,
Future<Directory> Function()? cacheDirFactory,
}) : _db = db,
_dioFactory = dioFactory,
_cacheDirFactory = cacheDirFactory ?? getApplicationCacheDirectory;
final AppDb _db;
final Future<Dio> Function() _dioFactory;
final Future<Directory> Function() _cacheDirFactory;
Future<String> _tracksDir() async {
final base = await _cacheDirFactory();
final d = Directory('${base.path}/audio_cache');
if (!await d.exists()) await d.create(recursive: true);
return d.path;
}
/// True if the trackId has a complete file on disk.
Future<bool> isCached(String trackId) async {
final row = await (_db.select(_db.audioCacheIndex)
..where((t) => t.trackId.equals(trackId)))
.getSingleOrNull();
if (row == null) return false;
return File(row.path).existsSync();
}
/// Returns the local file path if cached, else null.
Future<String?> pathFor(String trackId) async {
final row = await (_db.select(_db.audioCacheIndex)
..where((t) => t.trackId.equals(trackId)))
.getSingleOrNull();
if (row == null) return null;
return File(row.path).existsSync() ? row.path : null;
}
/// Downloads the track's stream to disk and indexes it. Idempotent —
/// returns the existing path if already cached.
Future<String?> pin(String trackId, {required CacheSource source}) async {
final existing = await pathFor(trackId);
if (existing != null) return existing;
final dir = await _tracksDir();
final path = '$dir/$trackId.mp3';
final dio = await _dioFactory();
try {
await dio.download('/api/tracks/$trackId/stream', path);
} catch (_) {
final f = File(path);
if (f.existsSync()) await f.delete();
return null;
}
final size = await File(path).length();
await _db.into(_db.audioCacheIndex).insertOnConflictUpdate(
AudioCacheIndexCompanion.insert(
trackId: trackId,
path: path,
sizeBytes: size,
source: source,
),
);
return path;
}
/// Registers a file already on disk in the cache index. Intended for
/// the streaming path (LockCachingAudioSource) which writes the file
/// itself; we need an index row so eviction can find and delete it
/// when usage exceeds the cap. `source` defaults to incidental so
/// stream-cached tracks are first to be evicted.
Future<void> registerStreamCache(
String trackId,
String path,
int sizeBytes, {
CacheSource source = CacheSource.incidental,
}) async {
await _db.into(_db.audioCacheIndex).insertOnConflictUpdate(
AudioCacheIndexCompanion.insert(
trackId: trackId,
path: path,
sizeBytes: sizeBytes,
source: source,
),
);
}
/// Removes a track from the index AND deletes the file.
Future<void> unpin(String trackId) async {
final row = await (_db.select(_db.audioCacheIndex)
..where((t) => t.trackId.equals(trackId)))
.getSingleOrNull();
if (row == null) return;
final f = File(row.path);
if (f.existsSync()) await f.delete();
await (_db.delete(_db.audioCacheIndex)
..where((t) => t.trackId.equals(trackId)))
.go();
}
/// Total bytes used by the cache. Walks the cache directory directly
/// instead of summing the index, because the streaming-as-you-play
/// path (audio_handler's LockCachingAudioSource) writes files
/// without registering an index row. The index sum would always
/// understate (often to zero) for users who only stream.
Future<int> usageBytes() async {
final dir = Directory(await _tracksDir());
if (!await dir.exists()) return 0;
var total = 0;
await for (final entity in dir.list(followLinks: false)) {
if (entity is File) {
try {
total += await entity.length();
} catch (_) {
// Race against concurrent writes / deletes — just skip.
}
}
}
return total;
}
/// Evicts files until usage ≤ targetBytes. Eviction order:
/// incidental → autoPrefetch → autoPlaylist → autoLiked.
/// `manual` never evicts via this path; only clearAll() removes them.
Future<void> evict({required int targetBytes}) async {
final used = await usageBytes();
if (used <= targetBytes) return;
final order = [
CacheSource.incidental,
CacheSource.autoPrefetch,
CacheSource.autoPlaylist,
CacheSource.autoLiked,
];
int remaining = used - targetBytes;
for (final src in order) {
if (remaining <= 0) break;
final rows = await (_db.select(_db.audioCacheIndex)
..where((t) => t.source.equalsValue(src))
..orderBy([(t) => OrderingTerm.asc(t.cachedAt)]))
.get();
for (final row in rows) {
if (remaining <= 0) break;
final f = File(row.path);
if (f.existsSync()) await f.delete();
await (_db.delete(_db.audioCacheIndex)
..where((t) => t.trackId.equals(row.trackId)))
.go();
remaining -= row.sizeBytes;
}
}
}
/// Clears EVERY row + EVERY file. Wired to the operator's "Clear cache"
/// button — `manual` source rows are removed here but only here.
Future<void> clearAll() async {
final dir = await _tracksDir();
final d = Directory(dir);
if (d.existsSync()) {
for (final entity in d.listSync()) {
if (entity is File) await entity.delete();
}
}
await _db.delete(_db.audioCacheIndex).go();
}
}
/// AppDb singleton. One per app run; ref.onDispose closes it.
final appDbProvider = Provider<AppDb>((ref) {
final db = AppDb();
ref.onDispose(db.close);
return db;
});
final audioCacheManagerProvider = Provider<AudioCacheManager>((ref) {
final db = ref.watch(appDbProvider);
return AudioCacheManager(
db: db,
dioFactory: () async => ref.read(dioProvider.future),
);
});
+88
View File
@@ -0,0 +1,88 @@
// Drift-first reactive read pattern with REST cold-cache fallback (#357 plan C).
//
// Subscribes to a drift watch() stream. On each emission:
// - non-empty → map to result type T and yield
// - empty + online → fetch via REST, populate drift, await re-emission
// - empty + offline → yield mapped empty result (UI shows empty state)
//
// With `alwaysRefresh: true`, also kicks off a one-shot REST refresh
// in the background after the first non-empty emission. Use for
// aggregate lists (playlists, etc.) where the server may have rows
// the local sync didn't pick up — yields cache immediately, refreshes
// silently, and drift watch() re-emits with whatever new rows landed.
//
// The pattern lets every read provider trust drift as the source of
// truth. SyncController keeps drift fresh in the background; widget
// rebuilds happen automatically as drift writes propagate via watch().
import 'dart:async';
import 'package:flutter/foundation.dart' show debugPrint;
// `tag` parameter is preserved for future ad-hoc instrumentation.
// Normal operation only logs failure paths so the per-screen log
// noise stays low.
/// Wraps the watch + cold-cache fallback pattern. Generic over:
/// D — the drift row type (or TypedResult for joins)
/// T — the result type the caller wants (e.g. `List<ArtistRef>`)
///
/// `fetchAndPopulate` is invoked when drift is empty AND `isOnline()`
/// returns true. It must populate drift via its own side-effect; the
/// drift watch() stream will re-emit and this helper yields the
/// populated rows on the next iteration.
///
/// REST failures are swallowed — the helper falls through to yielding
/// the empty result. Caller is responsible for surfacing errors via
/// toast etc.
Stream<T> cacheFirst<D, T>({
required Stream<List<D>> driftStream,
required Future<void> Function() fetchAndPopulate,
required T Function(List<D>) toResult,
required Future<bool> Function() isOnline,
bool alwaysRefresh = false,
String? tag,
}) async* {
// Tracks whether we've already kicked off a stale-while-revalidate
// refresh for this stream subscription, so we don't fire one on every
// drift re-emission (otherwise the populate cycles forever).
var revalidated = false;
await for (final rows in driftStream) {
if (rows.isNotEmpty) {
yield toResult(rows);
// Stale-while-revalidate: yield cache immediately, then kick off
// a REST refresh in the background. Drift watch() picks up the
// resulting writes and re-emits via this same stream loop.
// Useful for aggregate lists (e.g. playlists) where the server
// may have rows the local sync didn't pick up.
if (alwaysRefresh && !revalidated && await isOnline()) {
revalidated = true;
unawaited(_safeFetch(fetchAndPopulate));
}
continue;
}
if (await isOnline()) {
try {
await fetchAndPopulate();
// The drift watch() stream re-emits with the populated rows on
// the next loop iteration. Don't yield here.
} catch (e, st) {
if (tag != null) {
debugPrint('cacheFirst[$tag]: fetchAndPopulate failed: $e\n$st');
}
yield toResult(rows); // empty result; caller surfaces error
}
} else {
yield toResult(rows); // empty result; offline
}
}
}
Future<void> _safeFetch(Future<void> Function() fn) async {
try {
await fn();
} catch (_) {
// Background revalidate — swallow; UI already showed cached state.
}
}
+87
View File
@@ -0,0 +1,87 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import '../auth/auth_provider.dart' show secureStorageProvider;
/// Operator-tunable cache settings (#357 plan B). Persisted via
/// flutter_secure_storage on the same device.
class CacheSettings {
const CacheSettings({
required this.capBytes,
required this.prefetchWindow,
required this.cacheLikedTracks,
});
/// 0 = unlimited.
final int capBytes;
/// 1..10. Number of next-tracks the prefetcher pre-downloads.
final int prefetchWindow;
/// When true, every like_track event triggers a pin with source autoLiked.
final bool cacheLikedTracks;
CacheSettings copyWith({
int? capBytes,
int? prefetchWindow,
bool? cacheLikedTracks,
}) =>
CacheSettings(
capBytes: capBytes ?? this.capBytes,
prefetchWindow: prefetchWindow ?? this.prefetchWindow,
cacheLikedTracks: cacheLikedTracks ?? this.cacheLikedTracks,
);
static const defaults = CacheSettings(
capBytes: 5 * 1024 * 1024 * 1024,
prefetchWindow: 5,
cacheLikedTracks: true,
);
}
class CacheSettingsController extends AsyncNotifier<CacheSettings> {
static const _kCap = 'cache_cap_bytes';
static const _kPrefetch = 'cache_prefetch_window';
static const _kCacheLiked = 'cache_liked_tracks';
late FlutterSecureStorage _storage;
@override
Future<CacheSettings> build() async {
_storage = ref.read(secureStorageProvider);
final cap = await _storage.read(key: _kCap);
final pre = await _storage.read(key: _kPrefetch);
final liked = await _storage.read(key: _kCacheLiked);
return CacheSettings(
capBytes: cap == null
? CacheSettings.defaults.capBytes
: int.tryParse(cap) ?? CacheSettings.defaults.capBytes,
prefetchWindow: pre == null
? CacheSettings.defaults.prefetchWindow
: (int.tryParse(pre) ?? 5).clamp(1, 10),
cacheLikedTracks: liked == null
? CacheSettings.defaults.cacheLikedTracks
: liked == 'true',
);
}
Future<void> setCapBytes(int bytes) async {
await _storage.write(key: _kCap, value: bytes.toString());
state = AsyncData(state.value!.copyWith(capBytes: bytes));
}
Future<void> setPrefetchWindow(int n) async {
final clamped = n.clamp(1, 10);
await _storage.write(key: _kPrefetch, value: clamped.toString());
state = AsyncData(state.value!.copyWith(prefetchWindow: clamped));
}
Future<void> setCacheLikedTracks(bool on) async {
await _storage.write(key: _kCacheLiked, value: on.toString());
state = AsyncData(state.value!.copyWith(cacheLikedTracks: on));
}
}
final cacheSettingsProvider =
AsyncNotifierProvider<CacheSettingsController, CacheSettings>(
CacheSettingsController.new);
+35
View File
@@ -0,0 +1,35 @@
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
/// Online if at least one connectivity result is non-none.
/// connectivity_plus reports the union (wifi, mobile, vpn, etc.) — operator
/// chose "no Wi-Fi gate" for #357, so any connection means "go ahead and
/// pull/cache".
///
/// IMPORTANT: onConnectivityChanged only emits on *changes*, not on
/// subscription. Without seeding an initial value via checkConnectivity(),
/// any consumer using `ref.read(connectivityProvider.future)` would
/// block until the OS happened to report a connectivity flip — which
/// is exactly what made album/artist/playlist detail screens spin
/// forever for tiles tapped before the first event landed.
final connectivityProvider = StreamProvider<bool>((ref) async* {
final c = Connectivity();
bool isOnline(List<ConnectivityResult> rs) =>
rs.any((r) => r != ConnectivityResult.none);
// checkConnectivity() goes over a platform channel and on some
// Android builds it can stall. Fall back to "assume online" after
// 2s so consumers waiting on .future never block forever — being
// wrong about connectivity costs at most one failed request, but
// being stuck spins the UI indefinitely.
try {
final initial = await c.checkConnectivity().timeout(
const Duration(seconds: 2),
onTimeout: () => const [ConnectivityResult.wifi],
);
yield isOnline(initial);
} catch (_) {
yield true;
}
yield* c.onConnectivityChanged.map(isOnline);
});
+275
View File
@@ -0,0 +1,275 @@
// Drift database for Minstrel's offline cache (#357 plan B).
//
// Two cache layers in one database:
// - Metadata cache (CachedArtists, CachedAlbums, CachedTracks,
// CachedLikes, CachedPlaylists, CachedPlaylistTracks) — populated
// by SyncController via /api/library/sync
// - Audio cache index (AudioCacheIndex) — owned by AudioCacheManager
//
// Plus SyncMetadata holding the latest sync cursor.
//
// All entity ids are TEXT (server-side UUIDs serialized as strings).
// build_runner generates db.g.dart from this file; it's gitignored and
// regenerated in CI.
import 'package:drift/drift.dart';
import 'package:drift_flutter/drift_flutter.dart';
part 'db.g.dart';
class CachedArtists extends Table {
TextColumn get id => text()();
TextColumn get name => text()();
TextColumn get sortName => text()();
TextColumn get mbid => text().nullable()();
TextColumn get artistThumbPath => text().nullable()();
TextColumn get artistFanartPath => text().nullable()();
DateTimeColumn get fetchedAt => dateTime().withDefault(currentDateAndTime)();
@override
Set<Column> get primaryKey => {id};
}
class CachedAlbums extends Table {
TextColumn get id => text()();
TextColumn get artistId => text()();
TextColumn get title => text()();
TextColumn get sortTitle => text()();
TextColumn get releaseDate => text().nullable()();
TextColumn get coverPath => text().nullable()();
TextColumn get mbid => text().nullable()();
DateTimeColumn get fetchedAt => dateTime().withDefault(currentDateAndTime)();
@override
Set<Column> get primaryKey => {id};
}
class CachedTracks extends Table {
TextColumn get id => text()();
TextColumn get albumId => text()();
TextColumn get artistId => text()();
TextColumn get title => text()();
IntColumn get durationMs => integer().withDefault(const Constant(0))();
IntColumn get trackNumber => integer().nullable()();
IntColumn get discNumber => integer().nullable()();
TextColumn get filePath => text().nullable()();
TextColumn get fileFormat => text().nullable()();
TextColumn get genre => text().nullable()();
DateTimeColumn get fetchedAt => dateTime().withDefault(currentDateAndTime)();
@override
Set<Column> get primaryKey => {id};
}
class CachedLikes extends Table {
TextColumn get userId => text()();
TextColumn get entityType => text()(); // 'track' | 'album' | 'artist'
TextColumn get entityId => text()();
DateTimeColumn get likedAt => dateTime().withDefault(currentDateAndTime)();
@override
Set<Column> get primaryKey => {userId, entityType, entityId};
}
class CachedPlaylists extends Table {
TextColumn get id => text()();
TextColumn get userId => text()();
TextColumn get name => text()();
TextColumn get description => text().withDefault(const Constant(''))();
BoolColumn get isPublic => boolean().withDefault(const Constant(false))();
TextColumn get coverPath => text().nullable()();
IntColumn get trackCount => integer().withDefault(const Constant(0))();
IntColumn get durationSec => integer().withDefault(const Constant(0))();
/// Server's system_variant: null for user playlists, "for_you" /
/// "songs_like_artist" / "discover" for system-generated mixes.
/// Added in schemaVersion 2 to let the add-to-playlist sheet filter
/// out system playlists locally without a REST round-trip.
TextColumn get systemVariant => text().nullable()();
DateTimeColumn get fetchedAt => dateTime().withDefault(currentDateAndTime)();
@override
Set<Column> get primaryKey => {id};
}
class CachedPlaylistTracks extends Table {
TextColumn get playlistId => text()();
TextColumn get trackId => text()();
IntColumn get position => integer().withDefault(const Constant(0))();
@override
Set<Column> get primaryKey => {playlistId, trackId};
}
/// One row per fully-downloaded audio file. `source` drives tiered LRU
/// eviction; `incidental` evicts first, `manual` last.
class AudioCacheIndex extends Table {
TextColumn get trackId => text()();
TextColumn get path => text()();
IntColumn get sizeBytes => integer()();
DateTimeColumn get cachedAt => dateTime().withDefault(currentDateAndTime)();
TextColumn get source => textEnum<CacheSource>()();
@override
Set<Column> get primaryKey => {trackId};
}
/// Single-row table holding the latest sync cursor.
class SyncMetadata extends Table {
IntColumn get id => integer().withDefault(const Constant(1))();
IntColumn get cursor => integer().withDefault(const Constant(0))();
DateTimeColumn get lastSyncAt => dateTime().nullable()();
@override
Set<Column> get primaryKey => {id};
}
/// Single-row cache of the /api/home response (#357 follow-up). The
/// home screen is the first thing the user sees on app open; storing
/// the last successful HomeData as JSON lets us yield it immediately
/// before the REST round-trip resolves, eliminating the cold-start
/// blank on slow / remote connections. Schema 3+.
class CachedHomeSnapshot extends Table {
IntColumn get id => integer().withDefault(const Constant(1))();
TextColumn get json => text()();
DateTimeColumn get updatedAt => dateTime().withDefault(currentDateAndTime)();
@override
Set<Column> get primaryKey => {id};
}
/// Single-row cache of the /api/me/history response. Mirrors the
/// CachedHomeSnapshot pattern: opening the History tab in the Library
/// screen yields the last-known page immediately while a fresh REST
/// pull lands underneath via SWR. Also makes basic offline scrollback
/// possible — the last fetched page survives both app restart and
/// loss of connectivity. Schema 4+.
class CachedHistorySnapshot extends Table {
IntColumn get id => integer().withDefault(const Constant(1))();
TextColumn get json => text()();
DateTimeColumn get updatedAt => dateTime().withDefault(currentDateAndTime)();
@override
Set<Column> get primaryKey => {id};
}
/// Single-row cache of the /api/me/system-playlists-status response.
/// The home Playlists row reads this every render to pick between
/// real cards and placeholder cards for For-You / Discover / Songs-
/// like slots, so a fresh-mount cold fetch produces a visible
/// "building / pending / failed" flicker. Storing the last result
/// as a JSON blob means the home renders with the prior status
/// instantly, then SWR refreshes underneath. Schema 7+.
class CachedSystemPlaylistsStatus extends Table {
IntColumn get id => integer().withDefault(const Constant(1))();
TextColumn get json => text()();
DateTimeColumn get updatedAt => dateTime().withDefault(currentDateAndTime)();
@override
Set<Column> get primaryKey => {id};
}
/// Section→position→entity-id index for the home screen, populated
/// from the per-item discovery endpoint `/api/home/index`. Each row
/// pins one tile slot to an entity; the actual entity data lives in
/// cached_albums / cached_artists / cached_tracks. The home screen
/// reads this table to know the layout, then hydrates each tile
/// against the entity tables (per-item rendering). Schema 6+.
class CachedHomeIndex extends Table {
/// One of: 'recently_added_albums', 'rediscover_albums',
/// 'rediscover_artists', 'most_played_tracks', 'last_played_artists'.
/// Mirrors the keys /api/home and /api/home/index emit.
TextColumn get section => text()();
IntColumn get position => integer()();
/// One of: 'album', 'artist', 'track'. Used to dispatch hydration
/// to the right per-entity endpoint.
TextColumn get entityType => text()();
TextColumn get entityId => text()();
DateTimeColumn get fetchedAt => dateTime().withDefault(currentDateAndTime)();
@override
Set<Column> get primaryKey => {section, position};
}
/// Caller-scoped quarantine ("hidden") rows. Mirrors the wire shape of
/// /api/quarantine/mine — fully denormalized (track + album + artist
/// fields inline) because the Hidden tab renders straight from this row
/// without joining other tables. Columnar (vs JSON blob) so flag/unflag
/// can do row-level INSERT/DELETE; the drift watch() emission feeds
/// MyQuarantineController state directly. Schema 5+.
class CachedQuarantineMine extends Table {
TextColumn get trackId => text()();
TextColumn get reason => text()();
TextColumn get notes => text().nullable()();
TextColumn get createdAt => text()();
TextColumn get trackTitle => text()();
IntColumn get trackDurationMs => integer().withDefault(const Constant(0))();
TextColumn get albumId => text()();
TextColumn get albumTitle => text()();
TextColumn get albumCoverArtPath => text().nullable()();
TextColumn get artistId => text()();
TextColumn get artistName => text()();
DateTimeColumn get fetchedAt => dateTime().withDefault(currentDateAndTime)();
@override
Set<Column> get primaryKey => {trackId};
}
enum CacheSource { manual, autoLiked, autoPlaylist, autoPrefetch, incidental }
@DriftDatabase(tables: [
CachedArtists,
CachedAlbums,
CachedTracks,
CachedLikes,
CachedPlaylists,
CachedPlaylistTracks,
AudioCacheIndex,
SyncMetadata,
CachedHomeSnapshot,
CachedHistorySnapshot,
CachedQuarantineMine,
CachedHomeIndex,
CachedSystemPlaylistsStatus,
])
class AppDb extends _$AppDb {
AppDb([QueryExecutor? e]) : super(e ?? driftDatabase(name: 'minstrel_cache'));
@override
int get schemaVersion => 7;
@override
MigrationStrategy get migration => MigrationStrategy(
onCreate: (m) => m.createAll(),
onUpgrade: (m, from, to) async {
if (from < 2) {
// Schema 2: add CachedPlaylists.systemVariant. Existing
// rows get null and the next sync rebuilds them with the
// server's system_variant value.
await m.addColumn(cachedPlaylists, cachedPlaylists.systemVariant);
// Reset cursor so the next /api/library/sync re-emits all
// playlists; otherwise the new column would stay null on
// pre-existing rows until they happen to change server-side.
await customStatement('UPDATE sync_metadata SET cursor = 0');
}
if (from < 3) {
// Schema 3: cached_home_snapshot for #357 drift-first
// home page. No existing rows to migrate — table starts
// empty; the first /api/home fetch populates it.
await m.createTable(cachedHomeSnapshot);
}
if (from < 4) {
// Schema 4: cached_history_snapshot for drift-first
// History tab. Same pattern as cached_home_snapshot —
// empty on upgrade; first /api/me/history fetch populates.
await m.createTable(cachedHistorySnapshot);
}
if (from < 5) {
// Schema 5: cached_quarantine_mine for drift-first Hidden
// tab. Empty on upgrade; first /api/quarantine/mine fetch
// populates. Optimistic flag/unflag also writes here.
await m.createTable(cachedQuarantineMine);
}
if (from < 6) {
// Schema 6: cached_home_index for per-item rendering.
// Empty on upgrade; first /api/home/index fetch populates.
// cached_home_snapshot stays in place for now — older
// builds still read from it as a fallback path.
await m.createTable(cachedHomeIndex);
}
if (from < 7) {
// Schema 7: cached_system_playlists_status. Single-row
// snapshot of /api/me/system-playlists-status used by the
// home Playlists row. Empty on upgrade; first fetch
// populates.
await m.createTable(cachedSystemPlaylistsStatus);
}
},
);
}
+139
View File
@@ -0,0 +1,139 @@
// Per-item hydration coordinator for the home/playlist/liked surfaces.
//
// Tile widgets are reactive to their per-entity drift row. On first
// build, if drift has no row for the requested id, the tile asks this
// queue to hydrate it. The queue dispatches one /api/<type>/:id
// request, writes the result to drift, and the drift watch() on the
// tile re-emits with the populated row.
//
// Concurrency cap: HydrationQueue limits the number of in-flight
// requests so a 50-tile home screen doesn't fire 50 parallel /api/
// calls and stall the auth-token-bound dio pool. In-flight dedup
// (keyed by `<type>:<id>`) ensures a single hydration when multiple
// tiles share an entity (rare on home, common when several screens
// reference the same album).
//
// Failures are swallowed — a single failed hydration leaves the tile
// in skeleton state. A future retry-on-visit pass can layer on top
// without changing the queue's contract.
import 'dart:async';
import 'dart:collection';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../cache/adapters.dart';
import '../cache/audio_cache_manager.dart' show appDbProvider;
import '../library/library_providers.dart' show libraryApiProvider;
/// Bounded-concurrency request queue for per-entity hydration. One
/// instance per Riverpod scope (provider singleton below).
class HydrationQueue {
HydrationQueue(this._ref);
final Ref _ref;
/// Concurrent slot count. 4 keeps the dio token pool from saturating
/// while still pulling tiles down faster than a serial loop. Bump
/// if profiling shows the queue idle while the network is healthy.
static const _maxConcurrent = 4;
final Queue<_HydrationRequest> _pending = Queue();
final Set<String> _inFlightKeys = {};
int _inFlight = 0;
/// Request hydration for (entityType, entityId). Idempotent — second
/// call for the same key while the first is queued or in flight is
/// dropped, so multiple tile rebuilds during a fast scroll don't
/// inflate the queue.
void enqueue({required String entityType, required String entityId}) {
if (entityId.isEmpty) return;
final key = '$entityType:$entityId';
if (_inFlightKeys.contains(key)) return;
if (_pending.any((r) => r.key == key)) return;
_pending.add(_HydrationRequest(
entityType: entityType, entityId: entityId, key: key));
_pump();
}
void _pump() {
while (_inFlight < _maxConcurrent && _pending.isNotEmpty) {
final req = _pending.removeFirst();
_inFlightKeys.add(req.key);
_inFlight++;
// Unawaited on purpose — _pump returns immediately so further
// enqueues can fill remaining slots while this one runs.
unawaited(_execute(req).whenComplete(() {
_inFlight--;
_inFlightKeys.remove(req.key);
_pump();
}));
}
}
Future<void> _execute(_HydrationRequest req) async {
try {
switch (req.entityType) {
case 'album':
await _hydrateAlbum(req.entityId);
case 'artist':
await _hydrateArtist(req.entityId);
case 'track':
await _hydrateTrack(req.entityId);
}
} catch (_) {
// Swallow — tile stays in skeleton. A retry-on-visit pass can
// layer on top later without changing this contract.
}
}
Future<void> _hydrateAlbum(String id) async {
final api = await _ref.read(libraryApiProvider.future);
final result = await api.getAlbum(id);
final db = _ref.read(appDbProvider);
// Album + tracks come bundled in the same response; persist both
// so opening the album detail later is also a drift hit.
await db.transaction(() async {
await db
.into(db.cachedAlbums)
.insertOnConflictUpdate(result.album.toDrift());
if (result.tracks.isNotEmpty) {
await db.batch((b) {
b.insertAllOnConflictUpdate(
db.cachedTracks, result.tracks.map((t) => t.toDrift()).toList());
});
}
});
}
Future<void> _hydrateArtist(String id) async {
final api = await _ref.read(libraryApiProvider.future);
final fresh = await api.getArtist(id);
final db = _ref.read(appDbProvider);
await db.into(db.cachedArtists).insertOnConflictUpdate(fresh.toDrift());
}
Future<void> _hydrateTrack(String id) async {
final api = await _ref.read(libraryApiProvider.future);
final fresh = await api.getTrack(id);
final db = _ref.read(appDbProvider);
await db.into(db.cachedTracks).insertOnConflictUpdate(fresh.toDrift());
}
}
class _HydrationRequest {
_HydrationRequest({
required this.entityType,
required this.entityId,
required this.key,
});
final String entityType;
final String entityId;
final String key;
}
/// Singleton queue scoped to the Riverpod container. Kept as a plain
/// Provider (not StateProvider) since the queue's internal state is
/// pump-driven, not reactively observed.
final hydrationQueueProvider = Provider<HydrationQueue>((ref) {
return HydrationQueue(ref);
});
+74
View File
@@ -0,0 +1,74 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../library/library_providers.dart';
import '../models/home_data.dart';
/// Pre-warms the drift cache for likely-tap targets. Conservative on
/// purpose: only warms artistProvider rows (single row, single round
/// trip per id) and only ever fires once per id per session. Album
/// detail is NOT prewarmed — the albumProvider auto-fetches its track
/// list when missing, and pre-warming N albums fans out N parallel
/// "fetch tracks" round trips that compete with the user's actual
/// playback request for bandwidth.
class MetadataPrefetcher {
MetadataPrefetcher(this._ref) {
_ref.listen<AsyncValue<HomeData>>(homeProvider, (_, next) {
next.whenData(_warmHome);
});
}
final Ref _ref;
/// Per-session dedupe so re-rendering a screen (every UI rebuild
/// fires the data: callback) doesn't trigger N more fetches for
/// ids we've already warmed.
final Set<String> _warmedArtists = {};
/// Cap per section. Covers what fits on screen without scrolling.
static const _topN = 8;
/// Pre-warm artists. Albums are intentionally not pre-warmed —
/// see class comment.
void warmArtists(Iterable<String> ids) {
var n = 0;
for (final id in ids) {
if (id.isEmpty) continue;
if (!_warmedArtists.add(id)) continue; // already warmed
if (n++ >= _topN) break;
_swallow(_ref.read(artistProvider(id).future));
}
}
void _warmHome(HomeData h) {
final artistIds = <String>{};
for (final a in h.recentlyAddedAlbums.take(_topN)) {
if (a.artistId.isNotEmpty) artistIds.add(a.artistId);
}
for (final a in h.rediscoverAlbums.take(_topN)) {
if (a.artistId.isNotEmpty) artistIds.add(a.artistId);
}
for (final ar in h.rediscoverArtists.take(_topN)) {
if (ar.id.isNotEmpty) artistIds.add(ar.id);
}
for (final ar in h.lastPlayedArtists.take(_topN)) {
if (ar.id.isNotEmpty) artistIds.add(ar.id);
}
for (final t in h.mostPlayedTracks.take(_topN)) {
if (t.artistId.isNotEmpty) artistIds.add(t.artistId);
}
warmArtists(artistIds);
}
/// Discards the return value and any error from a fire-and-forget
/// provider read. We don't care about the value here — we only want
/// the side effect of writing drift.
void _swallow(Future<Object?> f) {
f.then<void>((_) {}).onError((_, __) {});
}
}
/// Read once at app start to activate the prefetcher (e.g. wire it
/// from a top-level Consumer or main.dart container override).
final metadataPrefetcherProvider = Provider<MetadataPrefetcher>((ref) {
return MetadataPrefetcher(ref);
});
+63
View File
@@ -0,0 +1,63 @@
import 'package:audio_service/audio_service.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../player/player_provider.dart';
import 'audio_cache_manager.dart';
import 'cache_settings_provider.dart';
import 'db.dart';
/// Listens to the player's currently-playing track. When it changes,
/// computes the next-N tracks ahead in the queue and pins them via
/// AudioCacheManager (source: autoPrefetch). After pinning, runs an
/// eviction pass against the operator-set cap.
///
/// The window N comes from cacheSettingsProvider.prefetchWindow
/// (default 5, configurable in Settings).
class Prefetcher {
Prefetcher(this._ref) {
// The mediaItem stream changes whenever the active track changes
// (skipNext/skipPrev or natural progression). Settings changes (e.g.
// operator bumps prefetch window) also trigger a reconcile.
_ref.listen<AsyncValue<MediaItem?>>(mediaItemProvider, (_, __) => _reconcile());
_ref.listen<AsyncValue<CacheSettings>>(cacheSettingsProvider, (_, __) => _reconcile());
}
final Ref _ref;
Future<void> _reconcile() async {
final settings = _ref.read(cacheSettingsProvider).value;
if (settings == null) return;
final queue = _ref.read(queueProvider).value ?? const <MediaItem>[];
final current = _ref.read(mediaItemProvider).value;
if (queue.isEmpty || current == null) return;
final currentIdx = queue.indexWhere((m) => m.id == current.id);
if (currentIdx < 0) return;
final endIdx =
(currentIdx + settings.prefetchWindow).clamp(0, queue.length - 1);
final mgr = _ref.read(audioCacheManagerProvider);
for (var i = currentIdx; i <= endIdx; i++) {
final trackId = queue[i].id;
if (await mgr.isCached(trackId)) continue;
// Fire-and-forget; downloads happen in the background. Errors
// inside pin() are caught + cleaned up internally.
// ignore: unawaited_futures
mgr.pin(trackId, source: CacheSource.autoPrefetch);
}
// Eviction pass after pinning new files.
if (settings.capBytes > 0) {
await mgr.evict(targetBytes: settings.capBytes);
}
}
}
/// Read this provider once at app start to activate the prefetcher.
/// Constructor wires the listeners.
final prefetcherProvider = Provider<Prefetcher>((ref) {
return Prefetcher(ref);
});
+360
View File
@@ -0,0 +1,360 @@
import 'dart:async';
import 'package:drift/drift.dart' as drift;
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../auth/auth_provider.dart' show serverUrlProvider, sessionTokenProvider;
import '../library/library_providers.dart' show dioProvider;
import 'audio_cache_manager.dart' show appDbProvider;
import 'db.dart';
/// Counts returned from a sync operation. Surfaced to the operator-
/// facing "Sync now" button + Settings card.
class SyncResult {
const SyncResult({
required this.upserts,
required this.deletes,
required this.cursor,
});
final int upserts;
final int deletes;
final int cursor;
}
/// Drives the delta-sync against the server (#357 Plan A endpoint).
/// Reads cursor from drift, calls `/api/library/sync?since={cursor}`,
/// applies upserts + deletes, advances cursor.
class SyncController extends AsyncNotifier<SyncResult?> {
@override
Future<SyncResult?> build() async => null;
Future<SyncResult?> sync() async {
state = const AsyncLoading();
try {
final db = ref.read(appDbProvider);
final dio = await ref.read(dioProvider.future);
final meta = await db.select(db.syncMetadata).getSingleOrNull();
final cursor = meta?.cursor ?? 0;
final resp = await dio.get<dynamic>(
'/api/library/sync',
queryParameters: {'since': cursor},
);
// 204 No Content — no changes since cursor.
if (resp.statusCode == 204) {
await db.into(db.syncMetadata).insertOnConflictUpdate(
SyncMetadataCompanion.insert(
lastSyncAt: drift.Value(DateTime.now()),
),
);
final r = SyncResult(upserts: 0, deletes: 0, cursor: cursor);
state = AsyncData(r);
return r;
}
// 410 Gone — cursor too old, server has compacted past it. Reset
// local state and retry once with cursor=0.
if (resp.statusCode == 410) {
await db.transaction(() async {
await db.delete(db.cachedArtists).go();
await db.delete(db.cachedAlbums).go();
await db.delete(db.cachedTracks).go();
await db.delete(db.cachedLikes).go();
await db.delete(db.cachedPlaylists).go();
await db.delete(db.cachedPlaylistTracks).go();
await db.into(db.syncMetadata).insertOnConflictUpdate(
SyncMetadataCompanion.insert(cursor: const drift.Value(0)),
);
});
return sync();
}
final body = resp.data as Map<String, dynamic>;
final newCursor = (body['cursor'] as num).toInt();
final upserts = body['upserts'] as Map<String, dynamic>? ?? {};
final deletes = body['deletes'] as Map<String, dynamic>? ?? {};
var upsertCount = 0;
var deleteCount = 0;
// IDs of upserted entities whose covers we'll pre-warm after the
// transaction commits. Filled inside the loops; consumed by
// _prewarmCovers fire-and-forget below. Artist covers are
// server-derived from "most-recent album" and aren't
// reconstructible client-side — album pre-warm already covers an
// artist's primary visual via its detail-page header.
final albumCoverIds = <String>[];
final playlistCoverIds = <String>[];
await db.transaction(() async {
// ---- Upserts ----
for (final a in (upserts['artist'] as List? ?? const [])) {
await db.into(db.cachedArtists).insertOnConflictUpdate(
_artistFromJson(a as Map<String, dynamic>),
);
upsertCount++;
}
for (final a in (upserts['album'] as List? ?? const [])) {
final m = a as Map<String, dynamic>;
await db.into(db.cachedAlbums).insertOnConflictUpdate(
_albumFromJson(m),
);
final id = m['id'];
if (id is String && id.isNotEmpty) albumCoverIds.add(id);
upsertCount++;
}
for (final t in (upserts['track'] as List? ?? const [])) {
await db.into(db.cachedTracks).insertOnConflictUpdate(
_trackFromJson(t as Map<String, dynamic>),
);
upsertCount++;
}
for (final l in (upserts['like_track'] as List? ?? const [])) {
final m = l as Map<String, dynamic>;
await db.into(db.cachedLikes).insertOnConflictUpdate(
CachedLikesCompanion.insert(
userId: m['user_id'] as String,
entityType: 'track',
entityId: m['track_id'] as String,
),
);
upsertCount++;
}
for (final l in (upserts['like_album'] as List? ?? const [])) {
final m = l as Map<String, dynamic>;
await db.into(db.cachedLikes).insertOnConflictUpdate(
CachedLikesCompanion.insert(
userId: m['user_id'] as String,
entityType: 'album',
entityId: m['album_id'] as String,
),
);
upsertCount++;
}
for (final l in (upserts['like_artist'] as List? ?? const [])) {
final m = l as Map<String, dynamic>;
await db.into(db.cachedLikes).insertOnConflictUpdate(
CachedLikesCompanion.insert(
userId: m['user_id'] as String,
entityType: 'artist',
entityId: m['artist_id'] as String,
),
);
upsertCount++;
}
for (final p in (upserts['playlist'] as List? ?? const [])) {
final m = p as Map<String, dynamic>;
await db.into(db.cachedPlaylists).insertOnConflictUpdate(
_playlistFromJson(m),
);
final id = m['id'];
if (id is String && id.isNotEmpty) playlistCoverIds.add(id);
upsertCount++;
}
for (final pt in (upserts['playlist_track'] as List? ?? const [])) {
final m = pt as Map<String, dynamic>;
await db.into(db.cachedPlaylistTracks).insertOnConflictUpdate(
CachedPlaylistTracksCompanion.insert(
playlistId: m['playlist_id'] as String,
trackId: m['track_id'] as String,
),
);
upsertCount++;
}
// ---- Deletes ----
for (final id in (deletes['artist'] as List? ?? const [])) {
await (db.delete(db.cachedArtists)
..where((t) => t.id.equals(id as String)))
.go();
deleteCount++;
}
for (final id in (deletes['album'] as List? ?? const [])) {
await (db.delete(db.cachedAlbums)
..where((t) => t.id.equals(id as String)))
.go();
deleteCount++;
}
for (final id in (deletes['track'] as List? ?? const [])) {
await (db.delete(db.cachedTracks)
..where((t) => t.id.equals(id as String)))
.go();
deleteCount++;
}
for (final id in (deletes['like_track'] as List? ?? const [])) {
final parts = (id as String).split(':');
if (parts.length != 2) continue;
await (db.delete(db.cachedLikes)
..where((t) =>
t.userId.equals(parts[0]) &
t.entityType.equals('track') &
t.entityId.equals(parts[1])))
.go();
deleteCount++;
}
for (final id in (deletes['like_album'] as List? ?? const [])) {
final parts = (id as String).split(':');
if (parts.length != 2) continue;
await (db.delete(db.cachedLikes)
..where((t) =>
t.userId.equals(parts[0]) &
t.entityType.equals('album') &
t.entityId.equals(parts[1])))
.go();
deleteCount++;
}
for (final id in (deletes['like_artist'] as List? ?? const [])) {
final parts = (id as String).split(':');
if (parts.length != 2) continue;
await (db.delete(db.cachedLikes)
..where((t) =>
t.userId.equals(parts[0]) &
t.entityType.equals('artist') &
t.entityId.equals(parts[1])))
.go();
deleteCount++;
}
for (final id in (deletes['playlist'] as List? ?? const [])) {
await (db.delete(db.cachedPlaylists)
..where((t) => t.id.equals(id as String)))
.go();
deleteCount++;
}
for (final id in (deletes['playlist_track'] as List? ?? const [])) {
final parts = (id as String).split(':');
if (parts.length != 2) continue;
await (db.delete(db.cachedPlaylistTracks)
..where((t) =>
t.playlistId.equals(parts[0]) &
t.trackId.equals(parts[1])))
.go();
deleteCount++;
}
// ---- Cursor + lastSyncAt ----
await db.into(db.syncMetadata).insertOnConflictUpdate(
SyncMetadataCompanion.insert(
cursor: drift.Value(newCursor),
lastSyncAt: drift.Value(DateTime.now()),
),
);
});
// Fire-and-forget cover pre-warm so a cold-start scroll through
// the home grid paints from disk on the very first frame instead
// of firing one HTTP request per visible tile. Unawaited because
// the sync's "done" signal should fire as soon as the metadata
// delta is durable; cover downloads can finish in the background.
if (albumCoverIds.isNotEmpty || playlistCoverIds.isNotEmpty) {
unawaited(_prewarmCovers(albumCoverIds, playlistCoverIds));
}
final result = SyncResult(
upserts: upsertCount,
deletes: deleteCount,
cursor: newCursor,
);
state = AsyncData(result);
return result;
} catch (e, st) {
state = AsyncError(e, st);
return null;
}
}
/// Downloads cover bytes for each id into the shared flutter_cache_
/// manager disk cache that cached_network_image reads from.
/// Best-effort: per-URL failures (404 collage-not-built-yet, 401
/// during a token refresh race, network blip) are swallowed so one
/// missing cover doesn't abort the rest.
///
/// Concurrency 3 balances disk-warming throughput against starving
/// foreground UI work — covers are ~30-200KB each, so three in
/// flight saturates most LAN connections without pinning the radio.
Future<void> _prewarmCovers(
List<String> albumIds,
List<String> playlistIds,
) async {
final baseUrl = await ref.read(serverUrlProvider.future);
if (baseUrl == null || baseUrl.isEmpty) return;
final token = await ref.read(sessionTokenProvider.future);
final headers = (token != null && token.isNotEmpty)
? {'Authorization': 'Bearer $token'}
: <String, String>{};
final base =
baseUrl.endsWith('/') ? baseUrl.substring(0, baseUrl.length - 1) : baseUrl;
final urls = <String>[
for (final id in albumIds) '$base/api/albums/$id/cover',
for (final id in playlistIds) '$base/api/playlists/$id/cover',
];
final mgr = DefaultCacheManager();
var index = 0;
Future<void> worker() async {
while (index < urls.length) {
final i = index++;
try {
await mgr.downloadFile(urls[i], authHeaders: headers);
} catch (_) {
// Best-effort prewarm — failures are expected for system
// playlists whose collage hasn't been built yet, and for
// any transient auth race. Don't surface or abort.
}
}
}
await Future.wait(List.generate(3, (_) => worker()));
}
CachedArtistsCompanion _artistFromJson(Map<String, dynamic> j) =>
CachedArtistsCompanion.insert(
id: j['id'] as String,
name: (j['name'] as String?) ?? '',
sortName: (j['sort_name'] as String?) ?? '',
mbid: drift.Value(j['mbid'] as String?),
artistThumbPath: drift.Value(j['artist_thumb_path'] as String?),
artistFanartPath: drift.Value(j['artist_fanart_path'] as String?),
);
CachedAlbumsCompanion _albumFromJson(Map<String, dynamic> j) =>
CachedAlbumsCompanion.insert(
id: j['id'] as String,
artistId: j['artist_id'] as String,
title: (j['title'] as String?) ?? '',
sortTitle: (j['sort_title'] as String?) ?? '',
releaseDate: drift.Value(j['release_date'] as String?),
coverPath: drift.Value(j['cover_art_path'] as String?),
mbid: drift.Value(j['mbid'] as String?),
);
CachedTracksCompanion _trackFromJson(Map<String, dynamic> j) =>
CachedTracksCompanion.insert(
id: j['id'] as String,
albumId: j['album_id'] as String,
artistId: j['artist_id'] as String,
title: (j['title'] as String?) ?? '',
durationMs: drift.Value((j['duration_ms'] as num?)?.toInt() ?? 0),
trackNumber: drift.Value((j['track_number'] as num?)?.toInt()),
discNumber: drift.Value((j['disc_number'] as num?)?.toInt()),
filePath: drift.Value(j['file_path'] as String?),
fileFormat: drift.Value(j['file_format'] as String?),
genre: drift.Value(j['genre'] as String?),
);
CachedPlaylistsCompanion _playlistFromJson(Map<String, dynamic> j) =>
CachedPlaylistsCompanion.insert(
id: j['id'] as String,
userId: j['user_id'] as String,
name: (j['name'] as String?) ?? '',
description: drift.Value((j['description'] as String?) ?? ''),
isPublic: drift.Value((j['is_public'] as bool?) ?? false),
coverPath: drift.Value(j['cover_path'] as String?),
trackCount: drift.Value((j['track_count'] as num?)?.toInt() ?? 0),
durationSec: drift.Value((j['duration_sec'] as num?)?.toInt() ?? 0),
systemVariant: drift.Value(j['system_variant'] as String?),
);
}
final syncControllerProvider =
AsyncNotifierProvider<SyncController, SyncResult?>(SyncController.new);
+144
View File
@@ -0,0 +1,144 @@
// Per-entity tile providers for the per-item rendering architecture
// (see docs/superpowers/specs/2026-05-13-per-item-rendering-design.md).
//
// Each provider is a StreamProvider.family<EntityRef?, String> keyed
// by entity id. The stream:
// 1. Watches the entity's drift row
// 2. Yields the populated row on every emission
// 3. Yields null while the row is absent (UI shows skeleton)
// 4. On the first missing-row emission, enqueues a hydration via
// HydrationQueue so the row eventually lands
//
// The tile widget reacts to AsyncValue<EntityRef?>:
// - loading or data:null → skeleton
// - data:non-null → real card
// - error → error placeholder
//
// Subscriptions are per-tile. A 50-tile home screen creates 50 drift
// subscriptions; drift handles this fine in practice but worth
// measuring if a future surface scales to hundreds.
import 'package:drift/drift.dart' as drift show OrderingTerm;
import 'package:drift/drift.dart' show leftOuterJoin;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../cache/adapters.dart';
import '../cache/audio_cache_manager.dart' show appDbProvider;
import '../models/album.dart';
import '../models/artist.dart';
import '../models/track.dart';
import 'hydration_queue.dart';
/// Watches the cached_albums row for [id]. Triggers background
/// hydration on miss; yields the row once it lands.
final albumTileProvider =
StreamProvider.family<AlbumRef?, String>((ref, id) async* {
if (id.isEmpty) {
yield null;
return;
}
final db = ref.watch(appDbProvider);
final query = (db.select(db.cachedAlbums)..where((t) => t.id.equals(id)))
.join([
leftOuterJoin(db.cachedArtists,
db.cachedArtists.id.equalsExp(db.cachedAlbums.artistId)),
]);
var enqueued = false;
await for (final rows in query.watch()) {
if (rows.isEmpty) {
if (!enqueued) {
enqueued = true;
ref
.read(hydrationQueueProvider)
.enqueue(entityType: 'album', entityId: id);
}
yield null;
continue;
}
final r = rows.first;
final album = r.readTable(db.cachedAlbums);
final artist = r.readTableOrNull(db.cachedArtists);
yield album.toRef(artistName: artist?.name ?? '');
}
});
/// Watches the cached_artists row for [id]. Triggers background
/// hydration on miss; yields the row once it lands.
///
/// LEFT JOIN cached_albums ordered by sort_title so the first row per
/// artist carries a representative album id; toRef() reconstructs
/// `/api/albums/<id>/cover` from it. Without this join the ArtistRef
/// has an empty coverUrl and tiles fall back to the music-notes
/// placeholder even though the server has the cover available.
final artistTileProvider =
StreamProvider.family<ArtistRef?, String>((ref, id) async* {
if (id.isEmpty) {
yield null;
return;
}
final db = ref.watch(appDbProvider);
final query = (db.select(db.cachedArtists)..where((t) => t.id.equals(id)))
.join([
leftOuterJoin(db.cachedAlbums,
db.cachedAlbums.artistId.equalsExp(db.cachedArtists.id)),
])
..orderBy([drift.OrderingTerm.asc(db.cachedAlbums.sortTitle)]);
var enqueued = false;
await for (final rows in query.watch()) {
if (rows.isEmpty) {
if (!enqueued) {
enqueued = true;
ref
.read(hydrationQueueProvider)
.enqueue(entityType: 'artist', entityId: id);
}
yield null;
continue;
}
// First row has the alphabetically-first album (or null if artist
// has no albums in drift yet — yields a coverless ArtistRef which
// the UI falls back to the placeholder icon for).
final artist = rows.first.readTable(db.cachedArtists);
final firstAlbum = rows.first.readTableOrNull(db.cachedAlbums);
yield artist.toRef(coverAlbumId: firstAlbum?.id ?? '');
}
});
/// Watches the cached_tracks row for [id]. Triggers background
/// hydration on miss; yields the row once it lands.
final trackTileProvider =
StreamProvider.family<TrackRef?, String>((ref, id) async* {
if (id.isEmpty) {
yield null;
return;
}
final db = ref.watch(appDbProvider);
final query = (db.select(db.cachedTracks)..where((t) => t.id.equals(id)))
.join([
leftOuterJoin(db.cachedArtists,
db.cachedArtists.id.equalsExp(db.cachedTracks.artistId)),
leftOuterJoin(db.cachedAlbums,
db.cachedAlbums.id.equalsExp(db.cachedTracks.albumId)),
]);
var enqueued = false;
await for (final rows in query.watch()) {
if (rows.isEmpty) {
if (!enqueued) {
enqueued = true;
ref
.read(hydrationQueueProvider)
.enqueue(entityType: 'track', entityId: id);
}
yield null;
continue;
}
final r = rows.first;
final t = r.readTable(db.cachedTracks);
final a = r.readTableOrNull(db.cachedArtists);
final al = r.readTableOrNull(db.cachedAlbums);
yield t.toRef(
artistName: a?.name ?? '',
albumTitle: al?.title ?? '',
);
}
});
@@ -0,0 +1,270 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../api/endpoints/discover.dart';
import '../api/errors.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/lidarr.dart';
import '../shared/widgets/main_app_bar_actions.dart';
import '../theme/theme_extension.dart';
final _discoverApiProvider = FutureProvider<DiscoverApi>((ref) async {
return DiscoverApi(await ref.watch(dioProvider.future));
});
class DiscoverScreen extends ConsumerStatefulWidget {
const DiscoverScreen({super.key});
@override
ConsumerState<DiscoverScreen> createState() => _DiscoverScreenState();
}
class _DiscoverScreenState extends ConsumerState<DiscoverScreen> {
final _ctrl = TextEditingController();
LidarrRequestKind _kind = LidarrRequestKind.artist;
Future<List<LidarrSearchResult>>? _resultsFuture;
@override
void dispose() {
_ctrl.dispose();
super.dispose();
}
void _runSearch() {
final q = _ctrl.text.trim();
if (q.isEmpty) {
setState(() => _resultsFuture = null);
return;
}
setState(() {
_resultsFuture = ref
.read(_discoverApiProvider.future)
.then((api) => api.search(q, _kind));
});
}
Future<void> _request(LidarrSearchResult row) async {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
try {
final api = await ref.read(_discoverApiProvider.future);
await api.createRequest(
kind: _kind,
artistMbid: _kind == LidarrRequestKind.artist ? row.mbid : row.artistMbid,
artistName: _kind == LidarrRequestKind.artist ? row.name : row.secondaryText,
albumMbid: _kind == LidarrRequestKind.album ? row.mbid : null,
albumTitle: _kind == LidarrRequestKind.album ? row.name : null,
);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Requested: ${row.name}'),
backgroundColor: fs.iron,
));
// Re-run search to refresh the `requested` flag on the row.
_runSearch();
}
} on DioException catch (e) {
if (mounted) {
final code = ApiError.fromDio(e).code;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Request failed: $code'),
backgroundColor: fs.error,
));
}
}
}
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return Scaffold(
backgroundColor: fs.obsidian,
appBar: AppBar(
backgroundColor: fs.obsidian,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: fs.parchment),
onPressed: () => context.pop(),
),
title: Text('Discover', style: TextStyle(color: fs.parchment)),
actions: const [MainAppBarActions(currentRoute: '/discover')],
),
body: Column(children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
child: Row(children: [
Expanded(
child: TextField(
controller: _ctrl,
style: TextStyle(color: fs.parchment),
cursorColor: fs.accent,
onSubmitted: (_) => _runSearch(),
decoration: InputDecoration(
hintText: 'Search Lidarr for new music',
hintStyle: TextStyle(color: fs.ash),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: fs.iron),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: fs.accent),
),
suffixIcon: IconButton(
icon: Icon(Icons.search, color: fs.ash),
onPressed: _runSearch,
),
),
),
),
]),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: SegmentedButton<LidarrRequestKind>(
segments: const [
ButtonSegment(value: LidarrRequestKind.artist, label: Text('Artists')),
ButtonSegment(value: LidarrRequestKind.album, label: Text('Albums')),
],
selected: {_kind},
onSelectionChanged: (s) {
setState(() {
_kind = s.first;
if (_ctrl.text.trim().isNotEmpty) _runSearch();
});
},
),
),
Expanded(
child: _resultsFuture == null
? Center(
child: Text(
'Type to search, then tap Request to send to Lidarr.',
textAlign: TextAlign.center,
style: TextStyle(color: fs.ash),
),
)
: FutureBuilder<List<LidarrSearchResult>>(
future: _resultsFuture,
builder: (ctx, snap) {
if (snap.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snap.hasError) {
final err = snap.error;
final code = err is DioException
? ApiError.fromDio(err).code
: 'unknown';
return Center(
child: Text('Search failed: $code',
style: TextStyle(color: fs.error)),
);
}
final rows = snap.data ?? const [];
if (rows.isEmpty) {
return Center(
child: Text('Nothing to add for that search yet.',
style: TextStyle(color: fs.ash),
textAlign: TextAlign.center),
);
}
return ListView.separated(
itemCount: rows.length,
separatorBuilder: (_, __) =>
Divider(height: 1, color: fs.iron),
itemBuilder: (ctx, i) => _ResultTile(
row: rows[i],
onRequest: () => _request(rows[i]),
),
);
},
),
),
]),
);
}
}
class _ResultTile extends StatelessWidget {
const _ResultTile({required this.row, required this.onRequest});
final LidarrSearchResult row;
final VoidCallback onRequest;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final disabled = row.inLibrary || row.requested;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: Row(children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Container(
width: 56,
height: 56,
color: fs.slate,
child: row.imageUrl.isEmpty
? Icon(Icons.album, color: fs.ash)
: CachedNetworkImage(
imageUrl: row.imageUrl,
fit: BoxFit.cover,
fadeInDuration: const Duration(milliseconds: 120),
fadeOutDuration: Duration.zero,
errorWidget: (_, __, ___) =>
Icon(Icons.album, color: fs.ash),
),
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(row.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14)),
if (row.secondaryText.isNotEmpty)
Text(row.secondaryText,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.ash, fontSize: 12)),
],
),
),
const SizedBox(width: 8),
if (row.inLibrary)
_Pill(label: 'In library', color: fs.ash)
else if (row.requested)
_Pill(label: 'Requested', color: fs.ash)
else
FilledButton(
onPressed: disabled ? null : onRequest,
style: FilledButton.styleFrom(
backgroundColor: fs.accent,
foregroundColor: fs.parchment,
),
child: const Text('Request'),
),
]),
);
}
}
class _Pill extends StatelessWidget {
const _Pill({required this.label, required this.color});
final String label;
final Color color;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: fs.iron,
borderRadius: BorderRadius.circular(4),
),
child: Text(label, style: TextStyle(color: color, fontSize: 11)),
);
}
}
@@ -2,30 +2,105 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/endpoints/likes.dart';
import '../models/album.dart';
import '../cache/audio_cache_manager.dart';
import '../cache/db.dart';
import '../likes/like_button.dart';
import '../player/player_provider.dart';
import '../shared/widgets/server_image.dart';
import '../theme/theme_extension.dart';
import 'library_providers.dart';
import 'widgets/track_row.dart';
class AlbumDetailScreen extends ConsumerWidget {
const AlbumDetailScreen({required this.id, super.key});
const AlbumDetailScreen({required this.id, this.seed, super.key});
final String id;
/// Optional album reference passed by the caller (typically the
/// tile they tapped) so the header can render immediately while
/// the full provider loads tracks. Hydration only — provider data
/// still wins once it arrives.
final AlbumRef? seed;
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final live = ref.watch(albumProvider(id));
// Pick the best header info available: live data > seed > nothing.
final headerTitle = live.value?.album.title.isNotEmpty == true
? live.value!.album.title
: seed?.title ?? '';
final headerArtist = live.value?.album.artistName.isNotEmpty == true
? live.value!.album.artistName
: seed?.artistName ?? '';
Widget header() => Padding(
padding: const EdgeInsets.all(16),
child: Row(children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: SizedBox(
width: 96,
height: 96,
child: ServerImage(
url: '/api/albums/$id/cover',
fit: BoxFit.cover,
fallback: Container(color: fs.slate),
),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
headerTitle,
style: TextStyle(
color: fs.parchment,
fontFamily: fs.display.fontFamily,
fontSize: 22,
),
),
if (headerArtist.isNotEmpty)
Text(headerArtist, style: TextStyle(color: fs.ash)),
],
),
),
]),
);
return Scaffold(
appBar: AppBar(),
backgroundColor: fs.obsidian,
body: ref.watch(albumProvider(id)).when(
body: live.when(
error: (e, _) => Center(child: Text('$e', style: TextStyle(color: fs.error))),
loading: () => const Center(child: CircularProgressIndicator()),
loading: () => seed != null
? ListView(children: [
header(),
const Padding(
padding: EdgeInsets.symmetric(vertical: 24),
child: Center(child: CircularProgressIndicator()),
),
])
: const Center(child: CircularProgressIndicator()),
data: (r) => ListView(children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(children: [
Container(width: 96, height: 96, color: fs.slate),
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: SizedBox(
width: 96,
height: 96,
child: ServerImage(
url: '/api/albums/$id/cover',
fit: BoxFit.cover,
fallback: Container(color: fs.slate),
),
),
),
const SizedBox(width: 16),
Expanded(child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -38,6 +113,21 @@ class AlbumDetailScreen extends ConsumerWidget {
Text(r.album.artistName, style: TextStyle(color: fs.ash)),
],
)),
IconButton(
key: const Key('download_album_button'),
icon: Icon(Icons.download, color: fs.ash),
tooltip: 'Download album',
onPressed: () {
final mgr = ref.read(audioCacheManagerProvider);
for (final t in r.tracks) {
// ignore: unawaited_futures
mgr.pin(t.id, source: CacheSource.autoPlaylist);
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Downloading ${r.tracks.length} tracks…')),
);
},
),
Container(
width: 48, height: 48,
decoration: BoxDecoration(color: fs.accent, shape: BoxShape.circle),
@@ -5,34 +5,75 @@ import 'package:go_router/go_router.dart';
import '../api/endpoints/likes.dart';
import '../likes/like_button.dart';
import '../models/album.dart';
import '../models/artist.dart';
import '../player/player_provider.dart';
import '../shared/widgets/server_image.dart';
import '../theme/theme_extension.dart';
import 'library_providers.dart';
import 'widgets/album_card.dart';
class ArtistDetailScreen extends ConsumerWidget {
const ArtistDetailScreen({required this.id, super.key});
const ArtistDetailScreen({required this.id, this.seed, super.key});
final String id;
/// Optional artist reference from the caller. Lets the screen render
/// the name + avatar immediately while albums load.
final ArtistRef? seed;
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final artist = ref.watch(artistProvider(id));
final albums = ref.watch(artistAlbumsProvider(id));
// Resolve which artist info to render in the header. Live wins
// when present and populated; seed fills the gap during the
// first frame after navigation.
final liveArtist = artist.value;
final hasLiveName = liveArtist != null && liveArtist.name.isNotEmpty;
final effective = hasLiveName ? liveArtist : (seed ?? liveArtist);
return Scaffold(
appBar: AppBar(),
backgroundColor: fs.obsidian,
body: artist.when(
error: (e, _) => Center(child: Text('$e', style: TextStyle(color: fs.error))),
loading: () => const Center(child: CircularProgressIndicator()),
data: (a) => ListView(children: [
// While loading: render header from seed if available so the
// page isn't blank.
loading: () => seed == null
? const Center(child: CircularProgressIndicator())
: _artistBody(context, ref, seed!, albums, fs),
data: (_) => _artistBody(context, ref, effective ?? seed!, albums, fs),
),
);
}
Widget _artistBody(
BuildContext context,
WidgetRef ref,
ArtistRef a,
AsyncValue<List<AlbumRef>> albums,
FabledSwordTheme fs,
) =>
ListView(children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(children: [
Container(
width: 96, height: 96,
decoration: BoxDecoration(color: fs.slate, shape: BoxShape.circle),
ClipOval(
child: SizedBox(
width: 96,
height: 96,
// Server derives artist cover from a representative
// album. Drift cache doesn't persist that pointer, so
// mirror the trick client-side: reuse the first album
// returned by artistAlbumsProvider. Falls back to
// slate while albums are loading or empty.
child: _ArtistAvatar(
serverCoverUrl: a.coverUrl,
albums: albums,
fs: fs,
),
),
),
const SizedBox(width: 16),
Expanded(
@@ -51,10 +92,31 @@ class ArtistDetailScreen extends ConsumerWidget {
child: IconButton(
icon: Icon(Icons.play_arrow, color: fs.parchment),
onPressed: () async {
final tracks = await ref.read(artistTracksProvider(id).future);
if (tracks.isEmpty) return;
final shuffled = [...tracks]..shuffle();
ref.read(playerActionsProvider).playTracks(shuffled);
try {
final tracks =
await ref.read(artistTracksProvider(id).future);
if (tracks.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'No tracks found for this artist yet.')),
);
}
return;
}
final shuffled = [...tracks]..shuffle();
await ref
.read(playerActionsProvider)
.playTracks(shuffled);
} catch (e) {
debugPrint('artist_detail: play failed: $e');
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Couldn't start playback: $e")),
);
}
}
},
),
),
@@ -68,23 +130,79 @@ class ArtistDetailScreen extends ConsumerWidget {
albums.when(
error: (e, _) => Center(child: Text('$e', style: TextStyle(color: fs.error))),
loading: () => const Padding(padding: EdgeInsets.all(16), child: Center(child: CircularProgressIndicator())),
data: (list) => GridView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
padding: const EdgeInsets.all(8),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.8,
),
itemCount: list.length,
itemBuilder: (_, i) {
final AlbumRef album = list[i];
return AlbumCard(album: album, onTap: () => context.push('/albums/${album.id}'));
},
),
data: (list) {
return LayoutBuilder(builder: (ctx, constraints) {
const cols = 3;
const sidePad = 8.0;
const gap = 8.0;
final cellW =
(constraints.maxWidth - sidePad * 2 - gap * (cols - 1)) /
cols;
// Card content: cover (cellW - 16) + 8 + title (≤2 lines
// ≈ 36) + slack. Artist line is suppressed in this
// grid (showArtist: false) since the page header already
// names the artist. Slack is generous on purpose — line-
// height variations would otherwise overflow by 1px.
final cellH = (cellW - 16) + 8 + 36 + 8;
return GridView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
padding: const EdgeInsets.fromLTRB(sidePad, 0, sidePad, 16),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: cols,
mainAxisExtent: cellH,
mainAxisSpacing: gap,
crossAxisSpacing: gap,
),
itemCount: list.length,
itemBuilder: (_, i) {
final AlbumRef album = list[i];
return AlbumCard(
album: album,
width: cellW,
titleMaxLines: 2,
showArtist: false,
onTap: () =>
context.push('/albums/${album.id}', extra: album),
);
},
);
});
},
),
]),
),
]);
}
/// Renders the artist's avatar. Server-emitted coverUrl wins when
/// non-empty; otherwise we mirror the server's "use the first album's
/// cover" rule client-side via the loaded album list.
class _ArtistAvatar extends StatelessWidget {
const _ArtistAvatar({
required this.serverCoverUrl,
required this.albums,
required this.fs,
});
final String serverCoverUrl;
final AsyncValue<List<AlbumRef>> albums;
final FabledSwordTheme fs;
@override
Widget build(BuildContext context) {
if (serverCoverUrl.isNotEmpty) {
return ServerImage(
url: serverCoverUrl,
fit: BoxFit.cover,
fallback: Container(color: fs.slate),
);
}
final firstId = albums.value?.isNotEmpty == true ? albums.value!.first.id : null;
if (firstId == null) {
return Container(color: fs.slate);
}
return ServerImage(
url: '/api/albums/$firstId/cover',
fit: BoxFit.cover,
fallback: Container(color: fs.slate),
);
}
}
+475 -60
View File
@@ -4,85 +4,500 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../api/errors.dart';
import '../models/album.dart';
import '../models/artist.dart';
import '../cache/tile_providers.dart';
import '../models/playlist.dart';
import '../models/system_playlists_status.dart';
import '../models/track.dart';
import '../player/player_provider.dart';
import '../playlists/playlists_provider.dart';
import '../playlists/widgets/playlist_card.dart';
import '../playlists/widgets/playlist_placeholder_card.dart';
import '../shared/widgets/connection_error_banner.dart';
import '../shared/widgets/main_app_bar_actions.dart';
import '../shared/widgets/skeletons.dart';
import '../theme/theme_extension.dart';
import 'library_providers.dart';
import 'widgets/album_card.dart';
import 'widgets/artist_card.dart';
import 'widgets/compact_track_card.dart';
import 'widgets/horizontal_scroll_row.dart';
import 'widgets/track_row.dart';
/// Home screen. Per-item rendering: a tiny /api/home/index discovery
/// fetch returns just section→IDs, then each tile hydrates itself
/// against the per-entity drift tables (sync-populated) with REST
/// fallback via the HydrationQueue. Cold-visit dead air shrinks to a
/// single small round-trip; tiles materialize as their data lands.
class HomeScreen extends ConsumerWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final index = ref.watch(homeIndexProvider);
final allPlaylists = ref.watch(playlistsListProvider('all'));
final status = ref.watch(systemPlaylistsStatusProvider);
return Scaffold(
backgroundColor: fs.obsidian,
appBar: AppBar(
backgroundColor: fs.obsidian,
elevation: 0,
title: Text('Minstrel', style: TextStyle(color: fs.parchment)),
actions: const [MainAppBarActions(currentRoute: '/home')],
),
body: SafeArea(
child: ref.watch(homeProvider).when(
error: (e, _) {
final code = e is DioException ? ApiError.fromDio(e).code : 'unknown';
if (code == 'connection_refused') {
return ConnectionErrorBanner(
onRetry: () => ref.refresh(homeProvider),
);
}
return Center(child: Text('$e', style: TextStyle(color: fs.error)));
},
loading: () => const Center(child: CircularProgressIndicator()),
data: (h) => RefreshIndicator(
onRefresh: () async => ref.refresh(homeProvider.future),
child: ListView(children: [
_albumsRow(context, 'Recently added', h.recentlyAddedAlbums),
_albumsRow(context, 'Rediscover', h.rediscoverAlbums),
_artistsRow(context, 'Rediscover artists', h.rediscoverArtists),
_tracksRow(context, ref, 'Most played', h.mostPlayedTracks),
_artistsRow(context, 'Last played artists', h.lastPlayedArtists),
const SizedBox(height: 96),
]),
),
child: index.when(
error: (e, _) {
final code = e is DioException ? ApiError.fromDio(e).code : 'unknown';
if (code == 'connection_refused') {
return ConnectionErrorBanner(
onRetry: () => ref.refresh(homeIndexProvider),
);
}
return Center(child: Text('$e', style: TextStyle(color: fs.error)));
},
loading: () => _HomeSkeleton(fs: fs),
data: (h) => RefreshIndicator(
onRefresh: () async => ref.refresh(homeIndexProvider.future),
child: ListView(
physics: const ClampingScrollPhysics(),
children: [
_PlaylistsSection(
playlists: allPlaylists.value?.owned ?? const [],
status: status.value ?? SystemPlaylistsStatus.empty(),
),
_RecentlyAddedSection(ids: h.recentlyAddedAlbums),
_RediscoverSection(
albumIds: h.rediscoverAlbums,
artistIds: h.rediscoverArtists,
),
_MostPlayedSection(ids: h.mostPlayedTracks),
_LastPlayedSection(ids: h.lastPlayedArtists),
const SizedBox(height: 140),
],
),
),
),
),
);
}
Widget _albumsRow(BuildContext ctx, String title, List<AlbumRef> albums) =>
HorizontalScrollRow(
title: title,
children: [
for (final a in albums)
AlbumCard(album: a, onTap: () => ctx.push('/albums/${a.id}')),
],
);
Widget _artistsRow(BuildContext ctx, String title, List<ArtistRef> artists) =>
HorizontalScrollRow(
title: title,
children: [
for (final a in artists)
ArtistCard(artist: a, onTap: () => ctx.push('/artists/${a.id}')),
],
);
Widget _tracksRow(BuildContext ctx, WidgetRef ref, String title, List<TrackRef> tracks) =>
HorizontalScrollRow(
title: title,
height: 64,
children: [
for (final t in tracks)
SizedBox(
width: 280,
child: TrackRow(
track: t,
onTap: () => ref.read(playerActionsProvider).playTracks([t]),
),
),
],
);
}
// ─── Per-tile widgets ────────────────────────────────────────────────
/// Duration of the skeleton→content cross-fade. 220ms reads as "tile
/// settled into place" — longer drags, shorter feels like a hard cut.
/// Each tile cross-fades independently when its data lands, so the
/// natural cascade from the hydration queue's bounded concurrency
/// produces a staged-reveal feel without any per-tile delay math.
const Duration _tileRevealDuration = Duration(milliseconds: 220);
/// Album tile: skeleton until albumTileProvider yields a populated row.
class _AlbumTile extends ConsumerWidget {
const _AlbumTile({required this.id});
final String id;
@override
Widget build(BuildContext context, WidgetRef ref) {
final asyncAlbum = ref.watch(albumTileProvider(id));
final album = asyncAlbum.asData?.value;
return AnimatedSwitcher(
duration: _tileRevealDuration,
switchInCurve: Curves.easeOut,
child: album == null
? const SkeletonAlbumTile(key: ValueKey('skeleton'))
: AlbumCard(
key: ValueKey('album-${album.id}'),
album: album,
onTap: () =>
context.push('/albums/${album.id}', extra: album),
),
);
}
}
/// Artist tile: skeleton until artistTileProvider yields a populated row.
class _ArtistTile extends ConsumerWidget {
const _ArtistTile({required this.id});
final String id;
@override
Widget build(BuildContext context, WidgetRef ref) {
final asyncArtist = ref.watch(artistTileProvider(id));
final artist = asyncArtist.asData?.value;
return AnimatedSwitcher(
duration: _tileRevealDuration,
switchInCurve: Curves.easeOut,
child: artist == null
? const SkeletonArtistTile(key: ValueKey('skeleton'))
: ArtistCard(
key: ValueKey('artist-${artist.id}'),
artist: artist,
onTap: () =>
context.push('/artists/${artist.id}', extra: artist),
),
);
}
}
/// Track tile (used by Most-Played). On tap, gathers the currently-
/// hydrated TrackRefs for the whole section so playback flows like
/// it did with the bulk-loaded list. Tracks that haven't hydrated yet
/// are skipped from the play list — typically transient on a cold
/// visit since hydration runs in parallel and finishes quickly.
class _TrackTile extends ConsumerWidget {
const _TrackTile({required this.id, required this.sectionIds});
final String id;
final List<String> sectionIds;
@override
Widget build(BuildContext context, WidgetRef ref) {
final asyncTrack = ref.watch(trackTileProvider(id));
final track = asyncTrack.asData?.value;
return AnimatedSwitcher(
duration: _tileRevealDuration,
switchInCurve: Curves.easeOut,
child: track == null
? const _CompactTrackSkeleton(key: ValueKey('skeleton'))
: CompactTrackCard(
key: ValueKey('track-${track.id}'),
track: track,
sectionTracks: _resolveSectionTracks(ref, sectionIds),
index:
sectionIds.indexOf(id).clamp(0, sectionIds.length - 1),
),
);
}
/// Snapshots the section's current track states. Used at tile
/// construction time — CompactTrackCard's onTap uses it as the play
/// queue. Tracks still hydrating are dropped; once they land, a
/// rebuild re-runs this lookup so the queue grows naturally.
static List<TrackRef> _resolveSectionTracks(WidgetRef ref, List<String> ids) {
final out = <TrackRef>[];
for (final i in ids) {
final v = ref.read(trackTileProvider(i)).asData?.value;
if (v != null) out.add(v);
}
return out;
}
}
/// Compact-track placeholder. 56dp cover + two text lines, matched to
/// CompactTrackCard so swapping in the real card doesn't shift the
/// row's height.
class _CompactTrackSkeleton extends StatelessWidget {
const _CompactTrackSkeleton({super.key});
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return Container(
width: 240,
margin: const EdgeInsets.symmetric(horizontal: 4),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
child: Row(children: [
Container(
width: 56,
height: 56,
decoration: BoxDecoration(
color: fs.slate,
borderRadius: BorderRadius.circular(6),
),
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(width: 120, height: 12, color: fs.slate),
const SizedBox(height: 6),
Container(width: 80, height: 10, color: fs.slate),
],
),
),
]),
);
}
}
// ─── Sections ────────────────────────────────────────────────────────
class _PlaylistsSection extends StatelessWidget {
const _PlaylistsSection({required this.playlists, required this.status});
final List<Playlist> playlists;
final SystemPlaylistsStatus status;
@override
Widget build(BuildContext context) {
final items = _buildPlaylistsRow(playlists, status);
return HorizontalScrollRow(
title: 'Playlists',
height: 220,
children: items.map((item) {
if (item is _RealPlaylist) {
return PlaylistCard(playlist: item.playlist);
}
final ph = item as _PlaceholderPlaylist;
return PlaylistPlaceholderCard(label: ph.label, variant: ph.variant);
}).toList(),
);
}
}
abstract class _PlaylistRowItem {}
class _RealPlaylist extends _PlaylistRowItem {
_RealPlaylist(this.playlist);
final Playlist playlist;
}
class _PlaceholderPlaylist extends _PlaylistRowItem {
_PlaceholderPlaylist(this.label, this.variant);
final String label;
final String variant;
}
List<_PlaylistRowItem> _buildPlaylistsRow(
List<Playlist> ownedAll,
SystemPlaylistsStatus status,
) {
final out = <_PlaylistRowItem>[];
Playlist? findFirst(bool Function(Playlist) test) {
for (final p in ownedAll) {
if (test(p)) return p;
}
return null;
}
final forYou = findFirst((p) => p.systemVariant == 'for_you');
out.add(forYou != null
? _RealPlaylist(forYou)
: _PlaceholderPlaylist('For You', _variantFor('for-you', status)));
final discover = findFirst((p) => p.systemVariant == 'discover');
out.add(discover != null
? _RealPlaylist(discover)
: _PlaceholderPlaylist('Discover', _variantFor('discover', status)));
final songsLike = ownedAll
.where((p) => p.systemVariant == 'songs_like_artist')
.take(3)
.toList();
for (var i = 0; i < 3; i++) {
out.add(i < songsLike.length
? _RealPlaylist(songsLike[i])
: _PlaceholderPlaylist('Songs like…', _variantFor('songs-like', status)));
}
for (final p in ownedAll.where((p) => p.systemVariant == null)) {
out.add(_RealPlaylist(p));
}
return out;
}
String _variantFor(String slot, SystemPlaylistsStatus s) {
if (s.inFlight) return 'building';
if (s.lastError != null) return 'failed';
if (slot == 'songs-like' && s.lastRunAt != null) return 'seed-needed';
return 'pending';
}
class _RecentlyAddedSection extends StatelessWidget {
const _RecentlyAddedSection({required this.ids});
final List<String> ids;
@override
Widget build(BuildContext context) {
if (ids.isEmpty) {
return const _EmptySection(
title: 'Recently added',
message: "Nothing added yet. Scan a folder via the server's config.",
);
}
final controller = ScrollController();
final rows = _chunk(ids, 25);
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
for (var i = 0; i < rows.length; i++)
HorizontalScrollRow(
title: i == 0 ? 'Recently added' : '',
controller: controller,
children: rows[i].map((id) => _AlbumTile(id: id)).toList(),
),
]);
}
}
class _RediscoverSection extends StatelessWidget {
const _RediscoverSection({required this.albumIds, required this.artistIds});
final List<String> albumIds;
final List<String> artistIds;
@override
Widget build(BuildContext context) {
if (albumIds.isEmpty && artistIds.isEmpty) {
return const _EmptySection(
title: 'Rediscover',
message:
'No forgotten favourites yet. Like some albums or artists to fill this in.',
);
}
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
if (albumIds.isNotEmpty)
HorizontalScrollRow(
title: 'Rediscover',
children: albumIds.map((id) => _AlbumTile(id: id)).toList(),
),
if (artistIds.isNotEmpty)
HorizontalScrollRow(
title: albumIds.isEmpty ? 'Rediscover' : '',
height: 168,
children: artistIds.map((id) => _ArtistTile(id: id)).toList(),
),
]);
}
}
class _MostPlayedSection extends StatelessWidget {
const _MostPlayedSection({required this.ids});
final List<String> ids;
@override
Widget build(BuildContext context) {
if (ids.isEmpty) {
return const _EmptySection(
title: 'Most played',
message: 'No plays to draw from. Listen to something.',
);
}
final controller = ScrollController();
final rows = _chunk(ids, 25);
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
for (var i = 0; i < rows.length; i++)
HorizontalScrollRow(
title: i == 0 ? 'Most played' : '',
height: 64,
controller: controller,
children: [
for (final id in rows[i]) _TrackTile(id: id, sectionIds: ids),
],
),
]);
}
}
class _LastPlayedSection extends StatelessWidget {
const _LastPlayedSection({required this.ids});
final List<String> ids;
@override
Widget build(BuildContext context) {
if (ids.isEmpty) {
return const _EmptySection(
title: 'Last played',
message: 'No recent plays.',
);
}
return HorizontalScrollRow(
title: 'Last played',
height: 168,
children: ids.map((id) => _ArtistTile(id: id)).toList(),
);
}
}
class _EmptySection extends StatelessWidget {
const _EmptySection({required this.title, required this.message});
final String title;
final String message;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(
title,
style: TextStyle(
fontFamily: fs.display.fontFamily,
fontSize: 18,
color: fs.parchment,
),
),
const SizedBox(height: 8),
Text(message, style: TextStyle(color: fs.ash)),
]),
);
}
}
/// Cold-start skeleton — shown only between mount and the first
/// homeIndexProvider emission (typically a single drift query + small
/// REST round-trip). Each section then renders its own per-tile
/// skeletons internally, so this widget's role is just the very first
/// pre-discovery frame.
class _HomeSkeleton extends StatelessWidget {
const _HomeSkeleton({required this.fs});
final FabledSwordTheme fs;
@override
Widget build(BuildContext context) {
return ListView(
physics: const ClampingScrollPhysics(),
children: [
_SkeletonSection(fs: fs, title: 'Playlists', cardWidth: 176),
_SkeletonSection(fs: fs, title: 'Recently added', cardWidth: 140),
_SkeletonSection(fs: fs, title: 'Rediscover', cardWidth: 140),
_SkeletonSection(fs: fs, title: 'Most played', cardWidth: 140),
_SkeletonSection(fs: fs, title: 'Last played', cardWidth: 140),
const SizedBox(height: 140),
],
);
}
}
class _SkeletonSection extends StatelessWidget {
const _SkeletonSection({
required this.fs,
required this.title,
required this.cardWidth,
});
final FabledSwordTheme fs;
final String title;
final double cardWidth;
@override
Widget build(BuildContext context) {
final coverSize = cardWidth - 16;
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: Text(
title,
style: TextStyle(
fontFamily: fs.display.fontFamily,
fontSize: 18,
color: fs.parchment,
),
),
),
SizedBox(
height: coverSize + 40,
child: ListView.builder(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 16),
physics: const NeverScrollableScrollPhysics(),
itemCount: 6,
itemBuilder: (_, __) => SkeletonAlbumTile(width: cardWidth),
),
),
]);
}
}
List<List<T>> _chunk<T>(List<T> items, int size) {
final out = <List<T>>[];
for (var i = 0; i < items.length; i += size) {
out.add(items.sublist(i, i + size > items.length ? items.length : i + size));
}
return out;
}
+457 -14
View File
@@ -1,12 +1,23 @@
import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:drift/drift.dart' as drift;
import 'package:flutter/foundation.dart' show debugPrint;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/client.dart';
import '../api/endpoints/library.dart';
import '../auth/auth_provider.dart';
import '../cache/adapters.dart';
import '../cache/audio_cache_manager.dart' show appDbProvider;
import '../cache/cache_first.dart';
import '../cache/connectivity_provider.dart';
import '../cache/db.dart';
import '../models/album.dart';
import '../models/artist.dart';
import '../models/home_data.dart';
import '../models/home_index.dart';
import '../models/track.dart';
/// Shared authenticated dio. This is the ONLY place tokenResolver is wired
@@ -33,28 +44,460 @@ final libraryApiProvider = FutureProvider<LibraryApi>((ref) async {
return LibraryApi(await ref.watch(dioProvider.future));
});
final homeProvider = FutureProvider<HomeData>((ref) async {
return (await ref.watch(libraryApiProvider.future)).getHome();
/// Drift-first home data (#357 follow-up). The home screen is the first
/// view the user sees on app open; without a local cache the cold-start
/// blocks on the /api/home round-trip, which is the dominant felt-
/// latency on slow / remote connections.
///
/// Cache layout: a single row in `cached_home_snapshot` storing the
/// last successful HomeData as JSON. On stream subscription:
///
/// - If a row exists, yield it immediately (parsed from JSON) and
/// kick off a background revalidation against /api/home (SWR).
/// The drift watch() re-emits when the new row is written.
/// - If no row exists yet (cold cache), fetch /api/home synchronously,
/// upsert into drift, and emit. Subsequent emissions come from the
/// drift watch as background revalidations land.
///
/// The HomeData JSON encodes back to the same wire shape /api/home
/// emits, so the existing HomeData.fromJson handles both sources.
final homeProvider = StreamProvider<HomeData>((ref) {
final db = ref.watch(appDbProvider);
return cacheFirst<CachedHomeSnapshotData, HomeData>(
driftStream: db.select(db.cachedHomeSnapshot).watch(),
fetchAndPopulate: () async {
final api = await ref.read(libraryApiProvider.future);
final fresh = await api.getHome();
await db.into(db.cachedHomeSnapshot).insertOnConflictUpdate(
CachedHomeSnapshotCompanion.insert(
json: _encodeHomeData(fresh),
updatedAt: drift.Value(DateTime.now()),
),
);
},
toResult: (rows) => rows.isEmpty
? const HomeData(
recentlyAddedAlbums: [],
rediscoverAlbums: [],
rediscoverArtists: [],
mostPlayedTracks: [],
lastPlayedArtists: [],
)
: HomeData.fromJson(jsonDecode(rows.first.json) as Map<String, dynamic>),
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
// SWR: when cached snapshot exists, still hit /api/home in the
// background so the user sees the freshest curation. The cache
// mostly serves the first frame, not the canonical state.
alwaysRefresh: true,
tag: 'home',
);
});
/// Drift-first per-item home index. Reads from cached_home_index
/// (populated by /api/home/index discovery) and yields a HomeIndex
/// the screen consumes to lay out section→tile slots. Each tile is
/// rendered by a per-entity tile provider that hydrates itself.
///
/// Section keys mirror the server's response shape so the encode /
/// decode round-trip is straightforward — the table stores
/// (section, position, entityType, entityId), and toResult reassembles
/// the parallel ID lists.
final homeIndexProvider = StreamProvider<HomeIndex>((ref) {
final db = ref.watch(appDbProvider);
final query = (db.select(db.cachedHomeIndex)
..orderBy([
(t) => drift.OrderingTerm.asc(t.section),
(t) => drift.OrderingTerm.asc(t.position),
]))
.watch();
return cacheFirst<CachedHomeIndexData, HomeIndex>(
driftStream: query,
fetchAndPopulate: () async {
final api = await ref.read(libraryApiProvider.future);
final fresh = await api.getHomeIndex();
// Full replace in a transaction so the watch() sees exactly one
// post-fetch emission with the merged state. Section ordering is
// re-asserted on read (orderBy above) so the write order doesn't
// matter — letting us batch flat instead of section-by-section.
await db.transaction(() async {
await db.delete(db.cachedHomeIndex).go();
await db.batch((b) {
void rows(String section, String entityType, List<String> ids) {
for (var i = 0; i < ids.length; i++) {
b.insert(
db.cachedHomeIndex,
CachedHomeIndexCompanion.insert(
section: section,
position: i,
entityType: entityType,
entityId: ids[i],
),
);
}
}
rows('recently_added_albums', 'album', fresh.recentlyAddedAlbums);
rows('rediscover_albums', 'album', fresh.rediscoverAlbums);
rows('rediscover_artists', 'artist', fresh.rediscoverArtists);
rows('most_played_tracks', 'track', fresh.mostPlayedTracks);
rows('last_played_artists', 'artist', fresh.lastPlayedArtists);
});
});
},
toResult: (rows) {
final recentlyAddedAlbums = <String>[];
final rediscoverAlbums = <String>[];
final rediscoverArtists = <String>[];
final mostPlayedTracks = <String>[];
final lastPlayedArtists = <String>[];
for (final r in rows) {
switch (r.section) {
case 'recently_added_albums':
recentlyAddedAlbums.add(r.entityId);
case 'rediscover_albums':
rediscoverAlbums.add(r.entityId);
case 'rediscover_artists':
rediscoverArtists.add(r.entityId);
case 'most_played_tracks':
mostPlayedTracks.add(r.entityId);
case 'last_played_artists':
lastPlayedArtists.add(r.entityId);
}
}
return HomeIndex(
recentlyAddedAlbums: recentlyAddedAlbums,
rediscoverAlbums: rediscoverAlbums,
rediscoverArtists: rediscoverArtists,
mostPlayedTracks: mostPlayedTracks,
lastPlayedArtists: lastPlayedArtists,
);
},
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
// SWR: cached layout shows instantly; fresh /api/home/index lands
// in the background and tiles re-resolve as the table mutates.
alwaysRefresh: true,
tag: 'homeIndex',
);
});
/// Encodes HomeData back to the wire-format JSON shape /api/home
/// emits, so HomeData.fromJson can round-trip through the drift cache.
String _encodeHomeData(HomeData h) => jsonEncode({
'recently_added_albums': h.recentlyAddedAlbums.map(_albumToJson).toList(),
'rediscover_albums': h.rediscoverAlbums.map(_albumToJson).toList(),
'rediscover_artists': h.rediscoverArtists.map(_artistToJson).toList(),
'most_played_tracks': h.mostPlayedTracks.map(_trackToJson).toList(),
'last_played_artists': h.lastPlayedArtists.map(_artistToJson).toList(),
});
Map<String, dynamic> _albumToJson(AlbumRef a) => {
'id': a.id,
'title': a.title,
'sort_title': a.sortTitle,
'artist_id': a.artistId,
'artist_name': a.artistName,
'year': a.year,
'track_count': a.trackCount,
'duration_sec': a.durationSec,
'cover_url': a.coverUrl,
};
Map<String, dynamic> _artistToJson(ArtistRef a) => {
'id': a.id,
'name': a.name,
'sort_name': a.sortName,
'album_count': a.albumCount,
'cover_url': a.coverUrl,
};
Map<String, dynamic> _trackToJson(TrackRef t) => {
'id': t.id,
'title': t.title,
'album_id': t.albumId,
'album_title': t.albumTitle,
'artist_id': t.artistId,
'artist_name': t.artistName,
'track_number': t.trackNumber,
'disc_number': t.discNumber,
'duration_sec': t.durationSec,
'stream_url': t.streamUrl,
};
/// Drift-first per #357 plan C. Watches cached_artists for the row;
/// when empty + online, fetches via REST + populates drift, which
/// re-emits via watch().
final artistProvider =
FutureProvider.family<ArtistRef, String>((ref, id) async {
return (await ref.watch(libraryApiProvider.future)).getArtist(id);
StreamProvider.family<ArtistRef, String>((ref, id) {
final db = ref.watch(appDbProvider);
// LEFT JOIN cached_albums for cover-URL reconstruction (see
// CachedArtistAdapter.toRef). First row carries the alphabetically-
// first album.
final query = (db.select(db.cachedArtists)..where((t) => t.id.equals(id)))
.join([
drift.leftOuterJoin(db.cachedAlbums,
db.cachedAlbums.artistId.equalsExp(db.cachedArtists.id)),
])
..orderBy([drift.OrderingTerm.asc(db.cachedAlbums.sortTitle)]);
return cacheFirst<drift.TypedResult, ArtistRef>(
driftStream: query.watch(),
fetchAndPopulate: () async {
final api = await ref.read(libraryApiProvider.future);
final fresh = await api.getArtist(id);
await db.into(db.cachedArtists).insertOnConflictUpdate(fresh.toDrift());
},
toResult: (rows) {
if (rows.isEmpty) return const ArtistRef(id: '', name: '');
final artist = rows.first.readTable(db.cachedArtists);
final firstAlbum = rows.first.readTableOrNull(db.cachedAlbums);
return artist.toRef(coverAlbumId: firstAlbum?.id ?? '');
},
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
// No alwaysRefresh: artist rows don't change frequently, and the
// metadata prefetcher creates many subscriptions in parallel —
// each silently re-fetching once would saturate the request
// pipeline behind the user's actual playback request.
tag: 'artist($id)',
);
});
final artistAlbumsProvider =
FutureProvider.family<List<AlbumRef>, String>((ref, id) async {
return (await ref.watch(libraryApiProvider.future)).getArtistAlbums(id);
StreamProvider.family<List<AlbumRef>, String>((ref, artistId) {
final db = ref.watch(appDbProvider);
// Join cached_albums + cached_artists to fill artist_name on each row.
final query = db.select(db.cachedAlbums).join([
drift.leftOuterJoin(db.cachedArtists,
db.cachedArtists.id.equalsExp(db.cachedAlbums.artistId)),
])..where(db.cachedAlbums.artistId.equals(artistId));
return cacheFirst<drift.TypedResult, List<AlbumRef>>(
driftStream: query.watch(),
fetchAndPopulate: () async {
final api = await ref.read(libraryApiProvider.future);
final fresh = await api.getArtistAlbums(artistId);
await db.batch((b) {
b.insertAllOnConflictUpdate(
db.cachedAlbums, fresh.map((a) => a.toDrift()).toList());
});
},
toResult: (rows) => rows.map((r) {
final album = r.readTable(db.cachedAlbums);
final artist = r.readTableOrNull(db.cachedArtists);
return album.toRef(artistName: artist?.name ?? '');
}).toList(),
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
// SWR: re-fetch the full album list on every visit. Without this,
// a previously-incomplete drift cache (e.g. user had only opened
// one album by this artist, so cachedAlbums had just that row)
// would render forever as a partial list. The prefetcher only
// warms artistProvider (single row), so this provider isn't
// mass-instantiated and the storm risk that motivated dropping
// alwaysRefresh elsewhere doesn't apply here.
alwaysRefresh: true,
tag: 'artistAlbums($artistId)',
);
});
final artistTracksProvider =
FutureProvider.family<List<TrackRef>, String>((ref, id) async {
return (await ref.watch(libraryApiProvider.future)).getArtistTracks(id);
StreamProvider.family<List<TrackRef>, String>((ref, artistId) {
final db = ref.watch(appDbProvider);
final query = db.select(db.cachedTracks).join([
drift.leftOuterJoin(db.cachedArtists,
db.cachedArtists.id.equalsExp(db.cachedTracks.artistId)),
drift.leftOuterJoin(db.cachedAlbums,
db.cachedAlbums.id.equalsExp(db.cachedTracks.albumId)),
])..where(db.cachedTracks.artistId.equals(artistId));
return cacheFirst<drift.TypedResult, List<TrackRef>>(
driftStream: query.watch(),
fetchAndPopulate: () async {
final api = await ref.read(libraryApiProvider.future);
final fresh = await api.getArtistTracks(artistId);
await db.batch((b) {
b.insertAllOnConflictUpdate(
db.cachedTracks, fresh.map((t) => t.toDrift()).toList());
});
},
toResult: (rows) => rows.map((r) {
final track = r.readTable(db.cachedTracks);
final artist = r.readTableOrNull(db.cachedArtists);
final album = r.readTableOrNull(db.cachedAlbums);
return track.toRef(
artistName: artist?.name ?? '',
albumTitle: album?.title ?? '',
);
}).toList(),
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
tag: 'artistTracks($artistId)',
);
});
final albumProvider =
FutureProvider.family<({AlbumRef album, List<TrackRef> tracks}), String>(
(ref, id) async {
return (await ref.watch(libraryApiProvider.future)).getAlbum(id);
},
);
/// Composite shape (album + tracks) — uses async* + Stream.combineLatest
/// for reactive updates over both rows.
final albumProvider = StreamProvider.family<
({AlbumRef album, List<TrackRef> tracks}), String>((ref, albumId) async* {
final db = ref.watch(appDbProvider);
final albumQuery = (db.select(db.cachedAlbums)
..where((t) => t.id.equals(albumId)))
.join([
drift.leftOuterJoin(db.cachedArtists,
db.cachedArtists.id.equalsExp(db.cachedAlbums.artistId)),
]);
final tracksQuery = (db.select(db.cachedTracks)
..where((t) => t.albumId.equals(albumId))
..orderBy([
(t) => drift.OrderingTerm.asc(t.discNumber),
(t) => drift.OrderingTerm.asc(t.trackNumber),
]))
.join([
drift.leftOuterJoin(db.cachedArtists,
db.cachedArtists.id.equalsExp(db.cachedTracks.artistId)),
]);
// Once-per-subscription guard so we don't re-fetch in a loop if the
// server genuinely returns zero tracks (or if the fetch fails).
var fetchAttempted = false;
// (revalidated flag removed; see SWR note below the yield.)
Future<bool> isOnline() async {
try {
return await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true);
} catch (_) {
return true;
}
}
// Cold-cache fetch: pulls the album + its tracks + any unique
// artists referenced and writes all three tables in one batch.
// Returns true on success (drift watch will re-emit), false on
// failure so the caller can yield an empty result.
Future<bool> fetchAndPopulate() async {
try {
final api = await ref.read(libraryApiProvider.future);
final fresh = await api
.getAlbum(albumId)
.timeout(const Duration(seconds: 10));
// Collect every artist mentioned by the album + its tracks so
// the JOINs that drive both the album header and the track rows
// have something to bind to. Without this, drift returns null
// for the artist row and artistName surfaces empty — visible
// as a missing artist line in the mini player and row list.
final artists = <String, ArtistRef>{};
if (fresh.album.artistId.isNotEmpty &&
fresh.album.artistName.isNotEmpty) {
artists[fresh.album.artistId] = ArtistRef(
id: fresh.album.artistId,
name: fresh.album.artistName,
);
}
for (final t in fresh.tracks) {
if (t.artistId.isNotEmpty &&
t.artistName.isNotEmpty &&
!artists.containsKey(t.artistId)) {
artists[t.artistId] = ArtistRef(
id: t.artistId,
name: t.artistName,
);
}
}
await db.batch((b) {
if (artists.isNotEmpty) {
b.insertAllOnConflictUpdate(
db.cachedArtists, artists.values.map((a) => a.toDrift()).toList());
}
b.insertAllOnConflictUpdate(db.cachedAlbums, [fresh.album.toDrift()]);
b.insertAllOnConflictUpdate(db.cachedTracks,
fresh.tracks.map((t) => t.toDrift()).toList());
});
return true;
} catch (e, st) {
debugPrint('albumProvider($albumId): cold-cache fetch failed: $e\n$st');
return false;
}
}
await for (final albumRows in albumQuery.watch()) {
// Case 1: no album row at all → cold-fetch.
if (albumRows.isEmpty) {
if (fetchAttempted) {
// Already tried and got nothing back.
yield (
album: const AlbumRef(id: '', title: '', artistId: ''),
tracks: const <TrackRef>[],
);
continue;
}
fetchAttempted = true;
if (!await isOnline()) {
yield (
album: const AlbumRef(id: '', title: '', artistId: ''),
tracks: const <TrackRef>[],
);
continue;
}
final ok = await fetchAndPopulate();
if (!ok) {
yield (
album: const AlbumRef(id: '', title: '', artistId: ''),
tracks: const <TrackRef>[],
);
}
// On success, drift watch re-emits with rows; loop continues.
continue;
}
final albumRow = albumRows.first;
final album = albumRow.readTable(db.cachedAlbums).toRef(
artistName: albumRow.readTableOrNull(db.cachedArtists)?.name ?? '',
);
final trackRows = await tracksQuery.get();
// Case 2: album row exists but no tracks. This happens when an
// upstream provider (artistAlbumsProvider, sync, etc.) populated
// album rows without their track lists. Trigger the same
// fetchAndPopulate so the album becomes complete; drift watch
// re-emits and we land in the populated branch on the next pass.
if (trackRows.isEmpty && !fetchAttempted) {
fetchAttempted = true;
if (await isOnline()) {
final ok = await fetchAndPopulate();
if (ok) continue; // wait for watch re-emit
}
// Fall through and yield with the album + empty tracks if the
// fetch failed or we're offline.
}
final tracks = trackRows.map((r) {
final track = r.readTable(db.cachedTracks);
final artist = r.readTableOrNull(db.cachedArtists);
return track.toRef(
artistName: artist?.name ?? '',
albumTitle: album.title,
);
}).toList();
// Note: NO SWR here on purpose. Prior code kicked a background
// refresh on every first cache hit, which combined with the
// metadata prefetcher meant every prewarmed album id triggered
// an extra fetch even when drift was already populated. Tracks
// and album metadata don't change on the same timescale as
// playlists; a stale read is fine until the user invalidates
// (pull-to-refresh) or the album is genuinely re-fetched.
yield (album: album, tracks: tracks);
}
});
@@ -0,0 +1,908 @@
import 'dart:convert';
import 'package:drift/drift.dart' as drift;
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../api/endpoints/library_lists.dart';
import '../api/endpoints/likes.dart';
import '../api/endpoints/me.dart';
import '../auth/auth_provider.dart' show authControllerProvider;
import '../cache/adapters.dart';
import '../cache/audio_cache_manager.dart' show appDbProvider;
import '../cache/cache_first.dart';
import '../cache/connectivity_provider.dart';
import '../cache/db.dart';
import '../cache/metadata_prefetcher.dart';
import '../cache/tile_providers.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/album.dart';
import '../models/artist.dart';
import '../models/history_event.dart';
import '../models/quarantine_mine.dart';
import '../models/track.dart';
import '../player/player_provider.dart';
import '../quarantine/quarantine_provider.dart';
import '../shared/live_events_provider.dart';
import '../shared/widgets/main_app_bar_actions.dart';
import '../shared/widgets/skeletons.dart';
import '../shared/widgets/server_image.dart';
import '../theme/theme_extension.dart';
import 'widgets/album_card.dart';
import 'widgets/artist_card.dart';
import 'widgets/track_row.dart';
// Providers scoped to this screen. Each tab gets its own first page.
// Infinite scroll is a future enhancement; for v1 phone testing the
// first 50 rows per tab is enough.
final _libraryListsApiProvider = FutureProvider<LibraryListsApi>((ref) async {
return LibraryListsApi(await ref.watch(dioProvider.future));
});
final _likesApiProvider = FutureProvider<LikesApi>((ref) async {
return LikesApi(await ref.watch(dioProvider.future));
});
final _meApiProvider = FutureProvider<MeApi>((ref) async {
return MeApi(await ref.watch(dioProvider.future));
});
/// Drift-first all-artists list. Reads cached_artists ordered by
/// sortName; GridView.builder takes care of lazy widget construction
/// so loading the full set up front is fine for typical library sizes.
/// SWR refresh on every subscription hits /api/artists with a generous
/// limit so newly-scanned-but-not-yet-synced rows land soon after.
///
/// The old AsyncNotifier+loadMore infinite-scroll path went away: the
/// previous "fetch one page at a time as you scroll" felt like the
/// rest of the app was buffering when this tab was the slow surface,
/// and SyncController already populates the full set of artist rows
/// via /api/library/sync.
final _libraryArtistsProvider = StreamProvider<List<ArtistRef>>((ref) {
final db = ref.watch(appDbProvider);
// LEFT JOIN cached_albums so each artist row carries a representative
// album id for cover-URL reconstruction. Sorted by artist sortName
// then album sortTitle: the first row per artist gets the
// alphabetically-first album. Dedup happens in toResult.
final query = db.select(db.cachedArtists).join([
drift.leftOuterJoin(db.cachedAlbums,
db.cachedAlbums.artistId.equalsExp(db.cachedArtists.id)),
])
..orderBy([
drift.OrderingTerm.asc(db.cachedArtists.sortName),
drift.OrderingTerm.asc(db.cachedAlbums.sortTitle),
]);
return cacheFirst<drift.TypedResult, List<ArtistRef>>(
driftStream: query.watch(),
fetchAndPopulate: () async {
// Cold-cache fallback: sync should have populated drift already,
// but a fresh install + first Library visit before sync completes
// will be empty. Fetch a generous chunk via /api/artists and
// persist; subsequent SWR refreshes keep things current.
final api = await ref.read(_libraryListsApiProvider.future);
final fresh = await api.listArtists(limit: 1000, offset: 0);
await db.batch((b) {
b.insertAllOnConflictUpdate(
db.cachedArtists,
fresh.items.map((a) => a.toDrift()).toList(),
);
});
},
toResult: (rows) {
// The join multiplies rows by album count; dedup by artist id
// keeping the first occurrence so we get one ArtistRef per
// artist with the alphabetically-first album's id for the
// cover-URL projection. Artists with no albums in drift yet
// come through as a single row with null cachedAlbums and an
// empty coverUrl — UI falls back to the placeholder icon.
final seen = <String>{};
final out = <ArtistRef>[];
for (final r in rows) {
final a = r.readTable(db.cachedArtists);
if (!seen.add(a.id)) continue;
final album = r.readTableOrNull(db.cachedAlbums);
out.add(a.toRef(coverAlbumId: album?.id ?? ''));
}
return out;
},
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
alwaysRefresh: true,
tag: 'libraryArtists',
);
});
/// Drift-first all-albums list. Joins cached_albums with cached_artists
/// for the artistName field. Same cold-cache fallback + SWR refresh
/// pattern as libraryArtistsProvider.
final _libraryAlbumsProvider = StreamProvider<List<AlbumRef>>((ref) {
final db = ref.watch(appDbProvider);
final query = db.select(db.cachedAlbums).join([
drift.leftOuterJoin(db.cachedArtists,
db.cachedArtists.id.equalsExp(db.cachedAlbums.artistId)),
])
..orderBy([drift.OrderingTerm.asc(db.cachedAlbums.sortTitle)]);
return cacheFirst<drift.TypedResult, List<AlbumRef>>(
driftStream: query.watch(),
fetchAndPopulate: () async {
final api = await ref.read(_libraryListsApiProvider.future);
final fresh = await api.listAlbums(limit: 1000, offset: 0);
await db.batch((b) {
b.insertAllOnConflictUpdate(
db.cachedAlbums,
fresh.items.map((a) => a.toDrift()).toList(),
);
});
},
toResult: (rows) => rows.map((r) {
final album = r.readTable(db.cachedAlbums);
final artist = r.readTableOrNull(db.cachedArtists);
return album.toRef(artistName: artist?.name ?? '');
}).toList(),
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
alwaysRefresh: true,
tag: 'libraryAlbums',
);
});
// Drift-first History tab. Mirrors homeProvider's pattern: store the
// last /api/me/history page as JSON in a single-row drift table, yield
// it immediately on subscribe (so the tab paints from disk on cold
// open), then SWR-refresh in the background. Also gives basic offline
// scrollback — the last fetched page survives connectivity loss.
//
// JSON blob (vs columnar) because the page is small, always read whole,
// and the HistoryPage.fromJson constructor already accepts the wire
// shape — no schema-evolution pain when server-side fields change.
final _historyProvider = StreamProvider<HistoryPage>((ref) {
final db = ref.watch(appDbProvider);
return cacheFirst<CachedHistorySnapshotData, HistoryPage>(
driftStream: db.select(db.cachedHistorySnapshot).watch(),
fetchAndPopulate: () async {
final api = await ref.read(_meApiProvider.future);
final fresh = await api.history();
await db.into(db.cachedHistorySnapshot).insertOnConflictUpdate(
CachedHistorySnapshotCompanion.insert(
json: _encodeHistoryPage(fresh),
updatedAt: drift.Value(DateTime.now()),
),
);
},
toResult: (rows) => rows.isEmpty
? const HistoryPage(events: [], hasMore: false)
: HistoryPage.fromJson(
jsonDecode(rows.first.json) as Map<String, dynamic>),
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
// SWR: yield cache instantly, then refresh in the background so the
// tab reflects the freshest plays. Matches homeProvider behavior.
alwaysRefresh: true,
tag: 'history',
);
});
/// Encodes HistoryPage back to the wire-format JSON shape
/// /api/me/history emits, so HistoryPage.fromJson can round-trip
/// through the drift cache.
String _encodeHistoryPage(HistoryPage h) => jsonEncode({
'events': h.events
.map((e) => {
'id': e.id,
'played_at': e.playedAt,
'track': {
'id': e.track.id,
'title': e.track.title,
'album_id': e.track.albumId,
'album_title': e.track.albumTitle,
'artist_id': e.track.artistId,
'artist_name': e.track.artistName,
'track_number': e.track.trackNumber,
'disc_number': e.track.discNumber,
'duration_sec': e.track.durationSec,
'stream_url': e.track.streamUrl,
},
})
.toList(),
'has_more': h.hasMore,
});
// Per-item Liked tabs (Slice E of the per-item rendering pass).
// Each provider yields just the ordered list of entity IDs; the UI
// then renders per-tile widgets that hydrate each entity individually
// via albumTileProvider / artistTileProvider / trackTileProvider.
//
// Reads come from cached_likes (sync- and optimistic-write-populated),
// projected with ORDER BY likedAt DESC. fetchAndPopulate hits the
// cheap /api/likes/ids endpoint — the bulk /api/likes/* endpoints
// that returned fully denormalized entities are no longer needed for
// this path since tile providers handle entity hydration themselves.
//
// likedAt ordering note: cached_likes.likedAt is whatever drift
// assigned via currentDateAndTime when the row was first inserted
// (either by sync or LikesController). insertOrIgnore on subsequent
// fetches preserves the existing likedAt so ordering stays stable.
// Approximate but acceptable — matches prior Slice 3 behavior.
List<String> _idsForEntity(List<CachedLike> rows) =>
rows.map((r) => r.entityId).toList(growable: false);
final _likedTrackIdsProvider = StreamProvider<List<String>>((ref) {
final db = ref.watch(appDbProvider);
final query = (db.select(db.cachedLikes)
..where((t) => t.entityType.equals('track'))
..orderBy([(t) => drift.OrderingTerm.desc(t.likedAt)]))
.watch();
return cacheFirst<CachedLike, List<String>>(
driftStream: query,
fetchAndPopulate: () => _populateLikeIds(ref),
toResult: _idsForEntity,
isOnline: () async => (await ref.read(connectivityProvider.future)),
alwaysRefresh: true,
tag: 'likedTrackIds',
);
});
final _likedAlbumIdsProvider = StreamProvider<List<String>>((ref) {
final db = ref.watch(appDbProvider);
final query = (db.select(db.cachedLikes)
..where((t) => t.entityType.equals('album'))
..orderBy([(t) => drift.OrderingTerm.desc(t.likedAt)]))
.watch();
return cacheFirst<CachedLike, List<String>>(
driftStream: query,
fetchAndPopulate: () => _populateLikeIds(ref),
toResult: _idsForEntity,
isOnline: () async => (await ref.read(connectivityProvider.future)),
alwaysRefresh: true,
tag: 'likedAlbumIds',
);
});
final _likedArtistIdsProvider = StreamProvider<List<String>>((ref) {
final db = ref.watch(appDbProvider);
final query = (db.select(db.cachedLikes)
..where((t) => t.entityType.equals('artist'))
..orderBy([(t) => drift.OrderingTerm.desc(t.likedAt)]))
.watch();
return cacheFirst<CachedLike, List<String>>(
driftStream: query,
fetchAndPopulate: () => _populateLikeIds(ref),
toResult: _idsForEntity,
isOnline: () async => (await ref.read(connectivityProvider.future)),
alwaysRefresh: true,
tag: 'likedArtistIds',
);
});
/// Shared cold-cache populator: hits /api/likes/ids once and writes
/// rows for all three entity types via insertOrIgnore. The three
/// providers above all trigger this on their first empty-drift
/// emission; the dedup in cacheFirst's revalidate state plus drift's
/// insertOrIgnore semantics make the multiple-trigger case cheap.
Future<void> _populateLikeIds(Ref ref) async {
final api = await ref.read(_likesApiProvider.future);
final user = ref.read(authControllerProvider).value;
if (user == null) return;
final fresh = await api.ids();
final db = ref.read(appDbProvider);
await db.batch((b) {
for (final id in fresh.tracks) {
b.insert(
db.cachedLikes,
CachedLikesCompanion.insert(
userId: user.id,
entityType: 'track',
entityId: id,
),
mode: drift.InsertMode.insertOrIgnore,
);
}
for (final id in fresh.albums) {
b.insert(
db.cachedLikes,
CachedLikesCompanion.insert(
userId: user.id,
entityType: 'album',
entityId: id,
),
mode: drift.InsertMode.insertOrIgnore,
);
}
for (final id in fresh.artists) {
b.insert(
db.cachedLikes,
CachedLikesCompanion.insert(
userId: user.id,
entityType: 'artist',
entityId: id,
),
mode: drift.InsertMode.insertOrIgnore,
);
}
});
}
// Hidden tab uses the canonical `myQuarantineProvider` (AsyncNotifier with
// optimistic flag/unflag) so flagging from any kebab and unflagging from
// the Hidden tab keep one source of truth.
class LibraryScreen extends ConsumerStatefulWidget {
const LibraryScreen({super.key});
@override
ConsumerState<LibraryScreen> createState() => _LibraryScreenState();
}
class _LibraryScreenState extends ConsumerState<LibraryScreen>
with TickerProviderStateMixin {
late final TabController _ctrl = TabController(length: 5, vsync: this);
@override
void dispose() {
_ctrl.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
// Pre-warm every tab's provider on Library mount so swiping
// between tabs feels instant rather than each tab paying its
// own cold-cache cost on first visit. ref.listen subscribes
// without rebuilding LibraryScreen on emit; subscriptions stay
// alive for the lifetime of this widget. cacheFirst handles
// dedupe of concurrent fetchAndPopulate triggers.
ref.listen(_libraryArtistsProvider, (_, __) {});
ref.listen(_libraryAlbumsProvider, (_, __) {});
ref.listen(_historyProvider, (_, __) {});
ref.listen(_likedTrackIdsProvider, (_, __) {});
ref.listen(_likedAlbumIdsProvider, (_, __) {});
ref.listen(_likedArtistIdsProvider, (_, __) {});
ref.listen(myQuarantineProvider, (_, __) {});
return Scaffold(
backgroundColor: fs.obsidian,
appBar: AppBar(
backgroundColor: fs.obsidian,
elevation: 0,
title: Text('Library', style: TextStyle(color: fs.parchment)),
actions: const [MainAppBarActions(currentRoute: '/library')],
bottom: TabBar(
controller: _ctrl,
isScrollable: true,
tabAlignment: TabAlignment.start,
labelColor: fs.parchment,
unselectedLabelColor: fs.ash,
indicatorColor: fs.accent,
tabs: const [
Tab(text: 'Artists'),
Tab(text: 'Albums'),
Tab(text: 'History'),
Tab(text: 'Liked'),
Tab(text: 'Hidden'),
],
),
),
body: TabBarView(
controller: _ctrl,
children: const [
_ArtistsTab(),
_AlbumsTab(),
_HistoryTab(),
_LikedTab(),
_HiddenTab(),
],
),
);
}
}
class _ArtistsTab extends ConsumerWidget {
const _ArtistsTab();
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return ref.watch(_libraryArtistsProvider).when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => Center(child: Text('$e', style: TextStyle(color: fs.error))),
data: (artists) {
// Warm details for the first screenful so taps are instant.
ref
.read(metadataPrefetcherProvider)
.warmArtists(artists.map((a) => a.id));
return artists.isEmpty
? Center(child: Text("No artists yet — scan a library folder via the server's config.", style: TextStyle(color: fs.ash), textAlign: TextAlign.center))
: RefreshIndicator(
onRefresh: () async => ref.refresh(_libraryArtistsProvider.future),
// LayoutBuilder + cell-aware ArtistCard width mirrors
// the AlbumsTab pattern so the circular avatar stays
// a true circle on narrow grid cells.
//
// Drift-first: GridView holds the full sorted list;
// .builder lazily realizes only visible cells, so
// even on large libraries the up-front cost is just
// a sort over cached_artists, not N network round
// trips.
child: LayoutBuilder(builder: (ctx, constraints) {
const cols = 3;
const sidePad = 8.0;
const gap = 8.0;
final cellW = (constraints.maxWidth -
sidePad * 2 -
gap * (cols - 1)) /
cols;
// avatar (cellW - 16) + gap (8) + 1 line name (~18)
// + slack matched to AlbumsTab's overflow guard.
final cellH = (cellW - 16) + 8 + 18 + 8;
return GridView.builder(
padding: const EdgeInsets.all(sidePad),
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: cols,
mainAxisExtent: cellH,
mainAxisSpacing: gap,
crossAxisSpacing: gap,
),
itemCount: artists.length,
itemBuilder: (ctx, i) {
final artist = artists[i];
return ArtistCard(
artist: artist,
width: cellW,
onTap: () => ctx.push('/artists/${artist.id}',
extra: artist),
);
},
);
}),
);
},
);
}
}
class _AlbumsTab extends ConsumerWidget {
const _AlbumsTab();
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return ref.watch(_libraryAlbumsProvider).when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => Center(child: Text('$e', style: TextStyle(color: fs.error))),
data: (albums) {
return albums.isEmpty
? Center(child: Text("No albums yet — scan a library folder via the server's config.", style: TextStyle(color: fs.ash), textAlign: TextAlign.center))
: RefreshIndicator(
onRefresh: () async => ref.refresh(_libraryAlbumsProvider.future),
// Same responsive 3-up grid as the artist detail
// album list — LayoutBuilder + AlbumCard sized to the
// cell, mainAxisExtent matched to actual card height.
// Drift-first; full sorted list, lazy realization via
// GridView.builder.
child: LayoutBuilder(builder: (ctx, constraints) {
const cols = 3;
const sidePad = 8.0;
const gap = 8.0;
final cellW = (constraints.maxWidth -
sidePad * 2 -
gap * (cols - 1)) /
cols;
// cover (cellW - 16) + gap (8) + 2-line title (~36)
// + artist line (~16) + slack. Slack is generous on
// purpose — line-height + font scaling variations
// would otherwise overflow the cell by a pixel
// (logged as a noisy RenderFlex warning).
final cellH = (cellW - 16) + 8 + 36 + 16 + 8;
return GridView.builder(
padding: const EdgeInsets.all(sidePad),
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: cols,
mainAxisExtent: cellH,
mainAxisSpacing: gap,
crossAxisSpacing: gap,
),
itemCount: albums.length,
itemBuilder: (ctx, i) {
final album = albums[i];
return AlbumCard(
album: album,
width: cellW,
titleMaxLines: 2,
onTap: () => ctx.push('/albums/${album.id}',
extra: album),
);
},
);
}),
);
},
);
}
}
class _HistoryTab extends ConsumerWidget {
const _HistoryTab();
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return ref.watch(_historyProvider).when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => Center(child: Text('$e', style: TextStyle(color: fs.error))),
data: (page) => page.events.isEmpty
? Center(child: Text('No listening history yet.', style: TextStyle(color: fs.ash)))
: RefreshIndicator(
onRefresh: () async => ref.refresh(_historyProvider.future),
child: ListView.separated(
itemCount: page.events.length,
separatorBuilder: (_, __) => Divider(height: 1, color: fs.iron),
itemBuilder: (ctx, i) {
final event = page.events[i];
return TrackRow(
track: event.track,
onTap: () => ref
.read(playerActionsProvider)
.playTracks([event.track]),
trailing: Text(
_relativeTime(event.playedAt),
style: TextStyle(color: fs.ash, fontSize: 12),
),
);
},
),
),
);
}
}
class _LikedTab extends ConsumerWidget {
const _LikedTab();
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
// SSE wire-up: any cross-device like / unlike triggers a refresh
// of the discovery providers. LikesController handles local
// mutations optimistically through the same cached_likes table,
// so toggling a like locally re-emits the streams instantly
// without needing an invalidate here.
ref.listen<AsyncValue<LiveEvent>>(liveEventsProvider, (_, next) {
final e = next.asData?.value;
if (e == null) return;
switch (e.kind) {
case 'track.liked':
case 'track.unliked':
case 'album.liked':
case 'album.unliked':
case 'artist.liked':
case 'artist.unliked':
ref.invalidate(_likedTrackIdsProvider);
ref.invalidate(_likedAlbumIdsProvider);
ref.invalidate(_likedArtistIdsProvider);
}
});
final tracksA = ref.watch(_likedTrackIdsProvider);
final albumsA = ref.watch(_likedAlbumIdsProvider);
final artistsA = ref.watch(_likedArtistIdsProvider);
if (tracksA.isLoading || albumsA.isLoading || artistsA.isLoading) {
return const Center(child: CircularProgressIndicator());
}
final trackIds = tracksA.value;
final albumIds = albumsA.value;
final artistIds = artistsA.value;
if (trackIds == null || albumIds == null || artistIds == null) {
return Center(child: Text("Couldn't load liked items.", style: TextStyle(color: fs.error)));
}
if (trackIds.isEmpty && albumIds.isEmpty && artistIds.isEmpty) {
return Center(child: Text('No liked artists, albums, or tracks yet.', style: TextStyle(color: fs.ash), textAlign: TextAlign.center));
}
return RefreshIndicator(
onRefresh: () async {
await Future.wait([
ref.refresh(_likedTrackIdsProvider.future),
ref.refresh(_likedAlbumIdsProvider.future),
ref.refresh(_likedArtistIdsProvider.future),
]);
},
child: ListView(children: [
if (artistIds.isNotEmpty) ...[
_SectionHeader(label: 'Artists', count: artistIds.length),
SizedBox(
height: 168,
child: ListView.builder(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 8),
itemCount: artistIds.length,
itemBuilder: (ctx, i) =>
_LikedArtistTile(id: artistIds[i]),
),
),
],
if (albumIds.isNotEmpty) ...[
_SectionHeader(label: 'Albums', count: albumIds.length),
SizedBox(
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 8),
itemCount: albumIds.length,
itemBuilder: (ctx, i) =>
_LikedAlbumTile(id: albumIds[i]),
),
),
],
if (trackIds.isNotEmpty) ...[
_SectionHeader(label: 'Tracks', count: trackIds.length),
...trackIds.map(
(id) => _LikedTrackRow(id: id, sectionIds: trackIds),
),
],
const SizedBox(height: 96),
]),
);
}
}
/// Skeleton→content cross-fade duration. Matches home_screen so the
/// reveal feel is consistent across surfaces. See _tileRevealDuration
/// in home_screen.dart for the rationale.
const Duration _likedTileReveal = Duration(milliseconds: 220);
/// Liked-Artists carousel tile. Skeleton until artistTileProvider
/// yields a populated row.
class _LikedArtistTile extends ConsumerWidget {
const _LikedArtistTile({required this.id});
final String id;
@override
Widget build(BuildContext context, WidgetRef ref) {
final artist = ref.watch(artistTileProvider(id)).asData?.value;
return AnimatedSwitcher(
duration: _likedTileReveal,
switchInCurve: Curves.easeOut,
child: artist == null
? const SkeletonArtistTile(key: ValueKey('skeleton'))
: ArtistCard(
key: ValueKey('artist-${artist.id}'),
artist: artist,
onTap: () =>
context.push('/artists/${artist.id}', extra: artist),
),
);
}
}
/// Liked-Albums carousel tile. Skeleton until albumTileProvider
/// yields a populated row.
class _LikedAlbumTile extends ConsumerWidget {
const _LikedAlbumTile({required this.id});
final String id;
@override
Widget build(BuildContext context, WidgetRef ref) {
final album = ref.watch(albumTileProvider(id)).asData?.value;
return AnimatedSwitcher(
duration: _likedTileReveal,
switchInCurve: Curves.easeOut,
child: album == null
? const SkeletonAlbumTile(key: ValueKey('skeleton'))
: AlbumCard(
key: ValueKey('album-${album.id}'),
album: album,
onTap: () => context.push('/albums/${album.id}', extra: album),
),
);
}
}
/// Liked-Tracks list row. Skeleton until trackTileProvider yields a
/// populated row. Tap plays the section starting at this track,
/// using whichever tracks are currently hydrated; still-loading
/// tracks are skipped from the play queue and join on next rebuild.
class _LikedTrackRow extends ConsumerWidget {
const _LikedTrackRow({required this.id, required this.sectionIds});
final String id;
final List<String> sectionIds;
@override
Widget build(BuildContext context, WidgetRef ref) {
final track = ref.watch(trackTileProvider(id)).asData?.value;
return AnimatedSwitcher(
duration: _likedTileReveal,
switchInCurve: Curves.easeOut,
child: track == null
? const SkeletonTrackRow(key: ValueKey('skeleton'))
: TrackRow(
key: ValueKey('track-${track.id}'),
track: track,
onTap: () {
final hydrated = <TrackRef>[];
for (final i in sectionIds) {
final v = ref.read(trackTileProvider(i)).asData?.value;
if (v != null) hydrated.add(v);
}
final start = hydrated.indexWhere((t) => t.id == id);
ref.read(playerActionsProvider).playTracks(
hydrated,
initialIndex: start < 0 ? 0 : start,
);
},
),
);
}
}
class _HiddenTab extends ConsumerWidget {
const _HiddenTab();
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return ref.watch(myQuarantineProvider).when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => Center(child: Text('$e', style: TextStyle(color: fs.error))),
data: (rows) => rows.isEmpty
? Center(
child: Text(
'No hidden tracks.\nUse a track\'s menu to flag bad rips or wrong tags.',
textAlign: TextAlign.center,
style: TextStyle(color: fs.ash),
),
)
: RefreshIndicator(
onRefresh: () async => ref.refresh(myQuarantineProvider.future),
child: ListView.separated(
itemCount: rows.length,
separatorBuilder: (_, __) => Divider(height: 1, color: fs.iron),
itemBuilder: (ctx, i) => _QuarantineTile(row: rows[i]),
),
),
);
}
}
class _QuarantineTile extends ConsumerWidget {
const _QuarantineTile({required this.row});
final QuarantineMineRow row;
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final reasonLabel = switch (row.reason) {
'bad_rip' => 'Bad rip',
'wrong_file' => 'Wrong file',
'wrong_tags' => 'Wrong tags',
'duplicate' => 'Duplicate',
_ => 'Other',
};
final coverUrl = row.albumId.isNotEmpty ? '/api/albums/${row.albumId}/cover' : '';
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: SizedBox(
width: 56,
height: 56,
child: coverUrl.isEmpty
? Container(color: fs.slate)
: ServerImage(
url: coverUrl,
fit: BoxFit.cover,
fallback: Container(color: fs.slate),
),
),
),
const SizedBox(width: 12),
Expanded(
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(
row.trackTitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14),
),
Text(
'${row.artistName} · ${row.albumTitle}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.ash, fontSize: 12),
),
Padding(
padding: const EdgeInsets.only(top: 4),
child: Row(children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: fs.iron,
borderRadius: BorderRadius.circular(4),
),
child: Text(reasonLabel, style: TextStyle(color: fs.ash, fontSize: 11)),
),
if (row.createdAt.isNotEmpty) ...[
const SizedBox(width: 8),
Text(_relativeTime(row.createdAt),
style: TextStyle(color: fs.ash, fontSize: 11)),
],
]),
),
]),
),
IconButton(
tooltip: 'Unhide',
icon: Icon(Icons.restore, color: fs.ash, size: 20),
onPressed: () async {
try {
await ref.read(myQuarantineProvider.notifier).unflag(row.trackId);
} catch (_) {
// Optimistic rollback handled by the notifier; surface
// the failure only if the user kept the tab open.
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Could not unhide; try again.')),
);
}
}
},
),
]),
);
}
}
class _SectionHeader extends StatelessWidget {
const _SectionHeader({required this.label, required this.count});
final String label;
final int count;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Row(children: [
Text(label,
style: TextStyle(
color: fs.parchment, fontSize: 18, fontWeight: FontWeight.w500)),
const SizedBox(width: 8),
Text('$count', style: TextStyle(color: fs.ash, fontSize: 13)),
]),
);
}
}
/// Lightweight relative-time formatter: <1h "23m ago" / <24h "3h ago"
/// / <7d "Tue 14:32" / older "May 1" / older diff-year "May 1, 2025".
/// Mirrors web/src/lib/components/HistoryRow.svelte's relativeTime.
String _relativeTime(String iso) {
final t = DateTime.tryParse(iso);
if (t == null) return '';
final now = DateTime.now();
final diff = now.difference(t);
if (diff.inMinutes < 60) {
final m = diff.inMinutes < 1 ? 1 : diff.inMinutes;
return '${m}m ago';
}
if (diff.inHours < 24) return '${diff.inHours}h ago';
if (diff.inDays < 7) {
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
final hh = t.hour.toString().padLeft(2, '0');
final mm = t.minute.toString().padLeft(2, '0');
return '${days[t.weekday - 1]} $hh:$mm';
}
const months = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
];
if (t.year == now.year) return '${months[t.month - 1]} ${t.day}';
return '${months[t.month - 1]} ${t.day}, ${t.year}';
}
@@ -1,51 +1,112 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../../models/album.dart';
import '../../player/player_provider.dart';
import '../../shared/widgets/server_image.dart';
import '../../theme/theme_extension.dart';
import '../library_providers.dart';
import 'play_circle_button.dart';
class AlbumCard extends StatelessWidget {
const AlbumCard({required this.album, required this.onTap, super.key});
class AlbumCard extends ConsumerWidget {
const AlbumCard({
required this.album,
required this.onTap,
this.width = 140,
this.titleMaxLines = 1,
this.showArtist = true,
super.key,
});
final AlbumRef album;
final VoidCallback onTap;
/// Outer width of the card. Cover is square at width - 16 (8dp
/// horizontal padding either side). Default suits horizontal lists;
/// grids should pass the cell width so the card scales down.
final double width;
/// Lets callers (e.g. the artist detail grid) allow the title to
/// wrap to a second line so it isn't truncated to a single
/// ellipsized character at narrower widths.
final int titleMaxLines;
/// Suppress the artist name. Useful on surfaces where the artist is
/// already implied by the page header (e.g. artist detail).
final bool showArtist;
@override
Widget build(BuildContext context) {
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return GestureDetector(
onTap: onTap,
child: SizedBox(
width: 140,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Container(
width: 124,
height: 124,
color: fs.slate,
child: album.coverUrl.isEmpty
? SvgPicture.asset('assets/svg/album-fallback.svg', fit: BoxFit.cover)
: Image.network(album.coverUrl, fit: BoxFit.cover),
),
final coverSize = width - 16;
return SizedBox(
width: width,
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Stack: cover image + overlaid play button at bottom-right.
Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Container(
width: coverSize,
height: coverSize,
color: fs.slate,
child: album.coverUrl.isEmpty
? SvgPicture.asset('assets/svg/album-fallback.svg',
fit: BoxFit.cover)
: ServerImage(url: album.coverUrl, fit: BoxFit.cover),
),
),
Positioned(
bottom: 6,
right: 6,
child: PlayCircleButton(
onPressed: () => _playAlbum(ref),
),
),
],
),
const SizedBox(height: 8),
Text(
album.title,
maxLines: titleMaxLines,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14),
),
if (showArtist && album.artistName.isNotEmpty)
Text(
album.artistName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.ash, fontSize: 12),
),
],
),
const SizedBox(height: 8),
Text(
album.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14),
),
Text(
album.artistName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.ash, fontSize: 12),
),
]),
),
),
),
);
}
/// Fetches the album's tracks via /api/albums/{id} and starts playback
/// from the first track. Errors are swallowed by the button's outer
/// try/finally; callers don't surface them — failed fetches just keep
/// the spinner visible until the button is retapped.
Future<void> _playAlbum(WidgetRef ref) async {
final api = await ref.read(libraryApiProvider.future);
final result = await api.getAlbum(album.id);
if (result.tracks.isEmpty) return;
await ref
.read(playerActionsProvider)
.playTracks(result.tracks, initialIndex: 0);
}
}
@@ -1,44 +1,101 @@
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../../models/artist.dart';
import '../../player/player_provider.dart';
import '../../shared/widgets/server_image.dart';
import '../../theme/theme_extension.dart';
import '../library_providers.dart';
import 'play_circle_button.dart';
class ArtistCard extends StatelessWidget {
const ArtistCard({required this.artist, required this.onTap, super.key});
class ArtistCard extends ConsumerWidget {
const ArtistCard({
required this.artist,
required this.onTap,
this.width = 140,
super.key,
});
final ArtistRef artist;
final VoidCallback onTap;
/// Outer width of the card. Avatar is a circle of width-16 (8dp
/// horizontal padding either side). Default suits horizontal lists;
/// grids should pass the cell width so the avatar shrinks
/// proportionally and stays a true circle.
final double width;
@override
Widget build(BuildContext context) {
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return GestureDetector(
onTap: onTap,
child: SizedBox(
width: 140,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
ClipOval(
child: Container(
width: 124,
height: 124,
color: fs.slate,
child: artist.coverUrl.isEmpty
? SvgPicture.asset('assets/svg/album-fallback.svg', fit: BoxFit.cover)
: Image.network(artist.coverUrl, fit: BoxFit.cover),
final coverSize = width - 16;
return SizedBox(
width: width,
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
// Stack: circular avatar + overlaid play button at bottom-right.
// Avatar size derives from the [width] parameter so the
// Library Artists 3-column grid can pass its cell width
// (~109dp on typical phones) and the avatar stays a
// perfect circle. Previous hardcoded 124×124 got squeezed
// horizontally in the grid (cell narrower than 124+16
// padding) but kept its 124dp height — ClipOval produced
// a visible vertical ellipse. Mirrors AlbumCard's width-
// parameter convention.
Stack(
children: [
ClipOval(
child: Container(
width: coverSize,
height: coverSize,
color: fs.slate,
child: artist.coverUrl.isEmpty
? SvgPicture.asset('assets/svg/album-fallback.svg',
fit: BoxFit.cover)
: ServerImage(url: artist.coverUrl, fit: BoxFit.cover),
),
),
Positioned(
bottom: 4,
right: 4,
child: PlayCircleButton(
onPressed: () => _playArtistShuffle(ref),
),
),
],
),
),
const SizedBox(height: 8),
Text(
artist.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14),
),
]),
const SizedBox(height: 8),
Text(
artist.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14),
),
]),
),
),
),
);
}
/// Fetches the artist's tracks via /api/artists/{id}/tracks, shuffles
/// them (Fisher-Yates, default Random), and plays from index 0.
/// Matches the web ArtistCard's `playQueue(shuffle(tracks), 0)`.
Future<void> _playArtistShuffle(WidgetRef ref) async {
final api = await ref.read(libraryApiProvider.future);
final tracks = await api.getArtistTracks(artist.id);
if (tracks.isEmpty) return;
final shuffled = List.of(tracks);
shuffled.shuffle(Random());
await ref
.read(playerActionsProvider)
.playTracks(shuffled, initialIndex: 0);
}
}
@@ -0,0 +1,29 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../cache/audio_cache_manager.dart';
import '../../theme/theme_extension.dart';
/// Small download glyph shown next to a track row when the track is
/// cached locally. FutureBuilder one-shot — track rows are short-lived
/// and cache state rarely changes mid-render.
class CachedIndicator extends ConsumerWidget {
const CachedIndicator({required this.trackId, super.key});
final String trackId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final mgr = ref.read(audioCacheManagerProvider);
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return FutureBuilder<bool>(
future: mgr.isCached(trackId),
builder: (ctx, snap) {
if (snap.data != true) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.only(left: 4),
child: Icon(Icons.download_done, size: 14, color: fs.accent),
);
},
);
}
}
@@ -0,0 +1,84 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../models/track.dart';
import '../../player/player_provider.dart';
import '../../shared/widgets/server_image.dart';
import '../../shared/widgets/track_actions/track_actions_button.dart';
import '../../theme/theme_extension.dart';
/// Small horizontal track cell used by the home Most-played section.
/// Mirrors the web CompactTrackCard sizing (~176dp wide, ~56dp tall).
/// Tap plays from this track within [sectionTracks] starting at [index].
class CompactTrackCard extends ConsumerWidget {
const CompactTrackCard({
super.key,
required this.track,
required this.sectionTracks,
required this.index,
});
final TrackRef track;
/// All tracks in the home section so play-from-here can queue them
/// in order.
final List<TrackRef> sectionTracks;
final int index;
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
// Cover URL derives from the track's album. Mirrors web
// CompactTrackCard which calls coverUrl(track.album_id).
final coverUrl = track.albumId.isNotEmpty
? '/api/albums/${track.albumId}/cover'
: '';
return SizedBox(
width: 176,
child: InkWell(
onTap: () => ref
.read(playerActionsProvider)
.playTracks(sectionTracks, initialIndex: index),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Row(children: [
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: SizedBox(
width: 48,
height: 48,
child: ServerImage(
url: coverUrl,
fit: BoxFit.cover,
fallback: Container(color: fs.slate),
),
),
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
track.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 13),
),
Text(
track.artistName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.ash, fontSize: 11),
),
],
),
),
TrackActionsButton(track: track),
]),
),
),
);
}
}
@@ -23,17 +23,18 @@ class HorizontalScrollRow extends StatelessWidget {
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: Text(
title,
style: TextStyle(
fontFamily: fs.display.fontFamily,
fontSize: 18,
color: fs.parchment,
if (title.isNotEmpty)
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: Text(
title,
style: TextStyle(
fontFamily: fs.display.fontFamily,
fontSize: 18,
color: fs.parchment,
),
),
),
),
SizedBox(
height: height,
child: ListView(
@@ -0,0 +1,96 @@
import 'package:flutter/material.dart';
import '../../theme/theme_extension.dart';
/// Always-visible 44dp circular play button overlaid on home-screen
/// card art (AlbumCard / ArtistCard / PlaylistCard). Mirrors the
/// hover-revealed `.play-overlay` on the web cards, but always shown
/// because hover is not a real interaction on touch.
///
/// Manages its own loading state via [_starting] so the caller's tap
/// handler can be `Future<void> Function()` without worrying about
/// re-entrancy. Disabled state suppresses the tap (used for empty
/// playlists).
class PlayCircleButton extends StatefulWidget {
const PlayCircleButton({
required this.onPressed,
this.enabled = true,
this.size = 44,
super.key,
});
/// Tap handler. Returns a Future so the button can show a spinner
/// during the play setup (fetch detail tracks, etc.).
final Future<void> Function() onPressed;
/// When false, the button is rendered semi-transparent and taps are
/// ignored. Empty playlists / artists with no tracks should disable.
final bool enabled;
/// Outer diameter in logical pixels. 44 is the iOS / Android
/// touch-target minimum; matches the design doc.
final double size;
@override
State<PlayCircleButton> createState() => _PlayCircleButtonState();
}
class _PlayCircleButtonState extends State<PlayCircleButton> {
bool _starting = false;
Future<void> _handleTap() async {
if (_starting || !widget.enabled) return;
setState(() => _starting = true);
try {
await widget.onPressed();
} finally {
if (mounted) setState(() => _starting = false);
}
}
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final iconSize = widget.size * 0.5;
return Material(
color: Colors.transparent,
shape: const CircleBorder(),
child: InkResponse(
onTap: widget.enabled ? _handleTap : null,
radius: widget.size / 2,
containedInkWell: true,
customBorder: const CircleBorder(),
child: Container(
width: widget.size,
height: widget.size,
decoration: BoxDecoration(
color: fs.accent.withValues(alpha: widget.enabled ? 1.0 : 0.5),
shape: BoxShape.circle,
boxShadow: const [
BoxShadow(
color: Color(0x66000000),
blurRadius: 6,
offset: Offset(0, 2),
),
],
),
alignment: Alignment.center,
child: _starting
? SizedBox(
width: iconSize,
height: iconSize,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(fs.parchment),
),
)
: Icon(
Icons.play_arrow,
color: fs.parchment,
size: iconSize,
),
),
),
);
}
}
@@ -1,60 +1,99 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../models/track.dart';
import '../../player/player_provider.dart';
import '../../shared/widgets/track_actions/track_actions_button.dart';
import '../../theme/theme_extension.dart';
import 'cached_indicator.dart';
class TrackRow extends StatelessWidget {
class TrackRow extends ConsumerWidget {
const TrackRow({
required this.track,
required this.onTap,
this.trailing,
this.actions = true,
super.key,
});
final TrackRef track;
final VoidCallback onTap;
final Widget? trailing;
/// Render the 3-dot TrackActionsButton at the end of the row. Default
/// true; pass false in surfaces that don't want the menu (e.g. when
/// showing a static read-only list).
final bool actions;
@override
Widget build(BuildContext context) {
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final mins = (track.durationSec ~/ 60).toString().padLeft(2, '0');
final secs = (track.durationSec % 60).toString().padLeft(2, '0');
return InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: Row(children: [
if (track.trackNumber != null)
SizedBox(
width: 28,
child: Text(
track.trackNumber.toString(),
style: TextStyle(color: fs.ash, fontSize: 13),
// Watch the currently-playing media item so the row's accent
// highlight tracks playback state. Matches _QueueRow's visual
// treatment in queue_screen.dart so the "you are here" cue is
// consistent across album / playlist / queue surfaces.
final currentId = ref.watch(mediaItemProvider).value?.id;
final isCurrent = currentId != null && currentId == track.id;
return Container(
decoration: BoxDecoration(
color: isCurrent ? fs.iron : null,
border: isCurrent
? Border(left: BorderSide(color: fs.accent, width: 2))
: null,
),
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
child: Row(children: [
if (track.trackNumber != null)
SizedBox(
width: 22,
child: Text(
track.trackNumber.toString(),
style: TextStyle(color: fs.ash, fontSize: 13),
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
track.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: isCurrent ? fs.accent : fs.parchment,
fontSize: 14,
fontWeight:
isCurrent ? FontWeight.w500 : FontWeight.w400,
),
),
// Skip the artist line entirely when empty so the row
// height collapses to a single line of title — keeps
// dense album views from looking padded.
if (track.artistName.isNotEmpty)
Text(
track.artistName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.ash, fontSize: 12),
),
],
),
),
Expanded(
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(
track.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14),
CachedIndicator(trackId: track.id),
Text('$mins:$secs', style: TextStyle(color: fs.ash, fontSize: 12)),
if (trailing != null)
Padding(
padding: const EdgeInsets.only(left: 8),
child: trailing!,
),
Text(
track.artistName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.ash, fontSize: 12),
),
]),
),
Text('$mins:$secs', style: TextStyle(color: fs.ash, fontSize: 12)),
if (trailing != null)
Padding(
padding: const EdgeInsets.only(left: 8),
child: trailing!,
),
]),
if (actions) TrackActionsButton(track: track),
]),
),
),
);
}
+1 -1
View File
@@ -30,7 +30,7 @@ class LikeButton extends ConsumerWidget {
color: liked ? fs.accent : fs.ash,
size: size,
),
onPressed: () => ref.read(likedIdsProvider.notifier).toggle(kind, id),
onPressed: () => ref.read(likesControllerProvider).toggle(kind, id),
);
}
}
+139 -46
View File
@@ -1,6 +1,12 @@
import 'package:drift/drift.dart' as drift;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/endpoints/likes.dart';
import '../auth/auth_provider.dart';
import '../cache/audio_cache_manager.dart' show appDbProvider;
import '../cache/cache_first.dart';
import '../cache/connectivity_provider.dart';
import '../cache/db.dart';
import '../library/library_providers.dart';
final likesApiProvider = FutureProvider<LikesApi>((ref) async {
@@ -22,67 +28,154 @@ class LikedIds {
LikeKind.album => albums.contains(id),
LikeKind.track => tracks.contains(id),
};
static const empty = LikedIds(artists: {}, albums: {}, tracks: {});
}
class LikedIdsController extends AsyncNotifier<LikedIds> {
@override
Future<LikedIds> build() async {
final api = await ref.watch(likesApiProvider.future);
final r = await api.ids();
return LikedIds(artists: r.artists, albums: r.albums, tracks: r.tracks);
}
/// Drift-first per #357 plan C. Reads from cached_likes (populated by
/// SyncController). Reactive — sync writes propagate via watch().
/// Empty + online triggers REST cold-cache fallback that re-populates.
final likedIdsProvider = StreamProvider<LikedIds>((ref) {
final db = ref.watch(appDbProvider);
return cacheFirst<CachedLike, LikedIds>(
driftStream: db.select(db.cachedLikes).watch(),
fetchAndPopulate: () async {
final api = await ref.read(likesApiProvider.future);
final fresh = await api.ids();
// Need a userId for the composite primary key. The auth controller
// exposes the current user.
final user = ref.read(authControllerProvider).value;
if (user == null) return; // not logged in; skip
await db.batch((b) {
for (final id in fresh.tracks) {
b.insert(
db.cachedLikes,
CachedLikesCompanion.insert(
userId: user.id,
entityType: 'track',
entityId: id,
),
mode: drift.InsertMode.insertOrIgnore,
);
}
for (final id in fresh.albums) {
b.insert(
db.cachedLikes,
CachedLikesCompanion.insert(
userId: user.id,
entityType: 'album',
entityId: id,
),
mode: drift.InsertMode.insertOrIgnore,
);
}
for (final id in fresh.artists) {
b.insert(
db.cachedLikes,
CachedLikesCompanion.insert(
userId: user.id,
entityType: 'artist',
entityId: id,
),
mode: drift.InsertMode.insertOrIgnore,
);
}
});
},
toResult: (rows) => LikedIds(
tracks: rows
.where((r) => r.entityType == 'track')
.map((r) => r.entityId)
.toSet(),
albums: rows
.where((r) => r.entityType == 'album')
.map((r) => r.entityId)
.toSet(),
artists: rows
.where((r) => r.entityType == 'artist')
.map((r) => r.entityId)
.toSet(),
),
isOnline: () async => (await ref.read(connectivityProvider.future)),
);
});
/// Mutation controller. Writes optimistically to drift first (so the
/// likedIdsProvider stream re-emits immediately for snappy UI), then to
/// REST. Rolls back drift on REST failure.
class LikesController {
LikesController(this._ref);
final Ref _ref;
Future<void> toggle(LikeKind kind, String id) async {
final api = await ref.read(likesApiProvider.future);
final current = state.value ??
const LikedIds(artists: {}, albums: {}, tracks: {});
final user = _ref.read(authControllerProvider).value;
if (user == null) return;
final db = _ref.read(appDbProvider);
final entityType = _entityType(kind);
final isLiked = current.has(kind, id);
final optimistic = _flip(current, kind, id);
state = AsyncData(optimistic);
final existing = await (db.select(db.cachedLikes)
..where((t) =>
t.userId.equals(user.id) &
t.entityType.equals(entityType) &
t.entityId.equals(id)))
.getSingleOrNull();
final wasLiked = existing != null;
// Optimistic mutation — drift watch() re-emits immediately.
if (wasLiked) {
await (db.delete(db.cachedLikes)
..where((t) =>
t.userId.equals(user.id) &
t.entityType.equals(entityType) &
t.entityId.equals(id)))
.go();
} else {
await db.into(db.cachedLikes).insert(
CachedLikesCompanion.insert(
userId: user.id,
entityType: entityType,
entityId: id,
),
mode: drift.InsertMode.insertOrIgnore,
);
}
try {
if (isLiked) {
final api = await _ref.read(likesApiProvider.future);
if (wasLiked) {
await api.unlike(kind, id);
} else {
await api.like(kind, id);
}
} catch (e, st) {
state = AsyncData(current);
// Rollback drift
if (wasLiked) {
await db.into(db.cachedLikes).insert(
CachedLikesCompanion.insert(
userId: user.id,
entityType: entityType,
entityId: id,
),
mode: drift.InsertMode.insertOrIgnore,
);
} else {
await (db.delete(db.cachedLikes)
..where((t) =>
t.userId.equals(user.id) &
t.entityType.equals(entityType) &
t.entityId.equals(id)))
.go();
}
Error.throwWithStackTrace(e, st);
}
}
LikedIds _flip(LikedIds before, LikeKind kind, String id) {
Set<String> swap(Set<String> s) {
final next = {...s};
if (s.contains(id)) {
next.remove(id);
} else {
next.add(id);
}
return next;
}
return switch (kind) {
LikeKind.artist => LikedIds(
artists: swap(before.artists),
albums: before.albums,
tracks: before.tracks,
),
LikeKind.album => LikedIds(
artists: before.artists,
albums: swap(before.albums),
tracks: before.tracks,
),
LikeKind.track => LikedIds(
artists: before.artists,
albums: before.albums,
tracks: swap(before.tracks),
),
};
}
String _entityType(LikeKind kind) => switch (kind) {
LikeKind.artist => 'artist',
LikeKind.album => 'album',
LikeKind.track => 'track',
};
}
final likedIdsProvider =
AsyncNotifierProvider<LikedIdsController, LikedIds>(LikedIdsController.new);
final likesControllerProvider =
Provider<LikesController>((ref) => LikesController(ref));
@@ -0,0 +1,92 @@
/// One user's report under an aggregated quarantine row.
class AdminQuarantineReport {
const AdminQuarantineReport({
required this.userId,
required this.username,
required this.reason,
this.notes,
required this.createdAt,
});
final String userId;
final String username;
final String reason;
final String? notes;
final String createdAt;
factory AdminQuarantineReport.fromJson(Map<String, dynamic> j) =>
AdminQuarantineReport(
userId: j['user_id'] as String? ?? '',
username: j['username'] as String? ?? '',
reason: j['reason'] as String? ?? '',
notes: j['notes'] as String?,
createdAt: j['created_at'] as String? ?? '',
);
}
/// Mirrors `adminQueueRowView` from internal/api/admin_quarantine.go.
/// One row aggregates all reports against a single track, with
/// per-reason counts and the underlying per-user reports nested.
class AdminQuarantineItem {
const AdminQuarantineItem({
required this.trackId,
required this.trackTitle,
required this.artistName,
required this.albumTitle,
required this.albumId,
this.lidarrAlbumMbid,
required this.reportCount,
required this.latestAt,
required this.reasonCounts,
required this.reports,
});
final String trackId;
final String trackTitle;
final String artistName;
final String albumTitle;
final String albumId;
final String? lidarrAlbumMbid;
final int reportCount;
final String latestAt;
/// Map of reason → number of reports citing that reason.
final Map<String, int> reasonCounts;
final List<AdminQuarantineReport> reports;
/// One-line summary of the most-cited reason. Returns just the top
/// reason when only one reason exists, or `top (+N more)` when there
/// are additional distinct reasons.
String get topReasonSummary {
if (reasonCounts.isEmpty) return '';
final entries = reasonCounts.entries.toList()
..sort((a, b) => b.value.compareTo(a.value));
final top = entries.first.key;
return entries.length > 1
? '$top (+${entries.length - 1} more)'
: top;
}
factory AdminQuarantineItem.fromJson(Map<String, dynamic> j) {
final reasonCountsRaw =
(j['reason_counts'] as Map?)?.cast<String, dynamic>() ?? const {};
final reportsRaw = (j['reports'] as List?) ?? const [];
return AdminQuarantineItem(
trackId: j['track_id'] as String? ?? '',
trackTitle: j['track_title'] as String? ?? '',
artistName: j['artist_name'] as String? ?? '',
albumTitle: j['album_title'] as String? ?? '',
albumId: j['album_id'] as String? ?? '',
lidarrAlbumMbid: j['lidarr_album_mbid'] as String?,
reportCount: (j['report_count'] as int?) ?? 0,
latestAt: j['latest_at'] as String? ?? '',
reasonCounts:
reasonCountsRaw.map((k, v) => MapEntry(k, (v as int?) ?? 0)),
reports: reportsRaw
.map((e) =>
AdminQuarantineReport.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false),
);
}
}
@@ -0,0 +1,77 @@
/// Mirrors `requestView` from internal/api/requests.go. Server returns
/// these as a flat list (no envelope) from GET /api/admin/requests.
///
/// Note the requester is exposed only as a UUID (`user_id`) — the
/// response does not include the username. The Flutter Requests screen
/// joins client-side against the AdminUser list for display.
class AdminRequest {
const AdminRequest({
required this.id,
required this.userId,
required this.status,
required this.kind,
required this.artistName,
this.albumTitle,
this.trackTitle,
required this.requestedAt,
this.decidedAt,
this.notes,
required this.importedAlbumCount,
required this.importedTrackCount,
this.matchedTrackId,
this.matchedAlbumId,
this.matchedArtistId,
});
final String id;
final String userId;
/// One of: pending, approved, rejected, completed, failed.
final String status;
/// One of: artist, album, track.
final String kind;
final String artistName;
final String? albumTitle;
final String? trackTitle;
final String requestedAt;
final String? decidedAt;
final String? notes;
final int importedAlbumCount;
final int importedTrackCount;
/// Set when the ingest matched into the local library. The user-side
/// "Listen" CTA on a completed request links to whichever id is set
/// (most-specific first: track → album → artist).
final String? matchedTrackId;
final String? matchedAlbumId;
final String? matchedArtistId;
/// Display label depending on the kind of request — what the user
/// asked for. For an album request it's the album title; for an
/// artist request it's the artist name; etc.
String get displayName => switch (kind) {
'album' => albumTitle ?? artistName,
'track' => trackTitle ?? artistName,
_ => artistName,
};
factory AdminRequest.fromJson(Map<String, dynamic> j) => AdminRequest(
id: j['id'] as String? ?? '',
userId: j['user_id'] as String? ?? '',
status: j['status'] as String? ?? 'pending',
kind: j['kind'] as String? ?? 'artist',
artistName: j['artist_name'] as String? ?? '',
albumTitle: j['album_title'] as String?,
trackTitle: j['track_title'] as String?,
requestedAt: j['requested_at'] as String? ?? '',
decidedAt: j['decided_at'] as String?,
notes: j['notes'] as String?,
importedAlbumCount: (j['imported_album_count'] as int?) ?? 0,
importedTrackCount: (j['imported_track_count'] as int?) ?? 0,
matchedTrackId: j['matched_track_id'] as String?,
matchedAlbumId: j['matched_album_id'] as String?,
matchedArtistId: j['matched_artist_id'] as String?,
);
}
+33
View File
@@ -0,0 +1,33 @@
/// Mirrors `adminUserView` from internal/api/admin_users.go. Distinct
/// from MyProfile because admin endpoints expose `auto_approve_requests`
/// and the canonical `created_at` that the user-scoped /me response
/// intentionally omits.
///
/// The list endpoint wraps these in `{"users": [...]}`; the parsing of
/// the envelope is done in `AdminUsersApi`, not here.
class AdminUser {
const AdminUser({
required this.id,
required this.username,
this.displayName,
required this.isAdmin,
required this.autoApproveRequests,
required this.createdAt,
});
final String id;
final String username;
final String? displayName;
final bool isAdmin;
final bool autoApproveRequests;
final String createdAt;
factory AdminUser.fromJson(Map<String, dynamic> j) => AdminUser(
id: j['id'] as String? ?? '',
username: j['username'] as String? ?? '',
displayName: j['display_name'] as String?,
isAdmin: j['is_admin'] as bool? ?? false,
autoApproveRequests: j['auto_approve_requests'] as bool? ?? false,
createdAt: j['created_at'] as String? ?? '',
);
}
@@ -0,0 +1,44 @@
import 'track.dart';
/// Mirrors web/src/lib/api/history.ts HistoryEvent. Server emits
/// `{events, has_more}` rather than the standard `Page<T>` envelope —
/// history is timestamp-keyed so total isn't meaningful, only "more
/// pages exist below."
class HistoryEvent {
const HistoryEvent({
required this.id,
required this.playedAt,
required this.track,
});
final String id;
/// RFC3339 timestamp; UI formats relative ("3h ago" / "Tue 14:32" /
/// "May 1, 2025") via formatRelative helper.
final String playedAt;
final TrackRef track;
factory HistoryEvent.fromJson(Map<String, dynamic> j) => HistoryEvent(
id: j['id'] as String? ?? '',
playedAt: j['played_at'] as String? ?? '',
track: TrackRef.fromJson(
(j['track'] as Map?)?.cast<String, dynamic>() ?? const {},
),
);
}
class HistoryPage {
const HistoryPage({required this.events, required this.hasMore});
final List<HistoryEvent> events;
final bool hasMore;
factory HistoryPage.fromJson(Map<String, dynamic> j) {
final raw = (j['events'] as List?) ?? const [];
return HistoryPage(
events: raw
.map((e) => HistoryEvent.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false),
hasMore: j['has_more'] as bool? ?? false,
);
}
}
+41
View File
@@ -0,0 +1,41 @@
/// Mirrors internal/api/types.go HomeIndexPayload. Five flat slices of
/// entity ID strings — the per-item rendering variant of HomeData.
/// Section name implies entity type; no per-entry type tag is needed.
///
/// Slices are non-null after fromJson so callers can branch on `length`
/// instead of dealing with null sections.
class HomeIndex {
const HomeIndex({
required this.recentlyAddedAlbums,
required this.rediscoverAlbums,
required this.rediscoverArtists,
required this.mostPlayedTracks,
required this.lastPlayedArtists,
});
final List<String> recentlyAddedAlbums;
final List<String> rediscoverAlbums;
final List<String> rediscoverArtists;
final List<String> mostPlayedTracks;
final List<String> lastPlayedArtists;
static const empty = HomeIndex(
recentlyAddedAlbums: [],
rediscoverAlbums: [],
rediscoverArtists: [],
mostPlayedTracks: [],
lastPlayedArtists: [],
);
factory HomeIndex.fromJson(Map<String, dynamic> j) {
List<String> ids(String key) =>
((j[key] as List?) ?? const []).map((e) => e.toString()).toList();
return HomeIndex(
recentlyAddedAlbums: ids('recently_added_albums'),
rediscoverAlbums: ids('rediscover_albums'),
rediscoverArtists: ids('rediscover_artists'),
mostPlayedTracks: ids('most_played_tracks'),
lastPlayedArtists: ids('last_played_artists'),
);
}
}
+40
View File
@@ -0,0 +1,40 @@
/// Mirrors `inviteResp` from internal/api/admin_invites.go. The list
/// endpoint wraps these in `{"invites": [...]}`; the create endpoint
/// returns a single bare invite. Envelope parsing is done in
/// `AdminInvitesApi`, not here.
///
/// `invitedBy` is the UUID of the inviting admin (not their username);
/// the server doesn't currently denormalize it. Likewise `redeemedBy`.
/// TTL is hardcoded server-side at 24h, so admins can't customise the
/// expiry — only the optional `note`.
class Invite {
const Invite({
required this.token,
required this.invitedBy,
this.note,
required this.createdAt,
required this.expiresAt,
this.redeemedAt,
this.redeemedBy,
});
final String token;
final String invitedBy;
final String? note;
final String createdAt;
final String expiresAt;
final String? redeemedAt;
final String? redeemedBy;
bool get isRedeemed => redeemedAt != null;
factory Invite.fromJson(Map<String, dynamic> j) => Invite(
token: j['token'] as String? ?? '',
invitedBy: j['invited_by'] as String? ?? '',
note: j['note'] as String?,
createdAt: j['created_at'] as String? ?? '',
expiresAt: j['expires_at'] as String? ?? '',
redeemedAt: j['redeemed_at'] as String?,
redeemedBy: j['redeemed_by'] as String?,
);
}
+47
View File
@@ -0,0 +1,47 @@
/// Mirrors web/src/lib/api/types.ts LidarrSearchResult — one row in
/// `/api/lidarr/search` results. `in_library` and `requested` let the
/// UI gray out rows the user can't act on (already imported / already
/// awaiting review).
class LidarrSearchResult {
const LidarrSearchResult({
required this.mbid,
required this.name,
required this.secondaryText,
required this.imageUrl,
required this.artistMbid,
required this.albumMbid,
required this.inLibrary,
required this.requested,
});
final String mbid;
final String name;
final String secondaryText;
final String imageUrl;
final String artistMbid;
final String albumMbid;
final bool inLibrary;
final bool requested;
factory LidarrSearchResult.fromJson(Map<String, dynamic> j) =>
LidarrSearchResult(
mbid: j['mbid'] as String? ?? '',
name: j['name'] as String? ?? '',
secondaryText: j['secondary_text'] as String? ?? '',
imageUrl: j['image_url'] as String? ?? '',
artistMbid: j['artist_mbid'] as String? ?? '',
albumMbid: j['album_mbid'] as String? ?? '',
inLibrary: j['in_library'] as bool? ?? false,
requested: j['requested'] as bool? ?? false,
);
}
enum LidarrRequestKind { artist, album, track }
extension LidarrRequestKindStr on LidarrRequestKind {
String get wire => switch (this) {
LidarrRequestKind.artist => 'artist',
LidarrRequestKind.album => 'album',
LidarrRequestKind.track => 'track',
};
}
+49
View File
@@ -0,0 +1,49 @@
/// Mirrors web/src/lib/api/me.ts MyProfile. The `display_name` and
/// `email` are nullable — server returns null when the user hasn't
/// set them yet (registration only requires a username).
class MyProfile {
const MyProfile({
required this.id,
required this.username,
this.displayName,
this.email,
required this.isAdmin,
});
final String id;
final String username;
final String? displayName;
final String? email;
final bool isAdmin;
factory MyProfile.fromJson(Map<String, dynamic> j) => MyProfile(
id: j['id'] as String? ?? '',
username: j['username'] as String? ?? '',
displayName: j['display_name'] as String?,
email: j['email'] as String?,
isAdmin: j['is_admin'] as bool? ?? false,
);
}
/// Mirrors web/src/lib/api/listenbrainz.ts LBStatus.
class ListenBrainzStatus {
const ListenBrainzStatus({
required this.enabled,
required this.tokenSet,
this.lastScrobbledAt,
});
final bool enabled;
/// True when the user has stored a token (token itself is never read
/// back from the server). UI uses this to show "token saved" vs
/// "no token" without exposing the value.
final bool tokenSet;
final String? lastScrobbledAt;
factory ListenBrainzStatus.fromJson(Map<String, dynamic> j) =>
ListenBrainzStatus(
enabled: j['enabled'] as bool? ?? false,
tokenSet: j['token_set'] as bool? ?? false,
lastScrobbledAt: j['last_scrobbled_at'] as String?,
);
}
+44
View File
@@ -0,0 +1,44 @@
// Mirrors the server's Page[T] envelope used by paged endpoints
// (/api/search, /api/library/artists, /api/library/albums,
// /api/likes/*). Class is named `Paged<T>` rather than `Page<T>`
// to avoid ambiguous imports with Flutter Material's Navigator-2.0
// `Page` class.
//
// Wire shape from internal/api/types.go Page[T]:
// { items: T[], total: int, limit: int, offset: int }
//
// Dart generics can't auto-infer T from JSON, so callers pass an
// itemFromJson function alongside the raw map. Parse logic stays in
// each entity's own fromJson; this class only handles the envelope.
class Paged<T> {
const Paged({
required this.items,
required this.total,
required this.limit,
required this.offset,
});
final List<T> items;
final int total;
final int limit;
final int offset;
factory Paged.fromJson(
Map<String, dynamic> j,
T Function(Map<String, dynamic>) itemFromJson,
) {
final raw = (j['items'] as List?) ?? const [];
return Paged<T>(
items: raw
.map((e) => itemFromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false),
total: (j['total'] as num?)?.toInt() ?? 0,
limit: (j['limit'] as num?)?.toInt() ?? 0,
offset: (j['offset'] as num?)?.toInt() ?? 0,
);
}
/// Convenience for endpoints that always return the first page or
/// when the caller just wants the items.
bool get hasMore => offset + items.length < total;
}
+117
View File
@@ -0,0 +1,117 @@
// Mirrors internal/api/playlists.go Playlist + PlaylistDetail wire shapes.
//
// Server distinguishes user playlists (created by the caller) from
// system playlists (server-generated mixes like for_you / discover).
// system_variant is null for user playlists; "for_you" / "discover"
// otherwise. Read-only operations work the same; PATCH/POST/DELETE
// are gated on user-owned playlists.
class Playlist {
const Playlist({
required this.id,
required this.userId,
required this.name,
required this.description,
required this.isPublic,
required this.systemVariant,
required this.trackCount,
required this.coverUrl,
required this.ownerUsername,
required this.createdAt,
required this.updatedAt,
});
final String id;
final String userId;
final String name;
final String description;
final bool isPublic;
/// "for_you" / "discover" / null
final String? systemVariant;
final int trackCount;
/// Server-emitted URL to the cover; empty when no tracks yet.
final String coverUrl;
/// Display name of the owner — for showing other users' public playlists.
final String ownerUsername;
final String createdAt;
final String updatedAt;
bool get isSystem => systemVariant != null;
factory Playlist.fromJson(Map<String, dynamic> j) => Playlist(
id: j['id'] as String,
userId: j['user_id'] as String? ?? '',
name: j['name'] as String? ?? '',
description: j['description'] as String? ?? '',
isPublic: j['is_public'] as bool? ?? false,
systemVariant: j['system_variant'] as String?,
trackCount: (j['track_count'] as num?)?.toInt() ?? 0,
coverUrl: j['cover_url'] as String? ?? '',
ownerUsername: j['owner_username'] as String? ?? '',
createdAt: j['created_at'] as String? ?? '',
updatedAt: j['updated_at'] as String? ?? '',
);
}
/// Playlist row as returned in PlaylistDetail.tracks. Each row carries
/// the track's display fields directly so the client doesn't need a
/// separate /api/tracks/{id} fetch per row.
///
/// track_id is nullable: when the upstream track has been removed from
/// the library, the row remains in the playlist with its title/artist
/// preserved but track_id=null and stream_url=null. UI should render
/// these greyed-out and unplayable.
class PlaylistTrack {
const PlaylistTrack({
required this.position,
required this.trackId,
required this.title,
required this.albumId,
required this.albumTitle,
required this.artistId,
required this.artistName,
required this.durationSec,
required this.streamUrl,
});
final int position;
final String? trackId;
final String title;
final String? albumId;
final String albumTitle;
final String? artistId;
final String artistName;
final int durationSec;
final String? streamUrl;
bool get isAvailable => trackId != null;
factory PlaylistTrack.fromJson(Map<String, dynamic> j) => PlaylistTrack(
position: (j['position'] as num?)?.toInt() ?? 0,
trackId: j['track_id'] as String?,
title: j['title'] as String? ?? '',
albumId: j['album_id'] as String?,
albumTitle: j['album_title'] as String? ?? '',
artistId: j['artist_id'] as String?,
artistName: j['artist_name'] as String? ?? '',
durationSec: (j['duration_sec'] as num?)?.toInt() ?? 0,
streamUrl: j['stream_url'] as String?,
);
}
class PlaylistDetail {
const PlaylistDetail({required this.playlist, required this.tracks});
final Playlist playlist;
final List<PlaylistTrack> tracks;
factory PlaylistDetail.fromJson(Map<String, dynamic> j) {
final tracksRaw = (j['tracks'] as List?) ?? const [];
return PlaylistDetail(
playlist: Playlist.fromJson(j),
tracks: tracksRaw
.map((e) => PlaylistTrack.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false),
);
}
}
@@ -0,0 +1,46 @@
/// Mirrors web/src/lib/api/types.ts LidarrQuarantineMineRow. One row
/// per quarantined track owned by the caller. Server returns a flat
/// list (no Page envelope) at /api/quarantine/mine.
class QuarantineMineRow {
const QuarantineMineRow({
required this.trackId,
required this.reason,
this.notes,
required this.createdAt,
required this.trackTitle,
required this.trackDurationMs,
required this.albumId,
required this.albumTitle,
this.albumCoverArtPath,
required this.artistId,
required this.artistName,
});
final String trackId;
/// One of: bad_rip / wrong_file / wrong_tags / duplicate / other.
final String reason;
final String? notes;
final String createdAt;
final String trackTitle;
final int trackDurationMs;
final String albumId;
final String albumTitle;
final String? albumCoverArtPath;
final String artistId;
final String artistName;
factory QuarantineMineRow.fromJson(Map<String, dynamic> j) =>
QuarantineMineRow(
trackId: j['track_id'] as String? ?? '',
reason: j['reason'] as String? ?? 'other',
notes: j['notes'] as String?,
createdAt: j['created_at'] as String? ?? '',
trackTitle: j['track_title'] as String? ?? '',
trackDurationMs: (j['track_duration_ms'] as num?)?.toInt() ?? 0,
albumId: j['album_id'] as String? ?? '',
albumTitle: j['album_title'] as String? ?? '',
albumCoverArtPath: j['album_cover_art_path'] as String?,
artistId: j['artist_id'] as String? ?? '',
artistName: j['artist_name'] as String? ?? '',
);
}
@@ -0,0 +1,38 @@
import 'album.dart';
import 'artist.dart';
import 'page.dart';
import 'track.dart';
/// Mirrors internal/api/search.go SearchResponse — three pages keyed by
/// facet, each independently paged. The mobile UI usually only walks
/// the first page of each facet (limit 20-50); infinite scroll within a
/// facet is a future enhancement, not v1.
class SearchResponse {
const SearchResponse({
required this.artists,
required this.albums,
required this.tracks,
});
final Paged<ArtistRef> artists;
final Paged<AlbumRef> albums;
final Paged<TrackRef> tracks;
factory SearchResponse.fromJson(Map<String, dynamic> j) => SearchResponse(
artists: Paged.fromJson(
(j['artists'] as Map?)?.cast<String, dynamic>() ?? const {},
ArtistRef.fromJson,
),
albums: Paged.fromJson(
(j['albums'] as Map?)?.cast<String, dynamic>() ?? const {},
AlbumRef.fromJson,
),
tracks: Paged.fromJson(
(j['tracks'] as Map?)?.cast<String, dynamic>() ?? const {},
TrackRef.fromJson,
),
);
bool get isEmpty =>
artists.items.isEmpty && albums.items.isEmpty && tracks.items.isEmpty;
}
@@ -0,0 +1,24 @@
/// Mirrors `systemPlaylistsStatusResp` from internal/api/me_system_playlists.go.
/// Reflects the caller's most recent system_playlist_runs row, or zero
/// values when no row exists yet (the user has never had a build attempted).
class SystemPlaylistsStatus {
const SystemPlaylistsStatus({
required this.inFlight,
this.lastRunAt,
this.lastError,
});
final bool inFlight;
final String? lastRunAt;
final String? lastError;
factory SystemPlaylistsStatus.empty() =>
const SystemPlaylistsStatus(inFlight: false);
factory SystemPlaylistsStatus.fromJson(Map<String, dynamic> j) =>
SystemPlaylistsStatus(
inFlight: j['in_flight'] as bool? ?? false,
lastRunAt: j['last_run_at'] as String?,
lastError: j['last_error'] as String?,
);
}
@@ -0,0 +1,83 @@
// Dominant-color extraction from album cover art (#396 item 1).
// The full-screen Now Playing screen uses this to paint a top-to-bottom
// gradient backdrop that grounds each track in its album's palette.
//
// Implementation: reuses AlbumCoverCache to get a local file path for
// the cover, then runs PaletteGenerator over it. Results are cached
// in-memory keyed by album_id so back-to-back plays of the same album
// don't repeat the work. Cache is process-lifetime; album-art changes
// are rare enough that LRU eviction isn't worth the complexity.
//
// Returns null on any failure (no cover, empty album_id, palette
// extraction returned nothing). Callers fall back to the FabledSword
// obsidian color for the gradient when null.
import 'dart:io';
import 'package:flutter/painting.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:palette_generator/palette_generator.dart';
import 'player_provider.dart';
/// Caches dominant colors keyed by album_id. Process-lifetime; refilled
/// on app restart.
class AlbumColorCache {
AlbumColorCache(this._ref);
final Ref _ref;
final Map<String, Color?> _cache = {};
/// Returns the dominant color for the album's cover, or null if no
/// cover is available or extraction fails. Same call for the same
/// album_id is cached after the first successful resolution.
Future<Color?> getOrExtract(String albumId) async {
if (albumId.isEmpty) return null;
if (_cache.containsKey(albumId)) return _cache[albumId];
final color = await _extract(albumId);
_cache[albumId] = color;
return color;
}
Future<Color?> _extract(String albumId) async {
try {
final coverCache = _ref.read(albumCoverCacheProvider);
final path = await coverCache.getOrFetch(albumId);
if (path == null) return null;
final file = File(path);
if (!await file.exists()) return null;
final palette = await PaletteGenerator.fromImageProvider(
FileImage(file),
// Small target size: palette extraction is CPU-bound and the
// gradient only needs a single dominant color, so we don't
// need full-resolution sampling.
size: const Size(80, 80),
maximumColorCount: 8,
);
// Prefer the explicit dominant color; fall back to the strongest
// muted swatch (which tends to read better as a background than
// a hot vibrant pick), then any populated swatch.
final swatch = palette.dominantColor ??
palette.darkMutedColor ??
palette.darkVibrantColor ??
palette.mutedColor;
return swatch?.color;
} catch (_) {
return null;
}
}
}
final albumColorCacheProvider = Provider<AlbumColorCache>(
(ref) => AlbumColorCache(ref),
);
/// Family provider: dominant color for the given album_id, or null if
/// no cover / extraction failed. The Now Playing screen watches this
/// keyed by the current MediaItem's album_id.
final albumColorProvider = FutureProvider.family<Color?, String>(
(ref, albumId) async {
final cache = ref.watch(albumColorCacheProvider);
return cache.getOrExtract(albumId);
},
);
@@ -0,0 +1,65 @@
import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
/// Caches album cover bytes to disk so MediaItem.artUri can point at a
/// file:// URI. Android's MediaSession framework fetches artUri itself
/// and doesn't carry our Bearer header, so we pre-fetch via the
/// authenticated dio and hand the system a local file path instead.
///
/// Cache layout: `{applicationCacheDirectory}/album_covers/{albumId}.jpg`.
/// No explicit eviction — covers are tiny and OS clears app cache when
/// space is tight.
class AlbumCoverCache {
AlbumCoverCache({
required Future<Dio> Function() dioFactory,
Future<Directory> Function()? cacheDirFactory,
}) : _dioFactory = dioFactory,
_cacheDirFactory = cacheDirFactory ?? getApplicationCacheDirectory;
final Future<Dio> Function() _dioFactory;
final Future<Directory> Function() _cacheDirFactory;
/// In-flight requests keyed by albumId so concurrent callers for the
/// same album dedupe to one fetch.
final Map<String, Future<String?>> _inflight = {};
/// Returns local file path to the album cover, or null on any
/// failure (network, 4xx/5xx, disk full, empty albumId).
Future<String?> getOrFetch(String albumId) {
if (albumId.isEmpty) return Future.value(null);
final existing = _inflight[albumId];
if (existing != null) return existing;
final fut = _doFetch(albumId);
_inflight[albumId] = fut;
fut.whenComplete(() => _inflight.remove(albumId));
return fut;
}
Future<String?> _doFetch(String albumId) async {
try {
final dir = await _cacheDirFactory();
final coversDir = Directory('${dir.path}/album_covers');
await coversDir.create(recursive: true);
final filePath = '${coversDir.path}/$albumId.jpg';
final file = File(filePath);
if (await file.exists()) return filePath;
final dio = await _dioFactory();
final r = await dio.get<List<int>>(
'/api/albums/$albumId/cover',
options: Options(responseType: ResponseType.bytes),
);
final bytes = r.data;
if (bytes == null || bytes.isEmpty) return null;
await file.writeAsBytes(bytes, flush: true);
return filePath;
} catch (e) {
debugPrint('AlbumCoverCache: fetch failed for $albumId: $e');
return null;
}
}
}
+406 -30
View File
@@ -1,52 +1,380 @@
import 'package:audio_service/audio_service.dart';
import 'package:just_audio/just_audio.dart';
import 'dart:async';
import 'dart:io';
import 'package:audio_service/audio_service.dart';
import 'package:flutter/foundation.dart';
import 'package:just_audio/just_audio.dart';
import 'package:path_provider/path_provider.dart';
import '../cache/audio_cache_manager.dart';
import '../models/track.dart';
import 'album_cover_cache.dart';
class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
MinstrelAudioHandler() {
_player.playbackEventStream.listen(_broadcastState);
_player.playbackEventStream.listen(
_broadcastState,
// ExoPlayer surfaces stream errors (404, premature EOS, decoder
// failure, network drop) here. Without an error sink, the
// player just goes quiet — exactly the "starts then stops"
// symptom we hit.
onError: (Object e, StackTrace st) {
debugPrint('audio_handler: playbackEventStream error: $e\n$st');
},
);
_player.currentIndexStream.listen(_onCurrentIndexChanged);
// Re-broadcast on shuffle/repeat changes so the PlaybackState's
// shuffleMode + repeatMode fields stay current for UI subscribers.
_player.shuffleModeEnabledStream.listen((_) => _broadcastState(null));
_player.loopModeStream.listen((_) => _broadcastState(null));
// Watch buffered-position so we can register stream-cached files
// in the audio cache index once they're fully downloaded. Without
// this, files written by LockCachingAudioSource never appear in
// the index and the eviction loop can't reclaim them.
_player.bufferedPositionStream
.listen((_) => unawaited(_maybeRegisterStreamCache()));
}
final AudioPlayer _player = AudioPlayer();
String _baseUrl = '';
String? _token;
AlbumCoverCache? _coverCache;
AudioCacheManager? _audioCacheManager;
void configure({required String baseUrl, required String? token}) {
/// Trackers to dedupe registration — once we've inserted an index row
/// for a trackId, don't repeat the work on every buffered-position
/// emit. Cleared on dispose only; surviving across queue rebuilds is
/// fine because the index is itself the source of truth.
final Set<String> _streamCacheRegistered = {};
/// Cached on first use so we don't hit the platform channel every
/// time the buffered-position stream emits (~200ms cadence).
String? _cacheDirPath;
/// True while _fillRemainingSources is doing backward-fill inserts
/// at index 0..initialIndex-1. Each insert shifts the player's
/// currentIndex (it tracks the actively-playing source through
/// list mutations), and the resulting _onCurrentIndexChanged
/// callbacks would push the wrong MediaItem onto the stream
/// (queue.value[shifted_idx] != actively-playing track). When
/// the fill completes, currentIndex == initialIndex, mediaItem
/// is already correct, and we re-enable normal listener behavior.
bool _suppressIndexUpdates = false;
/// Increments on every setQueueFromTracks call. The background
/// fill task captures the value at start and bails if the live
/// counter has moved on — without this, a stale fill will keep
/// addAudioSource'ing tracks from the previous playlist into the
/// new queue, leaving the player "locked" to a corrupted state.
int _queueGeneration = 0;
/// Tracks the most recent setQueueFromTracks() input so
/// skipToQueueItem can reconstruct the source list. just_audio
/// requires every source to be built before it can be a skip
/// target, but setQueueFromTracks only builds the initial source
/// and fills the rest in the background — so a skip to an index
/// past the fill front needs to rebuild from the stored tracks.
List<TrackRef> _lastTracks = const [];
/// Volume stream for UI subscribers. Mirrors the just_audio player's
/// volume directly; set via setVolume(double).
Stream<double> get volumeStream => _player.volumeStream;
double get volume => _player.volume;
/// Position stream for UI subscribers. just_audio emits roughly every
/// 200ms while playing, which is what makes the seek bar advance
/// smoothly. PlaybackState.updatePosition only changes on event
/// transitions (play/pause/buffer), so it's too coarse for live
/// scrubbing UI.
Stream<Duration> get positionStream => _player.positionStream;
Duration get position => _player.position;
void configure({
required String baseUrl,
required String? token,
AlbumCoverCache? coverCache,
AudioCacheManager? audioCacheManager,
}) {
_baseUrl = baseUrl;
_token = token;
if (coverCache != null) _coverCache = coverCache;
if (audioCacheManager != null) _audioCacheManager = audioCacheManager;
}
Future<void> setQueueFromTracks(List<TrackRef> tracks, {int initialIndex = 0}) async {
final items = tracks.map(_toMediaItem).toList();
queue.add(items);
if (items.isNotEmpty) {
mediaItem.add(items[initialIndex.clamp(0, items.length - 1)]);
if (tracks.isEmpty) return;
final clampedInitial = initialIndex.clamp(0, tracks.length - 1);
// Bump the generation FIRST. Any in-flight _fillRemainingSources
// from a previous play will see the mismatch on its next gen
// check and stop calling player mutations — important so a stale
// fill doesn't append old-playlist tracks into the new queue.
final myGen = ++_queueGeneration;
// Reset suppress flag in case a prior backward-fill bailed on
// gen check before reaching its `finally`.
_suppressIndexUpdates = false;
_lastTracks = tracks;
// Pause the old source immediately so the previous track stops
// audibly the moment the user taps, instead of bleeding through
// until the new source finishes building. setAudioSources below
// will swap the source list cleanly; pause is the simplest way
// to silence the player during the (possibly multi-100ms) build.
if (_player.playing) {
await _player.pause();
}
final headers = _token == null ? null : {'Authorization': 'Bearer $_token'};
final sources = tracks.map((t) {
final url = t.streamUrl.isNotEmpty
? (Uri.tryParse(t.streamUrl)?.hasScheme == true
? t.streamUrl
: '$_baseUrl${t.streamUrl}')
: '$_baseUrl/api/tracks/${t.id}/stream';
return AudioSource.uri(Uri.parse(url), headers: headers);
}).toList();
// Populate the visible queue + current mediaItem immediately so
// the player UI reflects the user's tap before any source has
// been built. Source list at the just_audio layer fills in
// asynchronously below.
final items = tracks.map(_toMediaItem).toList();
queue.add(items);
mediaItem.add(items[clampedInitial]);
await _player.setAudioSource(
ConcatenatingAudioSource(children: sources),
initialIndex: initialIndex,
// Fast path: build only the initial source so the player can
// start. Remaining sources stream in via _fillRemainingSources()
// in the background — addAudioSource for next/auto-advance
// tracks, insertAudioSource for skipPrev tracks.
final initial = await _buildAudioSource(tracks[clampedInitial]);
if (myGen != _queueGeneration) {
debugPrint('audio_handler: superseded before setAudioSources (gen=$myGen)');
return;
}
await _player.setAudioSources([initial], initialIndex: 0);
unawaited(_loadArtForCurrentItem());
unawaited(_fillRemainingSources(tracks, clampedInitial, myGen));
}
/// Switches playback to the [index]th queue item. The full
/// just_audio source list isn't necessarily built yet
/// (_fillRemainingSources runs in the background), so we
/// reconstruct from the stored TrackRef list rather than calling
/// _player.seek(index: ...) on a possibly-missing source. Calling
/// setQueueFromTracks again is the safe path: it bumps the
/// generation, cancels any in-flight fill, rebuilds source[0] as
/// the target, and re-fills around. play() restarts playback so
/// queue taps feel like "jump to this song" rather than "set the
/// pointer and wait for me to press play."
@override
Future<void> skipToQueueItem(int index) async {
if (index < 0 || index >= _lastTracks.length) return;
await setQueueFromTracks(_lastTracks, initialIndex: index);
await play();
}
/// Background fill of the rest of the just_audio source list after
/// the initial source is playing. Forward direction first (most
/// common skipNext target). Backward inserts shift the player's
/// currentIndex; we suppress _onCurrentIndexChanged side effects
/// for those so the mediaItem stream doesn't bounce to the wrong
/// queue entry.
///
/// `gen` is the queue generation captured when this fill started.
/// Every loop iteration checks against _queueGeneration; if a
/// newer setQueueFromTracks has run (user tapped play on something
/// else), bail immediately so we don't pollute the new queue with
/// addAudioSource calls from this stale fill.
Future<void> _fillRemainingSources(
List<TrackRef> tracks, int initialIndex, int gen) async {
for (var i = initialIndex + 1; i < tracks.length; i++) {
if (gen != _queueGeneration) return;
try {
final src = await _buildAudioSource(tracks[i]);
if (gen != _queueGeneration) return;
await _player.addAudioSource(src);
} catch (e) {
debugPrint('audio_handler: forward fill failed for ${tracks[i].id}: $e');
}
}
if (initialIndex > 0) {
_suppressIndexUpdates = true;
try {
for (var i = 0; i < initialIndex; i++) {
if (gen != _queueGeneration) return;
final src = await _buildAudioSource(tracks[i]);
if (gen != _queueGeneration) return;
await _player.insertAudioSource(i, src);
}
} catch (e) {
debugPrint('audio_handler: backward fill failed: $e');
} finally {
// Only release the flag if we're still the active gen — a
// newer setQueueFromTracks already reset it for itself.
if (gen == _queueGeneration) _suppressIndexUpdates = false;
}
}
}
String _resolveStreamUrl(TrackRef t) {
if (t.streamUrl.isEmpty) {
return '$_baseUrl/api/tracks/${t.id}/stream';
}
final parsed = Uri.tryParse(t.streamUrl);
if (parsed != null && parsed.hasScheme) {
return t.streamUrl;
}
return '$_baseUrl${t.streamUrl}';
}
/// Builds an AudioSource for a track. Cache-aware:
/// 1. If the track is fully cached on disk, returns a file:// source.
/// 2. Else returns a LockCachingAudioSource that streams + caches as
/// it plays (subsequent plays will hit the cache).
///
/// Without an audio cache manager configured (e.g. in older code paths
/// that pre-date #357), falls back to a plain network AudioSource.uri.
Future<AudioSource> _buildAudioSource(TrackRef t) async {
final headers = _token == null ? null : {'Authorization': 'Bearer $_token'};
final mgr = _audioCacheManager;
// 1. Cache hit: play from disk, no headers needed.
if (mgr != null) {
final path = await mgr.pathFor(t.id);
if (path != null) {
return AudioSource.uri(Uri.file(path));
}
}
final url = _resolveStreamUrl(t);
final parsed = Uri.parse(url);
if (!parsed.hasScheme || parsed.host.isEmpty) {
throw StateError(
'audio_handler: refused to play scheme-less URL "$url" '
'(baseUrl="$_baseUrl", track.streamUrl="${t.streamUrl}", '
'track.id="${t.id}"). configure() must be called with a '
'non-empty baseUrl before setQueueFromTracks().',
);
}
// 2. Cache miss WITH manager: stream + cache-as-you-play. Future
// plays of this track will hit the cache. If the cache write
// completes, we don't currently register an index row — that would
// require a download-complete hook from just_audio that's not
// exposed cleanly. Acceptable for v1: prefetcher / explicit
// pin / Download buttons cover the index path; LockCaching handles
// the network optimization.
if (mgr != null) {
_cacheDirPath ??= (await getApplicationCacheDirectory()).path;
final cacheFile = File('${_cacheDirPath!}/audio_cache/${t.id}.mp3');
// ignore: experimental_member_use
return LockCachingAudioSource(parsed,
headers: headers, cacheFile: cacheFile);
}
// 3. No manager configured: plain network source (legacy path).
return AudioSource.uri(parsed, headers: headers);
}
/// Inserts [track] right after the currently-playing item so it plays
/// next. If nothing is playing, appends to the end.
Future<void> playNext(TrackRef track) async {
final source = await _buildAudioSource(track);
final item = _toMediaItem(track);
final currentIdx = _player.currentIndex;
final insertAt = currentIdx == null ? queue.value.length : currentIdx + 1;
await _player.insertAudioSource(insertAt, source);
final current = queue.value;
queue.add([
...current.sublist(0, insertAt),
item,
...current.sublist(insertAt),
]);
}
/// Appends [track] to the end of the queue.
Future<void> enqueue(TrackRef track) async {
final source = await _buildAudioSource(track);
final item = _toMediaItem(track);
await _player.addAudioSource(source);
queue.add([...queue.value, item]);
}
MediaItem _toMediaItem(TrackRef t) {
// Stash album_id + artist_id in extras so widgets reconstructing
// a TrackRef from the MediaItem (player kebab → "Go to artist",
// "Go to album") have the IDs they need to navigate. Earlier code
// only carried album_id which left "Go to artist" pushing
// /artists/ (empty id, route 404).
final extras = <String, dynamic>{};
if (t.albumId.isNotEmpty) extras['album_id'] = t.albumId;
if (t.artistId.isNotEmpty) extras['artist_id'] = t.artistId;
return MediaItem(
id: t.id,
title: t.title,
artist: t.artistName,
album: t.albumTitle,
duration: Duration(seconds: t.durationSec),
extras: extras.isEmpty ? null : extras,
);
}
MediaItem _toMediaItem(TrackRef t) => MediaItem(
id: t.id,
title: t.title,
artist: t.artistName,
album: t.albumTitle,
duration: Duration(seconds: t.durationSec),
);
/// Once a track is fully buffered (LockCaching has written the whole
/// file to disk), insert an audio_cache_index row so the file shows
/// up to AudioCacheManager.evict() and clearAll(). No-op if the
/// cache manager isn't configured, no current track, the file isn't
/// fully buffered yet, the on-disk file is missing, or we already
/// registered this trackId during this subscription.
Future<void> _maybeRegisterStreamCache() async {
final mgr = _audioCacheManager;
if (mgr == null) return;
final current = mediaItem.value;
if (current == null) return;
final trackId = current.id;
if (_streamCacheRegistered.contains(trackId)) return;
final dur = _player.duration;
if (dur == null) return;
final buf = _player.bufferedPosition;
// 200ms slack for header bytes / encoding rounding.
if (buf < dur - const Duration(milliseconds: 200)) return;
_cacheDirPath ??= (await getApplicationCacheDirectory()).path;
final path = '${_cacheDirPath!}/audio_cache/$trackId.mp3';
final file = File(path);
if (!await file.exists()) return;
final size = await file.length();
if (size <= 0) return;
_streamCacheRegistered.add(trackId);
await mgr.registerStreamCache(trackId, path, size);
}
void _onCurrentIndexChanged(int? idx) {
if (idx == null) return;
if (_suppressIndexUpdates) return;
// Push the new track's MediaItem onto the mediaItem stream so
// the player UI rebuilds with the new title/artist/album/cover.
// Without this, the bar and full player stayed pinned to whichever
// track was passed via setQueueFromTracks(initialIndex:) regardless
// of skip/auto-advance.
final items = queue.value;
if (idx >= 0 && idx < items.length) {
mediaItem.add(items[idx]);
}
unawaited(_loadArtForCurrentItem());
}
/// Async-fetches the cover for whichever item is currently active and
/// pushes a MediaItem update with artUri set. No-op if no cache is
/// configured, no current item, the item has no album_id in extras,
/// or the fetch returns null.
Future<void> _loadArtForCurrentItem() async {
final cache = _coverCache;
if (cache == null) return;
final current = mediaItem.value;
if (current == null) return;
final albumId = current.extras?['album_id'] as String?;
if (albumId == null || albumId.isEmpty) return;
if (current.artUri != null) return; // already set
final path = await cache.getOrFetch(albumId);
if (path == null) return;
// Discard if the user advanced to another track while we waited.
if (mediaItem.value?.id != current.id) return;
mediaItem.add(current.copyWith(artUri: Uri.file(path)));
}
@override
Future<void> play() => _player.play();
@@ -63,7 +391,34 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
@override
Future<void> skipToPrevious() => _player.seekToPrevious();
void _broadcastState(PlaybackEvent event) {
@override
Future<void> setShuffleMode(AudioServiceShuffleMode shuffleMode) async {
await _player
.setShuffleModeEnabled(shuffleMode != AudioServiceShuffleMode.none);
// _broadcastState picks up the change via shuffleModeEnabledStream.
}
@override
Future<void> setRepeatMode(AudioServiceRepeatMode repeatMode) async {
final loop = switch (repeatMode) {
AudioServiceRepeatMode.none => LoopMode.off,
AudioServiceRepeatMode.one => LoopMode.one,
AudioServiceRepeatMode.all || AudioServiceRepeatMode.group => LoopMode.all,
};
await _player.setLoopMode(loop);
}
/// Sets player volume in [0.0, 1.0]. Note: most mobile browsers tie
/// page audio to system volume — this is the in-app slider for parity
/// with desktop/web; on mobile the system volume is the real control.
Future<void> setVolume(double v) async {
await _player.setVolume(v.clamp(0.0, 1.0));
}
// _broadcastState accepts a nullable event because the shuffle/repeat
// listeners don't have one — we just want to re-emit PlaybackState
// with up-to-date shuffleMode/repeatMode fields.
void _broadcastState(PlaybackEvent? event) {
final playing = _player.playing;
playbackState.add(PlaybackState(
controls: [
@@ -71,7 +426,20 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
if (playing) MediaControl.pause else MediaControl.play,
MediaControl.skipToNext,
],
systemActions: const {MediaAction.seek},
// androidCompactActionIndices tells the system which controls
// appear in the collapsed/lock-screen view. Without this, some
// Android versions render the player without working buttons.
androidCompactActionIndices: const [0, 1, 2],
// systemActions enumerates which actions the system can invoke
// on us — without play/pause/skip in here, taps on lock-screen
// controls don't route back to the handler on Android 13+.
systemActions: const {
MediaAction.play,
MediaAction.pause,
MediaAction.skipToNext,
MediaAction.skipToPrevious,
MediaAction.seek,
},
processingState: switch (_player.processingState) {
ProcessingState.idle => AudioProcessingState.idle,
ProcessingState.loading => AudioProcessingState.loading,
@@ -83,7 +451,15 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
updatePosition: _player.position,
bufferedPosition: _player.bufferedPosition,
speed: _player.speed,
queueIndex: event.currentIndex,
queueIndex: event?.currentIndex ?? _player.currentIndex,
shuffleMode: _player.shuffleModeEnabled
? AudioServiceShuffleMode.all
: AudioServiceShuffleMode.none,
repeatMode: switch (_player.loopMode) {
LoopMode.off => AudioServiceRepeatMode.none,
LoopMode.one => AudioServiceRepeatMode.one,
LoopMode.all => AudioServiceRepeatMode.all,
},
));
}
}
+563 -52
View File
@@ -1,75 +1,586 @@
import 'dart:io';
import 'package:audio_service/audio_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../api/endpoints/likes.dart' show LikeKind;
import '../likes/like_button.dart';
import '../models/track.dart';
import '../shared/widgets/server_image.dart';
import '../shared/widgets/track_actions/track_actions_button.dart';
import '../theme/theme_extension.dart';
import 'album_color_extractor.dart';
import 'player_provider.dart';
class NowPlayingScreen extends ConsumerWidget {
/// Hero tag shared between the mini player's cover and the full-screen
/// _AlbumArt's cover so tapping the mini bar animates the artwork from
/// the bar's footprint to the full-screen size. Stable per-route (not
/// keyed by media.id) so the transition works regardless of what's
/// playing.
const String kPlayerCoverHeroTag = 'player-cover';
/// Duration for the AnimatedSwitcher / AnimatedContainer track-change
/// crossfade. ~300ms reads as a smooth transition without dragging.
const Duration _trackChangeDuration = Duration(milliseconds: 300);
/// Full-screen player. Mounted on /now-playing. Pushed via a slide-up
/// transition (see routing.dart). Dismisses three ways:
///
/// - System back / leading button → Navigator.pop
/// - Vertical drag down past threshold → Navigator.pop (matches the
/// slide-down animation users expect from a "pull down to close"
/// sheet)
/// - Tap of the mini player ascends here; reverse motion descends back.
class NowPlayingScreen extends ConsumerStatefulWidget {
const NowPlayingScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final media = ref.watch(mediaItemProvider).valueOrNull;
final playback = ref.watch(playbackStateProvider).valueOrNull;
ConsumerState<NowPlayingScreen> createState() => _NowPlayingScreenState();
}
if (media == null) {
class _NowPlayingScreenState extends ConsumerState<NowPlayingScreen> {
// Cumulative drag distance used to decide if a vertical drag should
// dismiss. Reset on each drag start.
double _dragOffset = 0;
/// The MediaItem currently displayed on the screen. Held separately
/// from the live mediaItemProvider so we can preload the new track's
/// cover bytes + dominant color BEFORE flipping the visible state.
/// Without this gate the full-player UI swapped to the new track's
/// title/cover slot immediately while the image was still decoding,
/// producing a visible "pop in" once the bytes arrived.
MediaItem? _displayedMedia;
/// Dominant color of [_displayedMedia]'s cover. Tweened by the
/// backdrop AnimatedContainer when it changes.
Color? _displayedDominant;
/// The id of the most-recent track we kicked a preload for. Used to
/// drop stale preload completions when the user skips rapidly past
/// a track whose cover hadn't finished decoding yet.
String? _pendingPreloadId;
/// Preload the new track's cover bytes + dominant color, then
/// atomically flip _displayedMedia / _displayedDominant. Until both
/// resolve, the screen continues to render the previous track —
/// the new title/cover/gradient appear together in one frame.
///
/// Concurrency: if a second track change arrives while the first
/// preload is still in flight, the older preload's
/// _pendingPreloadId check fails and its completion is dropped.
Future<void> _scheduleSwap(MediaItem newMedia) async {
_pendingPreloadId = newMedia.id;
// 1. Precache the cover image bytes so when _AlbumArt mounts with
// the new media, FileImage paints synchronously. Non-file
// artUris fall through to ServerImage which handles its own
// network load + 120ms fade — they won't snap.
final artUri = newMedia.artUri;
if (artUri != null && artUri.isScheme('file') && context.mounted) {
try {
await precacheImage(FileImage(File.fromUri(artUri)), context);
} catch (_) {
// Decode failed (missing file, corrupt bytes) — proceed
// anyway; _AlbumArt's errorBuilder shows the slate fallback.
}
}
// 2. Wait for the dominant-color extraction so the gradient is
// populated when we swap. PaletteGenerator runs against the
// same FileImage, typically resolving within ~50ms once the
// decode completes.
Color? newDominant;
final albumId = newMedia.extras?['album_id'] as String?;
if (albumId != null && albumId.isNotEmpty) {
try {
newDominant = await ref.read(albumColorProvider(albumId).future);
} catch (_) {
// Color extraction failed — keep the previous dominant so the
// backdrop doesn't drop to obsidian on the swap.
}
}
// 3. Atomic flip. Bail if a newer swap superseded us, or the
// screen was disposed mid-preload.
if (!mounted) return;
if (_pendingPreloadId != newMedia.id) return;
setState(() {
_displayedMedia = newMedia;
if (newDominant != null) _displayedDominant = newDominant;
});
}
void _onDragStart(DragStartDetails _) {
_dragOffset = 0;
}
void _onDragUpdate(DragUpdateDetails d) {
_dragOffset += d.delta.dy;
}
void _onDragEnd(DragEndDetails d) {
// Pop when either the user has dragged > 80px down OR flicked
// downward at speed (>500 px/s). Either should feel responsive
// without dismissing on accidental drags.
final flicked = d.primaryVelocity != null && d.primaryVelocity! > 500;
if (_dragOffset > 80 || flicked) {
Navigator.of(context).maybePop();
}
_dragOffset = 0;
}
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
// Listen for mediaItem changes and schedule a preload-then-swap.
// Build renders _displayedMedia / _displayedDominant; the live
// mediaItemProvider only drives the swap pipeline.
//
// Decision process:
// - On the first non-null mediaItem after mount, seed
// _displayedMedia immediately so the screen has something to
// paint.
// - On a track id change, kick off a preload. The new track's
// cover bytes + dominant color must both resolve before we
// flip the displayed state. The user sees the previous track
// in full until the new one is fully ready, then a clean
// atomic swap (no fade, no placeholder flash).
// - On the same track id but the artUri-bearing rebroadcast
// (audio_handler sends MediaItem twice on track change),
// refresh through the same preload pipeline so the displayed
// cover reflects the freshly-written AlbumCoverCache file.
ref.listen<AsyncValue<MediaItem?>>(mediaItemProvider, (prev, next) {
final newMedia = next.asData?.value;
if (newMedia == null) {
if (_displayedMedia != null) {
setState(() {
_displayedMedia = null;
_displayedDominant = null;
_pendingPreloadId = null;
});
}
return;
}
if (_displayedMedia == null) {
// First mount with a track playing — seed immediately, then
// kick the preload pipeline to update the dominant color and
// ensure the cover is decoded.
setState(() => _displayedMedia = newMedia);
_scheduleSwap(newMedia);
return;
}
final isNewTrack = newMedia.id != _displayedMedia!.id;
final coverGotPopulated =
newMedia.id == _displayedMedia!.id &&
newMedia.artUri != null &&
_displayedMedia!.artUri == null;
if (isNewTrack || coverGotPopulated) {
_scheduleSwap(newMedia);
}
});
final playback = ref.watch(playbackStateProvider).value;
final displayedMedia = _displayedMedia;
if (displayedMedia == null) {
// Either nothing playing, or the very first mount before a
// mediaItem has been emitted. The ref.listen above will seed
// _displayedMedia as soon as a non-null MediaItem arrives.
return const Scaffold(body: Center(child: Text('Nothing playing.')));
}
final pos = playback?.updatePosition ?? Duration.zero;
final dur = media.duration ?? Duration.zero;
// Use positionProvider (just_audio's positionStream, ~200ms) for
// the seek bar so it scrubs live; PlaybackState.updatePosition
// only fires on state transitions and would leave the bar frozen
// between them.
final pos = ref.watch(positionProvider).value ?? Duration.zero;
final dur = displayedMedia.duration ?? Duration.zero;
final isPlaying = playback?.playing == true;
final shuffleOn = playback?.shuffleMode == AudioServiceShuffleMode.all;
final repeatMode = playback?.repeatMode ?? AudioServiceRepeatMode.none;
final actions = ref.read(playerActionsProvider);
final albumId = (displayedMedia.extras?['album_id'] as String?) ?? '';
// Backdrop color: render the dominant we've already committed to
// _displayedDominant. AnimatedContainer tweens between successive
// values, so the only color changes the user sees are the
// atomic-with-cover swaps from _scheduleSwap. 0.55 alpha keeps
// the gradient present without overwhelming the title/artist
// text below.
final dominant = _displayedDominant ?? fs.obsidian;
final gradientTop = dominant.withValues(alpha: 0.55);
return Scaffold(
backgroundColor: fs.obsidian,
appBar: AppBar(
backgroundColor: fs.obsidian,
leading: IconButton(
icon: Icon(Icons.expand_more, color: fs.parchment),
onPressed: () => Navigator.of(context).pop(),
),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(children: [
const Spacer(),
Container(
width: 280, height: 280, color: fs.slate,
// The whole screen accepts vertical drag for dismissal. Buttons
// and the seek slider are still tappable since gesture arena
// gives priority to their child gesture detectors.
body: GestureDetector(
onVerticalDragStart: _onDragStart,
onVerticalDragUpdate: _onDragUpdate,
onVerticalDragEnd: _onDragEnd,
behavior: HitTestBehavior.translucent,
child: AnimatedContainer(
duration: _trackChangeDuration,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [gradientTop, fs.obsidian],
stops: const [0.0, 0.7],
),
const SizedBox(height: 24),
Text(media.title, style: TextStyle(color: fs.parchment, fontSize: 22)),
Text(media.artist ?? '', style: TextStyle(color: fs.ash, fontSize: 14)),
const SizedBox(height: 16),
Slider(
activeColor: fs.accent,
min: 0,
max: dur.inMilliseconds.toDouble().clamp(1, double.infinity),
value: pos.inMilliseconds.toDouble().clamp(0, dur.inMilliseconds.toDouble()),
onChanged: (v) => ref.read(audioHandlerProvider).seek(Duration(milliseconds: v.toInt())),
),
Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
IconButton(
icon: Icon(Icons.skip_previous, color: fs.parchment, size: 32),
onPressed: () => ref.read(audioHandlerProvider).skipToPrevious(),
),
child: SafeArea(
child: Column(
children: [
_TopBar(fs: fs),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(
children: [
const Spacer(),
// No AnimatedSwitcher: _displayedMedia only
// advances after the preload pipeline has the
// new cover + color ready, so a track change
// is an atomic swap. Fading would just smear a
// transition the user explicitly asked us not
// to add.
_AlbumArt(
media: displayedMedia, albumId: albumId, fs: fs),
const SizedBox(height: 28),
_TitleRow(media: displayedMedia, fs: fs),
const SizedBox(height: 4),
Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
displayedMedia.artist ?? '',
style: TextStyle(color: fs.ash, fontSize: 14),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if ((displayedMedia.album ?? '').isNotEmpty) ...[
const SizedBox(height: 2),
Text(
displayedMedia.album!,
style: TextStyle(color: fs.ash, fontSize: 12),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
],
),
const SizedBox(height: 24),
_SecondaryControls(
fs: fs,
actions: actions,
shuffleOn: shuffleOn,
repeatMode: repeatMode,
media: displayedMedia,
),
const SizedBox(height: 8),
_SeekRow(position: pos, duration: dur, fs: fs, ref: ref),
const SizedBox(height: 24),
_PrimaryControls(
fs: fs,
ref: ref,
isPlaying: isPlaying,
),
const SizedBox(height: 24),
],
),
),
),
IconButton(
iconSize: 56,
icon: Icon(playback?.playing == true ? Icons.pause_circle_filled : Icons.play_circle_filled, color: fs.accent),
onPressed: () {
final h = ref.read(audioHandlerProvider);
if (playback?.playing == true) { h.pause(); } else { h.play(); }
},
),
IconButton(
icon: Icon(Icons.skip_next, color: fs.parchment, size: 32),
onPressed: () => ref.read(audioHandlerProvider).skipToNext(),
),
]),
const Spacer(),
]),
],
),
),
),
),
);
}
}
class _TopBar extends StatelessWidget {
const _TopBar({required this.fs});
final FabledSwordTheme fs;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 48,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Row(children: [
IconButton(
icon: Icon(Icons.expand_more, color: fs.parchment),
tooltip: 'Close',
onPressed: () => Navigator.of(context).maybePop(),
),
const Spacer(),
IconButton(
icon: Icon(Icons.queue_music, color: fs.parchment),
tooltip: 'Queue',
onPressed: () => GoRouter.of(context).push('/queue'),
),
]),
),
);
}
}
class _AlbumArt extends StatelessWidget {
const _AlbumArt({required this.media, required this.albumId, required this.fs});
final MediaItem media;
final String albumId;
final FabledSwordTheme fs;
@override
Widget build(BuildContext context) {
// Pick the best available source. AlbumCoverCache writes a file://
// URI to media.artUri once the cover lands on disk; before then,
// fall back to fetching via ServerImage from /api/albums/<id>/cover
// (which carries the auth header and falls back gracefully on
// failure).
Widget cover;
final artUri = media.artUri;
if (artUri != null && artUri.isScheme('file')) {
cover = Image(
image: FileImage(File.fromUri(artUri)),
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => Container(color: fs.slate),
);
} else if (albumId.isNotEmpty) {
cover = ServerImage(
url: '/api/albums/$albumId/cover',
fit: BoxFit.cover,
fallback: Container(color: fs.slate),
);
} else {
cover = Container(color: fs.slate);
}
return AspectRatio(
aspectRatio: 1,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 320, maxHeight: 320),
child: Hero(
tag: kPlayerCoverHeroTag,
// flightShuttleBuilder ensures the in-flight Hero renders the
// destination's cover image (not the mini bar's small one)
// during the entire animation, which reads as a smooth grow
// rather than a swap mid-flight.
flightShuttleBuilder:
(_, __, ___, ____, toHeroContext) => toHeroContext.widget,
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: cover,
),
),
),
);
}
}
class _TitleRow extends StatelessWidget {
const _TitleRow({required this.media, required this.fs});
final MediaItem media;
final FabledSwordTheme fs;
@override
Widget build(BuildContext context) {
// Title-only — like + kebab moved into _SecondaryControls above
// the seek bar so they share the same row as shuffle/repeat/queue.
return Text(
media.title,
style: TextStyle(color: fs.parchment, fontSize: 22),
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
);
}
}
class _SeekRow extends StatelessWidget {
const _SeekRow({
required this.position,
required this.duration,
required this.fs,
required this.ref,
});
final Duration position;
final Duration duration;
final FabledSwordTheme fs;
final WidgetRef ref;
String _fmt(Duration d) {
final m = d.inMinutes.remainder(60).toString();
final s = d.inSeconds.remainder(60).toString().padLeft(2, '0');
return '$m:$s';
}
@override
Widget build(BuildContext context) {
final maxMs = duration.inMilliseconds.toDouble().clamp(1.0, double.infinity);
return Column(children: [
SliderTheme(
data: SliderTheme.of(context).copyWith(
trackHeight: 3,
thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 7),
overlayShape: const RoundSliderOverlayShape(overlayRadius: 14),
),
child: Slider(
activeColor: fs.accent,
inactiveColor: fs.slate,
min: 0,
max: maxMs,
value: position.inMilliseconds
.toDouble()
.clamp(0.0, duration.inMilliseconds.toDouble()),
onChanged: (v) => ref
.read(audioHandlerProvider)
.seek(Duration(milliseconds: v.toInt())),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(_fmt(position), style: TextStyle(color: fs.ash, fontSize: 11)),
Text(_fmt(duration), style: TextStyle(color: fs.ash, fontSize: 11)),
],
),
),
]);
}
}
class _PrimaryControls extends StatelessWidget {
const _PrimaryControls({
required this.fs,
required this.ref,
required this.isPlaying,
});
final FabledSwordTheme fs;
final WidgetRef ref;
final bool isPlaying;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
IconButton(
iconSize: 36,
icon: Icon(Icons.skip_previous, color: fs.parchment),
onPressed: () => ref.read(audioHandlerProvider).skipToPrevious(),
),
IconButton(
iconSize: 72,
icon: Icon(
isPlaying ? Icons.pause_circle_filled : Icons.play_circle_filled,
color: fs.accent,
),
onPressed: () {
final h = ref.read(audioHandlerProvider);
if (isPlaying) {
h.pause();
} else {
h.play();
}
},
),
IconButton(
iconSize: 36,
icon: Icon(Icons.skip_next, color: fs.parchment),
onPressed: () => ref.read(audioHandlerProvider).skipToNext(),
),
],
);
}
}
/// Action row sitting just above the seek bar. Holds shuffle / repeat
/// / queue plus the like + kebab that used to live in the title row,
/// so the title can sit truly centered above and this row carries
/// every per-track action in one place.
class _SecondaryControls extends StatelessWidget {
const _SecondaryControls({
required this.fs,
required this.actions,
required this.shuffleOn,
required this.repeatMode,
required this.media,
});
final FabledSwordTheme fs;
final PlayerActions actions;
final bool shuffleOn;
final AudioServiceRepeatMode repeatMode;
final MediaItem media;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
IconButton(
tooltip: shuffleOn ? 'Shuffle on' : 'Shuffle off',
icon: Icon(
Icons.shuffle,
color: shuffleOn ? fs.accent : fs.ash,
),
onPressed: actions.toggleShuffle,
),
IconButton(
tooltip: switch (repeatMode) {
AudioServiceRepeatMode.none => 'Repeat off',
AudioServiceRepeatMode.one => 'Repeat one',
_ => 'Repeat all',
},
icon: Icon(
repeatMode == AudioServiceRepeatMode.one
? Icons.repeat_one
: Icons.repeat,
color: repeatMode == AudioServiceRepeatMode.none
? fs.ash
: fs.accent,
),
onPressed: actions.cycleRepeat,
),
IconButton(
tooltip: 'Queue',
icon: Icon(Icons.queue_music, color: fs.ash),
onPressed: () => GoRouter.of(context).push('/queue'),
),
LikeButton(kind: LikeKind.track, id: media.id, size: 22),
TrackActionsButton(
track: TrackRef(
id: media.id,
title: media.title,
albumId: (media.extras?['album_id'] as String?) ?? '',
albumTitle: media.album ?? '',
artistId: (media.extras?['artist_id'] as String?) ?? '',
artistName: media.artist ?? '',
durationSec: media.duration?.inSeconds ?? 0,
streamUrl: '',
),
hideQueueActions: true,
// /now-playing lives outside the ShellRoute. Pushing
// /artists/:id or /albums/:id (both shell-children) on top
// of it would make go_router try to mount a duplicate
// ShellRoute (the same _debugCheckDuplicatedPageKeys crash
// we hit before with /queue). Await our own pop fully
// before pushing the destination so go_router never sees
// both pages active in the same frame.
onNavigate: (path) async {
await Navigator.of(context).maybePop();
if (context.mounted) GoRouter.of(context).push(path);
},
),
],
);
}
}
+323 -31
View File
@@ -1,53 +1,345 @@
import 'dart:io';
import 'package:audio_service/audio_service.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../api/endpoints/likes.dart' show LikeKind;
import '../likes/like_button.dart';
import '../models/track.dart';
import '../shared/widgets/track_actions/track_actions_button.dart';
import '../theme/theme_extension.dart';
import 'now_playing_screen.dart' show kPlayerCoverHeroTag;
import 'player_provider.dart';
class PlayerBar extends ConsumerWidget {
/// Compact player bar mounted at the bottom of the app shell. Mini
/// view only — the heavyweight shuffle/repeat/queue/volume controls
/// live in NowPlayingScreen, accessible by tap or swipe-up.
///
/// ┌─────────────────────────────────────┬──────────┐
/// │ [art] Title ♥ ⋮ │ ⏮ ⏯ ⏭ │
/// │ Artist │ │
/// ├─────────────────────────────────────────────────┤
/// │ 0:00 ━━●━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3:06 │
/// └─────────────────────────────────────────────────┘
///
/// Tap anywhere on the bar (including art/title) ascends to the full
/// player. A vertical drag upward also ascends, so the gesture mirrors
/// the drag-down dismissal on the full screen.
class PlayerBar extends ConsumerStatefulWidget {
const PlayerBar({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ConsumerState<PlayerBar> createState() => _PlayerBarState();
}
class _PlayerBarState extends ConsumerState<PlayerBar> {
/// Last non-null artUri we've seen from the mediaItem stream. Held
/// across the audio_handler's two-broadcast track-change pattern
/// (bare MediaItem first, then with artUri once AlbumCoverCache
/// resolves) so the mini bar keeps showing the previous track's
/// cover until the new one is known. Without this hold the bar
/// flickered to the slate placeholder for ~100ms on every track
/// change.
Uri? _lastArtUri;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final mediaItem = ref.watch(mediaItemProvider).valueOrNull;
final playback = ref.watch(playbackStateProvider).valueOrNull;
if (mediaItem == null) return const SizedBox.shrink();
final media = ref.watch(mediaItemProvider).value;
final playback = ref.watch(playbackStateProvider).value;
if (media == null) return const SizedBox.shrink();
// Capture the latest non-null artUri so _TrackInfo's cover stays
// continuous across track changes.
if (media.artUri != null) _lastArtUri = media.artUri;
final displayMedia = media.artUri == null && _lastArtUri != null
? media.copyWith(artUri: _lastArtUri)
: media;
// positionProvider is just_audio's positionStream (~200ms cadence)
// so the mini bar's seek crawls forward smoothly. PlaybackState
// only updates on event transitions and would leave it frozen.
final pos = ref.watch(positionProvider).value ?? Duration.zero;
final dur = media.duration ?? Duration.zero;
return Material(
color: fs.iron,
child: InkWell(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => context.push('/now-playing'),
// Swipe up anywhere on the bar to expand into the full player.
// We only act on a clear upward flick (>200 px/s) so a slow
// tap-with-tiny-jitter doesn't accidentally open the screen.
onVerticalDragEnd: (d) {
final v = d.primaryVelocity ?? 0;
if (v < -200) context.push('/now-playing');
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: Row(children: [
Container(width: 48, height: 48, color: fs.slate),
const SizedBox(width: 12),
Expanded(child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(mediaItem.title, maxLines: 1, overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14)),
Text(mediaItem.artist ?? '', maxLines: 1, overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.ash, fontSize: 12)),
],
)),
IconButton(
icon: Icon(playback?.playing == true ? Icons.pause : Icons.play_arrow, color: fs.parchment),
onPressed: () {
final h = ref.read(audioHandlerProvider);
if (playback?.playing == true) { h.pause(); } else { h.play(); }
},
),
IconButton(
icon: Icon(Icons.skip_next, color: fs.parchment),
onPressed: () => ref.read(audioHandlerProvider).skipToNext(),
),
]),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(child: _TrackInfo(media: displayMedia)),
const SizedBox(width: 8),
_PlayControls(playback: playback, ref: ref),
],
),
),
const SizedBox(height: 4),
_SeekRow(position: pos, duration: dur),
],
),
),
),
);
}
}
class _TrackInfo extends StatelessWidget {
const _TrackInfo({required this.media});
final MediaItem media;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final artistName = (media.artist ?? '').trim();
// Cover is wrapped in a Hero with the shared kPlayerCoverHeroTag so
// tapping the mini bar to expand into NowPlayingScreen animates the
// artwork from this 48dp footprint to the full-screen size rather
// than fade-cutting. Tag is stable per-route (not keyed by media.id)
// so the transition works regardless of what's playing.
//
// Why no transition / placeholder handling: the audio_handler
// broadcasts MediaItem twice on track change — once with artUri
// null (the new track's bare metadata), then with artUri set once
// AlbumCoverCache resolves. The widget tree above hands us the
// most-recent non-null artUri (`displayArtUri`), so the previous
// track's cover stays visible across that null gap and the new
// cover snaps in the moment its artUri arrives. Rapid change is
// fine here per operator preference; AnimatedSwitcher previously
// smeared the swap and made the slate placeholder visible.
final displayArtUri = media.artUri;
final Widget cover;
if (displayArtUri != null) {
// CachedNetworkImageProvider for HTTPS art URIs so the mini bar
// hits the same disk cache the rest of the UI uses (ServerImage,
// discover thumbnails). FileImage stays for the file:// branch
// populated by AlbumCoverCache — bytes are already on disk and a
// second cache layer would only burn duplicate space.
cover = Image(
image: displayArtUri.isScheme('file')
? FileImage(File.fromUri(displayArtUri)) as ImageProvider
: CachedNetworkImageProvider(displayArtUri.toString()),
width: 48,
height: 48,
// Without a fit, Image paints the source at its intrinsic
// resolution inside the 48dp box — a thumbnail-sized cover
// would render as a tiny inset. Cover stretches/crops to fill
// the box uniformly.
fit: BoxFit.cover,
errorBuilder: (_, __, ___) =>
Container(width: 48, height: 48, color: fs.slate),
);
} else {
cover = Container(width: 48, height: 48, color: fs.slate);
}
return Row(
// Default centering vertically aligns the like/kebab buttons
// against the album art (48dp) — visually they span the title +
// artist block instead of sitting on the title baseline.
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Hero(
tag: kPlayerCoverHeroTag,
child: cover,
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Text(
media.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14),
),
if (artistName.isNotEmpty)
Text(
artistName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.ash, fontSize: 12),
),
],
),
),
// Like + kebab as siblings to the title/artist column rather
// than nested inside the title row. Width stays 32dp each so
// horizontal footprint matches what we had; height stretches
// to the row's full 48dp so the icons sit at vertical center
// against the title+artist block.
SizedBox(
width: 32,
height: 48,
child: LikeButton(
kind: LikeKind.track,
id: media.id,
size: 20,
),
),
SizedBox(
width: 32,
height: 48,
child: TrackActionsButton(
track: _trackRefFromMediaItem(media),
hideQueueActions: true,
),
),
],
);
}
}
class _PlayControls extends StatelessWidget {
const _PlayControls({required this.playback, required this.ref});
final PlaybackState? playback;
final WidgetRef ref;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final isPlaying = playback?.playing == true;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 36,
height: 36,
child: IconButton(
padding: EdgeInsets.zero,
iconSize: 22,
icon: Icon(Icons.skip_previous, color: fs.parchment),
onPressed: () => ref.read(audioHandlerProvider).skipToPrevious(),
),
),
SizedBox(
width: 44,
height: 44,
child: IconButton(
padding: EdgeInsets.zero,
iconSize: 32,
icon: Icon(
isPlaying ? Icons.pause_circle_filled : Icons.play_circle_filled,
color: fs.accent,
),
onPressed: () {
final h = ref.read(audioHandlerProvider);
if (isPlaying) {
h.pause();
} else {
h.play();
}
},
),
),
SizedBox(
width: 36,
height: 36,
child: IconButton(
padding: EdgeInsets.zero,
iconSize: 22,
icon: Icon(Icons.skip_next, color: fs.parchment),
onPressed: () => ref.read(audioHandlerProvider).skipToNext(),
),
),
],
);
}
}
class _SeekRow extends ConsumerWidget {
const _SeekRow({required this.position, required this.duration});
final Duration position;
final Duration duration;
String _fmt(Duration d) {
final m = d.inMinutes.remainder(60).toString();
final s = d.inSeconds.remainder(60).toString().padLeft(2, '0');
return '$m:$s';
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final maxMs =
duration.inMilliseconds.toDouble().clamp(1.0, double.infinity);
return Row(
children: [
SizedBox(
width: 36,
child: Text(
_fmt(position),
textAlign: TextAlign.right,
style: TextStyle(color: fs.ash, fontSize: 10),
),
),
Expanded(
child: SliderTheme(
data: SliderTheme.of(context).copyWith(
trackHeight: 2,
thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 6),
overlayShape: const RoundSliderOverlayShape(overlayRadius: 12),
),
child: Slider(
activeColor: fs.accent,
inactiveColor: fs.slate,
min: 0,
max: maxMs,
value: position.inMilliseconds
.toDouble()
.clamp(0.0, duration.inMilliseconds.toDouble()),
onChanged: (v) => ref
.read(audioHandlerProvider)
.seek(Duration(milliseconds: v.toInt())),
),
),
),
SizedBox(
width: 36,
child: Text(
_fmt(duration),
style: TextStyle(color: fs.ash, fontSize: 10),
),
),
],
);
}
}
/// Reconstructs a minimal TrackRef from a MediaItem so the
/// TrackActionsButton has the fields its sheet expects. Mirrors the
/// pattern used by NowPlayingScreen — extras['album_id'] is what
/// audio_handler stashed at queue-build time.
TrackRef _trackRefFromMediaItem(MediaItem media) => TrackRef(
id: media.id,
title: media.title,
albumId: (media.extras?['album_id'] as String?) ?? '',
albumTitle: media.album ?? '',
// artist_id is stashed in extras by audio_handler — without it
// the kebab's "Go to artist" pushes /artists/ (empty id) and 404s.
artistId: (media.extras?['artist_id'] as String?) ?? '',
artistName: media.artist ?? '',
durationSec: media.duration?.inSeconds ?? 0,
streamUrl: '',
);
+81 -1
View File
@@ -1,14 +1,24 @@
import 'package:audio_service/audio_service.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/endpoints/radio.dart';
import '../auth/auth_provider.dart';
import '../cache/audio_cache_manager.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/track.dart';
import 'album_cover_cache.dart';
import 'audio_handler.dart';
final audioHandlerProvider = Provider<MinstrelAudioHandler>((ref) {
throw UnimplementedError('overridden in main()');
});
final albumCoverCacheProvider = Provider<AlbumCoverCache>((ref) {
return AlbumCoverCache(
dioFactory: () => ref.read(dioProvider.future),
);
});
final playbackStateProvider = StreamProvider<PlaybackState>(
(ref) => ref.watch(audioHandlerProvider).playbackState,
);
@@ -21,6 +31,23 @@ final queueProvider = StreamProvider<List<MediaItem>>(
(ref) => ref.watch(audioHandlerProvider).queue,
);
/// Player volume in [0.0, 1.0]. Mirrors just_audio's player.volume;
/// modify via PlayerActions.setVolume(). Surfaced separately from
/// PlaybackState because audio_service's PlaybackState doesn't carry
/// volume — it's a player-side concern.
final volumeProvider = StreamProvider<double>(
(ref) => ref.watch(audioHandlerProvider).volumeStream,
);
/// Live playback position. just_audio emits at ~200ms cadence so seek
/// bars driven by this provider scrub smoothly. Don't use
/// PlaybackState.updatePosition for that — it only changes on state
/// transitions (play/pause/buffer/seek) and the bar would appear
/// frozen between events.
final positionProvider = StreamProvider<Duration>(
(ref) => ref.watch(audioHandlerProvider).positionStream,
);
class PlayerActions {
PlayerActions(this._ref);
final Ref _ref;
@@ -28,10 +55,63 @@ class PlayerActions {
Future<void> playTracks(List<TrackRef> tracks, {int initialIndex = 0}) async {
final url = await _ref.read(serverUrlProvider.future);
final token = await _ref.read(secureStorageProvider).read(key: 'session_token');
final h = _ref.read(audioHandlerProvider)..configure(baseUrl: url ?? '', token: token);
final cache = _ref.read(albumCoverCacheProvider);
final audioCache = _ref.read(audioCacheManagerProvider);
final h = _ref.read(audioHandlerProvider)
..configure(
baseUrl: url ?? '',
token: token,
coverCache: cache,
audioCacheManager: audioCache,
);
await h.setQueueFromTracks(tracks, initialIndex: initialIndex);
await h.play();
}
Future<void> playNext(TrackRef track) async {
final h = _ref.read(audioHandlerProvider);
await h.playNext(track);
}
Future<void> enqueue(TrackRef track) async {
final h = _ref.read(audioHandlerProvider);
await h.enqueue(track);
}
/// Toggles shuffle on/off. Pre-existing audio_service convention.
Future<void> toggleShuffle() async {
final h = _ref.read(audioHandlerProvider);
final state = await h.playbackState.first;
final next = state.shuffleMode == AudioServiceShuffleMode.none
? AudioServiceShuffleMode.all
: AudioServiceShuffleMode.none;
await h.setShuffleMode(next);
}
/// Cycles repeat mode: none → all → one → none.
Future<void> cycleRepeat() async {
final h = _ref.read(audioHandlerProvider);
final state = await h.playbackState.first;
final next = switch (state.repeatMode) {
AudioServiceRepeatMode.none => AudioServiceRepeatMode.all,
AudioServiceRepeatMode.all => AudioServiceRepeatMode.one,
_ => AudioServiceRepeatMode.none,
};
await h.setRepeatMode(next);
}
Future<void> setVolume(double v) async {
await _ref.read(audioHandlerProvider).setVolume(v);
}
/// Fetches `/api/radio?seed_track=<id>` and starts playing the
/// returned track list (seed at index 0 + recommended picks).
Future<void> startRadio(String trackId) async {
final dio = await _ref.read(dioProvider.future);
final tracks = await RadioApi(dio).seedTrack(trackId);
if (tracks.isEmpty) return;
await playTracks(tracks);
}
}
final playerActionsProvider = Provider<PlayerActions>((ref) => PlayerActions(ref));
+118
View File
@@ -0,0 +1,118 @@
import 'package:audio_service/audio_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../theme/theme_extension.dart';
import 'player_provider.dart';
class QueueScreen extends ConsumerWidget {
const QueueScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final queue = ref.watch(queueProvider).value ?? const [];
final current = ref.watch(mediaItemProvider).value;
return Scaffold(
backgroundColor: fs.obsidian,
appBar: AppBar(
backgroundColor: fs.obsidian,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: fs.parchment),
onPressed: () => context.pop(),
),
title: Text('Queue', style: TextStyle(color: fs.parchment)),
),
body: queue.isEmpty
? Center(
child: Text('Queue is empty.', style: TextStyle(color: fs.ash)),
)
: ListView.separated(
itemCount: queue.length,
separatorBuilder: (_, __) => Divider(height: 1, color: fs.iron),
itemBuilder: (ctx, i) => _QueueRow(
item: queue[i],
index: i,
isCurrent: current?.id == queue[i].id,
onTap: () async {
final h = ref.read(audioHandlerProvider);
await h.skipToQueueItem(i);
await h.play();
},
),
),
);
}
}
class _QueueRow extends StatelessWidget {
const _QueueRow({
required this.item,
required this.index,
required this.isCurrent,
required this.onTap,
});
final MediaItem item;
final int index;
final bool isCurrent;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final dur = item.duration;
String? durLabel;
if (dur != null) {
final m = (dur.inSeconds ~/ 60).toString().padLeft(2, '0');
final s = (dur.inSeconds % 60).toString().padLeft(2, '0');
durLabel = '$m:$s';
}
return InkWell(
onTap: isCurrent ? null : onTap,
child: Container(
decoration: BoxDecoration(
border: isCurrent
? Border(left: BorderSide(color: fs.accent, width: 2))
: null,
color: isCurrent ? fs.iron : null,
),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: Row(children: [
if (isCurrent)
Padding(
padding: const EdgeInsets.only(right: 8),
child: Icon(Icons.graphic_eq, color: fs.accent, size: 16),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: isCurrent ? fs.accent : fs.parchment,
fontSize: 14,
fontWeight: isCurrent ? FontWeight.w500 : FontWeight.w400,
),
),
Text(
'${item.artist ?? ''} · ${item.album ?? ''}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.ash, fontSize: 12),
),
],
),
),
if (durLabel != null)
Text(durLabel, style: TextStyle(color: fs.ash, fontSize: 12)),
]),
),
);
}
}
@@ -0,0 +1,370 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../cache/audio_cache_manager.dart';
import '../cache/db.dart';
import '../models/playlist.dart';
import '../models/track.dart';
import '../player/player_provider.dart';
import '../shared/live_events_provider.dart';
import '../shared/widgets/track_actions/track_actions_button.dart';
import '../theme/theme_extension.dart';
import 'playlists_provider.dart';
class PlaylistDetailScreen extends ConsumerWidget {
const PlaylistDetailScreen({required this.id, this.seed, super.key});
final String id;
/// Optional Playlist passed via go_router extra so the header
/// (title, cover, track count, play/download CTAs) can render
/// before the full detail fetch resolves. Same pattern as album
/// + artist nav hydration.
final Playlist? seed;
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
// #402 wire-up: invalidate the detail provider on playlist.updated /
// .tracks_changed events whose payload matches the visible id. On
// .deleted matching this id, navigate back so the user isn't left
// staring at a gone-from-server playlist.
ref.listen<AsyncValue<LiveEvent>>(liveEventsProvider, (_, next) {
final e = next.asData?.value;
if (e == null) return;
final eventPlaylistId = e.data['playlist_id'] as String?;
if (eventPlaylistId != id) return;
switch (e.kind) {
case 'playlist.updated':
case 'playlist.tracks_changed':
ref.invalidate(playlistDetailProvider(id));
case 'playlist.deleted':
if (context.mounted) context.pop();
}
});
final detail = ref.watch(playlistDetailProvider(id));
// Resolve the best playlist info available for the AppBar title.
final livePlaylist = detail.value?.playlist;
final headerName = (livePlaylist != null && livePlaylist.name.isNotEmpty)
? livePlaylist.name
: (seed?.name ?? '');
return Scaffold(
backgroundColor: fs.obsidian,
appBar: AppBar(
backgroundColor: fs.obsidian,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: fs.parchment),
onPressed: () => context.pop(),
),
title: headerName.isEmpty
? const SizedBox.shrink()
: Text(
headerName,
style: TextStyle(color: fs.parchment),
overflow: TextOverflow.ellipsis,
),
),
// AnimatedSwitcher between the skeleton body and the real body
// smooths the cold-visit moment when bulk detail lands. 220ms
// matches the per-tile reveal feel used on home / liked tabs.
body: AnimatedSwitcher(
duration: const Duration(milliseconds: 220),
switchInCurve: Curves.easeOut,
child: detail.when(
loading: () => _SkeletonBody(
key: const ValueKey('skeleton'),
seed: seed,
),
error: (e, _) => Center(
key: const ValueKey('error'),
child: Text('$e', style: TextStyle(color: fs.error)),
),
data: (d) => _Body(key: const ValueKey('body'), detail: d),
),
),
);
}
}
/// Cold-visit body: header from the seed (if any) + N skeleton rows.
/// N comes from the seed's trackCount so the row count matches the
/// real list when it lands — no layout jump on swap. Without a seed
/// (deep link straight to a playlist with no prior cache) the
/// skeleton renders a small default and grows when real data arrives.
class _SkeletonBody extends StatelessWidget {
const _SkeletonBody({super.key, this.seed});
final Playlist? seed;
static const _defaultSkeletonCount = 8;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final count = seed?.trackCount ?? _defaultSkeletonCount;
return ListView.builder(
itemCount: count + 1, // +1 for header
itemBuilder: (ctx, i) {
if (i == 0) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (seed != null && seed!.description.isNotEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Text(
seed!.description,
style: TextStyle(color: fs.ash, fontSize: 13),
),
),
Text(
seed == null
? 'Loading…'
: '${seed!.trackCount} ${seed!.trackCount == 1 ? "track" : "tracks"}',
style: TextStyle(color: fs.ash, fontSize: 12),
),
],
),
);
}
return const _PlaylistTrackSkeleton();
},
);
}
}
/// Skeleton matched to _PlaylistTrackRow's layout (no cover image —
/// playlist rows are text-only). Two text-shaped placeholders for
/// title + secondary line, plus a duration block on the right.
class _PlaylistTrackSkeleton extends StatelessWidget {
const _PlaylistTrackSkeleton();
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Container(width: 200, height: 14, color: fs.slate),
const SizedBox(height: 6),
Container(width: 140, height: 12, color: fs.slate),
],
),
),
const SizedBox(width: 16),
Container(width: 32, height: 12, color: fs.slate),
],
),
);
}
}
class _Body extends ConsumerWidget {
const _Body({super.key, required this.detail});
final PlaylistDetail detail;
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final tracks = detail.tracks;
final playable = tracks.where((t) => t.isAvailable).toList();
return RefreshIndicator(
onRefresh: () async =>
ref.refresh(playlistDetailProvider(detail.playlist.id).future),
child: ListView.builder(
// Header + (track rows | empty hint).
itemCount: tracks.isEmpty ? 2 : tracks.length + 1,
itemBuilder: (ctx, i) {
if (i == 0) return _Header(detail: detail, playable: playable);
if (tracks.isEmpty) {
return Padding(
padding: const EdgeInsets.all(24),
child: Center(
child: Text(
'No tracks yet. Add some via the "Add to playlist…" entry on any track row.',
style: TextStyle(color: fs.ash),
textAlign: TextAlign.center,
),
),
);
}
final t = tracks[i - 1];
return _PlaylistTrackRow(
row: t,
onTap: t.isAvailable
? () {
final ref = ProviderScope.containerOf(ctx);
final liveTrack = _toTrackRef(t);
final playableRefs =
playable.map(_toTrackRef).toList(growable: false);
final startIdx = playable.indexWhere((p) => p.trackId == t.trackId);
ref.read(playerActionsProvider).playTracks(
playableRefs,
initialIndex: startIdx >= 0 ? startIdx : 0,
);
// Keep liveTrack referenced to avoid an unused-variable
// warning while we leave hooks for menu wiring later.
assert(liveTrack.id == t.trackId);
}
: null,
);
},
),
);
}
}
TrackRef _toTrackRef(PlaylistTrack t) => TrackRef(
id: t.trackId ?? '',
title: t.title,
albumId: t.albumId ?? '',
albumTitle: t.albumTitle,
artistId: t.artistId ?? '',
artistName: t.artistName,
durationSec: t.durationSec,
streamUrl: t.streamUrl ?? '',
);
class _Header extends ConsumerWidget {
const _Header({required this.detail, required this.playable});
final PlaylistDetail detail;
final List<PlaylistTrack> playable;
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final p = detail.playlist;
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
if (p.description.isNotEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Text(
p.description,
style: TextStyle(color: fs.ash, fontSize: 13),
),
),
Row(children: [
Text(
'${p.trackCount} ${p.trackCount == 1 ? "track" : "tracks"}',
style: TextStyle(color: fs.ash, fontSize: 12),
),
const Spacer(),
if (playable.isNotEmpty) ...[
OutlinedButton.icon(
key: const Key('download_playlist_button'),
onPressed: () {
final mgr = ref.read(audioCacheManagerProvider);
for (final t in playable) {
final id = t.trackId ?? '';
if (id.isEmpty) continue;
// Fire-and-forget; downloads happen in background.
// ignore: unawaited_futures
mgr.pin(id, source: CacheSource.autoPlaylist);
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Downloading ${playable.length} tracks…')),
);
},
icon: const Icon(Icons.download, size: 16),
label: const Text('Download'),
),
const SizedBox(width: 8),
FilledButton.icon(
onPressed: () {
final refs = playable.map(_toTrackRef).toList(growable: false);
ref.read(playerActionsProvider).playTracks(refs);
},
icon: const Icon(Icons.play_arrow),
label: const Text('Play'),
style: FilledButton.styleFrom(
backgroundColor: fs.accent,
foregroundColor: fs.parchment,
),
),
],
]),
]),
);
}
}
class _PlaylistTrackRow extends ConsumerWidget {
const _PlaylistTrackRow({required this.row, required this.onTap});
final PlaylistTrack row;
final VoidCallback? onTap;
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final mins = (row.durationSec ~/ 60).toString().padLeft(2, '0');
final secs = (row.durationSec % 60).toString().padLeft(2, '0');
// "Now playing" highlight — matches _QueueRow and TrackRow so the
// user sees which playlist row is current without reading the
// player bar. Unavailable rows never match.
final currentId = ref.watch(mediaItemProvider).value?.id;
final isCurrent = row.isAvailable &&
currentId != null &&
currentId == row.trackId;
final baseColor = row.isAvailable ? fs.parchment : fs.ash;
final titleColor = isCurrent ? fs.accent : baseColor;
return Container(
decoration: BoxDecoration(
color: isCurrent ? fs.iron : null,
border: isCurrent
? Border(left: BorderSide(color: fs.accent, width: 2))
: null,
),
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: Row(children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
row.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: titleColor,
fontSize: 14,
fontWeight:
isCurrent ? FontWeight.w500 : FontWeight.w400,
decoration: row.isAvailable
? null
: TextDecoration.lineThrough,
),
),
Text(
'${row.artistName} · ${row.albumTitle}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.ash, fontSize: 12),
),
],
),
),
Text('$mins:$secs', style: TextStyle(color: fs.ash, fontSize: 12)),
if (row.trackId != null)
TrackActionsButton(track: _toTrackRef(row)),
]),
),
),
);
}
}
@@ -0,0 +1,136 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../models/playlist.dart';
import '../shared/widgets/main_app_bar_actions.dart';
import '../shared/widgets/server_image.dart';
import '../theme/theme_extension.dart';
import 'playlists_provider.dart';
class PlaylistsListScreen extends ConsumerWidget {
const PlaylistsListScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
// "all" returns user-created + system mixes. Most useful default
// on mobile where the user wants to see for-you/discover alongside
// their own playlists in one tap.
final list = ref.watch(playlistsListProvider('all'));
return Scaffold(
backgroundColor: fs.obsidian,
appBar: AppBar(
backgroundColor: fs.obsidian,
elevation: 0,
title: Text('Playlists', style: TextStyle(color: fs.parchment)),
actions: const [MainAppBarActions(currentRoute: '/playlists')],
),
body: list.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => Center(
child: Text('$e', style: TextStyle(color: fs.error)),
),
data: (lists) {
final items = lists.all;
if (items.isEmpty) {
return Center(
child: Text(
'No playlists yet.',
style: TextStyle(color: fs.ash),
),
);
}
return RefreshIndicator(
onRefresh: () async => ref.refresh(playlistsListProvider('all').future),
child: ListView.separated(
itemCount: items.length,
separatorBuilder: (_, __) =>
Divider(height: 1, color: fs.iron),
itemBuilder: (ctx, i) {
final p = items[i];
return _PlaylistTile(
playlist: p,
onTap: () => ctx.push('/playlists/${p.id}', extra: p),
);
},
),
);
},
),
);
}
}
class _PlaylistTile extends StatelessWidget {
const _PlaylistTile({required this.playlist, required this.onTap});
final Playlist playlist;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Container(
width: 56,
height: 56,
color: fs.slate,
child: playlist.coverUrl.isEmpty
? Icon(Icons.queue_music, color: fs.ash)
: ServerImage(
url: playlist.coverUrl,
fit: BoxFit.cover,
fallback: Icon(Icons.queue_music, color: fs.ash),
),
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Flexible(
child: Text(
playlist.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 15),
),
),
if (playlist.isSystem) ...[
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: fs.iron,
borderRadius: BorderRadius.circular(4),
),
child: Text(
playlist.systemVariant!.replaceAll('_', ' '),
style: TextStyle(color: fs.accent, fontSize: 11),
),
),
],
]),
const SizedBox(height: 2),
Text(
'${playlist.trackCount} ${playlist.trackCount == 1 ? "track" : "tracks"}',
style: TextStyle(color: fs.ash, fontSize: 12),
),
],
),
),
Icon(Icons.chevron_right, color: fs.ash),
]),
),
);
}
}
@@ -0,0 +1,403 @@
import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:drift/drift.dart' as drift;
import 'package:flutter/foundation.dart' show debugPrint;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/endpoints/me.dart';
import '../api/endpoints/playlists.dart';
import '../auth/auth_provider.dart';
import '../cache/adapters.dart';
import '../cache/audio_cache_manager.dart' show appDbProvider;
import '../cache/cache_first.dart';
import '../cache/connectivity_provider.dart';
import '../cache/db.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/playlist.dart';
import '../models/system_playlists_status.dart';
final playlistsApiProvider = FutureProvider<PlaylistsApi>((ref) async {
return PlaylistsApi(await ref.watch(dioProvider.future));
});
/// Drift-first per #357 plan C. Returns cached playlists filtered to
/// match the `kind` family arg:
/// - 'user' → only user-created (systemVariant null), owned by current user
/// - 'system' → only system-generated (systemVariant non-null), owned
/// - 'all' → everything: own user playlists + own system + others' public
///
/// systemVariant column added in drift schema v2 (#357 follow-up); previous
/// behavior leaked system playlists into add-to-playlist sheet because we
/// couldn't filter locally.
final playlistsListProvider =
StreamProvider.family<PlaylistsList, String>((ref, kind) {
final db = ref.watch(appDbProvider);
final user = ref.watch(authControllerProvider).value;
return cacheFirst<CachedPlaylist, PlaylistsList>(
driftStream: db.select(db.cachedPlaylists).watch(),
fetchAndPopulate: () async {
final api = await ref.read(playlistsApiProvider.future);
final fresh = await api.list(kind: kind);
// Reconcile: BuildSystemPlaylists rotates system-playlist UUIDs
// every rebuild, so insertOrReplace alone leaves stale rows in
// drift. Tapping one of those stale tiles 404s. Delete every
// owned drift row whose id isn't in the fresh response, then
// upsert the fresh set.
final freshOwnedIds =
fresh.owned.map((p) => p.id).toSet();
await db.batch((b) {
if (user != null) {
b.deleteWhere(db.cachedPlaylists, (t) {
return t.userId.equals(user.id) &
t.id.isNotIn(freshOwnedIds);
});
}
for (final p in fresh.all) {
b.insert(db.cachedPlaylists, p.toDrift(),
mode: drift.InsertMode.insertOrReplace);
}
});
},
toResult: (rows) {
if (user == null) return PlaylistsList.empty();
final filtered = rows.where((r) {
if (kind == 'user') return r.systemVariant == null;
if (kind == 'system') return r.systemVariant != null;
return true; // 'all'
}).toList();
final owned = filtered
.where((r) => r.userId == user.id)
.map((r) => r.toRef())
.toList();
final pub = filtered
.where((r) => r.userId != user.id && r.isPublic)
.map((r) => r.toRef())
.toList();
return PlaylistsList(owned: owned, public: pub);
},
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
// Aggregate list — server may add system playlists (For-You /
// Discover) that the per-user delta sync doesn't always emit.
// Stale-while-revalidate ensures the home tile row reflects the
// current server state on every screen visit.
alwaysRefresh: true,
);
});
/// Composite shape (playlist + tracks). async* over the playlist watch
/// stream + a one-shot tracks fetch per emission.
final playlistDetailProvider =
StreamProvider.family<PlaylistDetail, String>((ref, id) async* {
final db = ref.watch(appDbProvider);
final user = ref.watch(authControllerProvider).value;
final playlistQuery = db.select(db.cachedPlaylists)
..where((t) => t.id.equals(id));
final tracksQuery = (db.select(db.cachedPlaylistTracks)
..where((t) => t.playlistId.equals(id))
..orderBy([(t) => drift.OrderingTerm.asc(t.position)]))
.join([
drift.leftOuterJoin(db.cachedTracks,
db.cachedTracks.id.equalsExp(db.cachedPlaylistTracks.trackId)),
drift.leftOuterJoin(db.cachedArtists,
db.cachedArtists.id.equalsExp(db.cachedTracks.artistId)),
drift.leftOuterJoin(db.cachedAlbums,
db.cachedAlbums.id.equalsExp(db.cachedTracks.albumId)),
]);
PlaylistDetail emptyDetail() => PlaylistDetail(
playlist: Playlist(
id: id,
userId: user?.id ?? '',
name: '',
description: '',
isPublic: false,
systemVariant: null,
trackCount: 0,
coverUrl: '',
ownerUsername: '',
createdAt: '',
updatedAt: '',
),
tracks: const [],
);
Future<bool> isOnline() async {
try {
return await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true);
} catch (_) {
return true;
}
}
Future<bool> fetchAndPopulate() async {
try {
final api = await ref.read(playlistsApiProvider.future);
final fresh = await api.get(id).timeout(const Duration(seconds: 10));
// Collect the track + artist + album rows referenced by these
// playlist entries. Without writing the cachedTracks rows
// themselves, the detail-screen JOIN against cachedTracks
// returns null on every row (only the playlist_tracks join
// succeeds), so the UI shows a list with empty titles and
// unplayable tracks.
final tracks = <String, _TrackRefRow>{};
final artists = <String, ArtistRefRow>{};
final albums = <String, AlbumRefRow>{};
for (final t in fresh.tracks) {
final tId = t.trackId;
if (tId != null && tId.isNotEmpty) {
tracks.putIfAbsent(
tId,
() => _TrackRefRow(
id: tId,
title: t.title,
albumId: t.albumId ?? '',
artistId: t.artistId ?? '',
durationSec: t.durationSec,
),
);
}
final aId = t.artistId;
final aName = t.artistName;
if (aId != null && aId.isNotEmpty && aName.isNotEmpty) {
artists.putIfAbsent(aId, () => ArtistRefRow(aId, aName));
}
final lbId = t.albumId;
final lbTitle = t.albumTitle;
if (lbId != null && lbId.isNotEmpty && lbTitle.isNotEmpty) {
albums.putIfAbsent(lbId, () => AlbumRefRow(lbId, lbTitle, aId ?? ''));
}
}
await db.batch((b) {
b.insert(db.cachedPlaylists, fresh.playlist.toDrift(),
mode: drift.InsertMode.insertOrReplace);
// Wipe + re-insert this playlist's track positions so deletions
// propagate. Without the wipe, removed tracks would linger in
// drift after the playlist mutated server-side.
b.deleteWhere(
db.cachedPlaylistTracks, (t) => t.playlistId.equals(id));
for (var i = 0; i < fresh.tracks.length; i++) {
final t = fresh.tracks[i];
if (t.trackId == null) continue;
b.insert(
db.cachedPlaylistTracks,
CachedPlaylistTracksCompanion.insert(
playlistId: id,
trackId: t.trackId!,
position: drift.Value(i),
),
mode: drift.InsertMode.insertOrReplace,
);
}
if (artists.isNotEmpty) {
b.insertAllOnConflictUpdate(
db.cachedArtists,
artists.values
.map((a) => CachedArtistsCompanion.insert(
id: a.id,
name: a.name,
sortName: a.name,
))
.toList(),
);
}
if (tracks.isNotEmpty) {
// Insert/update cachedTracks so the detail screen's JOIN
// produces real titles + durations. We don't have
// track_number / disc_number on the wire (PlaylistTrack
// omits them), so they default to 0 — UI doesn't surface
// them on this screen so it's fine.
b.insertAllOnConflictUpdate(
db.cachedTracks,
tracks.values
.map((t) => CachedTracksCompanion.insert(
id: t.id,
albumId: t.albumId,
artistId: t.artistId,
title: t.title,
durationMs: drift.Value(t.durationSec * 1000),
))
.toList(),
);
}
if (albums.isNotEmpty) {
b.insertAllOnConflictUpdate(
db.cachedAlbums,
albums.values
.map((a) => CachedAlbumsCompanion.insert(
id: a.id,
artistId: a.artistId,
title: a.title,
sortTitle: a.title,
))
.toList(),
);
}
});
return true;
} catch (e, st) {
// 404 = the playlist row in drift is stale (BuildSystemPlaylists
// rotates UUIDs on each rebuild, so old For-You / Songs-Like
// tiles can outlive the actual server-side playlist). Wipe the
// stale row + its track positions so the home tile disappears
// on next render and we don't keep trying.
if (e is DioException && e.response?.statusCode == 404) {
await db.batch((b) {
b.deleteWhere(
db.cachedPlaylistTracks, (t) => t.playlistId.equals(id));
b.deleteWhere(db.cachedPlaylists, (t) => t.id.equals(id));
});
return false;
}
debugPrint('playlistDetailProvider($id): fetch failed: $e\n$st');
return false;
}
}
// Once-per-subscription guard so an empty server response doesn't
// cause repeated re-fetches.
var fetchAttempted = false;
await for (final playlistRows in playlistQuery.watch()) {
if (playlistRows.isEmpty) {
if (fetchAttempted) {
yield emptyDetail();
continue;
}
fetchAttempted = true;
if (!await isOnline()) {
yield emptyDetail();
continue;
}
final ok = await fetchAndPopulate();
if (!ok) yield emptyDetail();
continue;
}
final playlist = playlistRows.first.toRef();
final trackRows = await tracksQuery.get();
// Same pattern as albumProvider: playlist row exists but no tracks
// (e.g., playlistsListProvider wrote the row, sync hasn't carried
// tracks for system playlists). Trigger the same fetch, drift
// watch re-emits with populated tracks.
if (trackRows.isEmpty && !fetchAttempted) {
fetchAttempted = true;
if (await isOnline()) {
final ok = await fetchAndPopulate();
if (ok) continue; // wait for watch re-emit
}
}
final tracks = trackRows.asMap().entries.map((e) {
final r = e.value;
final track = r.readTableOrNull(db.cachedTracks);
final artist = r.readTableOrNull(db.cachedArtists);
final album = r.readTableOrNull(db.cachedAlbums);
return PlaylistTrack(
position: e.key,
trackId: track?.id,
title: track?.title ?? '',
albumId: album?.id,
albumTitle: album?.title ?? '',
artistId: artist?.id,
artistName: artist?.name ?? '',
durationSec: track == null ? 0 : track.durationMs ~/ 1000,
streamUrl: null,
);
}).toList();
yield PlaylistDetail(playlist: playlist, tracks: tracks);
// No SWR refresh here. The aggregate playlistsListProvider does
// alwaysRefresh (system playlists rotate UUIDs), but per-detail
// refresh on every visit was multiplying with the prefetcher's
// parallel fetches and starving user-initiated playback. Pull-
// to-refresh on the detail page invalidates the provider, which
// is the right path for an explicit refresh.
}
});
/// Lightweight tuples used inside fetchAndPopulate to dedupe artist
/// and album rows referenced by playlist tracks before we batch-write
/// them to drift.
class ArtistRefRow {
ArtistRefRow(this.id, this.name);
final String id;
final String name;
}
class AlbumRefRow {
AlbumRefRow(this.id, this.title, this.artistId);
final String id;
final String title;
final String artistId;
}
class _TrackRefRow {
_TrackRefRow({
required this.id,
required this.title,
required this.albumId,
required this.artistId,
required this.durationSec,
});
final String id;
final String title;
final String albumId;
final String artistId;
final int durationSec;
}
/// Drift-first per #357 pattern. Reads from cached_system_playlists_
/// status (single-row JSON blob populated by /api/me/system-playlists-
/// status). Home Playlists row reads this every render to choose
/// between real cards and "building / pending / failed" placeholders
/// — drift-first means the row paints with the prior status instantly
/// rather than flickering through SystemPlaylistsStatus.empty() while
/// the REST round-trip resolves. SWR refresh on every visit keeps it
/// current.
final systemPlaylistsStatusProvider =
StreamProvider<SystemPlaylistsStatus>((ref) {
final db = ref.watch(appDbProvider);
return cacheFirst<CachedSystemPlaylistsStatusData, SystemPlaylistsStatus>(
driftStream: db.select(db.cachedSystemPlaylistsStatus).watch(),
fetchAndPopulate: () async {
final dio = await ref.read(dioProvider.future);
final fresh = await MeApi(dio).systemPlaylistsStatus();
await db.into(db.cachedSystemPlaylistsStatus).insertOnConflictUpdate(
CachedSystemPlaylistsStatusCompanion.insert(
json: jsonEncode({
'in_flight': fresh.inFlight,
'last_run_at': fresh.lastRunAt,
'last_error': fresh.lastError,
}),
updatedAt: drift.Value(DateTime.now()),
),
);
},
toResult: (rows) => rows.isEmpty
? SystemPlaylistsStatus.empty()
: SystemPlaylistsStatus.fromJson(
jsonDecode(rows.first.json) as Map<String, dynamic>),
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
alwaysRefresh: true,
tag: 'systemPlaylistsStatus',
);
});
@@ -0,0 +1,125 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../library/widgets/play_circle_button.dart';
import '../../models/playlist.dart';
import '../../models/track.dart';
import '../../player/player_provider.dart';
import '../../shared/widgets/server_image.dart';
import '../../theme/theme_extension.dart';
import '../playlists_provider.dart';
/// Mirrors the web PlaylistCard. ~176dp wide, square cover (~144dp),
/// name + optional system-variant badge below. Tap pushes
/// `/playlists/{id}`. The bottom-right play button fetches the
/// playlist and starts playback from track 0; disabled when the
/// playlist has no tracks.
class PlaylistCard extends ConsumerWidget {
const PlaylistCard({super.key, required this.playlist});
final Playlist playlist;
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final hasTracks = playlist.trackCount > 0;
return SizedBox(
width: 176,
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: () =>
context.push('/playlists/${playlist.id}', extra: playlist),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
// Stack: collage + overlaid play button at bottom-right.
Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Container(
width: 144,
height: 144,
color: fs.slate,
// coverUrl is deterministic per playlist (see
// CachedPlaylistAdapter.toRef). When the server's
// collage isn't built yet, ServerImage's
// errorBuilder shows the queue_music icon over the
// slate background.
child: playlist.coverUrl.isEmpty
? Icon(Icons.queue_music, color: fs.ash, size: 56)
: ServerImage(
url: playlist.coverUrl,
fit: BoxFit.cover,
fallback:
Icon(Icons.queue_music, color: fs.ash, size: 56),
),
),
),
Positioned(
bottom: 6,
right: 6,
child: PlayCircleButton(
enabled: hasTracks,
onPressed: () => _playPlaylist(ref),
),
),
],
),
const SizedBox(height: 8),
Text(
playlist.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14),
),
if (playlist.isSystem)
Padding(
padding: const EdgeInsets.only(top: 2),
child: Container(
padding:
const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: fs.iron,
borderRadius: BorderRadius.circular(4),
),
child: Text(
playlist.systemVariant!.replaceAll('_', ' '),
style: TextStyle(color: fs.accent, fontSize: 11),
),
),
),
]),
),
),
),
);
}
/// Fetches the playlist via /api/playlists/{id}, materializes each
/// PlaylistTrack into a TrackRef (filtering out unavailable rows
/// whose `trackId` is null after a track-delete), and plays from
/// index 0. Mirrors the web PlaylistCard's onPlayClick.
Future<void> _playPlaylist(WidgetRef ref) async {
final api = await ref.read(playlistsApiProvider.future);
final detail = await api.get(playlist.id);
final refs = <TrackRef>[];
for (final t in detail.tracks) {
if (t.trackId == null) continue;
refs.add(TrackRef(
id: t.trackId!,
title: t.title,
albumId: t.albumId ?? '',
albumTitle: t.albumTitle,
artistId: t.artistId ?? '',
artistName: t.artistName,
durationSec: t.durationSec,
streamUrl: t.streamUrl ?? '',
));
}
if (refs.isEmpty) return;
await ref.read(playerActionsProvider).playTracks(refs, initialIndex: 0);
}
}
@@ -0,0 +1,86 @@
import 'package:flutter/material.dart';
import '../../theme/theme_extension.dart';
/// Same dimensions as PlaylistCard so the home Playlists row keeps
/// visual rhythm whether real or placeholder. Mirrors the web
/// PlaylistPlaceholderCard. Variant decides the state copy below
/// the label.
class PlaylistPlaceholderCard extends StatelessWidget {
const PlaylistPlaceholderCard({
super.key,
required this.label,
required this.variant,
});
/// "For You" or "Songs like…" — what the slot is reserved for.
final String label;
/// One of: 'building' | 'failed' | 'pending' | 'seed-needed'.
final String variant;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return SizedBox(
width: 176,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Container(
width: 144,
height: 144,
decoration: BoxDecoration(
color: fs.iron,
borderRadius: BorderRadius.circular(6),
border: Border.all(color: fs.slate, width: 1),
),
child: Center(child: _stateIcon(fs)),
),
const SizedBox(height: 8),
Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14),
),
Padding(
padding: const EdgeInsets.only(top: 2),
child: Text(
_stateText(),
style: TextStyle(color: fs.ash, fontSize: 11),
),
),
]),
),
);
}
Widget _stateIcon(FabledSwordTheme fs) {
switch (variant) {
case 'building':
return SizedBox(
width: 28,
height: 28,
child: CircularProgressIndicator(strokeWidth: 2, color: fs.accent),
);
case 'failed':
return Icon(Icons.warning_amber, color: fs.error, size: 32);
default:
return Icon(Icons.queue_music, color: fs.ash, size: 40);
}
}
String _stateText() {
switch (variant) {
case 'building':
return 'Building…';
case 'failed':
return "Couldn't generate";
case 'seed-needed':
return 'Like more music';
default:
return 'Coming soon';
}
}
}
@@ -0,0 +1,184 @@
import 'dart:async';
import 'package:drift/drift.dart' as drift;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/endpoints/me.dart';
import '../api/endpoints/quarantine.dart';
import '../cache/audio_cache_manager.dart' show appDbProvider;
import '../cache/connectivity_provider.dart';
import '../cache/db.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/quarantine_mine.dart';
import '../models/track.dart';
final quarantineApiProvider = FutureProvider<QuarantineApi>((ref) async {
return QuarantineApi(await ref.watch(dioProvider.future));
});
/// Drift-first ("hidden") tab controller. Reads from cached_quarantine_
/// mine via a drift watch() subscription set up in build(), so any drift
/// mutation (incoming sync, optimistic flag/unflag, SSE-triggered
/// refresh) re-emits the list automatically.
///
/// API surface unchanged from the prior FutureProvider-backed controller
/// — call sites still do `ref.read(myQuarantineProvider.notifier).flag()`
/// / `.unflag()` / `.isHidden()`. Internal storage moved from in-memory
/// AsyncNotifier state to drift so the Hidden tab paints from disk on
/// cold open and the quarantine list is queryable offline.
class MyQuarantineController extends AsyncNotifier<List<QuarantineMineRow>> {
@override
Future<List<QuarantineMineRow>> build() async {
final db = ref.watch(appDbProvider);
// Subscribe to drift first so any mutation (incoming sync, flag/
// unflag, etc.) propagates without needing a manual invalidate.
// Disposed when the provider rebuilds or the listener detaches.
final sub = db.select(db.cachedQuarantineMine).watch().listen((rows) {
state = AsyncData(rows.map(_rowToModel).toList());
});
ref.onDispose(sub.cancel);
// SWR refresh on every build so the freshest server-side state
// overtakes drift in the background. Don't await — UI gets the
// cached snapshot first, freshness lands later via the watch().
unawaited(_refreshFromServer());
final initial = await db.select(db.cachedQuarantineMine).get();
return initial.map(_rowToModel).toList();
}
/// Hits /api/quarantine/mine and replaces the local table with the
/// authoritative server set. Best-effort: offline / 5xx / unresolved
/// dependencies (e.g. uninitialised serverUrl in tests) all collapse
/// to a no-op — drift stays on the prior cached state.
Future<void> _refreshFromServer() async {
try {
final online = await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true);
if (!online) return;
final dio = await ref.read(dioProvider.future);
final fresh = await MeApi(dio).quarantineMine();
final db = ref.read(appDbProvider);
await db.transaction(() async {
// Full replace — quarantine list is small and we want server
// unflags from other devices to take effect. Doing this in a
// transaction means the watch() sees exactly one emission with
// the merged state, not a delete-then-insert flicker.
await db.delete(db.cachedQuarantineMine).go();
for (final r in fresh) {
await db
.into(db.cachedQuarantineMine)
.insertOnConflictUpdate(_modelToCompanion(r));
}
});
} catch (_) {
// Swallow — cached state stays visible.
}
}
/// True when this track is in the caller's quarantine list.
bool isHidden(String trackId) =>
(state.value ?? const []).any((r) => r.trackId == trackId);
/// Optimistic flag: inserts the synthetic row into drift (watch fires
/// immediately so the UI updates), calls server, rolls back on error.
Future<void> flag(TrackRef track, String reason, String notes) async {
final db = ref.read(appDbProvider);
final existed = await (db.select(db.cachedQuarantineMine)
..where((t) => t.trackId.equals(track.id)))
.getSingleOrNull();
if (existed != null) return; // already hidden
final companion = CachedQuarantineMineCompanion.insert(
trackId: track.id,
reason: reason,
notes: notes.isEmpty
? const drift.Value.absent()
: drift.Value(notes),
createdAt: DateTime.now().toUtc().toIso8601String(),
trackTitle: track.title,
trackDurationMs: drift.Value(track.durationSec * 1000),
albumId: track.albumId,
albumTitle: track.albumTitle,
artistId: track.artistId,
artistName: track.artistName,
);
await db.into(db.cachedQuarantineMine).insertOnConflictUpdate(companion);
try {
final api = await ref.read(quarantineApiProvider.future);
await api.flag(track.id, reason, notes: notes);
} catch (e, st) {
// Rollback the optimistic insert; watch() re-emits the prior set.
await (db.delete(db.cachedQuarantineMine)
..where((t) => t.trackId.equals(track.id)))
.go();
Error.throwWithStackTrace(e, st);
}
}
/// Optimistic unflag: removes the drift row, calls server, restores
/// on error.
Future<void> unflag(String trackId) async {
final db = ref.read(appDbProvider);
final existing = await (db.select(db.cachedQuarantineMine)
..where((t) => t.trackId.equals(trackId)))
.getSingleOrNull();
if (existing == null) return;
await (db.delete(db.cachedQuarantineMine)
..where((t) => t.trackId.equals(trackId)))
.go();
try {
final api = await ref.read(quarantineApiProvider.future);
await api.unflag(trackId);
} catch (e, st) {
// Restore the row we just deleted — toCompanion(true) preserves
// every field including the original fetchedAt timestamp.
await db
.into(db.cachedQuarantineMine)
.insertOnConflictUpdate(existing.toCompanion(true));
Error.throwWithStackTrace(e, st);
}
}
static QuarantineMineRow _rowToModel(CachedQuarantineMineData r) =>
QuarantineMineRow(
trackId: r.trackId,
reason: r.reason,
notes: r.notes,
createdAt: r.createdAt,
trackTitle: r.trackTitle,
trackDurationMs: r.trackDurationMs,
albumId: r.albumId,
albumTitle: r.albumTitle,
albumCoverArtPath: r.albumCoverArtPath,
artistId: r.artistId,
artistName: r.artistName,
);
static CachedQuarantineMineCompanion _modelToCompanion(QuarantineMineRow r) =>
CachedQuarantineMineCompanion.insert(
trackId: r.trackId,
reason: r.reason,
notes: r.notes == null ? const drift.Value.absent() : drift.Value(r.notes),
createdAt: r.createdAt,
trackTitle: r.trackTitle,
trackDurationMs: drift.Value(r.trackDurationMs),
albumId: r.albumId,
albumTitle: r.albumTitle,
albumCoverArtPath: r.albumCoverArtPath == null
? const drift.Value.absent()
: drift.Value(r.albumCoverArtPath),
artistId: r.artistId,
artistName: r.artistName,
);
}
final myQuarantineProvider =
AsyncNotifierProvider<MyQuarantineController, List<QuarantineMineRow>>(
MyQuarantineController.new,
);
@@ -0,0 +1,61 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/endpoints/requests.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/admin_request.dart';
final requestsApiProvider = FutureProvider<RequestsApi>((ref) async {
return RequestsApi(await ref.watch(dioProvider.future));
});
/// Mirrors the web's createMyRequestsQuery auto-poll (#369): refresh
/// every 12s while any row is mid-ingest (status='approved'), stop when
/// all rows settle. Polls regardless of app foreground/background — a
/// future enhancement could pause via WidgetsBindingObserver, but for
/// v1 the small extra refresh is acceptable.
class MyRequestsController extends AsyncNotifier<List<AdminRequest>> {
static const Duration _pollInterval = Duration(seconds: 12);
Timer? _pollTimer;
@override
Future<List<AdminRequest>> build() async {
ref.onDispose(() {
_pollTimer?.cancel();
_pollTimer = null;
});
final api = await ref.watch(requestsApiProvider.future);
final rows = await api.listMine();
_maybeStartPolling(rows);
return rows;
}
void _maybeStartPolling(List<AdminRequest> rows) {
_pollTimer?.cancel();
if (rows.any((r) => r.status == 'approved')) {
_pollTimer = Timer.periodic(_pollInterval, (_) {
ref.invalidateSelf();
});
}
}
/// Optimistic remove + REST cancel. Restores the row on failure so
/// the user can retry — silent failure would lie about success.
Future<void> cancel(String id) async {
final api = await ref.read(requestsApiProvider.future);
final current = state.value ?? const <AdminRequest>[];
state = AsyncData(current.where((r) => r.id != id).toList());
try {
await api.cancel(id);
} catch (e, st) {
state = AsyncData(current);
Error.throwWithStackTrace(e, st);
}
}
}
final myRequestsProvider =
AsyncNotifierProvider<MyRequestsController, List<AdminRequest>>(
MyRequestsController.new);
@@ -0,0 +1,252 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../models/admin_request.dart';
import '../shared/live_events_provider.dart';
import '../shared/widgets/main_app_bar_actions.dart';
import '../theme/theme_extension.dart';
import 'requests_provider.dart';
class RequestsScreen extends ConsumerWidget {
const RequestsScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
// #402 wire-up: refresh the user's own requests list on
// request.status_changed. Server-side events are user-scoped
// (admin actions on someone else's request route to that other
// user's stream); the dispatcher's filter already drops mismatches.
ref.listen<AsyncValue<LiveEvent>>(liveEventsProvider, (_, next) {
final e = next.asData?.value;
if (e?.kind == 'request.status_changed') {
ref.invalidate(myRequestsProvider);
}
});
final requests = ref.watch(myRequestsProvider);
return Scaffold(
backgroundColor: fs.obsidian,
appBar: AppBar(
backgroundColor: fs.obsidian,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: fs.parchment),
onPressed: () => context.pop(),
),
title: Text('Your requests', style: TextStyle(color: fs.parchment)),
actions: const [MainAppBarActions(currentRoute: '/requests')],
),
body: SafeArea(
child: requests.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text('$e', style: TextStyle(color: fs.error)),
),
),
data: (rows) {
if (rows.isEmpty) {
return Center(
child: Text('Nothing requested yet.',
style: TextStyle(color: fs.ash)),
);
}
final notifier = ref.read(myRequestsProvider.notifier);
return RefreshIndicator(
onRefresh: () async => ref.refresh(myRequestsProvider.future),
child: ListView.separated(
itemCount: rows.length,
padding: const EdgeInsets.symmetric(vertical: 8),
separatorBuilder: (_, __) => Divider(color: fs.iron, height: 1),
itemBuilder: (_, i) => _RequestRow(
key: Key('request_row_${rows[i].id}'),
request: rows[i],
onCancel: () => notifier.cancel(rows[i].id),
),
),
);
},
),
),
);
}
}
class _RequestRow extends StatelessWidget {
const _RequestRow({
super.key,
required this.request,
required this.onCancel,
});
final AdminRequest request;
final VoidCallback onCancel;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final href = _listenHref(request);
return ListTile(
leading: _kindAvatar(fs),
title: Text(
request.displayName,
style: TextStyle(
color: fs.parchment,
fontFamily: 'Fraunces',
fontSize: 16,
),
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 4),
Row(
children: [
_KindPill(label: request.kind),
const SizedBox(width: 6),
_StatusPill(status: request.status),
],
),
if (request.importedAlbumCount > 0 ||
request.importedTrackCount > 0) ...[
const SizedBox(height: 4),
Text(
_ingestProgressText(request),
style: TextStyle(color: fs.accent, fontSize: 13),
),
],
if (request.status == 'rejected' && (request.notes ?? '').isNotEmpty) ...[
const SizedBox(height: 4),
Text(request.notes!, style: TextStyle(color: fs.ash, fontSize: 13)),
],
],
),
trailing: _trailing(context, fs, href),
);
}
Widget _kindAvatar(FabledSwordTheme fs) {
final icon = switch (request.kind) {
'artist' => Icons.album,
'album' => Icons.library_music,
_ => Icons.music_note,
};
return CircleAvatar(
backgroundColor: fs.iron,
child: Icon(icon, size: 20, color: fs.ash),
);
}
Widget? _trailing(BuildContext context, FabledSwordTheme fs, String? href) {
if (request.status == 'pending') {
return TextButton.icon(
onPressed: () async {
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Cancel request?'),
content: Text('Cancel "${request.displayName}"?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text('Keep'),
),
TextButton(
onPressed: () => Navigator.pop(ctx, true),
style: TextButton.styleFrom(foregroundColor: fs.oxblood),
child: const Text('Cancel request'),
),
],
),
);
if (ok == true) onCancel();
},
icon: const Icon(Icons.close, size: 16),
label: const Text('Cancel'),
style: TextButton.styleFrom(foregroundColor: fs.ash),
);
}
if (request.status == 'completed' && href != null) {
return TextButton.icon(
onPressed: () => context.push(href),
icon: const Icon(Icons.play_arrow, size: 16),
label: const Text('Listen'),
style: TextButton.styleFrom(foregroundColor: fs.accent),
);
}
return null;
}
String _ingestProgressText(AdminRequest r) {
if (r.kind == 'artist') {
final albums = '${r.importedAlbumCount} '
'${r.importedAlbumCount == 1 ? 'album' : 'albums'}';
final tracks = '${r.importedTrackCount} '
'${r.importedTrackCount == 1 ? 'track' : 'tracks'} ingested';
return '$albums · $tracks';
}
if (r.kind == 'album') {
return '${r.importedTrackCount} '
'${r.importedTrackCount == 1 ? 'track' : 'tracks'} ingested';
}
return 'Track ingested';
}
String? _listenHref(AdminRequest r) {
if (r.matchedTrackId != null) return '/albums/${r.matchedAlbumId ?? r.matchedTrackId}';
if (r.matchedAlbumId != null) return '/albums/${r.matchedAlbumId}';
if (r.matchedArtistId != null) return '/artists/${r.matchedArtistId}';
return null;
}
}
class _KindPill extends StatelessWidget {
const _KindPill({required this.label});
final String label;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: fs.accent.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(999),
),
child: Text(
label,
style: TextStyle(color: fs.accent, fontSize: 11),
),
);
}
}
class _StatusPill extends StatelessWidget {
const _StatusPill({required this.status});
final String status;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final color = switch (status) {
'pending' => fs.ash,
'approved' => fs.bronze,
'completed' => fs.moss,
'rejected' => fs.oxblood,
'failed' => fs.oxblood,
_ => fs.ash,
};
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(999),
),
child: Text(
status,
style: TextStyle(color: color, fontSize: 11),
),
);
}
}
@@ -0,0 +1,37 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/endpoints/search.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/search_response.dart';
final searchApiProvider = FutureProvider<SearchApi>((ref) async {
return SearchApi(await ref.watch(dioProvider.future));
});
/// Current search query text. The screen's TextField writes here on
/// every keystroke; the resultsProvider below debounces.
class SearchQueryNotifier extends Notifier<String> {
@override
String build() => '';
void set(String q) => state = q;
}
final searchQueryProvider =
NotifierProvider<SearchQueryNotifier, String>(SearchQueryNotifier.new);
/// Debounced search results. Returns null for empty queries so the
/// screen can show a neutral empty state instead of "0 results."
///
/// Debounce: 250ms. After the wait, re-reads the live query — if the
/// user has typed more in that window, this attempt is silently
/// abandoned (returns null) and a newer attempt fires on the next
/// rebuild. No request hits the server while the user is mid-typing.
final searchResultsProvider = FutureProvider<SearchResponse?>((ref) async {
final q = ref.watch(searchQueryProvider).trim();
if (q.isEmpty) return null;
await Future<void>.delayed(const Duration(milliseconds: 250));
// Re-read the (possibly newer) query; if the user typed more, bail.
if (ref.read(searchQueryProvider).trim() != q) return null;
final api = await ref.watch(searchApiProvider.future);
return api.search(q);
});

Some files were not shown because too many files have changed in this diff Show More