Compare commits

...

62 Commits

Author SHA1 Message Date
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
49 changed files with 3243 additions and 722 deletions
+42 -6
View File
@@ -72,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/')
@@ -87,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
@@ -102,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"
+9 -4
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,7 +62,7 @@ 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
@@ -72,14 +74,14 @@ jobs:
if: steps.guard.outputs.ready == 'true' && 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}"
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 ${RELEASE_TOKEN}" \
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
@@ -93,4 +95,7 @@ jobs:
- 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 }} .
+7 -1
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 \
+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")
}
}
}
}
@@ -12,9 +12,16 @@ class LibraryListsApi {
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/library/artists',
queryParameters: {'limit': limit, 'offset': offset},
'/api/artists',
queryParameters: {
'limit': limit,
'offset': offset,
'sort': 'alpha',
},
);
return Paged.fromJson(r.data ?? const {}, ArtistRef.fromJson);
}
@@ -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);
}
}
+6
View File
@@ -1,6 +1,7 @@
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/routing.dart';
@@ -27,6 +28,11 @@ class _MinstrelAppState extends ConsumerState<MinstrelApp> {
// 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);
});
}
+13 -1
View File
@@ -34,12 +34,18 @@ extension ArtistRefDriftWrite on ArtistRef {
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',
);
}
@@ -82,6 +88,12 @@ extension TrackRefDriftWrite on TrackRef {
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,
@@ -90,7 +102,7 @@ extension CachedPlaylistAdapter on CachedPlaylist {
isPublic: isPublic,
systemVariant: systemVariant,
trackCount: trackCount,
coverUrl: '', // server-derived; cache doesn't persist
coverUrl: '/api/playlists/$id/cover',
ownerUsername: ownerUsername,
createdAt: '',
updatedAt: '',
+39 -6
View File
@@ -83,6 +83,27 @@ class AudioCacheManager {
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)
@@ -96,13 +117,25 @@ class AudioCacheManager {
.go();
}
/// Total bytes used by the cache.
/// 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 result = await _db.customSelect(
'SELECT COALESCE(SUM(size_bytes), 0) AS total FROM audio_cache_index',
readsFrom: {_db.audioCacheIndex},
).getSingle();
return result.read<int>('total');
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:
+42 -1
View File
@@ -5,12 +5,20 @@
// - 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;
/// 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>`)
@@ -28,22 +36,55 @@ Stream<T> cacheFirst<D, T>({
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;
void log(String msg) {
if (tag != null) debugPrint('cacheFirst[$tag]: $msg');
}
await for (final rows in driftStream) {
if (rows.isNotEmpty) {
log('drift hit (${rows.length} rows)');
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;
}
log('drift miss; checking connectivity');
if (await isOnline()) {
log('online; calling fetchAndPopulate');
try {
await fetchAndPopulate();
log('fetchAndPopulate done; awaiting drift re-emit');
// The drift watch() stream re-emits with the populated rows on
// the next loop iteration. Don't yield here.
} catch (_) {
} catch (e, st) {
log('fetchAndPopulate failed: $e\n$st');
yield toResult(rows); // empty result; caller surfaces error
}
} else {
log('offline; yielding empty');
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.
}
}
+26 -4
View File
@@ -5,9 +5,31 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
/// 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".
final connectivityProvider = StreamProvider<bool>((ref) {
///
/// 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();
return c.onConnectivityChanged.map(
(results) => results.any((r) => r != ConnectivityResult.none),
);
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);
});
+76
View File
@@ -0,0 +1,76 @@
import 'package:flutter/foundation.dart' show debugPrint;
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));
}
if (n > 0) debugPrint('metadataPrefetcher: warming $n artists');
}
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);
});
@@ -2,32 +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,
@@ -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,33 @@ 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);
debugPrint(
'artist_detail: play tapped — ${tracks.length} tracks for $id');
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 +132,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),
);
}
}
+111 -27
View File
@@ -12,7 +12,6 @@ import '../models/track.dart';
import '../playlists/playlists_provider.dart';
import '../playlists/widgets/playlist_card.dart';
import '../playlists/widgets/playlist_placeholder_card.dart';
import '../shared/delayed_loading.dart';
import '../shared/widgets/connection_error_banner.dart';
import '../shared/widgets/main_app_bar_actions.dart';
import '../theme/theme_extension.dart';
@@ -50,28 +49,33 @@ class HomeScreen extends ConsumerWidget {
}
return Center(child: Text('$e', style: TextStyle(color: fs.error)));
},
loading: () => const DelayedLoading(
isLoading: true,
whenReady: SizedBox.shrink(),
whileDelayed:
Center(child: CircularProgressIndicator()),
),
loading: () => _HomeSkeleton(fs: fs),
data: (h) => RefreshIndicator(
onRefresh: () async => ref.refresh(homeProvider.future),
child: ListView(children: [
_PlaylistsSection(
playlists: allPlaylists.value?.owned ?? const [],
status: status.value ?? SystemPlaylistsStatus.empty(),
),
_RecentlyAddedSection(albums: h.recentlyAddedAlbums),
_RediscoverSection(
albums: h.rediscoverAlbums,
artists: h.rediscoverArtists,
),
_MostPlayedSection(tracks: h.mostPlayedTracks),
_LastPlayedSection(artists: h.lastPlayedArtists),
const SizedBox(height: 96),
]),
child: ListView(
// ClampingScrollPhysics: no bounce overscroll past the
// content. Combined with the bottom padding below, this
// makes "scroll to end" land the last item just above the
// player bar — no empty void.
physics: const ClampingScrollPhysics(),
children: [
_PlaylistsSection(
playlists: allPlaylists.value?.owned ?? const [],
status: status.value ?? SystemPlaylistsStatus.empty(),
),
_RecentlyAddedSection(albums: h.recentlyAddedAlbums),
_RediscoverSection(
albums: h.rediscoverAlbums,
artists: h.rediscoverArtists,
),
_MostPlayedSection(tracks: h.mostPlayedTracks),
_LastPlayedSection(artists: h.lastPlayedArtists),
// Bottom padding ≈ player bar height (top row 80 + seek
// 30 + padding 16 ≈ ~140) so the last section's bottom
// edge lands right above the player when scrolled.
const SizedBox(height: 140),
],
),
),
),
),
@@ -180,7 +184,7 @@ class _RecentlyAddedSection extends StatelessWidget {
.map((a) => AlbumCard(
album: a,
onTap: () =>
_push(context, '/albums/${a.id}'),
context.push('/albums/${a.id}', extra: a),
))
.toList(),
),
@@ -210,7 +214,7 @@ class _RediscoverSection extends StatelessWidget {
.map((a) => AlbumCard(
album: a,
onTap: () =>
_push(context, '/albums/${a.id}'),
context.push('/albums/${a.id}', extra: a),
))
.toList(),
),
@@ -222,7 +226,7 @@ class _RediscoverSection extends StatelessWidget {
.map((ar) => ArtistCard(
artist: ar,
onTap: () =>
_push(context, '/artists/${ar.id}'),
context.push('/artists/${ar.id}', extra: ar),
))
.toList(),
),
@@ -281,7 +285,8 @@ class _LastPlayedSection extends StatelessWidget {
children: artists
.map((ar) => ArtistCard(
artist: ar,
onTap: () => _push(context, '/artists/${ar.id}'),
onTap: () =>
context.push('/artists/${ar.id}', extra: ar),
))
.toList(),
);
@@ -314,8 +319,87 @@ class _EmptySection extends StatelessWidget {
}
}
void _push(BuildContext context, String path) {
context.push(path);
/// Cold-start skeleton. Renders the same shape as the real home (a few
/// section titles + card-sized placeholders) so the page feels alive
/// while /api/home is in flight, instead of a 30-second blank spinner.
/// Each section drops in independently as data arrives via the
/// individual providers.
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: (_, __) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: coverSize,
height: coverSize,
decoration: BoxDecoration(
color: fs.slate,
borderRadius: BorderRadius.circular(6),
),
),
const SizedBox(height: 8),
Container(width: coverSize * 0.7, height: 12, color: fs.slate),
const SizedBox(height: 4),
Container(width: coverSize * 0.4, height: 10, color: fs.iron),
],
),
),
),
),
]);
}
}
List<List<T>> _chunk<T>(List<T> items, int size) {
+136 -24
View File
@@ -1,5 +1,8 @@
import 'dart:async';
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';
@@ -60,8 +63,14 @@ final artistProvider =
toResult: (rows) => rows.isEmpty
? const ArtistRef(id: '', name: '')
: rows.first.toRef(),
isOnline: () async =>
(await ref.read(connectivityProvider.future)),
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)',
);
});
@@ -89,8 +98,10 @@ final artistAlbumsProvider =
final artist = r.readTableOrNull(db.cachedArtists);
return album.toRef(artistName: artist?.name ?? '');
}).toList(),
isOnline: () async =>
(await ref.read(connectivityProvider.future)),
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
tag: 'artistAlbums($artistId)',
);
});
@@ -123,8 +134,10 @@ final artistTracksProvider =
albumTitle: album?.title ?? '',
);
}).toList(),
isOnline: () async =>
(await ref.read(connectivityProvider.future)),
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
tag: 'artistTracks($artistId)',
);
});
@@ -152,33 +165,107 @@ final albumProvider = StreamProvider.family<
db.cachedArtists.id.equalsExp(db.cachedTracks.artistId)),
]);
await for (final albumRows in albumQuery.watch()) {
if (albumRows.isEmpty) {
// Cold cache fallback
if (await ref.read(connectivityProvider.future)) {
try {
final api = await ref.read(libraryApiProvider.future);
final fresh = await api.getAlbum(albumId);
await db.batch((b) {
b.insertAllOnConflictUpdate(db.cachedAlbums, [fresh.album.toDrift()]);
b.insertAllOnConflictUpdate(db.cachedTracks,
fresh.tracks.map((t) => t.toDrift()).toList());
});
// watch() re-emits with the populated rows; loop continues.
} catch (_) {
yield (
album: const AlbumRef(id: '', title: '', artistId: ''),
tracks: const <TrackRef>[],
// 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);
debugPrint('albumProvider($albumId): calling getAlbum');
final fresh = await api
.getAlbum(albumId)
.timeout(const Duration(seconds: 10));
debugPrint('albumProvider($albumId): got ${fresh.tracks.length} tracks, writing to drift');
// 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,
);
}
} else {
}
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());
});
debugPrint('albumProvider($albumId): drift write done; awaiting watch re-emit');
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) {
debugPrint('albumProvider($albumId): drift miss, attempting cold-cache fetch');
if (fetchAttempted) {
// Already tried and got nothing back.
yield (
album: const AlbumRef(id: '', title: '', artistId: ''),
tracks: const <TrackRef>[],
);
continue;
}
fetchAttempted = true;
final online = await isOnline();
debugPrint('albumProvider($albumId): online=$online');
if (!online) {
debugPrint('albumProvider($albumId): offline, yielding empty');
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;
}
debugPrint('albumProvider($albumId): drift hit (${albumRows.length} rows)');
final albumRow = albumRows.first;
final album = albumRow.readTable(db.cachedAlbums).toRef(
@@ -186,6 +273,23 @@ final albumProvider = StreamProvider.family<
);
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) {
debugPrint('albumProvider($albumId): album hit but no tracks; fetching');
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);
@@ -195,6 +299,14 @@ final albumProvider = StreamProvider.family<
);
}).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);
}
});
+200 -46
View File
@@ -5,6 +5,7 @@ import 'package:go_router/go_router.dart';
import '../api/endpoints/library_lists.dart';
import '../api/endpoints/likes.dart';
import '../api/endpoints/me.dart';
import '../cache/metadata_prefetcher.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/album.dart';
import '../models/artist.dart';
@@ -37,13 +38,89 @@ final _meApiProvider = FutureProvider<MeApi>((ref) async {
return MeApi(await ref.watch(dioProvider.future));
});
final _libraryArtistsProvider = FutureProvider<wire.Paged<ArtistRef>>((ref) async {
return (await ref.watch(_libraryListsApiProvider.future)).listArtists();
});
/// Paginated artist list. AsyncNotifier so the screen can call
/// `loadMore()` when the scroll approaches the bottom; subsequent
/// pages append to the existing items rather than replacing them.
class _LibraryArtistsNotifier extends AsyncNotifier<wire.Paged<ArtistRef>> {
static const _pageSize = 50;
bool _loadingMore = false;
final _libraryAlbumsProvider = FutureProvider<wire.Paged<AlbumRef>>((ref) async {
return (await ref.watch(_libraryListsApiProvider.future)).listAlbums();
});
@override
Future<wire.Paged<ArtistRef>> build() async {
final api = await ref.watch(_libraryListsApiProvider.future);
return api.listArtists(limit: _pageSize, offset: 0);
}
Future<void> loadMore() async {
if (_loadingMore) return;
final cur = state.value;
if (cur == null) return;
if (cur.items.length >= cur.total) return;
_loadingMore = true;
try {
final api = await ref.read(_libraryListsApiProvider.future);
final next = await api.listArtists(
limit: _pageSize,
offset: cur.items.length,
);
state = AsyncData(wire.Paged(
items: [...cur.items, ...next.items],
total: next.total,
limit: next.limit,
offset: 0,
));
} catch (_) {
// Swallow — the next near-bottom event will retry. The current
// partial list stays visible.
} finally {
_loadingMore = false;
}
}
}
final _libraryArtistsProvider = AsyncNotifierProvider<
_LibraryArtistsNotifier,
wire.Paged<ArtistRef>>(_LibraryArtistsNotifier.new);
class _LibraryAlbumsNotifier extends AsyncNotifier<wire.Paged<AlbumRef>> {
static const _pageSize = 50;
bool _loadingMore = false;
@override
Future<wire.Paged<AlbumRef>> build() async {
final api = await ref.watch(_libraryListsApiProvider.future);
return api.listAlbums(limit: _pageSize, offset: 0);
}
Future<void> loadMore() async {
if (_loadingMore) return;
final cur = state.value;
if (cur == null) return;
if (cur.items.length >= cur.total) return;
_loadingMore = true;
try {
final api = await ref.read(_libraryListsApiProvider.future);
final next = await api.listAlbums(
limit: _pageSize,
offset: cur.items.length,
);
state = AsyncData(wire.Paged(
items: [...cur.items, ...next.items],
total: next.total,
limit: next.limit,
offset: 0,
));
} catch (_) {
// Swallow — next scroll event will retry.
} finally {
_loadingMore = false;
}
}
}
final _libraryAlbumsProvider = AsyncNotifierProvider<
_LibraryAlbumsNotifier,
wire.Paged<AlbumRef>>(_LibraryAlbumsNotifier.new);
final _historyProvider = FutureProvider<HistoryPage>((ref) async {
return (await ref.watch(_meApiProvider.future)).history();
@@ -131,25 +208,53 @@ class _ArtistsTab extends ConsumerWidget {
return ref.watch(_libraryArtistsProvider).when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => Center(child: Text('$e', style: TextStyle(color: fs.error))),
data: (page) => page.items.isEmpty
data: (page) {
// Warm details for the first screenful so taps are instant.
ref
.read(metadataPrefetcherProvider)
.warmArtists(page.items.map((a) => a.id));
return page.items.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),
child: GridView.builder(
padding: const EdgeInsets.all(8),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
childAspectRatio: 0.78,
),
itemCount: page.items.length,
itemBuilder: (ctx, i) => ArtistCard(
artist: page.items[i],
onTap: () => ctx.push('/artists/${page.items[i].id}'),
onRefresh: () async {
ref.invalidate(_libraryArtistsProvider);
await ref.read(_libraryArtistsProvider.future);
},
// Listen for scroll-near-bottom and ask the notifier
// to fetch the next page. 800px lookahead so the next
// page lands before the user reaches the visible end.
child: NotificationListener<ScrollNotification>(
onNotification: (n) {
if (n.metrics.pixels >=
n.metrics.maxScrollExtent - 800) {
ref
.read(_libraryArtistsProvider.notifier)
.loadMore();
}
return false;
},
child: GridView.builder(
padding: const EdgeInsets.all(8),
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
childAspectRatio: 0.78,
),
itemCount: page.items.length,
itemBuilder: (ctx, i) {
final artist = page.items[i];
return ArtistCard(
artist: artist,
onTap: () => ctx.push('/artists/${artist.id}',
extra: artist),
);
},
),
),
),
);
},
);
}
}
@@ -163,25 +268,66 @@ class _AlbumsTab extends ConsumerWidget {
return ref.watch(_libraryAlbumsProvider).when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => Center(child: Text('$e', style: TextStyle(color: fs.error))),
data: (page) => page.items.isEmpty
data: (page) {
return page.items.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),
child: GridView.builder(
padding: const EdgeInsets.all(8),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
childAspectRatio: 0.78,
),
itemCount: page.items.length,
itemBuilder: (ctx, i) => AlbumCard(
album: page.items[i],
onTap: () => ctx.push('/albums/${page.items[i].id}'),
),
),
),
onRefresh: () async {
ref.invalidate(_libraryAlbumsProvider);
await ref.read(_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.
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 NotificationListener<ScrollNotification>(
onNotification: (n) {
if (n.metrics.pixels >=
n.metrics.maxScrollExtent - 800) {
ref
.read(_libraryAlbumsProvider.notifier)
.loadMore();
}
return false;
},
child: GridView.builder(
padding: const EdgeInsets.all(sidePad),
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: cols,
mainAxisExtent: cellH,
mainAxisSpacing: gap,
crossAxisSpacing: gap,
),
itemCount: page.items.length,
itemBuilder: (ctx, i) {
final album = page.items[i];
return AlbumCard(
album: album,
width: cellW,
titleMaxLines: 2,
onTap: () => ctx.push('/albums/${album.id}',
extra: album),
);
},
),
);
}),
);
},
);
}
}
@@ -260,10 +406,14 @@ class _LikedTab extends ConsumerWidget {
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 8),
itemCount: ar.items.length,
itemBuilder: (ctx, i) => ArtistCard(
artist: ar.items[i],
onTap: () => ctx.push('/artists/${ar.items[i].id}'),
),
itemBuilder: (ctx, i) {
final artist = ar.items[i];
return ArtistCard(
artist: artist,
onTap: () =>
ctx.push('/artists/${artist.id}', extra: artist),
);
},
),
),
],
@@ -275,10 +425,14 @@ class _LikedTab extends ConsumerWidget {
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 8),
itemCount: al.items.length,
itemBuilder: (ctx, i) => AlbumCard(
album: al.items[i],
onTap: () => ctx.push('/albums/${al.items[i].id}'),
),
itemBuilder: (ctx, i) {
final album = al.items[i];
return AlbumCard(
album: album,
onTap: () =>
ctx.push('/albums/${album.id}', extra: album),
);
},
),
),
],
@@ -6,45 +6,76 @@ import '../../shared/widgets/server_image.dart';
import '../../theme/theme_extension.dart';
class AlbumCard extends StatelessWidget {
const AlbumCard({required this.album, required this.onTap, super.key});
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) {
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)
: ServerImage(url: 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: [
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),
),
),
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),
),
]),
),
),
),
);
@@ -13,31 +13,35 @@ class ArtistCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
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)
: ServerImage(url: artist.coverUrl, fit: BoxFit.cover),
return SizedBox(
width: 140,
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
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)
: ServerImage(url: artist.coverUrl, fit: BoxFit.cover),
),
),
),
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),
),
]),
),
),
),
);
@@ -30,31 +30,39 @@ class TrackRow extends StatelessWidget {
return InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
child: Row(children: [
if (track.trackNumber != null)
SizedBox(
width: 28,
width: 22,
child: Text(
track.trackNumber.toString(),
style: TextStyle(color: fs.ash, fontSize: 13),
),
),
Expanded(
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(
track.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14),
),
Text(
track.artistName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.ash, fontSize: 12),
),
]),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
track.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: fs.parchment, fontSize: 14),
),
// 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),
),
],
),
),
CachedIndicator(trackId: track.id),
Text('$mins:$secs', style: TextStyle(color: fs.ash, fontSize: 12)),
+171 -16
View File
@@ -12,8 +12,36 @@ 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()));
// Diagnostic: log every player-state transition so silent stops
// surface as something we can read in the log.
_player.playerStateStream.listen((s) {
debugPrint(
'audio_handler: state playing=${s.playing} processing=${s.processingState}');
});
_player.processingStateStream.listen((ps) {
debugPrint('audio_handler: processingState=$ps');
});
}
final AudioPlayer _player = AudioPlayer();
@@ -22,6 +50,29 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
AlbumCoverCache? _coverCache;
AudioCacheManager? _audioCacheManager;
/// 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;
/// 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,
@@ -47,12 +98,18 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
debugPrint('audio_handler.setQueueFromTracks: '
'_baseUrl="$_baseUrl" trackCount=${tracks.length}');
final sw = Stopwatch()..start();
final sources = await Future.wait(tracks.map(_buildAudioSource));
debugPrint('audio_handler: built ${sources.length} sources in '
'${sw.elapsedMilliseconds}ms');
sw.reset();
sw.start();
await _player.setAudioSources(
sources,
initialIndex: initialIndex,
);
debugPrint('audio_handler: setAudioSources ${sw.elapsedMilliseconds}ms');
// Kick the cover fetch for the initial item — async, doesn't block
// playback. Subsequent track changes are handled by the
@@ -110,8 +167,8 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
// pin / Download buttons cover the index path; LockCaching handles
// the network optimization.
if (mgr != null) {
final cacheDir = await getApplicationCacheDirectory();
final cacheFile = File('${cacheDir.path}/audio_cache/${t.id}.mp3');
_cacheDirPath ??= (await getApplicationCacheDirectory()).path;
final cacheFile = File('${_cacheDirPath!}/audio_cache/${t.id}.mp3');
debugPrint('audio_handler: cache miss for track.id=${t.id}, '
'using LockCachingAudioSource → ${cacheFile.path}');
// ignore: experimental_member_use
@@ -148,19 +205,69 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
queue.add([...queue.value, item]);
}
MediaItem _toMediaItem(TrackRef t) => MediaItem(
id: t.id,
title: t.title,
artist: t.artistName,
album: t.albumTitle,
duration: Duration(seconds: t.durationSec),
// Stash album_id in extras so _loadArtForCurrentItem can pull it
// back without re-walking the track list.
extras: t.albumId.isEmpty ? null : {'album_id': t.albumId},
);
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,
);
}
/// 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);
debugPrint(
'audio_handler: registered stream cache for $trackId ($size bytes)');
}
void _onCurrentIndexChanged(int? idx) {
if (idx == null) 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());
}
@@ -198,7 +305,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: [
@@ -206,7 +340,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,
@@ -218,7 +365,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,
},
));
}
}
+374 -76
View File
@@ -1,17 +1,59 @@
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 'player_provider.dart';
class NowPlayingScreen extends ConsumerWidget {
/// 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) {
ConsumerState<NowPlayingScreen> createState() => _NowPlayingScreenState();
}
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;
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>()!;
final media = ref.watch(mediaItemProvider).value;
final playback = ref.watch(playbackStateProvider).value;
@@ -20,87 +62,343 @@ class NowPlayingScreen extends ConsumerWidget {
return const Scaffold(body: Center(child: Text('Nothing playing.')));
}
final pos = playback?.updatePosition ?? 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 = media.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 = (media.extras?['album_id'] as String?) ?? '';
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(),
),
actions: [
IconButton(
icon: Icon(Icons.queue_music, color: fs.parchment),
tooltip: 'Queue',
onPressed: () => GoRouter.of(context).push('/queue'),
// 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: SafeArea(
child: Column(
children: [
_TopBar(fs: fs),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(
children: [
const Spacer(),
_AlbumArt(media: media, albumId: albumId, fs: fs),
const SizedBox(height: 28),
_TitleRow(media: media, fs: fs),
const SizedBox(height: 4),
Text(
media.artist ?? '',
style: TextStyle(color: fs.ash, fontSize: 14),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if ((media.album ?? '').isNotEmpty) ...[
const SizedBox(height: 2),
Text(
media.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: media,
),
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),
],
),
),
),
],
),
],
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(children: [
const Spacer(),
Container(
width: 280, height: 280, color: fs.slate,
),
const SizedBox(height: 24),
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
Flexible(
child: Text(
media.title,
style: TextStyle(color: fs.parchment, fontSize: 22),
overflow: TextOverflow.ellipsis,
),
),
TrackActionsButton(
track: TrackRef(
id: media.id,
title: media.title,
albumId: (media.extras?['album_id'] as String?) ?? '',
albumTitle: media.album ?? '',
artistId: '', // not stashed in MediaItem.extras today
artistName: media.artist ?? '',
durationSec: media.duration?.inSeconds ?? 0,
streamUrl: '',
),
hideQueueActions: true,
),
]),
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(),
),
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: 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,
),
],
);
}
}
+270 -28
View File
@@ -1,53 +1,295 @@
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/track_actions/track_actions_button.dart';
import '../theme/theme_extension.dart';
import 'player_provider.dart';
/// 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 ConsumerWidget {
const PlayerBar({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final mediaItem = ref.watch(mediaItemProvider).value;
final media = ref.watch(mediaItemProvider).value;
final playback = ref.watch(playbackStateProvider).value;
if (mediaItem == null) return const SizedBox.shrink();
if (media == null) return const SizedBox.shrink();
// 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: media)),
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();
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: [
if (media.artUri != null)
Image(
image: media.artUri!.isScheme('file')
? FileImage(File.fromUri(media.artUri!)) as ImageProvider
: NetworkImage(media.artUri.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
Container(width: 48, height: 48, color: fs.slate),
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: '',
);
@@ -1,6 +1,8 @@
import 'package:audio_service/audio_service.dart';
import 'package:flutter/foundation.dart' show debugPrint;
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;
@@ -30,13 +32,44 @@ 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;
Future<void> playTracks(List<TrackRef> tracks, {int initialIndex = 0}) async {
// Stage-by-stage timing so we can see exactly where the
// "tap → audio" delay lives. Look for "playTracks: ..." lines
// in the next log capture; each stage label is followed by its
// elapsed millis since the previous stage.
final sw = Stopwatch()..start();
int lap() {
final ms = sw.elapsedMilliseconds;
sw.reset();
sw.start();
return ms;
}
final url = await _ref.read(serverUrlProvider.future);
debugPrint('playTracks: serverUrl ${lap()}ms');
final token = await _ref.read(secureStorageProvider).read(key: 'session_token');
debugPrint('playTracks: token ${lap()}ms');
final cache = _ref.read(albumCoverCacheProvider);
final audioCache = _ref.read(audioCacheManagerProvider);
final h = _ref.read(audioHandlerProvider)
@@ -46,8 +79,11 @@ class PlayerActions {
coverCache: cache,
audioCacheManager: audioCache,
);
debugPrint('playTracks: configure ${lap()}ms');
await h.setQueueFromTracks(tracks, initialIndex: initialIndex);
debugPrint('playTracks: setQueue (${tracks.length} tracks) ${lap()}ms');
await h.play();
debugPrint('playTracks: play() returned ${lap()}ms');
}
Future<void> playNext(TrackRef track) async {
@@ -59,6 +95,41 @@ class PlayerActions {
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));
@@ -83,7 +83,11 @@ class _PlaylistTile extends StatelessWidget {
color: fs.slate,
child: playlist.coverUrl.isEmpty
? Icon(Icons.queue_music, color: fs.ash)
: ServerImage(url: playlist.coverUrl, fit: BoxFit.cover),
: ServerImage(
url: playlist.coverUrl,
fit: BoxFit.cover,
fallback: Icon(Icons.queue_music, color: fs.ash),
),
),
),
const SizedBox(width: 12),
@@ -1,4 +1,8 @@
import 'dart:async';
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';
@@ -36,7 +40,26 @@ final playlistsListProvider =
fetchAndPopulate: () async {
final api = await ref.read(playlistsApiProvider.future);
final fresh = await api.list(kind: kind);
final ownedSysCount =
fresh.owned.where((p) => p.systemVariant != null).length;
debugPrint(
'playlistsListProvider($kind): wire returned owned=${fresh.owned.length} '
'(system=$ownedSysCount) public=${fresh.public.length}');
// 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);
@@ -49,7 +72,7 @@ final playlistsListProvider =
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())
@@ -58,9 +81,23 @@ final playlistsListProvider =
.where((r) => r.userId != user.id && r.isPublic)
.map((r) => r.toRef())
.toList();
final ownedSys = owned.where((p) => p.isSystem).length;
final driftSys = filtered.where((r) => r.systemVariant != null).length;
debugPrint(
'playlistsListProvider($kind): drift rows=${rows.length} '
'filtered=${filtered.length} (system=$driftSys) '
'owned=${owned.length} (system=$ownedSys) pub=${pub.length} '
'userId=${user.id}');
return PlaylistsList(owned: owned, public: pub);
},
isOnline: () async => (await ref.read(connectivityProvider.future)),
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,
);
});
@@ -103,41 +140,193 @@ final playlistDetailProvider =
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);
debugPrint('playlistDetailProvider($id): calling get');
final fresh = await api.get(id).timeout(const Duration(seconds: 10));
debugPrint(
'playlistDetailProvider($id): got ${fresh.tracks.length} tracks, writing');
// 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(),
);
}
});
debugPrint(
'playlistDetailProvider($id): drift write done; awaiting watch re-emit');
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) {
debugPrint(
'playlistDetailProvider($id): server says 404, evicting stale drift rows');
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 (await ref.read(connectivityProvider.future)) {
try {
final api = await ref.read(playlistsApiProvider.future);
final fresh = await api.get(id);
await db.batch((b) {
b.insert(db.cachedPlaylists, fresh.playlist.toDrift(),
mode: drift.InsertMode.insertOrReplace);
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,
);
}
});
// watch() re-emits next iteration with populated row.
} catch (_) {
yield emptyDetail();
}
} else {
debugPrint('playlistDetailProvider($id): drift miss, cold-fetching');
if (fetchAttempted) {
yield emptyDetail();
continue;
}
fetchAttempted = true;
if (!await isOnline()) {
yield emptyDetail();
continue;
}
final ok = await fetchAndPopulate();
if (!ok) yield emptyDetail();
continue;
}
debugPrint(
'playlistDetailProvider($id): drift hit (${playlistRows.length} rows)');
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) {
debugPrint(
'playlistDetailProvider($id): playlist hit but no tracks; fetching');
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);
@@ -157,9 +346,47 @@ final playlistDetailProvider =
}).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;
}
final systemPlaylistsStatusProvider =
FutureProvider<SystemPlaylistsStatus>((ref) async {
final dio = await ref.watch(dioProvider.future);
@@ -18,45 +18,59 @@ class PlaylistCard extends StatelessWidget {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
return SizedBox(
width: 176,
child: GestureDetector(
onTap: () => context.push('/playlists/${playlist.id}'),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Container(
width: 144,
height: 144,
color: fs.slate,
child: playlist.coverUrl.isEmpty
? Icon(Icons.queue_music, color: fs.ash, size: 56)
: ServerImage(url: playlist.coverUrl, fit: BoxFit.cover),
),
),
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: Material(
color: Colors.transparent,
child: InkWell(
onTap: () => context.push('/playlists/${playlist.id}'),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
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),
),
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),
),
),
),
]),
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),
),
),
),
]),
),
),
),
);
+67 -7
View File
@@ -7,6 +7,8 @@ import '../auth/login_screen.dart';
import '../auth/server_url_screen.dart';
import '../library/album_detail_screen.dart';
import '../library/artist_detail_screen.dart';
import '../models/album.dart';
import '../models/artist.dart';
import '../discover/discover_screen.dart';
import '../library/home_screen.dart';
import '../library/library_screen.dart';
@@ -18,6 +20,7 @@ import '../playlists/playlists_list_screen.dart';
import '../requests/requests_screen.dart';
import '../search/search_screen.dart';
import '../settings/settings_screen.dart';
import '../update/client_update_provider.dart';
import '../update/update_banner.dart';
import '../admin/admin_landing_screen.dart';
import '../admin/admin_requests_screen.dart';
@@ -54,20 +57,62 @@ GoRouter buildRouter(Ref ref) {
GoRoute(path: '/', redirect: (_, __) => '/home'),
GoRoute(path: '/server-url', builder: (_, __) => const ServerUrlScreen()),
GoRoute(path: '/login', builder: (_, __) => const LoginScreen()),
// /now-playing lives outside the ShellRoute on purpose. The full
// player IS the player UI when active, and we don't want the mini
// bar from the shell underneath fighting for the bottom strip.
// Pushing this route unmounts the shell entirely; the slide-up
// transition still feels right because the shell stays painted
// for the duration of the animation.
GoRoute(
path: '/now-playing',
pageBuilder: (_, __) => CustomTransitionPage(
child: const NowPlayingScreen(),
transitionDuration: const Duration(milliseconds: 280),
reverseTransitionDuration: const Duration(milliseconds: 240),
transitionsBuilder: (_, anim, __, child) {
final eased = CurvedAnimation(
parent: anim,
curve: Curves.easeOutCubic,
reverseCurve: Curves.easeInCubic,
);
return SlideTransition(
position: Tween(
begin: const Offset(0, 1),
end: Offset.zero,
).animate(eased),
child: child,
);
},
),
),
// /queue lives outside the ShellRoute too. Why: pushing /queue
// from /now-playing (which is also outside the shell) used to
// cause go_router to mount a second ShellRoute instance under
// the existing one, producing a duplicate page-key assertion
// (NavigatorState._debugCheckDuplicatedPageKeys). Top-level
// routes can stack on each other freely; shell-children can't
// when something on top of the shell is already routing.
GoRoute(path: '/queue', builder: (_, __) => const QueueScreen()),
ShellRoute(
builder: (ctx, state, child) => VersionGate(child: _ShellWithPlayerBar(child: child)),
routes: [
GoRoute(path: '/home', builder: (_, __) => const HomeScreen()),
GoRoute(
path: '/artists/:id',
builder: (_, s) => ArtistDetailScreen(id: s.pathParameters['id']!),
// `extra` carries an optional ArtistRef so the detail
// header renders immediately while tracks/albums load.
builder: (_, s) => ArtistDetailScreen(
id: s.pathParameters['id']!,
seed: s.extra is ArtistRef ? s.extra as ArtistRef : null,
),
),
GoRoute(
path: '/albums/:id',
builder: (_, s) => AlbumDetailScreen(id: s.pathParameters['id']!),
builder: (_, s) => AlbumDetailScreen(
id: s.pathParameters['id']!,
seed: s.extra is AlbumRef ? s.extra as AlbumRef : null,
),
),
GoRoute(path: '/now-playing', builder: (_, __) => const NowPlayingScreen()),
GoRoute(path: '/queue', builder: (_, __) => const QueueScreen()),
GoRoute(path: '/search', builder: (_, __) => const SearchScreen()),
GoRoute(path: '/library', builder: (_, __) => const LibraryScreen()),
GoRoute(path: '/discover', builder: (_, __) => const DiscoverScreen()),
@@ -88,15 +133,30 @@ GoRouter buildRouter(Ref ref) {
);
}
class _ShellWithPlayerBar extends StatelessWidget {
class _ShellWithPlayerBar extends ConsumerWidget {
const _ShellWithPlayerBar({required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
Widget build(BuildContext context, WidgetRef ref) {
// The banner sits above the routed child and uses SafeArea to clear
// the system status bar. MediaQuery.padding is screen-relative
// though, so the child's Scaffold/AppBar would still apply its own
// top status-bar inset on top of the banner — doubling the gap.
// When the banner is showing, strip that inset from the child so
// its AppBar lands directly under the banner.
final hasBanner = ref.watch(shouldShowUpdateBannerProvider) != null;
return Column(
children: [
const UpdateBanner(),
Expanded(child: child),
Expanded(
child: hasBanner
? MediaQuery.removePadding(
context: context,
removeTop: true,
child: child,
)
: child,
),
const PlayerBar(),
],
);
@@ -35,11 +35,31 @@ class ServerImage extends ConsumerWidget {
// doesn't carry cookies/Bearer tokens automatically the way the
// browser's <img> tag does, so we forward the session token as a
// header. Without this, the server returns 401 and the image fails.
final token = ref.watch(sessionTokenProvider).value;
final headers = (token != null && token.isNotEmpty)
? {'Authorization': 'Bearer $token'}
: null;
return Image.network(resolved, fit: fit, headers: headers);
//
// sessionTokenProvider is a FutureProvider — on first read after a
// hot restart its .value is null until the secure-storage read
// resolves. If we fired Image.network with headers:null at that
// moment, the network image cache would lock in the 401 response
// and never retry. Instead, hold the fallback until the token is
// available, then mount the Image with the auth header attached.
final tokenAsync = ref.watch(sessionTokenProvider);
return tokenAsync.when(
loading: () => empty,
error: (_, __) => empty,
data: (token) {
final headers = (token != null && token.isNotEmpty)
? {'Authorization': 'Bearer $token'}
: null;
return Image.network(
resolved,
fit: fit,
headers: headers,
// Keep failures local — a single 401/timeout shouldn't dump
// a stack trace or replace the parent Container's background.
errorBuilder: (_, __, ___) => empty,
);
},
);
}
static String? _resolve(String? baseUrl, String url) {
@@ -117,6 +117,23 @@ class TrackActionsSheet extends ConsumerWidget {
}
},
),
_MenuItem(
key: const Key('track_actions_start_radio'),
icon: Icons.radio,
label: 'Start radio',
onTap: () async {
Navigator.pop(context);
try {
await ref.read(playerActionsProvider).startRadio(track.id);
} catch (e) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Couldn't start radio: $e")),
);
}
}
},
),
const _Divider(),
_MenuItem(
key: const Key('track_actions_go_to_album'),
@@ -3,7 +3,6 @@ import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:pub_semver/pub_semver.dart';
import '../library/library_providers.dart' show dioProvider;
import 'installer.dart';
@@ -50,20 +49,52 @@ class ClientUpdateController extends AsyncNotifier<UpdateInfo?> {
}
/// True when `serverVersion` is strictly newer than `installedVersion`.
/// Both strings are normalized (leading 'v' stripped) and parsed as
/// semver. On parse failure, falls back to string inequality (treats
/// any difference as "newer" — operator can dismiss if wrong).
///
/// Comparison strategy: split both strings on `.`, parse each component
/// as an int (non-numeric = 0), pad the shorter list with zeros, then
/// compare component-wise. This handles our date-style versions
/// (2026.05.10.1) which exceed the 3-part semver shape that
/// `pub_semver.Version.parse` accepts, and treats "2026.05.10" as
/// equal to "2026.05.10.0" rather than "different = newer".
///
/// Falls back to pub_semver as a secondary attempt when the components
/// look semver-like (handles pre-release suffixes, build metadata, etc).
///
/// Exposed for testing; the polling logic in ClientUpdateController
/// is the only production caller.
bool isVersionNewer(String serverVersion, String installedVersion) {
final svr = serverVersion.replaceFirst(RegExp(r'^v'), '');
final ins = installedVersion.replaceFirst(RegExp(r'^v'), '');
try {
return Version.parse(svr) > Version.parse(ins);
} catch (_) {
return svr != ins;
List<int> parts(String v) => v
.replaceFirst(RegExp(r'^v'), '')
.split('.')
.map((p) => int.tryParse(p) ?? 0)
.toList();
final svr = parts(serverVersion);
final ins = parts(installedVersion);
// Safety net for non-numeric versions (e.g. branch-name builds like
// "main" vs "dev"): if neither side parsed any non-zero component,
// fall back to string inequality so an operator on a dev build
// still gets the banner instead of silently matching everything.
final svrAllZero = svr.every((c) => c == 0);
final insAllZero = ins.every((c) => c == 0);
if (svrAllZero && insAllZero) {
return serverVersion.replaceFirst(RegExp(r'^v'), '') !=
installedVersion.replaceFirst(RegExp(r'^v'), '');
}
final n = svr.length > ins.length ? svr.length : ins.length;
while (svr.length < n) {
svr.add(0);
}
while (ins.length < n) {
ins.add(0);
}
for (var i = 0; i < n; i++) {
if (svr[i] > ins[i]) return true;
if (svr[i] < ins[i]) return false;
}
return false;
}
final clientUpdateProvider =
+31 -15
View File
@@ -62,11 +62,12 @@ class _UpdateBannerState extends ConsumerState<UpdateBanner> {
child: SafeArea(
bottom: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 4, 8),
padding: const EdgeInsets.fromLTRB(12, 4, 4, 4),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(Icons.system_update, color: fs.parchment, size: 18),
const SizedBox(width: 10),
Icon(Icons.system_update, color: fs.parchment, size: 16),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -76,11 +77,11 @@ class _UpdateBannerState extends ConsumerState<UpdateBanner> {
_stage == _Stage.error
? 'Update failed'
: 'Update Minstrel · ${info.version} available',
style: TextStyle(color: fs.parchment, fontSize: 13),
style: TextStyle(color: fs.parchment, fontSize: 12),
overflow: TextOverflow.ellipsis,
),
if (_stage == _Stage.downloading) ...[
const SizedBox(height: 4),
const SizedBox(height: 2),
LinearProgressIndicator(
value: _progress > 0 ? _progress : null,
minHeight: 2,
@@ -89,11 +90,11 @@ class _UpdateBannerState extends ConsumerState<UpdateBanner> {
),
],
if (_stage == _Stage.error && _error != null) ...[
const SizedBox(height: 2),
const SizedBox(height: 1),
Text(
_error!,
style: TextStyle(color: fs.ash, fontSize: 11),
maxLines: 2,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
@@ -105,20 +106,35 @@ class _UpdateBannerState extends ConsumerState<UpdateBanner> {
onPressed: () => _onInstall(info),
style: TextButton.styleFrom(
foregroundColor: fs.accent,
minimumSize: const Size(64, 36),
minimumSize: const Size(56, 28),
padding: const EdgeInsets.symmetric(horizontal: 8),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.compact,
),
child: const Text('Install'),
child: const Text('Install', style: TextStyle(fontSize: 13)),
),
if (_stage == _Stage.error)
TextButton(
onPressed: () => _onInstall(info),
style: TextButton.styleFrom(foregroundColor: fs.accent),
child: const Text('Retry'),
style: TextButton.styleFrom(
foregroundColor: fs.accent,
minimumSize: const Size(56, 28),
padding: const EdgeInsets.symmetric(horizontal: 8),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.compact,
),
child: const Text('Retry', style: TextStyle(fontSize: 13)),
),
SizedBox(
width: 32,
height: 32,
child: IconButton(
tooltip: 'Dismiss',
padding: EdgeInsets.zero,
iconSize: 16,
icon: Icon(Icons.close, color: fs.ash),
onPressed: () => _onDismiss(info),
),
IconButton(
tooltip: 'Dismiss',
icon: Icon(Icons.close, size: 18, color: fs.ash),
onPressed: () => _onDismiss(info),
),
],
),
+209 -1
View File
@@ -73,6 +73,54 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.2"
build:
dependency: transitive
description:
name: build
sha256: a156715e7cd728130c592f30552575908aae5b100005fbc1f0fb16b3c03a3d10
url: "https://pub.dev"
source: hosted
version: "4.0.6"
build_config:
dependency: transitive
description:
name: build_config
sha256: "4070d2a59f8eec34c97c86ceb44403834899075f66e8a9d59706f8e7834f6f71"
url: "https://pub.dev"
source: hosted
version: "1.3.0"
build_daemon:
dependency: transitive
description:
name: build_daemon
sha256: bf05f6e12cfea92d3c09308d7bcdab1906cd8a179b023269eed00c071004b957
url: "https://pub.dev"
source: hosted
version: "4.1.1"
build_runner:
dependency: "direct dev"
description:
name: build_runner
sha256: "1523ce62448ebac2c15a8ba5fbad8acac169788658a7dd2a1c2d9c2a9318b9a6"
url: "https://pub.dev"
source: hosted
version: "2.15.0"
built_collection:
dependency: transitive
description:
name: built_collection
sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100"
url: "https://pub.dev"
source: hosted
version: "5.1.1"
built_value:
dependency: transitive
description:
name: built_value
sha256: "34e4067d30ce212937df995f03b69992eea683539ceeac7f679a1f1eba055b56"
url: "https://pub.dev"
source: hosted
version: "8.12.6"
characters:
dependency: transitive
description:
@@ -81,6 +129,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.1"
charcode:
dependency: transitive
description:
name: charcode
sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a
url: "https://pub.dev"
source: hosted
version: "1.4.0"
checked_yaml:
dependency: transitive
description:
name: checked_yaml
sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f"
url: "https://pub.dev"
source: hosted
version: "2.0.4"
cli_config:
dependency: transitive
description:
@@ -89,6 +153,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.2.0"
cli_util:
dependency: transitive
description:
name: cli_util
sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c
url: "https://pub.dev"
source: hosted
version: "0.4.2"
clock:
dependency: transitive
description:
@@ -113,6 +185,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.19.1"
connectivity_plus:
dependency: "direct main"
description:
name: connectivity_plus
sha256: b5e72753cf63becce2c61fd04dfe0f1c430cc5278b53a1342dc5ad839eab29ec
url: "https://pub.dev"
source: hosted
version: "6.1.5"
connectivity_plus_platform_interface:
dependency: transitive
description:
name: connectivity_plus_platform_interface
sha256: "3c09627c536d22fd24691a905cdd8b14520de69da52c7a97499c8be5284a32ed"
url: "https://pub.dev"
source: hosted
version: "2.1.0"
convert:
dependency: transitive
description:
@@ -145,6 +233,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.9"
dart_style:
dependency: transitive
description:
name: dart_style
sha256: "29f7ecc274a86d32920b1d9cfc7502fa87220da41ec60b55f329559d5732e2b2"
url: "https://pub.dev"
source: hosted
version: "3.1.7"
dbus:
dependency: transitive
description:
name: dbus
sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270
url: "https://pub.dev"
source: hosted
version: "0.7.12"
dio:
dependency: "direct main"
description:
@@ -161,6 +265,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.2"
drift:
dependency: "direct main"
description:
name: drift
sha256: "970cd188fddb111b26ea6a9b07a62bf5c2432d74147b8122c67044ae3b97e99e"
url: "https://pub.dev"
source: hosted
version: "2.31.0"
drift_dev:
dependency: "direct dev"
description:
name: drift_dev
sha256: "917184b2fb867b70a548a83bf0d36268423b38d39968c06cce4905683da49587"
url: "https://pub.dev"
source: hosted
version: "2.31.0"
drift_flutter:
dependency: "direct main"
description:
name: drift_flutter
sha256: c07120854742a0cae2f7501a0da02493addde550db6641d284983c08762e60a7
url: "https://pub.dev"
source: hosted
version: "0.2.8"
fake_async:
dependency: transitive
description:
@@ -320,6 +448,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "8.1.0"
graphs:
dependency: transitive
description:
name: graphs
sha256: "741bbf84165310a68ff28fe9e727332eef1407342fca52759cb21ad8177bb8d0"
url: "https://pub.dev"
source: hosted
version: "2.3.2"
hooks:
dependency: transitive
description:
@@ -384,6 +520,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.6.7"
json_annotation:
dependency: transitive
description:
name: json_annotation
sha256: cb09e7dac6210041fad964ed7fbee004f14258b4eca4040f72d1234062ace4c8
url: "https://pub.dev"
source: hosted
version: "4.11.0"
just_audio:
dependency: "direct main"
description:
@@ -496,6 +640,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.17.6"
nm:
dependency: transitive
description:
name: nm
sha256: "2c9aae4127bdc8993206464fcc063611e0e36e72018696cd9631023a31b24254"
url: "https://pub.dev"
source: hosted
version: "0.5.0"
node_preamble:
dependency: transitive
description:
@@ -553,7 +705,7 @@ packages:
source: hosted
version: "1.1.0"
path_provider:
dependency: transitive
dependency: "direct main"
description:
name: path_provider
sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
@@ -640,6 +792,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.2.0"
pubspec_parse:
dependency: transitive
description:
name: pubspec_parse
sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082"
url: "https://pub.dev"
source: hosted
version: "1.5.0"
recase:
dependency: transitive
description:
name: recase
sha256: e4eb4ec2dcdee52dcf99cb4ceabaffc631d7424ee55e56f280bc039737f89213
url: "https://pub.dev"
source: hosted
version: "4.1.0"
record_use:
dependency: transitive
description:
@@ -701,6 +869,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
source_gen:
dependency: transitive
description:
name: source_gen
sha256: ec37cc0e6694374cbef59ed79685572c870a54ede6fa30a3e420feb3adffea02
url: "https://pub.dev"
source: hosted
version: "4.2.3"
source_map_stack_trace:
dependency: transitive
description:
@@ -765,6 +941,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.4.0"
sqlite3:
dependency: transitive
description:
name: sqlite3
sha256: "3145bd74dcdb4fd6f5c6dda4d4e4490a8087d7f286a14dee5d37087290f0f8a2"
url: "https://pub.dev"
source: hosted
version: "2.9.4"
sqlite3_flutter_libs:
dependency: "direct main"
description:
name: sqlite3_flutter_libs
sha256: eeb9e3a45207649076b808f8a5a74d68770d0b7f26ccef6d5f43106eee5375ad
url: "https://pub.dev"
source: hosted
version: "0.5.42"
sqlparser:
dependency: transitive
description:
name: sqlparser
sha256: "337e9997f7141ffdd054259128553c348635fa318f7ca492f07a4ab76f850d19"
url: "https://pub.dev"
source: hosted
version: "0.43.1"
stack_trace:
dependency: transitive
description:
@@ -789,6 +989,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.4"
stream_transform:
dependency: transitive
description:
name: stream_transform
sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871
url: "https://pub.dev"
source: hosted
version: "2.1.1"
string_scanner:
dependency: transitive
description:
+1 -1
View File
@@ -1,7 +1,7 @@
name: minstrel
description: Minstrel mobile client
publish_to: 'none'
version: 0.1.0+1
version: 2026.5.11+1
environment:
sdk: '>=3.5.0 <4.0.0'
@@ -24,17 +24,19 @@ void main() {
expect(isVersionNewer('v0.1.0', 'v0.1.0'), isFalse);
});
test('honors prerelease ordering', () {
// 0.1.0 > 0.1.0-rc.1 per semver
expect(isVersionNewer('0.1.0', '0.1.0-rc.1'), isTrue);
expect(isVersionNewer('0.1.0-rc.1', '0.1.0'), isFalse);
test('zero-pads shorter version when comparing', () {
// "1.2" treated as "1.2.0" — shorter side gets zero-padded so
// comparison is component-wise.
expect(isVersionNewer('1.2.1', '1.2'), isTrue);
expect(isVersionNewer('1.2', '1.2.1'), isFalse);
expect(isVersionNewer('1.2', '1.2.0'), isFalse);
});
});
group('isVersionNewer (date-style versions parse as semver)', () {
// pub_semver is permissive with leading zeros — '2026.05.10'
// parses as 2026.5.10. So date-style tags get strict ordering,
// not the unparseable-fallback path.
group('isVersionNewer (date-style versions)', () {
// Date tags are 3- or 4-part: 2026.05.10 or 2026.05.10.1. The
// numeric comparator parses each component as int (so "05" == 5)
// and zero-pads the shorter side.
test('newer date → newer', () {
expect(isVersionNewer('2026.05.10', '2026.05.09'), isTrue);
});
@@ -44,6 +46,18 @@ void main() {
test('equal date → not newer', () {
expect(isVersionNewer('2026.05.10', '2026.05.10'), isFalse);
});
test('leading zeros do not affect ordering', () {
// "2026.5.11" and "2026.05.11" parse to the same components.
// 12 > 5 numerically so month rollover stays correct.
expect(isVersionNewer('2026.5.11', '2026.05.11'), isFalse);
expect(isVersionNewer('2026.12.1', '2026.5.31'), isTrue);
});
test('4-part build suffix breaks the tie', () {
// 2026.05.10 vs 2026.05.10.1 — first three equal, server has a
// 4th component (1), client zero-pads → server is newer.
expect(isVersionNewer('2026.05.10.1', '2026.05.10'), isTrue);
expect(isVersionNewer('2026.05.10', '2026.05.10.0'), isFalse);
});
});
group('isVersionNewer (truly non-semver fallback)', () {
+27 -20
View File
@@ -40,19 +40,28 @@ func (h *handlers) handleGetTrack(w http.ResponseWriter, r *http.Request) {
// handleGetAlbum implements GET /api/albums/{id}. Returns the album plus its
// tracks (ordered by disc/track number via the underlying query) with
// duration summed from the track list — keeps one source of truth.
//
// Two DB round trips: the album+artist join and the per-user tracks
// list. Down from three (separate album, artist, tracks) before
// GetAlbumWithArtist landed.
func (h *handlers) handleGetAlbum(w http.ResponseWriter, r *http.Request) {
q := dbq.New(h.pool)
album, apiErr := resolveByID(r, "id", q.GetAlbumByID, "album")
if apiErr != nil {
writeErr(w, apiErr)
id, ok := requireURLUUID(w, r, "id")
if !ok {
return
}
artist, err := q.GetArtistByID(r.Context(), album.ArtistID)
row, err := q.GetAlbumWithArtist(r.Context(), id)
if err != nil {
h.logger.Error("api: get album artist failed", "err", err)
if errors.Is(err, pgx.ErrNoRows) {
writeErr(w, apierror.NotFound("album"))
return
}
h.logger.Error("api: get album+artist failed", "err", err)
writeErr(w, apierror.InternalMsg("lookup failed", err))
return
}
album := row.Album
artistName := row.ArtistName
var userID pgtype.UUID
if user, ok := auth.UserFromContext(r.Context()); ok {
userID = user.ID
@@ -68,20 +77,24 @@ func (h *handlers) handleGetAlbum(w http.ResponseWriter, r *http.Request) {
refs := make([]TrackRef, 0, len(tracks))
durSec := 0
for _, t := range tracks {
ref := trackRefFrom(t, album.Title, artist.Name)
ref := trackRefFrom(t, album.Title, artistName)
refs = append(refs, ref)
durSec += ref.DurationSec
}
detail := AlbumDetail{
AlbumRef: albumRefFrom(album, artist.Name, len(tracks), durSec),
AlbumRef: albumRefFrom(album, artistName, len(tracks), durSec),
Tracks: refs,
}
writeJSON(w, http.StatusOK, detail)
}
// handleGetArtist implements GET /api/artists/{id}. Returns artist + albums;
// each album carries its own track_count (one count query per album, same
// pattern as subsonic). At M1 sizes (albums-per-artist << 100) this is fine.
// each album carries its own track_count.
//
// Down from 1 + 1 + N queries (artist, albums, per-album CountTracksByAlbum)
// to 1 + 1 (artist, albums-with-track-count via correlated subquery).
// On a 30-album artist that's ~32 round trips collapsed to 2 — the
// difference between "feels slow" and "feels instant" on detail nav.
func (h *handlers) handleGetArtist(w http.ResponseWriter, r *http.Request) {
q := dbq.New(h.pool)
artist, apiErr := resolveByID(r, "id", q.GetArtistByID, "artist")
@@ -89,25 +102,19 @@ func (h *handlers) handleGetArtist(w http.ResponseWriter, r *http.Request) {
writeErr(w, apiErr)
return
}
albums, err := q.ListAlbumsByArtist(r.Context(), artist.ID)
rows, err := q.ListAlbumsByArtistWithTrackCount(r.Context(), artist.ID)
if err != nil {
h.logger.Error("api: list albums by artist failed", "err", err)
writeErr(w, apierror.InternalMsg("lookup failed", err))
return
}
refs := make([]AlbumRef, 0, len(albums))
for _, a := range albums {
count, cerr := q.CountTracksByAlbum(r.Context(), a.ID)
if cerr != nil {
h.logger.Error("api: count tracks failed", "err", cerr)
writeErr(w, apierror.InternalMsg("lookup failed", cerr))
return
}
refs := make([]AlbumRef, 0, len(rows))
for _, row := range rows {
// durationSec=0: not aggregated for nested album lists per spec data flow.
refs = append(refs, albumRefFrom(a, artist.Name, int(count), 0))
refs = append(refs, albumRefFrom(row.Album, artist.Name, int(row.TrackCount), 0))
}
detail := ArtistDetail{
ArtistRef: artistRefFrom(artist, len(albums)),
ArtistRef: artistRefFrom(artist, len(rows)),
Albums: refs,
}
writeJSON(w, http.StatusOK, detail)
+85
View File
@@ -168,6 +168,41 @@ func (q *Queries) GetAlbumCoverageRollup(ctx context.Context) (GetAlbumCoverageR
return i, err
}
const getAlbumWithArtist = `-- name: GetAlbumWithArtist :one
SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, artists.name AS artist_name
FROM albums
JOIN artists ON artists.id = albums.artist_id
WHERE albums.id = $1
`
type GetAlbumWithArtistRow struct {
Album Album
ArtistName string
}
// Combined fetch for /api/albums/{id}: returns the album row + the
// joined artist name in a single round trip. Replaces a sequential
// GetAlbumByID + GetArtistByID pair on the hot detail-page path.
func (q *Queries) GetAlbumWithArtist(ctx context.Context, id pgtype.UUID) (GetAlbumWithArtistRow, error) {
row := q.db.QueryRow(ctx, getAlbumWithArtist, id)
var i GetAlbumWithArtistRow
err := row.Scan(
&i.Album.ID,
&i.Album.Title,
&i.Album.SortTitle,
&i.Album.ArtistID,
&i.Album.ReleaseDate,
&i.Album.Mbid,
&i.Album.CoverArtPath,
&i.Album.CreatedAt,
&i.Album.UpdatedAt,
&i.Album.CoverArtSource,
&i.Album.CoverArtSourcesVersion,
&i.ArtistName,
)
return i, err
}
const getAlbumsByIDs = `-- name: GetAlbumsByIDs :many
SELECT id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at, cover_art_source, cover_art_sources_version FROM albums WHERE id = ANY($1::uuid[])
`
@@ -389,6 +424,56 @@ func (q *Queries) ListAlbumsByArtist(ctx context.Context, artistID pgtype.UUID)
return items, nil
}
const listAlbumsByArtistWithTrackCount = `-- name: ListAlbumsByArtistWithTrackCount :many
SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version,
(SELECT count(*) FROM tracks t WHERE t.album_id = albums.id)::bigint
AS track_count
FROM albums
WHERE albums.artist_id = $1
ORDER BY release_date NULLS LAST, sort_title
`
type ListAlbumsByArtistWithTrackCountRow struct {
Album Album
TrackCount int64
}
// Replaces the N+1 pattern in handleGetArtist (1 + N CountTracksByAlbum
// per album). Returns each album joined with its track count via a
// correlated subquery — single round trip regardless of album count.
func (q *Queries) ListAlbumsByArtistWithTrackCount(ctx context.Context, artistID pgtype.UUID) ([]ListAlbumsByArtistWithTrackCountRow, error) {
rows, err := q.db.Query(ctx, listAlbumsByArtistWithTrackCount, artistID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAlbumsByArtistWithTrackCountRow
for rows.Next() {
var i ListAlbumsByArtistWithTrackCountRow
if err := rows.Scan(
&i.Album.ID,
&i.Album.Title,
&i.Album.SortTitle,
&i.Album.ArtistID,
&i.Album.ReleaseDate,
&i.Album.Mbid,
&i.Album.CoverArtPath,
&i.Album.CreatedAt,
&i.Album.UpdatedAt,
&i.Album.CoverArtSource,
&i.Album.CoverArtSourcesVersion,
&i.TrackCount,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAlbumsByGenre = `-- name: ListAlbumsByGenre :many
SELECT DISTINCT ON (albums.id) albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version
FROM albums
+41 -25
View File
@@ -12,17 +12,19 @@ import (
)
const listLastPlayedArtistsForUser = `-- name: ListLastPlayedArtistsForUser :many
SELECT a.id, a.name, a.sort_name, a.mbid, a.created_at, a.updated_at, a.artist_thumb_path, a.artist_fanart_path, a.artist_art_source, a.artist_art_sources_version,
cov.id AS cover_album_id,
cnt.album_count::bigint AS album_count,
max_started.started_at::timestamptz AS last_played_at
FROM artists a
JOIN LATERAL (
SELECT max(pe.started_at) AS started_at
WITH user_plays AS (
SELECT t.artist_id, max(pe.started_at) AS last_started
FROM play_events pe
JOIN tracks t ON t.id = pe.track_id
WHERE pe.user_id = $1 AND t.artist_id = a.id
) max_started ON max_started.started_at IS NOT NULL
WHERE pe.user_id = $1
GROUP BY t.artist_id
)
SELECT a.id, a.name, a.sort_name, a.mbid, a.created_at, a.updated_at, a.artist_thumb_path, a.artist_fanart_path, a.artist_art_source, a.artist_art_sources_version,
cov.id AS cover_album_id,
cnt.album_count::bigint AS album_count,
up.last_started::timestamptz AS last_played_at
FROM user_plays up
JOIN artists a ON a.id = up.artist_id
LEFT JOIN LATERAL (
SELECT id FROM albums
WHERE artist_id = a.id AND cover_art_path IS NOT NULL
@@ -32,7 +34,7 @@ LEFT JOIN LATERAL (
SELECT count(*) AS album_count
FROM albums WHERE artist_id = a.id
) cnt ON true
ORDER BY max_started.started_at DESC, a.id
ORDER BY up.last_started DESC, a.id
LIMIT $2
`
@@ -52,6 +54,15 @@ type ListLastPlayedArtistsForUserRow struct {
// a derived cover_album_id via a representative-album lateral join (most
// recent album that has cover_art_path set). album_count joined for the
// ArtistRef wire shape.
//
// Earlier shape iterated `FROM artists a` and ran a LATERAL play_events
// subquery per artist — O(total_artists) plan even for users with a
// handful of plays. New shape aggregates the user's plays by artist
// via the play_events → tracks join up front (uses
// play_events_user_track_idx + tracks pkey lookups), then attaches
// the artist row and lateral cover/count subqueries only for the
// artists that actually appear. Distinct-artists set is small for a
// typical user, so cost is bounded by play history not library size.
func (q *Queries) ListLastPlayedArtistsForUser(ctx context.Context, arg ListLastPlayedArtistsForUserParams) ([]ListLastPlayedArtistsForUserRow, error) {
rows, err := q.db.Query(ctx, listLastPlayedArtistsForUser, arg.UserID, arg.Limit)
if err != nil {
@@ -87,24 +98,24 @@ func (q *Queries) ListLastPlayedArtistsForUser(ctx context.Context, arg ListLast
}
const listMostPlayedTracksForUser = `-- name: ListMostPlayedTracksForUser :many
WITH plays AS (
SELECT track_id, count(*) AS cnt
FROM play_events
WHERE user_id = $1 AND was_skipped = false
GROUP BY track_id
)
SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at,
albums.title AS album_title,
artists.name AS artist_name
FROM tracks t
JOIN albums ON albums.id = t.album_id
JOIN artists ON artists.id = t.artist_id
JOIN play_events pe ON pe.track_id = t.id
WHERE pe.user_id = $1
AND pe.was_skipped = false
AND NOT EXISTS (
SELECT 1 FROM lidarr_quarantine q
WHERE q.user_id = $1 AND q.track_id = t.id
)
GROUP BY t.id, t.title, t.album_id, t.artist_id, t.duration_ms, t.file_path,
t.file_format, t.file_size, t.bitrate, t.track_number, t.disc_number,
t.mbid, t.genre, t.added_at, t.updated_at,
albums.title, artists.name
ORDER BY count(*) DESC, t.id
FROM plays p
JOIN tracks t ON t.id = p.track_id
JOIN albums ON albums.id = t.album_id
JOIN artists ON artists.id = t.artist_id
WHERE NOT EXISTS (
SELECT 1 FROM lidarr_quarantine q
WHERE q.user_id = $1 AND q.track_id = t.id
)
ORDER BY p.cnt DESC, t.id
LIMIT $2
`
@@ -122,6 +133,11 @@ type ListMostPlayedTracksForUserRow struct {
// M6a: top-N tracks by completed-play count for the user. was_skipped
// excludes skips so a user spamming next doesn't fabricate a top track.
// Quarantined tracks (per-user soft-hide from M5b) are filtered out.
//
// Aggregate play_events first (uses play_events_user_track_idx) and
// join through tracks/albums/artists only for the survivors. Earlier
// shape did the join across every play_event row before grouping —
// O(plays) instead of O(distinct tracks).
func (q *Queries) ListMostPlayedTracksForUser(ctx context.Context, arg ListMostPlayedTracksForUserParams) ([]ListMostPlayedTracksForUserRow, error) {
rows, err := q.db.Query(ctx, listMostPlayedTracksForUser, arg.UserID, arg.Limit)
if err != nil {
+20
View File
@@ -14,6 +14,26 @@ RETURNING *;
-- name: GetAlbumByID :one
SELECT * FROM albums WHERE id = $1;
-- name: GetAlbumWithArtist :one
-- Combined fetch for /api/albums/{id}: returns the album row + the
-- joined artist name in a single round trip. Replaces a sequential
-- GetAlbumByID + GetArtistByID pair on the hot detail-page path.
SELECT sqlc.embed(albums), artists.name AS artist_name
FROM albums
JOIN artists ON artists.id = albums.artist_id
WHERE albums.id = $1;
-- name: ListAlbumsByArtistWithTrackCount :many
-- Replaces the N+1 pattern in handleGetArtist (1 + N CountTracksByAlbum
-- per album). Returns each album joined with its track count via a
-- correlated subquery — single round trip regardless of album count.
SELECT sqlc.embed(albums),
(SELECT count(*) FROM tracks t WHERE t.album_id = albums.id)::bigint
AS track_count
FROM albums
WHERE albums.artist_id = $1
ORDER BY release_date NULLS LAST, sort_title;
-- name: GetAlbumByArtistAndTitle :one
-- Scanner uses this for the no-mbid dedupe path: resolve-or-create.
SELECT * FROM albums WHERE artist_id = $1 AND title = $2 LIMIT 1;
+41 -25
View File
@@ -206,24 +206,29 @@ LIMIT $3;
-- M6a: top-N tracks by completed-play count for the user. was_skipped
-- excludes skips so a user spamming next doesn't fabricate a top track.
-- Quarantined tracks (per-user soft-hide from M5b) are filtered out.
--
-- Aggregate play_events first (uses play_events_user_track_idx) and
-- join through tracks/albums/artists only for the survivors. Earlier
-- shape did the join across every play_event row before grouping —
-- O(plays) instead of O(distinct tracks).
WITH plays AS (
SELECT track_id, count(*) AS cnt
FROM play_events
WHERE user_id = $1 AND was_skipped = false
GROUP BY track_id
)
SELECT sqlc.embed(t),
albums.title AS album_title,
artists.name AS artist_name
FROM tracks t
JOIN albums ON albums.id = t.album_id
JOIN artists ON artists.id = t.artist_id
JOIN play_events pe ON pe.track_id = t.id
WHERE pe.user_id = $1
AND pe.was_skipped = false
AND NOT EXISTS (
SELECT 1 FROM lidarr_quarantine q
WHERE q.user_id = $1 AND q.track_id = t.id
)
GROUP BY t.id, t.title, t.album_id, t.artist_id, t.duration_ms, t.file_path,
t.file_format, t.file_size, t.bitrate, t.track_number, t.disc_number,
t.mbid, t.genre, t.added_at, t.updated_at,
albums.title, artists.name
ORDER BY count(*) DESC, t.id
FROM plays p
JOIN tracks t ON t.id = p.track_id
JOIN albums ON albums.id = t.album_id
JOIN artists ON artists.id = t.artist_id
WHERE NOT EXISTS (
SELECT 1 FROM lidarr_quarantine q
WHERE q.user_id = $1 AND q.track_id = t.id
)
ORDER BY p.cnt DESC, t.id
LIMIT $2;
-- name: ListLastPlayedArtistsForUser :many
@@ -231,17 +236,28 @@ LIMIT $2;
-- a derived cover_album_id via a representative-album lateral join (most
-- recent album that has cover_art_path set). album_count joined for the
-- ArtistRef wire shape.
SELECT sqlc.embed(a),
cov.id AS cover_album_id,
cnt.album_count::bigint AS album_count,
max_started.started_at::timestamptz AS last_played_at
FROM artists a
JOIN LATERAL (
SELECT max(pe.started_at) AS started_at
--
-- Earlier shape iterated `FROM artists a` and ran a LATERAL play_events
-- subquery per artist — O(total_artists) plan even for users with a
-- handful of plays. New shape aggregates the user's plays by artist
-- via the play_events → tracks join up front (uses
-- play_events_user_track_idx + tracks pkey lookups), then attaches
-- the artist row and lateral cover/count subqueries only for the
-- artists that actually appear. Distinct-artists set is small for a
-- typical user, so cost is bounded by play history not library size.
WITH user_plays AS (
SELECT t.artist_id, max(pe.started_at) AS last_started
FROM play_events pe
JOIN tracks t ON t.id = pe.track_id
WHERE pe.user_id = $1 AND t.artist_id = a.id
) max_started ON max_started.started_at IS NOT NULL
WHERE pe.user_id = $1
GROUP BY t.artist_id
)
SELECT sqlc.embed(a),
cov.id AS cover_album_id,
cnt.album_count::bigint AS album_count,
up.last_started::timestamptz AS last_played_at
FROM user_plays up
JOIN artists a ON a.id = up.artist_id
LEFT JOIN LATERAL (
SELECT id FROM albums
WHERE artist_id = a.id AND cover_art_path IS NOT NULL
@@ -251,7 +267,7 @@ LEFT JOIN LATERAL (
SELECT count(*) AS album_count
FROM albums WHERE artist_id = a.id
) cnt ON true
ORDER BY max_started.started_at DESC, a.id
ORDER BY up.last_started DESC, a.id
LIMIT $2;
-- name: ListRediscoverAlbumsForUser :many
+1
View File
@@ -148,6 +148,7 @@ func (s *Server) handleHealthz(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(map[string]string{
"status": "ok",
"version": ServerVersion,
"min_client_version": MinClientVersion,
})
}
+10
View File
@@ -4,3 +4,13 @@ package server
// accepts. Bump it when a server change requires a paired client update;
// older clients see version_too_old at /healthz and refuse to operate.
const MinClientVersion = "0.1.0"
// ServerVersion is the deployed server image's version tag. Defaults to
// "dev" for local builds; overridden at link time via:
//
// -ldflags="-X 'git.fabledsword.com/bvandeusen/minstrel/internal/server.ServerVersion=v2026.05.10.2'"
//
// release.yml passes the git tag through MINSTREL_VERSION build-arg →
// Dockerfile ldflag. Surfaced at /healthz so operators can verify which
// image their container is running without exec'ing into it.
var ServerVersion = "dev"
+26 -16
View File
@@ -11,6 +11,10 @@
// bandwidth abuse on the APK stream, so this component only shows
// for logged-in users. Mount in Settings, never in pre-auth surfaces.
// Server returns snake_case (clientVersionResponse in
// internal/api/client_assets.go). Map to a camelCase struct for
// the rest of the component.
type WireInfo = { version: string; apk_url: string; size_bytes: number };
type Info = { version: string; apkUrl: string; sizeBytes: number };
let info = $state<Info | null>(null);
@@ -22,12 +26,12 @@
onMount(async () => {
try {
const body = await api.get<Partial<Info>>('/api/client/version');
if (!body.version || !body.apkUrl) return;
const body = await api.get<Partial<WireInfo>>('/api/client/version');
if (!body.version || !body.apk_url) return;
info = {
version: body.version,
apkUrl: body.apkUrl,
sizeBytes: body.sizeBytes ?? 0
apkUrl: body.apk_url,
sizeBytes: body.size_bytes ?? 0
};
} catch {
// 404 (no APK), 401 (somehow unauthed), network error — silent.
@@ -36,17 +40,23 @@
</script>
{#if info}
<a
href={info.apkUrl}
download="minstrel.apk"
class="mobile-app-download flex items-center gap-3 rounded-md border border-border bg-surface px-3 py-2 text-sm text-text-primary no-underline transition-colors hover:bg-surface-hover hover:text-accent focus-visible:ring-2 focus-visible:ring-accent"
>
<Smartphone size={18} strokeWidth={1.5} class="shrink-0 text-accent" />
<span class="flex flex-col leading-tight">
<span class="font-medium">Get the Android app</span>
<span class="text-xs text-text-secondary">
{info.version}{info.sizeBytes > 0 ? ` · ${formatSize(info.sizeBytes)}` : ''}
<section class="space-y-3 rounded border border-border bg-surface p-4">
<h2 class="text-lg font-semibold">Mobile app</h2>
<p class="text-sm text-text-secondary">
Install the Android app paired to this server. Sign in with the same account.
</p>
<a
href={info.apkUrl}
download="minstrel.apk"
class="mobile-app-download flex items-center gap-3 rounded-md border border-border bg-surface px-3 py-2 text-sm text-text-primary no-underline transition-colors hover:bg-surface-hover hover:text-accent focus-visible:ring-2 focus-visible:ring-accent"
>
<Smartphone size={18} strokeWidth={1.5} class="shrink-0 text-accent" />
<span class="flex flex-col leading-tight">
<span class="font-medium">Get the Android app</span>
<span class="text-xs text-text-secondary">
{info.version}{info.sizeBytes > 0 ? ` · ${formatSize(info.sizeBytes)}` : ''}
</span>
</span>
</span>
</a>
</a>
</section>
{/if}
+188 -18
View File
@@ -15,7 +15,6 @@
import { FALLBACK_COVER, coverUrl } from '$lib/media/covers';
import LikeButton from './LikeButton.svelte';
import TrackMenu from './TrackMenu.svelte';
import PlayerOverflowMenu from './PlayerOverflowMenu.svelte';
const current = $derived(player.current);
@@ -29,7 +28,6 @@
player.repeat === 'all' ? 'Repeat all' : 'Repeat one'
);
// Volume icon tracks level so the right-edge anchor reads at a glance.
const VolumeIcon = $derived(
player.volume === 0 ? VolumeX :
player.volume < 0.5 ? Volume1 : Volume2
@@ -49,9 +47,187 @@
</script>
{#if current}
<div class="flex flex-col md:flex-row md:min-h-[108px] min-h-[88px] md:items-center gap-2 md:gap-4 border-t border-border bg-surface px-3 md:px-4 py-2 md:py-1.5">
<!--
COMPACT view (below md). Layout per operator design:
┌─────────┬───────────┬───────────────────┐
│ art │ ♥ ⋮ │ 🔀 🔁 ☰ │ ← short sub-row
│ title │ │ │
│ artist │ ⏮ ⏯ ⏭ │ volume slider │ ← play row at full size
├─────────┴───────────┴───────────────────┤
│ 0:42 ━━━━━●━━━━━━━━━━━━━━━━━━━━━━ 3:21 │
└─────────────────────────────────────────┘
Play controls maintain 40/48/40 size; like+kebab and column-3 sub-rows
are shorter so column 2's bottom edge aligns with column 3's bottom.
-->
<div
data-testid="player-bar-compact"
class="md:hidden flex flex-col gap-1.5 border-t border-border bg-surface px-3 py-2"
>
{#if player.state === 'error'}
<div role="alert" class="flex items-center justify-center gap-3 text-sm text-text-primary">
<span>{player.error ?? 'Playback failed.'}</span>
<button
type="button"
class="rounded bg-accent px-3 py-1.5 text-sm text-text-primary"
onclick={() => playQueue(player.queue, player.index)}
>
Try again
</button>
</div>
{:else}
<!-- Top row: 3 columns -->
<div class="flex items-stretch gap-3">
<!-- Column 1: art + title + artist -->
<a
href={`/albums/${current.album_id}`}
aria-label="Open album"
class="flex min-w-0 items-center gap-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
style="flex: 1 1 35%;"
>
<img
src={coverUrl(current.album_id)}
alt=""
class="h-12 w-12 shrink-0 rounded-md object-cover"
onerror={onCoverError}
/>
<div class="min-w-0">
<div class="truncate text-sm font-medium text-text-primary">{current.title}</div>
<div class="truncate text-xs text-text-secondary">{current.artist_name}</div>
</div>
</a>
<!-- Column 2: like+kebab (top), play controls (bottom) -->
<div class="flex flex-col items-center justify-between gap-1 shrink-0">
<div class="flex items-center gap-0.5">
<LikeButton entityType="track" entityId={current.id} />
<TrackMenu track={current} direction="up" hideQueueActions />
</div>
<div class="flex items-center gap-1.5">
<button
type="button"
aria-label="Previous"
disabled={skipPrevDisabled}
onclick={skipPrev}
class="flex h-10 w-10 items-center justify-center rounded-full text-text-secondary transition-colors hover:bg-surface-hover hover:text-text-primary disabled:opacity-40 disabled:hover:bg-transparent"
>
<SkipBack size={18} strokeWidth={1.5} fill="currentColor" />
</button>
<button
type="button"
aria-label={player.isPlaying ? 'Pause' : 'Play'}
onclick={togglePlay}
class="flex h-12 w-12 items-center justify-center rounded-full bg-accent text-text-primary shadow transition-transform hover:scale-105 focus-visible:ring-2 focus-visible:ring-accent"
>
{#if player.state === 'loading' || player.state === 'idle'}
<Loader2 data-testid="play-spinner" size={22} strokeWidth={1.5} class="animate-spin" />
{:else if player.isPlaying}
<Pause size={22} strokeWidth={1.5} fill="currentColor" />
{:else}
<Play size={22} strokeWidth={1.5} fill="currentColor" class="ml-0.5" />
{/if}
</button>
<button
type="button"
aria-label="Next"
disabled={skipNextDisabled}
onclick={skipNext}
class="flex h-10 w-10 items-center justify-center rounded-full text-text-secondary transition-colors hover:bg-surface-hover hover:text-text-primary disabled:opacity-40 disabled:hover:bg-transparent"
>
<SkipForward size={18} strokeWidth={1.5} fill="currentColor" />
</button>
</div>
</div>
<!-- Column 3: shuffle/repeat/queue (top), volume slider (bottom) -->
<div class="flex min-w-0 flex-col items-stretch justify-between gap-1" style="flex: 1 1 30%;">
<div class="flex items-center justify-end gap-0.5">
<button
type="button"
aria-label="Shuffle"
aria-pressed={player.shuffle}
onclick={toggleShuffle}
class="flex h-8 w-8 items-center justify-center rounded-full transition-colors {player.shuffle
? 'bg-accent-tint text-accent'
: 'text-text-secondary hover:bg-surface-hover hover:text-text-primary'}"
>
<Shuffle size={16} strokeWidth={1.5} />
</button>
<button
type="button"
aria-label={repeatLabel}
onclick={cycleRepeat}
class="flex h-8 w-8 items-center justify-center rounded-full transition-colors {player.repeat !== 'off'
? 'bg-accent-tint text-accent'
: 'text-text-secondary hover:bg-surface-hover hover:text-text-primary'}"
>
{#if player.repeat === 'one'}
<Repeat1 size={16} strokeWidth={1.5} />
{:else}
<Repeat size={16} strokeWidth={1.5} />
{/if}
</button>
<button
type="button"
onclick={() => toggleQueueDrawer()}
aria-label={player.queueDrawerOpen ? 'Close queue' : 'Open queue'}
aria-pressed={player.queueDrawerOpen}
class="flex h-8 w-8 items-center justify-center rounded-full transition-colors {player.queueDrawerOpen
? 'bg-accent-tint text-accent'
: 'text-text-secondary hover:bg-surface-hover hover:text-text-primary'}"
>
<ListMusic size={16} strokeWidth={1.5} />
</button>
</div>
<label class="flex items-center gap-1">
<span class="sr-only">Volume</span>
<VolumeIcon size={14} strokeWidth={1.5} class="shrink-0 text-text-secondary" />
<input
type="range"
aria-label="Volume"
min="0"
max="1"
step="0.01"
value={player.volume}
oninput={onVolumeInput}
class="min-w-0 flex-1 accent-accent"
/>
</label>
</div>
</div>
<!-- Bottom row: full-width seek slider + time labels -->
<div class="flex items-center gap-2">
<span class="w-9 shrink-0 text-right text-[10px] tabular-nums text-text-secondary">
{formatDuration(player.position)}
</span>
<input
type="range"
aria-label="Seek"
min="0"
max={player.duration || 0}
step="0.1"
value={player.position}
oninput={onSeekInput}
class="flex-1 accent-accent"
/>
<span class="w-9 shrink-0 text-[10px] tabular-nums text-text-secondary">
{formatDuration(player.duration)}
</span>
</div>
{/if}
</div>
<!--
DESKTOP view (md+). Original 3-column layout — unchanged except that
the redundant PlayerOverflowMenu kebab is no longer mounted (volume,
shuffle, repeat, queue all live inline in the right cluster).
-->
<div
data-testid="player-bar-desktop"
class="hidden md:flex md:flex-row md:min-h-[108px] md:items-center md:gap-4 border-t border-border bg-surface md:px-4 md:py-1.5"
>
<!-- Left: cover + title + artist + like + menu -->
<div class="flex w-full md:w-72 min-w-0 items-center gap-3">
<div class="flex w-72 min-w-0 items-center gap-3">
<a
href={`/albums/${current.album_id}`}
aria-label="Open album"
@@ -60,7 +236,7 @@
<img
src={coverUrl(current.album_id)}
alt=""
class="h-10 w-10 md:h-24 md:w-24 rounded-md object-cover"
class="h-24 w-24 rounded-md object-cover"
onerror={onCoverError}
/>
</a>
@@ -74,14 +250,13 @@
</a>
{#if player.queue.length > player.index + 1}
{@const nextTrack = player.queue[player.index + 1]}
<span class="text-text-secondary text-xs truncate hidden md:block">
<span class="block truncate text-xs text-text-secondary">
Next · {nextTrack.title}{nextTrack.artist_name}
</span>
{/if}
</div>
<LikeButton entityType="track" entityId={current.id} />
<TrackMenu track={current} direction="up" hideQueueActions />
<PlayerOverflowMenu direction="up" />
</div>
<!-- Center: seek row + transport row -->
@@ -98,7 +273,7 @@
</div>
{:else}
<div class="flex flex-1 flex-col items-stretch gap-2">
<!-- Transport row: prev / play / next, play is the accent focal point -->
<!-- Transport row -->
<div class="flex items-center justify-center gap-3">
<button
type="button"
@@ -116,12 +291,7 @@
class="flex h-12 w-12 items-center justify-center rounded-full bg-accent text-text-primary shadow transition-transform hover:scale-105 focus-visible:ring-2 focus-visible:ring-accent"
>
{#if player.state === 'loading' || player.state === 'idle'}
<Loader2
data-testid="play-spinner"
size={24}
strokeWidth={1.5}
class="animate-spin"
/>
<Loader2 size={24} strokeWidth={1.5} class="animate-spin" />
{:else if player.isPlaying}
<Pause size={24} strokeWidth={1.5} fill="currentColor" />
{:else}
@@ -140,7 +310,7 @@
</div>
<!-- Seek row -->
<div class="flex items-center gap-3">
<span class="w-10 md:w-12 shrink-0 text-right text-[10px] md:text-xs tabular-nums text-text-secondary">
<span class="w-12 shrink-0 text-right text-xs tabular-nums text-text-secondary">
{formatDuration(player.position)}
</span>
<input
@@ -153,15 +323,15 @@
oninput={onSeekInput}
class="flex-1 accent-accent"
/>
<span class="w-10 md:w-12 shrink-0 text-[10px] md:text-xs tabular-nums text-text-secondary">
<span class="w-12 shrink-0 text-xs tabular-nums text-text-secondary">
{formatDuration(player.duration)}
</span>
</div>
</div>
{/if}
<!-- Right: shuffle + repeat + volume -->
<div class="hidden md:flex w-60 items-center justify-end gap-2">
<!-- Right: shuffle + repeat + queue + volume -->
<div class="flex w-60 items-center justify-end gap-2">
<button
type="button"
aria-label="Shuffle"
+41 -24
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/svelte';
import { render, screen, fireEvent, within } from '@testing-library/svelte';
import type { TrackRef } from '$lib/api/types';
import { emptyLikesMock } from '../../test-utils/mocks/likes';
import { emptyQuarantineMock } from '../../test-utils/mocks/quarantine';
@@ -66,6 +66,15 @@ function track(): TrackRef {
});
}
// PlayerBar renders both a compact (mobile, md:hidden) and desktop
// (hidden md:flex) block. jsdom doesn't apply CSS media queries, so
// both DOM trees are present in tests. Scope every query to the
// compact block — that's the user-facing change in #358; desktop
// behavior is covered structurally by the same store + handlers.
function compact() {
return within(screen.getByTestId('player-bar-compact'));
}
beforeEach(() => {
state.queue = [track()];
state.current = state.queue[0];
@@ -85,9 +94,11 @@ afterEach(() => vi.clearAllMocks());
describe('PlayerBar', () => {
test('renders title, linked artist, linked cover', () => {
render(PlayerBar);
expect(screen.getByText('So What')).toBeInTheDocument();
expect(screen.getByRole('link', { name: /Miles Davis/ })).toHaveAttribute('href', '/artists/md');
const cover = screen.getByRole('link', { name: /open album/i });
expect(compact().getByText('So What')).toBeInTheDocument();
// The artist label sits under the title in compact (no link wrapper);
// look for it as plain text.
expect(compact().getByText('Miles Davis')).toBeInTheDocument();
const cover = compact().getByRole('link', { name: /open album/i });
expect(cover).toHaveAttribute('href', '/albums/xyz');
});
@@ -95,14 +106,14 @@ describe('PlayerBar', () => {
render(PlayerBar);
// Anchored regex — "Player options" (the new overflow ⋮) also matches
// /play|pause/i otherwise.
await fireEvent.click(screen.getByRole('button', { name: /^(play|pause)$/i }));
await fireEvent.click(compact().getByRole('button', { name: /^(play|pause)$/i }));
expect(togglePlay).toHaveBeenCalledTimes(1);
});
test('skip-next click calls skipNext; skip-prev click calls skipPrev', async () => {
render(PlayerBar);
await fireEvent.click(screen.getByRole('button', { name: /next/i }));
await fireEvent.click(screen.getByRole('button', { name: /previous/i }));
await fireEvent.click(compact().getByRole('button', { name: /next/i }));
await fireEvent.click(compact().getByRole('button', { name: /previous/i }));
expect(skipNext).toHaveBeenCalledTimes(1);
expect(skipPrev).toHaveBeenCalledTimes(1);
});
@@ -111,7 +122,7 @@ describe('PlayerBar', () => {
state.index = 0;
state.position = 1;
render(PlayerBar);
expect(screen.getByRole('button', { name: /previous/i })).toBeDisabled();
expect(compact().getByRole('button', { name: /previous/i })).toBeDisabled();
});
test('skip-next disabled at end with repeat=off', () => {
@@ -119,19 +130,19 @@ describe('PlayerBar', () => {
state.index = 0;
state.repeat = 'off';
render(PlayerBar);
expect(screen.getByRole('button', { name: /next/i })).toBeDisabled();
expect(compact().getByRole('button', { name: /next/i })).toBeDisabled();
});
test('seek slider input calls seekTo(value)', async () => {
render(PlayerBar);
const slider = screen.getByLabelText(/seek/i) as HTMLInputElement;
const slider = compact().getByLabelText(/seek/i) as HTMLInputElement;
await fireEvent.input(slider, { target: { value: '120' } });
expect(seekTo).toHaveBeenCalledWith(120);
});
test('volume slider input calls setVolume(value)', async () => {
render(PlayerBar);
const slider = screen.getByLabelText(/volume/i) as HTMLInputElement;
const slider = compact().getByLabelText(/volume/i) as HTMLInputElement;
await fireEvent.input(slider, { target: { value: '0.3' } });
expect(setVolume).toHaveBeenCalledWith(0.3);
});
@@ -139,28 +150,28 @@ describe('PlayerBar', () => {
test('shuffle button click calls toggleShuffle; active class reflects shuffle', () => {
state.shuffle = true;
render(PlayerBar);
const btn = screen.getByRole('button', { name: /shuffle/i });
const btn = compact().getByRole('button', { name: /shuffle/i });
expect(btn.getAttribute('aria-pressed')).toBe('true');
});
test('repeat button aria-label reflects current mode', () => {
state.repeat = 'one';
render(PlayerBar);
expect(screen.getByRole('button', { name: /repeat one/i })).toBeInTheDocument();
expect(compact().getByRole('button', { name: /repeat one/i })).toBeInTheDocument();
});
test('loading state shows spinner in place of play icon', () => {
state.state = 'loading';
render(PlayerBar);
expect(screen.getByTestId('play-spinner')).toBeInTheDocument();
expect(compact().getByTestId('play-spinner')).toBeInTheDocument();
});
test('error state renders retry card; retry click calls playQueue(queue, index)', async () => {
state.state = 'error';
state.error = 'Playback failed.';
render(PlayerBar);
expect(screen.getByText(/playback failed/i)).toBeInTheDocument();
await fireEvent.click(screen.getByRole('button', { name: /try again/i }));
expect(compact().getByText(/playback failed/i)).toBeInTheDocument();
await fireEvent.click(compact().getByRole('button', { name: /try again/i }));
expect(playQueue).toHaveBeenCalledWith(state.queue, state.index);
});
@@ -168,21 +179,21 @@ describe('PlayerBar', () => {
state.position = 65;
state.duration = 245;
render(PlayerBar);
expect(screen.getByText('1:05')).toBeInTheDocument();
expect(screen.getByText('4:05')).toBeInTheDocument();
expect(compact().getByText('1:05')).toBeInTheDocument();
expect(compact().getByText('4:05')).toBeInTheDocument();
});
test('renders the TrackMenu kebab button when a track is current', () => {
render(PlayerBar);
expect(
screen.getByRole('button', { name: /track actions for/i })
compact().getByRole('button', { name: /track actions for/i })
).toBeInTheDocument();
});
describe('queue toggle button', () => {
test('clicking the queue toggle calls toggleQueueDrawer', async () => {
render(PlayerBar);
const btn = screen.getByLabelText(/(open|close) queue/i);
const btn = compact().getByLabelText(/(open|close) queue/i);
await fireEvent.click(btn);
expect(toggleQueueDrawer).toHaveBeenCalled();
});
@@ -190,12 +201,18 @@ describe('PlayerBar', () => {
test('aria-pressed reflects queueDrawerOpen state', () => {
state.queueDrawerOpen = true;
render(PlayerBar);
const btn = screen.getByLabelText(/close queue/i);
const btn = compact().getByLabelText(/close queue/i);
expect(btn).toHaveAttribute('aria-pressed', 'true');
});
});
describe('"Up next" line', () => {
describe('"Up next" line (desktop only)', () => {
// The "Next · …" copy was dropped from compact per #358; only the
// desktop block surfaces it. Scope queries to desktop.
function desktop() {
return within(screen.getByTestId('player-bar-desktop'));
}
test('renders the next track title when index + 1 < queue.length', () => {
state.queue = [
{ id: 'a', title: 'Track A', artist_name: 'Art A' } as TrackRef,
@@ -204,7 +221,7 @@ describe('PlayerBar', () => {
state.index = 0;
state.current = state.queue[0];
render(PlayerBar);
expect(screen.getByText(/track b/i)).toBeInTheDocument();
expect(desktop().getByText(/track b/i)).toBeInTheDocument();
});
test('omits the line on the last track in queue', () => {
@@ -214,7 +231,7 @@ describe('PlayerBar', () => {
state.index = 0;
state.current = state.queue[0];
render(PlayerBar);
expect(screen.queryByText(/^Next ·/i)).not.toBeInTheDocument();
expect(desktop().queryByText(/^Next ·/i)).not.toBeInTheDocument();
});
test('omits the line when queue is empty', () => {
@@ -1,97 +0,0 @@
<script lang="ts">
import { MoreVertical, Shuffle, Repeat, Repeat1, ListMusic, Volume2 } from 'lucide-svelte';
import {
player, toggleShuffle, cycleRepeat, toggleQueueDrawer, setVolume
} from '$lib/player/store.svelte';
import TrackMenuItem from './TrackMenuItem.svelte';
import TrackMenuDivider from './TrackMenuDivider.svelte';
let { direction = 'up' }: { direction?: 'up' | 'down' } = $props();
let menuOpen = $state(false);
function toggleMenu(e: MouseEvent) {
e.stopPropagation();
menuOpen = !menuOpen;
}
const repeatLabel = $derived(
player.repeat === 'off' ? 'Repeat off' :
player.repeat === 'all' ? 'Repeat all' : 'Repeat one'
);
const repeatIcon = $derived(player.repeat === 'one' ? Repeat1 : Repeat);
function onShuffle() {
toggleShuffle();
}
function onRepeat() {
cycleRepeat();
}
function onQueue() {
toggleQueueDrawer();
menuOpen = false;
}
function onVolume(e: Event) {
setVolume(Number((e.currentTarget as HTMLInputElement).value));
}
</script>
<svelte:window onclick={() => { menuOpen = false; }} onkeydown={(e) => e.key === 'Escape' && (menuOpen = false)} />
<div class="relative inline-block">
<button
type="button"
aria-label="Player options"
aria-haspopup="menu"
aria-expanded={menuOpen}
onclick={toggleMenu}
class="rounded p-1 text-text-muted hover:text-text-primary min-h-[44px] min-w-[44px]
flex items-center justify-center"
>
<MoreVertical size={18} strokeWidth={1} />
</button>
{#if menuOpen}
<div
role="menu"
tabindex="-1"
class="absolute right-0 z-20 w-56 rounded-md border border-border bg-surface p-1 shadow-lg
{direction === 'up' ? 'bottom-full mb-1' : 'top-full mt-1'}"
onclick={(e) => e.stopPropagation()}
onkeydown={(e) => e.stopPropagation()}
>
<TrackMenuItem
icon={Shuffle}
label={player.shuffle ? 'Shuffle on' : 'Shuffle off'}
onclick={onShuffle}
/>
<TrackMenuItem
icon={repeatIcon}
label={repeatLabel}
onclick={onRepeat}
/>
<TrackMenuItem
icon={ListMusic}
label={player.queueDrawerOpen ? 'Hide queue' : 'Show queue'}
onclick={onQueue}
/>
<TrackMenuDivider />
<div class="flex items-center gap-2 px-2 py-1.5">
<Volume2 size={14} strokeWidth={1} class="shrink-0 text-text-secondary" />
<input
type="range"
aria-label="Volume"
min="0"
max="1"
step="0.01"
value={player.volume}
oninput={onVolume}
class="flex-1 accent-accent"
/>
</div>
</div>
{/if}
</div>
@@ -1,31 +0,0 @@
import { describe, it, expect } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/svelte';
import PlayerOverflowMenu from './PlayerOverflowMenu.svelte';
describe('PlayerOverflowMenu', () => {
it('renders the trigger button closed by default', () => {
render(PlayerOverflowMenu);
const trigger = screen.getByLabelText('Player options');
expect(trigger.getAttribute('aria-expanded')).toBe('false');
});
it('opens the menu on click and shows shuffle/repeat/queue/volume', async () => {
render(PlayerOverflowMenu);
const trigger = screen.getByLabelText('Player options');
await fireEvent.click(trigger);
expect(trigger.getAttribute('aria-expanded')).toBe('true');
expect(screen.getByText(/shuffle/i)).toBeInTheDocument();
expect(screen.getByText(/repeat/i)).toBeInTheDocument();
expect(screen.getByText(/queue/i)).toBeInTheDocument();
expect(screen.getByLabelText('Volume')).toBeInTheDocument();
});
it('Escape key closes the menu', async () => {
render(PlayerOverflowMenu);
await fireEvent.click(screen.getByLabelText('Player options'));
expect(screen.getByLabelText('Player options').getAttribute('aria-expanded')).toBe('true');
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
await Promise.resolve();
expect(screen.getByLabelText('Player options').getAttribute('aria-expanded')).toBe('false');
});
});
@@ -0,0 +1,37 @@
<script lang="ts">
import { onMount } from 'svelte';
// Reads /healthz on mount and surfaces the deployed server version
// as understated text. Useful when verifying which image a container
// is actually running (came up debugging the in-app update flow when
// it wasn't obvious whether v2026.05.10.0 or .1 was deployed).
//
// /healthz is unauthenticated, so the bare fetch works without
// credentials. Renders nothing on parse failure or pre-version
// images that don't include the field — graceful degradation.
type Health = { status: string; version?: string };
let version = $state<string | null>(null);
onMount(async () => {
try {
const res = await fetch('/healthz');
if (!res.ok) return;
const body = (await res.json()) as Partial<Health>;
if (body.version && body.version !== 'dev') {
version = body.version;
} else if (body.version === 'dev') {
// Local dev images report "dev" — show it so the operator
// can tell they're not on a release tag.
version = 'dev';
}
} catch {
// network / parse error — silent.
}
});
</script>
{#if version}
<p class="text-xs text-text-secondary">Server {version}</p>
{/if}
+6 -7
View File
@@ -18,6 +18,7 @@
import { errCode } from '$lib/api/errors';
import { pushToast } from '$lib/stores/toast.svelte';
import MobileAppDownload from '$lib/components/MobileAppDownload.svelte';
import ServerVersion from '$lib/components/ServerVersion.svelte';
const queryClient = useQueryClient();
@@ -325,11 +326,9 @@
</ul>
</section>
<section class="space-y-3 rounded border border-border bg-surface p-4">
<h2 class="text-lg font-semibold">Mobile app</h2>
<p class="text-sm text-text-secondary">
Install the Android app paired to this server. Sign in with the same account.
</p>
<MobileAppDownload />
</section>
<MobileAppDownload />
<div class="pt-2 text-center">
<ServerVersion />
</div>
</div>