Skip to content

Native Android client for Spotify, built with Jetpack Compose

2.0.0-beta.9

kota-zof25ddfe4e012
diff --git a/.gitignore b/.gitignore
index 0055d0ed..8a5ec3cd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,3 +12,9 @@ base/tools/captures/
__pycache__/
.idea/
PROMPT-*.md
+# internal working notes (account, device, local paths): kept on the machine, never published
+HANDOFF.md
+ANNEXE-ETAT.txt
+docs/RESTE-A-FAIRE.md
+tools/handoff_state.sh
+REDDIT-*.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5341fadd..d3bfbffb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,51 @@
Each release on GitHub shows its section below. The app shows it too when it offers the update. Every detail: [docs/CHANGELOG-full.md](docs/CHANGELOG-full.md).
+## 2.0.0-beta.9
+
+- **Fast skips during an ad or a reload**: the song your taps point to plays once the ad or the reload is over, and the screen shows that same song (the sound and the screen no longer drift apart); "previous" during an ad no longer restarts the ad.
+- **Ad breaks are stopped at the source**: the player page's own ad managers (audio and in-stream) are switched off from the app, and again each time an ad shows up, instead of patching the web player's own files (the way SpotX does it, done here at runtime so an update of the page cannot break it). The device also no longer tells Spotify it cannot read mp3 (`file_urls_mp3`) — the registration some free accounts were refused for (`402 COMMAND_FAILED`).
+- **No more silence until a restart**: an ad mute whose unmute was lost (the page never reports the end of a break) is lifted after 75 s, the mute is only trusted once it reached the media elements, and a podcast stalling is caught like a song.
+- **The login page can no longer spin for ever**: the app does not wait on the address alone any more; no signed-in token 25 s after the player page came back, and the login page is shown again so it can be tried.
+- **The page rebuilds itself after a renderer crash** (the reported "the app crashed", "no sound until the player is restarted") instead of leaving a dead page behind.
+- **One client identity across launches**: the client token's device id is kept, so Spotify no longer sees a new client at every start.
+- **Your phone tells Spotify its own name**: the device registration now carries the phone's name (the one Android knows), so the other devices' list shows it instead of a generic one, and the registration is again exactly what the real web player sends (no ad-format difference left to single it out).
+- **Every install looks like its own browser**: the browser version and the system it claims are drawn once per install instead of being the same string on every phone. A single rule could have covered every Myspoti at once; it now covers one client, like a real browser would.
+- **A login that goes nowhere leaves a trail**: each sign-in step reaches the log (`login step #n POST /login/v3/…`) with the status of anything Spotify refuses, instead of ending on a spinner with nothing to look at.
+- **A report you can send us**: Settings → **Export a diagnostic report** writes the app's recent log (the player page, the relay, the ads, the refusals) and the device details to a file and opens the share sheet — the log needed `adb` until now, so a report of a refusal or a login that fails was impossible to hand over.
+- **Covers and profile pictures that never loaded are fixed**: the profile endpoints hand out `spotify:image:…` identifiers rather than a picture's address, and the image loader was given that identifier as it was. Public playlists of a user and their profile picture now show their covers.
+- **Upcoming lyrics are readable on a dark card**: they were drawn in black at 55 % of opacity, so invisible on the AMOLED card; they now follow the card's own background.
+- **During an ad the screen says so** instead of leaving the previous song stuck on "buffering", and the player header keeps the playlist's own name when Spotify's label comes back empty; the artist page has its own options menu again and the separator reported missing from the profile header is back.
+- **No more light band under the app**: the navigation bar was left to the system (a white strip with dark icons under an always-dark UI) — it now blends in.
+- **Crossfade, for real this time**: the player had a stub that always answered "no crossfade" and the setting had been removed, so the slider testers were looking for did nothing. Settings → Playback now offers Off / 3 / 6 / 9 / 12 s: the current song fades out over its last seconds and the next one fades in — one player, one stream, so the two never overlap, and the label says so. Two independent fail-safes put the volume back, and no exit path can leave the sound down.
+- **Scrolling the player no longer opens the lyrics**: any upward drag used to count as the swipe shortcut; it now takes a deliberate flick, judged on release.
+- **A Connect switch no longer restarts the song**: when another device had taken playback and Myspoti takes it back, the position is remembered and restored if the page rolled back to the start.
+- **The notification keeps up in the background**: the refresh loop waited for a device that had taken playback, which only a pull-back sets — so an app started in the background never refreshed it. It now runs whenever the service is up.
+- **Local Files lists what other players list**: the query only took what Android's index calls music of 30 s or more, so a phone full of recordings or downloads showed "your audio files will appear here" while another player listed them (reported: 29 tracks). Everything over 20 s now counts, minus Ringtones/Notifications/Alarms/Android — 59 files listed on the test phone where 77 exist.
+- **Remove a song from a playlist, and add it to another**: a playlist you can edit now offers « Remove from this playlist » in the song's own menu (with Undo), and « Add to another playlist » opens a picker of your playlists with a search field.
+- **Stop all downloads**: one action cancels everything running or waiting **without deleting a single file** (« Remove all downloads » is still the separate, destructive one).
+- **Updates on your terms**: a setting turns the automatic check off (it stays on by default) and « Check for updates now » is right there.
+- **The mini player names your headphones**: Bluetooth icon and device name (or « Headphones » for wired) when the sound does not come from the phone.
+- **Android Auto works from a cold start**: the car's tree is there at once and a browse or a play waits for the player instead of failing while it loads.
+- **The player keeps its colour on AMOLED**: the tint from the cover's colour used to disappear in AMOLED mode; it is now there in both, as asked.
+- **A song Spotify marks unavailable is still tried**, and if it really cannot play the app says « Not available in your region » instead of leaving a tap that does nothing.
+
+- **Podcasts download without SpotiFLAC and play like in the stock app**: an episode now downloads with a free account — the file is the **publisher's own plain MP3** (`passthroughUrl`, resolved right before each attempt), fetched in chunks with resume, checked (type, header, size), encrypted and kept in the offline store under `episode:<id>`. Spotify exclusives (`passthrough = NONE`, Widevine-encrypted) are **refused with a clear message**, DRM is never attempted. A queue of its own, one worker, resumed at start-up.
+- **Show and episode pages**: a header with the cover and its gradient, publisher/authors/narrators, rating, **Follow**, Episodes/Chapters and About tabs, newest/oldest sort, episode rows with "11 min left" and a "played" mark; the episode page has its actions (✓, download, share, ⋮, Play) and **"Mark as played / unplayed"**, written to the account's collection (so it follows you). An audiobook page is no longer empty: chapters plus authors and narrators.
+- **A podcast player of its own**: −15 s / +15 s, speed 1 → 3×, a clock that toggles elapsed/remaining, sleep timer, no shuffle or repeat. Two causes of episodes stopping in the background are fixed: the autoplay guard paused episodes, and a resume the page ignored was never asked again.
+- **The stock app's gestures**: tapping the active tab again scrolls **Home** and **Your Library** (list and grid) back to the top without reloading, tapping **Search** again focuses the field; tapping the **cover** in the player switches to an **immersive full screen** (controls folded into a strip), undone by another tap — the quick swipe to the lyrics still works.
+- **Recents, as in the official app**: the entry leaves Your Library for the profile panel, under "Your recap". The page has a "Recents" header with back, **Music / Podcasts** pills, dated sections (Today, Yesterday, then the date) and rows **grouped by container** — "4 tracks played • EP • …", "9 tracks played • Playlist", "12 tracks added • Playlist" for Liked Songs (heart badge), an artist with their round picture, a Blend — 56 dp covers, a round chevron to **unfold** the container's tracks, a tap on the row to open it. The counts come from the page itself (groups, content type, "added" vs "played"), not a guess, and match the stock app's on the same account.
+
+- **A bottom bar that looks like Spotify's**: the icons were declared bigger but a Material component clipped them to 24 dp, the tabs sat in the middle of the bar instead of spreading evenly, and the selected label could turn grey under a white icon. The bar now uses three equal tabs across the full width, 28 dp icons, 11 sp medium labels, Spotify's idle grey, and the selected tint on both icon and label — on top of the system gesture bar.
+- **Signing in no longer lies**: Spotify's e-mail step sends the page back to open.spotify.com, and the app took that address for a session — so leaving it to read the mail ended on an anonymous player with nothing playable. The sign-in page now stays in front until a real token exists, the short grace only counts while the app is on screen, coming back re-reads the token, and an anonymous token sends you to the sign-in page instead of pretending.
+- **The app presents itself like a real browser, consistently**: the user agent now carries the reduced version every desktop Chrome sends (no build number in it), the brand list follows the version the way Chromium builds it, and what is remembered per install is how far behind the WebView it sits — so the claim follows WebView updates instead of drifting.
+
+- **Dragging a song to the edge of the queue scrolls the list**: the reorder used to work only among the visible rows; a drag near the top or bottom now scrolls the sheet (speed growing toward the edge) and the song can be moved across the whole queue.
+- The log line `login=` (it only meant "the page is on a login URL") is now `session=signed-in|anonymous|login-page`, read from the token; a relayed request now carries the page's cookies and the browser's own transport headers.
+- **Fewer needless reloads**: a page that misses one answer (a long render, a busy main thread) is no longer taken for a dead one — the reload waits for two silent ticks in a row, so a short hiccup does not cost a full page reload.
+- **An episode stuck at its end goes on to the next one** instead of starting again from 0:00 (the stall recovery only knew songs).
+- **Spotify's colours everywhere, and smoother motion**: switches, sliders, radio buttons, dialogs and spinners took the phone's wallpaper colours (or Material purple); they now use Spotify's green and greys. Covers fade in instead of popping, play/pause morphs instead of swapping, the mini player's colour cross-fades from one song to the next, the podcast player takes the cover's colour, unfolded Recents rows slide in, and the bottom bar's fade is dense enough that covers no longer show through the tab labels. The episode page's Play button now turns into Pause while it plays.
+
## 2.0.0-beta.8
- **SpotiFLAC**: when it is not verified (or the verification lapsed), Downloads and any download open the verification first, then the songs download; its page is full screen (Retry and Skip were hidden under the mini player); sessions follow SpotiFLAC Mobile's rules (renewed once, in their last hour, and a download refused because another one just renewed it is sent again), so many downloads at once no longer end the verification; you are told when it must be done again.
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/Mappers.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/Mappers.kt
index 5a6631fe..ef980562 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/Mappers.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/Mappers.kt
@@ -136,6 +136,7 @@ internal fun nowPlaying(t: JsonElement?): NowPlaying? {
durationMs = t.long("durationMs") ?: 0,
explicit = t.bool("explicit") ?: false,
provider = t.str("provider"),
+ mediaType = t.str("mediaType"),
)
}
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt
index fe0a0a84..cb60c22d 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt
@@ -34,9 +34,13 @@ class SpotifyApi(
http: OkHttpClient = OkHttpClient(),
language: String = "en",
val ops: GqlOps = GqlOps.bundled(),
+ /** The client's device id, kept across launches by the host (see SpotifyHttp.deviceId). */
+ deviceId: String? = null,
+ /** The browser this install presents to Spotify (see [SpotifyHttp.browserUserAgent]); null keeps the constant. */
+ userAgent: String? = null,
) : MyspotiApi {
val bridge = Bridge(host, scope)
- val http = SpotifyHttp(http, bridge, language)
+ val http = SpotifyHttp(http, bridge, language, userAgent, deviceId ?: java.util.UUID.randomUUID().toString())
@Volatile private var currentOps: GqlOps = ops
/** The operation table in use; [updateOps] swaps it when Spotify ships a new build. */
val opsInUse: GqlOps get() = currentOps
@@ -53,11 +57,12 @@ class SpotifyApi(
override val library = SpotifyLibrary(bridge, gql)
override val playlists = SpotifyPlaylists(gql, bridge, this.http)
override val home = SpotifyHome(gql)
- override val podcasts = SpotifyPodcasts(gql, bridge)
+ override val podcasts = SpotifyPodcasts(gql, bridge, this.http)
override val users = SpotifyUsers(gql, bridge, this.http)
override val extras = SpotifyTrackExtras(gql, bridge, this.http)
override val devices = SpotifyDevices(bridge)
override val jam = SpotifyJam(bridge)
+ override val recents = SpotifyRecents(gql)
/** Escape hatch to the 179 GraphQL operations and 89 page services, for what is not typed yet. */
val raw = Raw()
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyMore.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyMore.kt
index bab20d62..ea583e87 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyMore.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyMore.kt
@@ -10,6 +10,7 @@ import app.myspoti.api.Credits
import app.myspoti.api.Device
import app.myspoti.api.Devices
import app.myspoti.api.Episode
+import app.myspoti.api.EpisodeAudio
import app.myspoti.api.FriendActivity
import app.myspoti.api.HistoryEntry
import app.myspoti.api.Home
@@ -54,6 +55,22 @@ import java.util.TimeZone
private fun idOf(uri: Uri) = uri.substringAfterLast(':')
+/**
+ * A soundfinder response read into [EpisodeAudio]. Only `passthroughUrl` is usable: `url[]`
+ * is the Widevine-encrypted copy, so it is never returned. "MANDATORY" wants the publisher
+ * file as much as "ALLOWED" (the Web Player's format mapping is inconsistent there), so only
+ * "NONE" means there is no clear file.
+ */
+internal fun episodeAudio(json: JsonElement): EpisodeAudio {
+ val pass = json.str("passthrough")?.uppercase().orEmpty()
+ val passUrl = json.str("passthroughUrl")?.takeIf { it.isNotBlank() }
+ return EpisodeAudio(
+ url = passUrl?.takeIf { pass != "NONE" },
+ passthrough = pass.ifBlank { "NONE" },
+ format = json.str("format").orEmpty(),
+ )
+}
+
/** Promotions and ads (HomePromotionShelf, sponsored cards…): never shown as content. */
internal fun isPromotion(typename: String?): Boolean =
typename != null && Regex("Promotion|Sponsor|Advert|(^|[a-z])Ad([A-Z]|$)").containsMatchIn(typename)
@@ -117,13 +134,26 @@ class SpotifyHome(private val gql: Gql) : Home {
}
}
-class SpotifyPodcasts(private val gql: Gql, private val bridge: Bridge) : Podcasts {
+class SpotifyPodcasts(private val gql: Gql, private val bridge: Bridge, private val http: SpotifyHttp) : Podcasts {
private suspend fun showUnion(uri: Uri) = gql.query("queryShowMetadataV2", vars(
"uri" to uri, "includeContentCapabilityTrait" to true, "includeEpisodeContentRatingsV2" to true,
)).entity("data.podcastUnionV2", "queryShowMetadataV2")
override suspend fun show(uri: Uri): Show = show(showUnion(uri)) ?: throw GqlException("queryShowMetadataV2", "bad show")
+ /**
+ * The audio of one episode, from the Web Player's soundfinder endpoint. The key system is
+ * part of the path and is mandatory (anything else answers 400). The endpoint is `unauth`
+ * (probed without a token), but going through [SpotifyHttp] keeps the cookie and token
+ * story the same as every other call, and the host allow-list applies.
+ */
+ override suspend fun audioUrl(uri: Uri): EpisodeAudio {
+ val id = idOf(uri)
+ val json = http.getJson("https://spclient.wg.spotify.com/soundfinder/v1/unauth/episode/$id/com.widevine.alpha")
+ ?: return EpisodeAudio(null, "NONE", "") // 404: no audio for this episode
+ return episodeAudio(json)
+ }
+
override suspend fun episodes(uri: Uri, offset: Int, limit: Int): Page<Episode> {
val e = gql.query("queryPodcastEpisodes", vars("uri" to uri, "offset" to offset, "limit" to limit, "includeEpisodeContentRatingsV2" to true))
.entity("data.podcastUnionV2", "queryPodcastEpisodes").at("episodesV2")
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
index 8f9b8b47..fb10a5d8 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
@@ -59,6 +59,16 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
* accounts (DEVICE_DOES_NOT_SUPPORT_COMMAND), leaving the ad audible.
*/
@Volatile private var adMuted = false
+ /** When [muteForAd] was applied, so a mute outliving the break is lifted (never stuck). */
+ @Volatile private var adMutedAt = 0L
+ /** When the page last reported the ad break (it never reports the end of one). */
+ @Volatile private var adStateAt = 0L
+ /** The page's own ad managers were switched off for this break (see [BridgeHost]). */
+ @Volatile private var adsOffSent = false
+ /** The page's in-stream ad manager was asked to end this break (a lighter lever than a reload). */
+ @Volatile private var adSkipped = false
+ /** How many times the ad mute was sent this break: the media element may appear late. */
+ @Volatile private var adMuteTries = 0
/** A pause asked through [pause]; it holds until playback is asked for again, never expires. */
@Volatile private var pausedByUser = false
/** The order given to the last [play] (context uri to songs), kept for a stall restart. */
@@ -83,6 +93,12 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
@Volatile var audioQuality: String = "auto"
private set
+ /**
+ * Wakes the watcher before its next tick (an ad has just started). Declared before init:
+ * the watcher starts there, at once on the main dispatcher.
+ */
+ private val wake = kotlinx.coroutines.channels.Channel<Unit>(kotlinx.coroutines.channels.Channel.CONFLATED)
+
init {
scope.launch {
bridge.events.collect { (type, payload) ->
@@ -111,7 +127,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
val lost = playingAtLoss
playingAtLoss = null
- if (lost != null && !ownReload) scope.launch { runCatching { resumeAfterReload(lost) } }
+ if (!ownReload && (lost != null || liveIntent() != null)) scope.launch {
+ runCatching { if (lost != null) resumeAfterReload(lost) else { delay(RESTORE_GAP_MS); playIntent() } }
+ }
if (audioQuality != "auto") applyAudioQuality()
// The page keeps its volume: an app closed during a muted ad must not stay silent.
runCatching { if (volume() == 0.0) setVolume(wantedVolume?.takeIf { v -> v > 0.0 } ?: 1.0) }
@@ -173,6 +191,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
* where it was, checked and tried again, unless the user paused or played something since.
*/
private suspend fun resumeAfterReload(lost: PlayerState) {
+ // Skipped during the reload: that song, not the one that played before it.
+ if (liveIntent() != null) {
+ val seq = stateSeq
+ withTimeoutOrNull(RESTORE_WAIT_MS) { while (stateSeq == seq) delay(100) }
+ playIntent()
+ return
+ }
val item = lost.item ?: return
val uri = item.uri
val at = lost.positionMs
@@ -267,6 +292,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
var adAttempts = 0
var adReloaded = false
var frozenReloadAt = 0L
+ /** Consecutive ticks where the page answered nothing (see FROZEN_MISSES). */
+ var frozenMisses = 0
var tick = 0
var lastMediaTime = -1.0
var silentSince = 0L
@@ -274,7 +301,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
// A song plays (or an ad is on): the watcher looks every [WATCH_TICK_MS] to hear a
// stall in seconds. Nothing plays: there is less to see, so it looks less often.
val quiet = !_adPlaying.value && _state.value.let { it == null || it.isPaused }
- delay(if (quiet) WATCH_IDLE_TICK_MS else WATCH_TICK_MS)
+ // An ad starting wakes it at once: its recovery starts AD_PLAYING_SKIP_MS after it.
+ if (withTimeoutOrNull(if (quiet) WATCH_IDLE_TICK_MS else WATCH_TICK_MS) { wake.receive() } != null)
+ delay(AD_PLAYING_SKIP_MS + 50)
tick++
if (!bridge.ready.value || ownReload) { key = null; attempts = 0; silentSince = 0L; continue }
val now = System.currentTimeMillis()
@@ -282,26 +311,83 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
// at once, the song going on where it was.
val read = runCatching { readMedia() }
if (read.isFailure && bridge.ready.value && !bridge.ping() && bridge.ready.value) {
+ // One silent page is not a dead one: a busy main thread (a long render, a reload
+ // still settling, an ad break starting) also holds the bridge for seconds, and
+ // reloading on the first miss turned a short hiccup into a full page reload — the
+ // one the user actually sees. The reload needs two misses in a row
+ // ([FROZEN_MISSES] ticks of WATCH_TICK_MS, so about four seconds of real silence).
+ frozenMisses++
+ if (frozenMisses < FROZEN_MISSES) { key = null; silentSince = 0L; continue }
if (now - frozenReloadAt > FROZEN_RELOAD_GAP_MS) {
frozenReloadAt = now
- bridge.logger?.invoke("page not answering: reloading the player")
+ frozenMisses = 0
+ bridge.logger?.invoke("page not answering ($FROZEN_MISSES misses in a row): reloading the player")
val playing = lastTrackState?.takeIf { !pausedByUser && !it.isPaused }
reloadAndPlayOn(playing?.copy(positionMs = playing.positionAt(now), timestampMs = now), next = false)
key = null; attempts = 0; silentSince = 0L
}
continue
}
+ // The page answered: it is alive, whatever happened before.
+ frozenMisses = 0
val media = read.getOrNull()
lastMedia = media
val s = _state.value
preloadNextSong(s, media)
+ tickCrossfade(s, media, now)
if (tick % VOLUME_CHECK_TICKS == 0) guardVolume(s, media)
if (_adPlaying.value) {
val ad = adState
+ // The break just started: the page's own ad managers are switched off, so the
+ // *next* break never starts (SpotX's adsEnabled patch, done at runtime instead of
+ // by patching the bundle). The bridge repeats it on every state push.
+ if (!adsOffSent) {
+ adsOffSent = true
+ runCatching { bridge.call("ads.off") }
+ }
+ // The mute ran once when the break started, but the player's media element lives in
+ // the player's own objects (not the DOM) and can appear late: sending it again here,
+ // bounded, is what keeps an ad from being heard.
+ if (adMuteTries < AD_MUTE_TRIES) {
+ adMuteTries++
+ runCatching { bridge.call("media.mute", buildJsonObject { put("on", true) }) }
+ }
+ // The mute outlived the break: the page went quiet without ever publishing the
+ // next song, so nothing clears the ad flag and the phone stays silent for good
+ // (reported as "no sound until the app is restarted"). The sound comes back
+ // anyway, and the state is read again.
+ if (adMutedAt > 0 && now - adMutedAt > AD_MUTE_MAX_MS) {
+ bridge.logger?.invoke("ad mute older than ${AD_MUTE_MAX_MS / 1000}s: unmuted")
+ runCatching { unmuteAfterAd() }
+ if (adStateAt > 0 && now - adStateAt > AD_MUTE_MAX_MS) {
+ adState = null; adStateAt = 0L
+ adAttempts = 0; adReloaded = false; adsOffSent = false
+ _adPlaying.value = false
+ runCatching { refresh() }
+ }
+ key = null; silentSince = 0L
+ continue
+ }
// A refused ad sits at 0:00, buffering; a real one plays to its end.
val refused = ad != null && (ad.isBuffering || ad.speed == 0.0) && now - adSince > AD_STUCK_MS
- val playing = ad != null && !refused && now - adSince > AD_PLAYING_SKIP_MS && !adReloaded
- if (refused || playing || now - adSince > AD_BREAK_MAX_MS) {
+ // A video ad reports neither a position nor a speed the way an audio one does: it
+ // is taken as playing from the start, so it is got past instead of waited on.
+ val videoAd = ad?.item?.mediaType == "video"
+ val playing = ad != null && !refused && (videoAd || now - adSince > AD_PLAYING_SKIP_MS) && !adReloaded
+ val stuck = refused || playing || now - adSince > AD_BREAK_MAX_MS
+ // The page's in-stream ad manager can end its own break. Asked once per break,
+ // before the skip/reload recovery, because that recovery is what the user sees: a
+ // "Test ad" used to cost a full reload of the page. The recovery below still runs
+ // if the ad is still there on the next turn.
+ if (stuck && !adSkipped) {
+ adSkipped = true
+ val lever = runCatching { bridge.call("ads.skip") }.getOrNull()
+ bridge.logger?.invoke("ad ${ad?.item?.name}: asked the page to end the break ($lever)")
+ adSince = System.currentTimeMillis()
+ key = null; silentSince = 0L
+ continue
+ }
+ if (stuck) {
adAttempts++
val last = lastTrackState
// Playing on can land on the same refused ad again: after a few tries the
@@ -360,6 +446,15 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
*/
private suspend fun guardVolume(s: PlayerState?, media: Media?) {
if (s == null || s.isPaused || s.isBuffering || _adPlaying.value || fadeBackTo != null || fadeBack?.isActive == true) return
+ // A crossfade owns the element level until it ends: the guard must not undo the ramp.
+ // Past its deadline, though, it is exactly the lost unmute it exists to catch.
+ if (crossfadeArmed) {
+ if (System.currentTimeMillis() >= crossfadeUntil) {
+ bridge.logger?.invoke("crossfade overdue: volume restored")
+ endCrossfade(restore = true)
+ }
+ return
+ }
// The unmute after an ad was lost (page busy): the song would play silent.
if (adMuted) unmuteAfterAd()
else if (media?.muted == true) {
@@ -392,34 +487,165 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
/** Plays the song after [s] (or [s] again when it is the last one) in its context. */
+ /**
+ * The song the user's skips point at, kept through what the page cannot take a skip in:
+ * an ad break (skips refused, "The operation is not allowed"), a reload ("local player is
+ * disabled", "not ready"). Skips then move this intent instead of reaching the page, and
+ * whatever recovers playback (the ad recovery, a reload, the end of the ad) plays it.
+ * [from]: the song shown when it was set (the page has not moved while it reports it).
+ */
+ private data class Intent(val context: Uri?, val item: NowPlaying, val from: Uri?, val at: Long, val adSeen: Boolean = false)
+ @Volatile private var intent: Intent? = null
+ /** The song and time the intent was last played, so that a slow page is not asked twice. */
+ @Volatile private var intentPlayedAt = 0L
+ @Volatile private var intentPlayedUri: Uri? = null
+ /** The intent is being played after an ad or a reload: skips meanwhile only move it. */
+ @Volatile private var playingIntent = false
+
+ /** The page cannot take a skip now. */
+ private val skipsHeld: Boolean get() = _adPlaying.value || ownReload || playingIntent || !bridge.ready.value
+
+ private fun liveIntent(): Intent? = intent?.takeIf { System.currentTimeMillis() - it.at < INTENT_MAX_MS }
+
+ /** The songs after the last real one, as the page listed them (queued first). */
+ private fun upcoming(): List<NowPlaying> =
+ _queue.value?.let { it.queued + it.nextUp }.orEmpty().filter { it.kind == ItemKind.TRACK || it.kind == ItemKind.EPISODE }
+
+ /**
+ * A skip the page cannot take: the intent moves [by] songs from where it is (or from the
+ * song shown: the first "next" is the song after it, the first "previous" that song again)
+ * and is shown at once.
+ */
+ private fun stepIntent(by: Int) {
+ val base = lastWithSong() ?: return
+ val current = base.item ?: return
+ val seq = listOfNotNull(base.previous) + current + upcoming().ifEmpty { listOfNotNull(base.next) }
+ val baseIdx = if (base.previous != null) 1 else 0
+ val at = liveIntent()?.let { i -> seq.indexOfFirst { it.uri == i.item.uri }.takeIf { it >= 0 } }
+ // No intent yet: "next" lands on the song after the one shown, "previous" on that one.
+ val idx = ((at ?: (baseIdx + if (by > 0) 0 else 1)) + by).coerceIn(0, seq.lastIndex)
+ setIntent(base.contextUri, seq[idx], current.uri)
+ }
+
+ private fun setIntent(context: Uri?, item: NowPlaying, from: Uri?) {
+ val now = System.currentTimeMillis()
+ intent = Intent(context, item, from, now, adSeen = _adPlaying.value || liveIntent()?.adSeen == true)
+ bridge.logger?.invoke("skip held (${if (_adPlaying.value) "ad" else "page reloading"}): ${item.name} goes on next")
+ showIntent()
+ }
+
+ /** The screen shows the song the user is on, waiting, while the page is elsewhere. */
+ private fun showIntent() {
+ val i = liveIntent() ?: return
+ val base = lastWithSong() ?: return
+ val now = System.currentTimeMillis()
+ _state.value = base.copy(item = i.item, positionMs = 0, timestampMs = now, isPaused = false, isBuffering = true)
+ }
+
+ /**
+ * Plays the intent until the page is on it; skips made meanwhile move the intent and the
+ * newest one is played. False when there is none.
+ */
+ private suspend fun playIntent(): Boolean {
+ if (liveIntent() == null || playingIntent) return liveIntent() != null
+ playingIntent = true
+ try {
+ repeat(INTENT_PLAYS) {
+ val i = liveIntent() ?: return true
+ val uri = i.item.uri
+ if (lastTrackState?.item?.uri == uri) { intent = null; return true }
+ val now = System.currentTimeMillis()
+ // Asked for a moment ago (a slow page): not again, wait for it below.
+ if (uri != intentPlayedUri || now - intentPlayedAt >= INTENT_REPLAY_MS) {
+ intentPlayedUri = uri
+ intentPlayedAt = now
+ bridge.logger?.invoke("playing the song the skips pointed at: ${i.item.name}")
+ val ctx = i.context
+ runCatching {
+ if (ctx != null) play(ctx, trackUri = uri, order = lastOrder?.takeIf { it.first == ctx }?.second)
+ else play(uri)
+ }.onFailure { bridge.logger?.invoke("intent not played: ${it.message}") }
+ }
+ // The page on it, or the user skipped again (then that song is played).
+ withTimeoutOrNull(INTENT_REPLAY_MS) {
+ while (lastTrackState?.item?.uri != uri && liveIntent()?.item?.uri == uri) delay(100)
+ }
+ if (lastTrackState?.item?.uri == uri && liveIntent()?.item?.uri == uri) { intent = null; return true }
+ }
+ return true
+ } finally {
+ playingIntent = false
+ }
+ }
+
private suspend fun playOn(s: PlayerState) {
+ // The user skipped meanwhile: their song, not the one after the last state seen.
+ if (playIntent()) return
val ctx = s.contextUri
- val target = s.next?.takeIf { it.kind == ItemKind.TRACK }?.uri
- ?: _queue.value?.nextUp?.firstOrNull { it.kind == ItemKind.TRACK }?.uri
+ val target = onwardTarget(s, _queue.value?.nextUp.orEmpty())
when {
ctx != null && target != null -> play(ctx, trackUri = target, order = lastOrder?.takeIf { it.first == ctx }?.second)
target != null -> next()
- ctx != null -> play(ctx, trackUri = s.item?.uri)
+ // Nothing after it: a song is started again (the page's own end-of-context behaviour);
+ // an episode is left finished rather than replayed from the start.
+ ctx != null && s.item?.kind == ItemKind.TRACK -> play(ctx, trackUri = s.item?.uri)
}
}
private fun onState(s: PlayerState?) {
stateSeq++
+ // Another song than the one a crossfade is fading out: the ramp up, at once (the
+ // watcher's next tick would leave the new song's first second at the faded level).
+ if (crossfadeArmed) {
+ val item = s?.item
+ when {
+ // An ad takes the sound over (and is muted on its own): the fade is over.
+ item?.kind == ItemKind.AD -> disarmCrossfade()
+ item != null && item.uri != crossfadeUri -> {
+ disarmCrossfade()
+ scope.launch { fadeInCrossfade() }
+ }
+ }
+ }
if (s?.item?.kind == ItemKind.AD) {
// Keep showing the last real track, buffering, while the ad plays.
if (!_adPlaying.value) {
adSince = System.currentTimeMillis()
+ adMuteTries = 0
}
adState = s
+ adStateAt = System.currentTimeMillis()
+ if (!_adPlaying.value) wake.trySend(Unit)
_adPlaying.value = true
+ intent = intent?.copy(adSeen = true)
_state.value = lastTrackState?.copy(isBuffering = true) ?: s.copy(item = null)
+ showIntent()
return
}
_adPlaying.value = false
+ adsOffSent = false
+ adSkipped = false
+ adMuteTries = 0
+ // A real song is playing: the fallback after a refusal (play the list without picking the
+ // song) is armed again for the next command, not held once per five seconds for all of them.
+ refusedRetried = false
if (s?.item != null) lastSong = s
else if (lastTrackState?.item != null) lastSongUntil = System.currentTimeMillis()
lastTrackState = s
_state.value = s
+ val i = liveIntent() ?: run { intent = null; return }
+ val uri = s?.item?.uri
+ when {
+ uri == i.item.uri -> intent = null
+ // The page has not moved yet (or reports nothing): during an ad or a reload the
+ // screen stays on the intent. On a plain skip it shows what the page plays: a
+ // skip the page lost must not leave the screen on a song that is not heard.
+ uri == null || uri == i.from -> if (i.adSeen || skipsHeld) showIntent()
+ // Somewhere else after an ad or a reload: the user's song is asked for again.
+ i.adSeen || skipsHeld -> { showIntent(); scope.launch { runCatching { if (!skipsHeld) playIntent() } } }
+ // Somewhere else on a plain skip: the page knows its queue best.
+ else -> intent = null
+ }
}
@@ -440,15 +666,18 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
* does not wait for them (a call per step delayed the first sound by one round trip each).
* [restore] ends on the page player's own volume, as [restoreLevel] does.
*/
- private suspend fun fade(levels: List<Double>, restore: Boolean = false) {
+ private suspend fun fade(levels: List<Double>, restore: Boolean = false, ms: Long = FADE_STEP_MS) {
bridge.call("media.fade", buildJsonObject {
putJsonArray("steps") { levels.forEach { add(kotlinx.serialization.json.JsonPrimitive(it.coerceIn(0.0, 1.0))) } }
- put("ms", FADE_STEP_MS)
+ put("ms", ms)
put("restore", restore)
}, timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)
}
private suspend fun withFade(block: suspend () -> Unit) {
+ // A crossfade under way owns the level: ended here, so its ramp (or its up-ramp, when the
+ // song changes under it) cannot fight the fade below.
+ endCrossfade(restore = true)
val s = _state.value
// Nothing heard (paused, an ad muted): nothing to fade.
if (s == null || s.isPaused || _adPlaying.value || adMuted) { block(); return }
@@ -483,7 +712,14 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
private suspend fun muteForAd() = runCatching {
adMuted = true
- val muted = bridge.call("media.mute", buildJsonObject { put("on", true) })
+ adMutedAt = System.currentTimeMillis()
+ var muted = bridge.call("media.mute", buildJsonObject { put("on", true) })
+ // No media element reached (the page is reloading, or the ad is taking the stream over):
+ // once more before the count is trusted.
+ if (muted.toString().trim('"').toIntOrNull() == 0) {
+ delay(200)
+ muted = bridge.call("media.mute", buildJsonObject { put("on", true) })
+ }
bridge.logger?.invoke("ad muted ($muted media elements)")
}
@@ -491,9 +727,139 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
if (!adMuted) return@runCatching
bridge.call("media.mute", buildJsonObject { put("on", false) })
adMuted = false
+ adMutedAt = 0L
+ // The song after an ad is preloaded again: the key (current|next) is usually the same as
+ // before the break, so without this the preload of that very song was skipped and the next
+ // skip after an ad was slow.
+ preloadedFor = null
+ }
+
+ /**
+ * Crossfade length in seconds (0 = off). Only a fade is possible: the page plays one media
+ * element, so two songs never overlap. Set by the app from the user's setting, at start and
+ * whenever it changes.
+ */
+ @Volatile var crossfadeSeconds: Int = 0
+ set(value) {
+ val v = value.coerceIn(0, CROSSFADE_MAX_SECONDS)
+ if (field == v) return
+ field = v
+ // Turned off while a ramp runs: the sound comes back at once rather than at the end
+ // of a fade nobody wants any more.
+ if (v == 0) {
+ val was = crossfadeArmed
+ disarmCrossfade()
+ if (was) scope.launch { runCatching { restoreLevel() } }
+ }
+ }
+
+ /** True while a crossfade is fading a song out, or the next one in. */
+ fun isCrossfading(): Boolean = crossfadeArmed
+
+ /**
+ * The page's element level, ramped down over the last seconds of a song: one media element
+ * means the next song cannot start before this one ends, so this is a fade, not an overlap.
+ */
+ @Volatile private var crossfadeArmed = false
+ /** The song the ramp belongs to: the song after it (another uri) ends the fade-out. */
+ @Volatile private var crossfadeUri: String? = null
+ /** When the ramp will have reached its floor; past that the next song must have come. */
+ @Volatile private var crossfadeUntil = 0L
+ /** The fail-safe that puts the level back if the page never moved on. */
+ private var crossfadeJob: kotlinx.coroutines.Job? = null
+
+ private fun disarmCrossfade() {
+ crossfadeArmed = false
+ crossfadeUri = null
+ crossfadeUntil = 0L
+ crossfadeJob?.cancel()
+ crossfadeJob = null
+ }
+
+ /** Ends a crossfade; [restore] puts the element back on the page player's own volume. */
+ private suspend fun endCrossfade(restore: Boolean) {
+ if (!crossfadeArmed) return
+ disarmCrossfade()
+ if (restore) runCatching { restoreLevel() }
+ }
+
+ /**
+ * Called each watch tick: arms the fade-out when the song is inside its last
+ * [crossfadeSeconds]. The ramp ends with the song (the window is what is left of it), so a
+ * late tick only shortens the fade, it never runs past the next song.
+ */
+ private suspend fun tickCrossfade(s: PlayerState?, media: Media?, now: Long) {
+ val secs = crossfadeSeconds
+ // Off, or nothing to fade out of: an armed ramp is lifted (never left down).
+ if (secs <= 0 || s == null || s.isPaused || _adPlaying.value) { endCrossfade(restore = true); return }
+ val item = s.item ?: return
+ if (item.kind == ItemKind.AD || item.durationMs <= 0) return
+ // Another device is playing: this phone's element is not where the sound is, and a ramp
+ // set on it would greet the user at 2% after a transfer back.
+ if (media?.active == false) { endCrossfade(restore = true); return }
+ val window = secs * 1000L
+ val remaining = item.durationMs - s.positionAt(now)
+ if (crossfadeArmed) {
+ // The next song is handled where it is reported (see [onState]). Here: the song was
+ // seeked back out of the window, or the setting was shortened under the ramp.
+ if (item.uri != crossfadeUri || remaining > window) endCrossfade(restore = true)
+ return
+ }
+ if (remaining <= 0 || remaining > window) return
+ // Nothing after it: a fade-out into silence is not a crossfade.
+ if (s.next == null && upcoming().isEmpty()) return
+ val own = (media?.own ?: 1.0).coerceIn(0.0, 1.0)
+ // Silent already (volume at 0): there is nothing to fade.
+ if (own <= 0.001) return
+ armCrossfade(item.uri, remaining, own)
+ }
+
+ private suspend fun armCrossfade(uri: String, remainingMs: Long, own: Double) {
+ val steps = (remainingMs / CROSSFADE_STEP_MS).toInt().coerceIn(2, CROSSFADE_MAX_STEPS)
+ val per = (remainingMs / steps).coerceAtLeast(1L)
+ // A linear ramp in amplitude, ending on CROSSFADE_FLOOR of the page's own level: the last
+ // step lands on the song's end, so the fade is over exactly when the song is.
+ val levels = (1..steps).map { i ->
+ (own * (1.0 - (1.0 - CROSSFADE_FLOOR) * i / steps)).coerceAtLeast(CROSSFADE_SILENT)
+ }
+ crossfadeArmed = true
+ crossfadeUri = uri
+ crossfadeUntil = System.currentTimeMillis() + remainingMs + CROSSFADE_FAILSAFE_MS
+ crossfadeJob?.cancel()
+ // The hard floor: whatever the page does (a stall, a lost state, a reload, a song that
+ // repeats), the sound is back a few seconds after the ramp was due. A volume left down
+ // is the one failure the user cannot work around.
+ crossfadeJob = scope.launch {
+ delay(remainingMs + CROSSFADE_FAILSAFE_MS)
+ if (crossfadeArmed) {
+ bridge.logger?.invoke("crossfade left the sound down ${(remainingMs + CROSSFADE_FAILSAFE_MS) / 1000}s: volume restored")
+ endCrossfade(restore = true)
+ }
+ }
+ bridge.logger?.invoke("crossfade: ${remainingMs / 1000.0}s out on ${_state.value?.item?.name}")
+ // One call: the page runs the whole ramp itself (see [fade]).
+ runCatching { fade(levels, ms = per) }
+ .onFailure { endCrossfade(restore = true) }
+ }
+
+ /** The next song is on: a short ramp back to the user's volume. */
+ private suspend fun fadeInCrossfade() {
+ // Read the element as it is now: the page may have reset its volume with the new track,
+ // and dipping it to the ramp's first step would be heard for nothing.
+ val m = runCatching { readMedia() }.getOrNull()
+ if (m == null || m.level >= m.own * 0.9) {
+ runCatching { restoreLevel() }
+ return
+ }
+ val own = m.own.coerceAtLeast(CROSSFADE_SILENT)
+ // Ends on the page player's own volume, so a volume change during the fade is kept.
+ runCatching { fade(CROSSFADE_IN.map { it * own }, restore = true, ms = CROSSFADE_IN_STEP_MS) }
+ .onFailure { runCatching { restoreLevel() } }
}
override suspend fun play(contextUri: Uri, trackUri: Uri?, index: Int?, positionMs: Long?, order: List<Uri>?) {
+ // A new song picked (or the intent itself played): any earlier skip is over.
+ if (trackUri == null || trackUri != liveIntent()?.item?.uri) intent = null
lastOrder = order?.let { contextUri to it }
lastPlay = Triple(contextUri, trackUri, System.currentTimeMillis())
refusedRetried = false
@@ -529,15 +895,42 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
}
}
- override suspend fun pause() { pausedByUser = true; command("player.pause") }
+ override suspend fun pause() { pausedByUser = true; endCrossfade(restore = true); command("player.pause") }
override suspend fun resume() { pausedByUser = false; command("player.resume") }
- override suspend fun seek(positionMs: Long) { command("player.seek", buildJsonObject { put("positionMs", positionMs) }) }
- override suspend fun next() { pausedByUser = false; withFade { command("player.next") } }
+ override suspend fun seek(positionMs: Long) { endCrossfade(restore = true); command("player.seek", buildJsonObject { put("positionMs", positionMs) }) }
+ override suspend fun next() {
+ pausedByUser = false
+ if (skipsHeld) { stepIntent(1); return }
+ // Remembered: should the page go into an ad break instead, this song comes after it.
+ val base = lastWithSong()
+ val after = base?.next?.takeIf { it.kind == ItemKind.TRACK || it.kind == ItemKind.EPISODE }
+ if (after != null && base.item?.kind != ItemKind.AD) intent = Intent(base.contextUri, after, base.item?.uri, System.currentTimeMillis())
+ runCatching { withFade { command("player.next") } }.onFailure { e ->
+ if (!heldError(e, base?.restrictions?.canSkipNext != false)) throw e
+ stepIntent(1)
+ }
+ }
+
+ /**
+ * The page refused a skip because of an ad or a reload under way, not because the song
+ * forbids it: "not allowed" counts only when the song's own restrictions allow the skip
+ * (the ad itself is often reported seconds later).
+ */
+ private fun heldError(e: Throwable, allowed: Boolean): Boolean {
+ val m = e.message.orEmpty()
+ return skipsHeld || RELOADING.any { it in m } || (allowed && "not allowed" in m)
+ }
+
override suspend fun previous() {
pausedByUser = false
+ if (skipsHeld) { stepIntent(-1); return }
+ intent = null
withFade {
val s = _state.value
runCatching { command("player.previous") }.onFailure { e ->
+ // Refused because of an ad or a reload: kept for after it, never a seek (that
+ // restarted the ad).
+ if (heldError(e, s?.restrictions?.canSkipPrevious == true)) { stepIntent(-1); return@onFailure }
// Refused by the page (a restriction on the account or the context): the song
// starts over, or the one before plays, as the button would have done.
val pos = s?.positionAt(System.currentTimeMillis()) ?: 0L
@@ -570,7 +963,19 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
private fun ref(item: NowPlaying) = buildJsonObject { put("uri", item.uri); item.uid?.let { put("uid", it) } }
- override suspend fun skipTo(item: NowPlaying) { pausedByUser = false; withFade { command("queue.skipTo", ref(item)) } }
+ /** The last state with a song: a reloading page reports none for a moment. */
+ private fun lastWithSong(): PlayerState? = lastTrackState?.takeIf { it.item != null } ?: lastSong
+
+ override suspend fun skipTo(item: NowPlaying) {
+ pausedByUser = false
+ val base = lastWithSong()
+ if (skipsHeld) { setIntent(base?.contextUri, item, base?.item?.uri); return }
+ if (base?.item?.kind != ItemKind.AD) intent = Intent(base?.contextUri, item, base?.item?.uri, System.currentTimeMillis())
+ runCatching { withFade { command("queue.skipTo", ref(item)) } }.onFailure { e ->
+ if (!heldError(e, base?.restrictions?.canSkipNext != false)) throw e
+ setIntent(base?.contextUri, item, base?.item?.uri)
+ }
+ }
override suspend fun playNext(uris: List<Uri>) {
val first = _queue.value?.queued?.firstOrNull()
@@ -626,12 +1031,26 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
companion object {
/** A refused ad left current that long: the page will not move on by itself. */
const val AD_STUCK_MS = 4_000L
+ /**
+ * An ad mute that old is lifted. The page never reports the end of a break, so a lost
+ * unmute used to leave the phone silent until the app was restarted; longer than any ad
+ * break (15-30 s), shorter than a song.
+ */
+ const val AD_MUTE_MAX_MS = 75_000L
/** A reloaded page reports its restored state within that long. */
const val RESTORE_WAIT_MS = 6_000L
/** A page going away reports "nothing plays" that long before it is gone, at most. */
const val UNLOAD_NULL_MS = 5_000L
/** Errors of a page not able to take a command yet (see [command]). */
- val TRANSIENT = listOf("No such device", "not ready", "page reloaded")
+ val TRANSIENT = listOf("No such device", "not ready", "page reloaded", "local player is disabled")
+ /** Refusals of a page being reloaded: a skip is then held (see [Intent]). */
+ val RELOADING = listOf("local player is disabled", "not ready", "page reloaded")
+ /** A held skip is forgotten after that long (an ad break and a reload fit in it). */
+ const val INTENT_MAX_MS = 90_000L
+ /** The intent is asked for at most that often. */
+ const val INTENT_REPLAY_MS = 4_000L
+ /** Plays of the intent at most, after an ad or a reload. */
+ const val INTENT_PLAYS = 3
const val COMMAND_RETRIES = 3
const val COMMAND_RETRY_MS = 700L
const val READY_WAIT_MS = 30_000L
@@ -657,12 +1076,43 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
const val FADE_STEP_MS = 12L
/** The sound always comes back after that long, whatever the page does. */
const val FADE_BACK_MAX_MS = 2_500L
+ /** Crossfade: the setting's range (seconds, 0 = off). */
+ const val CROSSFADE_MAX_SECONDS = 12
+ /**
+ * Where a crossfade's ramp down ends, as a share of the page player's own level. Not 0:
+ * the page keeps a floor on the element (see [FADE_STEPS]), and a media element set to 0
+ * is paused by Chromium.
+ */
+ const val CROSSFADE_FLOOR = 0.02
+ /** The floor the bridge itself keeps on a media element. */
+ const val CROSSFADE_SILENT = 0.001
+ /** One ramp step per that many ms; the page runs them itself (see [fade]). */
+ private const val CROSSFADE_STEP_MS = 100L
+ /** A 12 s ramp at 100 ms a step; more steps would not be heard. */
+ private const val CROSSFADE_MAX_STEPS = 60
+ /**
+ * How long after the ramp was due the level is put back whatever the page did: a song
+ * that stalled, a state lost in a reload, a repeated track. A volume left down is the
+ * failure a user cannot work around.
+ */
+ const val CROSSFADE_FAILSAFE_MS = 6_000L
+ /** The next song's ramp up: short, it is already playing. Ends on the own level. */
+ val CROSSFADE_IN = listOf(0.2, 0.45, 0.7, 0.9)
+ const val CROSSFADE_IN_STEP_MS = 100L
/** Play commands: the page answers within a few seconds or not at all. */
const val PLAY_TIMEOUT_MS = 10_000L
/** A refusal that long after a play belongs to it. */
const val REFUSED_WINDOW_MS = 5_000L
/** Never two "frozen page" reloads closer than that. */
const val FROZEN_RELOAD_GAP_MS = 60_000L
+ /**
+ * Consecutive silent ticks before the page is called dead and reloaded. One miss is not
+ * enough: a busy main thread looks exactly like a frozen page for a couple of seconds, and
+ * the reload that followed was itself the interruption the user complained about.
+ */
+ private const val FROZEN_MISSES = 2
+ /** Extra ad-mute sends during a break (the media element may appear after the break starts). */
+ private const val AD_MUTE_TRIES = 2
/** The volume is checked every that many ticks. */
const val VOLUME_CHECK_TICKS = 3
/** An ad that plays (silent, muted) is got past after that long. */
@@ -686,9 +1136,22 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
* its end without a new song, when it paused itself at its end with a song after it,
* or while it buffers too long.
*/
+ /**
+ * What a song or episode stuck at its end moves on to: the next playable item. B11: an
+ * episode counts too; with tracks only, an episode stuck at its end found no target and
+ * was played again from 0:00.
+ */
+ fun onwardTarget(s: PlayerState, nextUp: List<NowPlaying>): String? {
+ val playable = { k: ItemKind -> k == ItemKind.TRACK || k == ItemKind.EPISODE }
+ return s.next?.takeIf { playable(it.kind) }?.uri ?: nextUp.firstOrNull { playable(it.kind) }?.uri
+ }
+
fun stallOf(s: PlayerState, now: Long, userPaused: Boolean): String? {
val item = s.item ?: return null
- if (item.kind != ItemKind.TRACK || item.durationMs <= 0) return null
+ // Episodes stall exactly like songs once their duration is known (a podcast playing
+ // silent with a frozen progress bar is the same bug); only ads are left out, their
+ // recovery is [adRecovery].
+ if (item.kind == ItemKind.AD || item.durationMs <= 0) return null
if (s.isPaused) {
val atEnd = s.positionMs >= item.durationMs - 2_000
return if (atEnd && s.next != null && !userPaused) "paused at the end" else null
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyRecents.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyRecents.kt
new file mode 100644
index 00000000..c4351fff
--- /dev/null
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyRecents.kt
@@ -0,0 +1,206 @@
+package app.myspoti.spotify
+
+import app.myspoti.api.MediaKind
+import app.myspoti.api.Page
+import app.myspoti.api.RecentEntry
+import app.myspoti.api.RecentItem
+import app.myspoti.api.Recents
+import app.myspoti.spotify.gql.Gql
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonPrimitive
+import java.time.LocalDate
+import java.time.ZoneId
+import java.util.Base64
+
+/**
+ * The account's "Recently played", read from the Web Player's own list page.
+ *
+ * The app keeps a play counter of its own, but it only knows what this phone played. Spotify
+ * keeps the account's list, so this is the same one the Web Player shows: `recents` with
+ * `uris: ["spotify:list:recents:page"]` (offset, limit) returns a list page like a playlist's.
+ *
+ * Each row also carries a `formatListAttributes` array, and that array holds the grouping the
+ * official page renders: a context row announces `children_group_id: N`, the plays it collected
+ * carry `group_id_N`, `group_metadata` gives the context's play count and content type (music or
+ * not), and `recent_type_saved` marks rows that were added rather than played (Liked Songs).
+ */
+class SpotifyRecents(private val gql: Gql) : Recents {
+ override suspend fun recentEntries(offset: Int, limit: Int): Page<RecentEntry> {
+ val response = gql.query("recents", vars(
+ "uris" to listOf(RECENTS_PAGE),
+ "offset" to offset,
+ "limit" to limit,
+ ))
+ // data.lists[0] is the page itself: {name, uri, items{items[], pagingInfo, totalCount}}.
+ val list = response.list("data.lists").firstOrNull() ?: return Page(emptyList(), offset, 0, null)
+ val rows = list.obj("items") ?: return Page(emptyList(), offset, 0, null)
+ return page(rows, offset, ::recentEntry)
+ }
+
+ private fun recentEntry(row: JsonElement): RecentEntry? {
+ val item = recentItem(row) ?: return null
+ val attributes = row.list("formatListAttributes")
+ val keys = attributes.mapNotNull { it.str("key") }
+ fun value(key: String): String? = attributes.firstOrNull { it.str("key") == key }?.str("value")
+ // The id sits in the key, not in the value (`{"key":"group_id_1","value":""}`), and
+ // group_id_0 is the root of the list: a context row carries it, no play belongs to it.
+ val group = keys.firstNotNullOfOrNull { key ->
+ key.takeIf { it.startsWith("group_id_") }
+ ?.removePrefix("group_id_")
+ ?.takeIf { it != "0" }
+ }
+ val metadata = groupMetadata(value("group_metadata"))
+ return RecentEntry(
+ item = item,
+ childrenGroup = value("children_group_id"),
+ group = group,
+ groupCount = metadata?.count,
+ // Spotify words a saved row "titres ajoutés": the flag is the attribute, not the count.
+ saved = keys.contains("recent_type_saved"),
+ music = when {
+ // The server names the content a row holds; music rows say "music".
+ metadata?.contentType != null -> metadata.contentType == "music"
+ // Any other content_type_* attribute means the row is not music.
+ keys.any { it.startsWith("content_type_") && it != "content_type_music" } -> false
+ else -> item.kind !in PODCAST_KINDS
+ },
+ )
+ }
+
+ private fun recentItem(row: JsonElement): RecentItem? {
+ // A row wraps its entity: `entity.data` is the entity, `entity._uri` repeats its uri.
+ val entity = row.obj("entity") ?: return null
+ val d = entity.obj("data") ?: entity
+ val uri = d.str("uri") ?: entity.str("_uri") ?: return null
+ val identity = d.obj("identityTrait")
+ val title = identity.str("name") ?: d.str("name") ?: return null
+ // identityTrait.type is localised by the server ("Titre", "Playlist", "EP"): it is the
+ // type label the page prints, so it is kept rather than rebuilt from the entity type.
+ val people = identity.list("contributors.items").mapNotNull { it.str("name") }
+ // Artists carry a plain image, not a square cover: without the fallback their rows would
+ // show an empty circle.
+ val square = d.list("visualIdentityTrait.squareCoverImage.image.data.sources")
+ return RecentItem(
+ uri = uri,
+ kind = kindOf(d.str("entityTypeTrait.type"), uri),
+ title = title,
+ subtitle = people.joinToString(", ").ifBlank { null },
+ images = images(square).ifEmpty { images(d.list("visualIdentityTrait.image.data.sources")) },
+ // Durations come in seconds here, unlike the tracks of the other operations.
+ durationMs = (d.long("consumptionExperienceTrait.duration.seconds") ?: 0) * 1000,
+ explicit = d.list("consumptionExperienceTrait.contentRatings")
+ .any { (it as? JsonPrimitive)?.content == "CONTENT_RATING_EXPLICIT" },
+ playedAtMs = playedOn(row.obj("addedAt")),
+ typeLabel = identity.str("type"),
+ )
+ }
+
+ private fun kindOf(entityType: String?, uri: String): MediaKind = when (entityType) {
+ "ENTITY_TYPE_TRACK" -> MediaKind.TRACK
+ "ENTITY_TYPE_ALBUM" -> MediaKind.ALBUM
+ "ENTITY_TYPE_ARTIST" -> MediaKind.ARTIST
+ "ENTITY_TYPE_PLAYLIST" -> MediaKind.PLAYLIST
+ "ENTITY_TYPE_SHOW", "ENTITY_TYPE_PODCAST" -> MediaKind.SHOW
+ "ENTITY_TYPE_EPISODE" -> MediaKind.EPISODE
+ "ENTITY_TYPE_AUDIOBOOK" -> MediaKind.AUDIOBOOK
+ else -> MediaKind.of(uri)
+ }
+
+ /** The row dates the play (`addedAt: {year, month, day}`): a day, with no time of day. */
+ private fun playedOn(node: JsonElement?): Long? {
+ val year = node.int("year") ?: return null
+ val month = node.int("month") ?: return null
+ val day = node.int("day") ?: return null
+ return runCatching {
+ LocalDate.of(year, month, day).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()
+ }.getOrNull()
+ }
+
+ /** What `group_metadata` names: the row's content type ("music") and its play count. */
+ private data class GroupMeta(val contentType: String?, val count: Int?)
+
+ /**
+ * `group_metadata` is a small protobuf blob: `1: index`, `4: {1: content type, 2: plays}`.
+ * Its count is the "N titres lus" the row prints, and it stays right where counting the rows
+ * would not: the last group of a page is cut by the page size.
+ */
+ private fun groupMetadata(base64: String?): GroupMeta? {
+ if (base64.isNullOrBlank()) return null
+ return runCatching {
+ val bytes = Base64.getDecoder().decode(base64)
+ var i = 0
+ var type: String? = null
+ var count: Int? = null
+ while (i < bytes.size) {
+ val tag = bytes[i++].toInt() and 0xFF
+ when (tag and 7) {
+ // Varint field (the index): skipped, it repeats what children_group_id says.
+ 0 -> { while (i < bytes.size && (bytes[i].toInt() and 0x80) != 0) i++; i++ }
+ 2 -> {
+ val length = bytes[i++].toInt() and 0xFF
+ if (tag ushr 3 == 4 && i + length <= bytes.size) {
+ val inner = bytes.copyOfRange(i, i + length)
+ type = innerString(inner)
+ count = innerCount(inner)
+ }
+ i += length
+ }
+ else -> return@runCatching GroupMeta(type, count)
+ }
+ }
+ GroupMeta(type, count)
+ }.getOrNull()
+ }
+
+ /** Field 1 of the inner message: the content type, as plain UTF-8. */
+ private fun innerString(inner: ByteArray): String? {
+ var i = 0
+ while (i < inner.size) {
+ val tag = inner[i++].toInt() and 0xFF
+ when (tag and 7) {
+ 0 -> { while (i < inner.size && (inner[i].toInt() and 0x80) != 0) i++; i++ }
+ 2 -> {
+ val length = inner[i++].toInt() and 0xFF
+ if (tag ushr 3 == 1) return String(inner, i, length)
+ i += length
+ }
+ else -> return null
+ }
+ }
+ return null
+ }
+
+ /** Field 2 of the inner message: the play count. */
+ private fun innerCount(inner: ByteArray): Int? {
+ var i = 0
+ while (i < inner.size) {
+ val tag = inner[i++].toInt() and 0xFF
+ when (tag and 7) {
+ 0 -> {
+ var value = 0
+ var shift = 0
+ while (i < inner.size) {
+ val byte = inner[i++].toInt() and 0xFF
+ value = value or ((byte and 0x7F) shl shift)
+ shift += 7
+ if (byte and 0x80 == 0) break
+ }
+ if (tag ushr 3 == 2) return value
+ }
+ 2 -> {
+ val length = inner[i++].toInt() and 0xFF
+ i += length
+ }
+ else -> return null
+ }
+ }
+ return null
+ }
+
+ private companion object {
+ const val RECENTS_PAGE = "spotify:list:recents:page"
+
+ /** Kinds that never count as music for the page's pills, whatever the attributes say. */
+ val PODCAST_KINDS = setOf(MediaKind.SHOW, MediaKind.EPISODE, MediaKind.AUDIOBOOK, MediaKind.CHAPTER)
+ }
+}
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt
index 2b7b129c..60c16414 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt
@@ -64,9 +64,6 @@ object AdBlock {
/** Paths refused on Spotify's api hosts; none, see [blockedHosts]. */
val blockedPaths = emptyList<String>()
- /** Formats only ads use: the ad mp3 links and the ad manifests. Songs and episodes use others. */
- val adFormats = setOf("manifest_urls_audio_ad", "file_urls_mp3")
-
fun isBlocked(url: String): Boolean {
val rest = url.substringAfter("://")
val host = rest.substringBefore('/').substringBefore('?').substringBefore(':').lowercase()
@@ -76,17 +73,30 @@ object AdBlock {
return blockedPaths.any { path.startsWith(it) }
}
- /** The player's registration (POST track-playback/v1/devices), to rewrite with [withoutAdFormats]. */
+ /** The player's registration (POST track-playback/v1/devices), to rewrite with [withDeviceName]. */
fun isDeviceRegistration(method: String, url: String): Boolean =
method.equals("POST", ignoreCase = true) && url.substringBefore('?').endsWith("/track-playback/v1/devices")
- /** [body] (the registration JSON) without [adFormats] in its manifest formats; unchanged when unreadable. */
- fun withoutAdFormats(body: String): String = runCatching {
- val root = Json.parseToJsonElement(body).jsonObject
- val device = root["device"]?.jsonObject ?: return body
- val caps = device["capabilities"]?.jsonObject ?: return body
- val formats = caps["manifest_formats"]?.jsonArray ?: return body
- val kept = JsonArray(formats.filter { (it as? JsonPrimitive)?.contentOrNull !in adFormats })
- JsonObject(root + ("device" to JsonObject(device + ("capabilities" to JsonObject(caps + ("manifest_formats" to kept)))))).toString()
+ /**
+ * The name the player registers itself under is the name Spotify shows on every other device.
+ * The Web Player's own ("Web Player (Chrome)") is replaced by the name the phone already has,
+ * so this client appears as the phone it runs on; **nothing else is touched** — capabilities,
+ * platform, versions stay byte-for-byte what the real Web Player sends.
+ *
+ * An earlier version also removed `manifest_urls_audio_ad` from the manifest formats, which made
+ * this registration the only one of its kind (the real one declares it twice) and was the prime
+ * suspect for the `402 COMMAND_FAILED` refusals. Ads are blocked at the URL level instead
+ * ([blockedHosts]), not by lying about what this client can play.
+ */
+ fun withDeviceName(body: String, name: String): String = runCatching {
+ val device = Json.parseToJsonElement(body).jsonObject["device"]?.jsonObject ?: return body
+ val raw = device["name"] as? kotlinx.serialization.json.JsonPrimitive ?: return body
+ if (raw is kotlinx.serialization.json.JsonNull) return body
+ val old = raw.content
+ if (old.isBlank() || old == name || name.isBlank()) return body
+ // A plain string swap, not a re-serialisation: the registration keeps its exact shape,
+ // duplicate array entries included.
+ val quoted = name.replace("\\", "\\\\").replace("\"", "\\\"")
+ body.replace("\"$old\"", "\"$quoted\"")
}.getOrDefault(body)
}
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt
index 5a20ded6..b3dbaef8 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt
@@ -70,6 +70,18 @@ class SpotifyHttp(
private val http: OkHttpClient,
private val bridge: Bridge,
private val language: String = "en",
+ /**
+ * The browser this app presents to Spotify, drawn once per install by the host
+ * (`Fingerprint`). Handing every install the same user agent made the whole user base one
+ * profile; null keeps the previous constant.
+ */
+ private val browserUserAgent: String? = null,
+ /**
+ * The id this client announces when it mints its client token. It used to be a fresh UUID at
+ * every launch, so Spotify saw a brand-new client every start (a new client token each time,
+ * one more device). The host passes an id kept across restarts; null keeps the old behaviour.
+ */
+ private val deviceId: String = java.util.UUID.randomUUID().toString(),
) {
private data class WebToken(val access: String, val expiresAtMs: Long, val clientId: String, val appVersion: String, val anonymous: Boolean)
private data class ClientToken(val value: String, val expiresAtMs: Long)
@@ -77,7 +89,6 @@ class SpotifyHttp(
private val lock = Mutex()
private var web: WebToken? = null
private var client: ClientToken? = null
- private val deviceId = UUID.randomUUID().toString()
/** Drops the cached web token (it belongs to one account); the client token is kept. */
suspend fun forgetWebToken() = lock.withLock { web = null }
@@ -115,7 +126,7 @@ class SpotifyHttp(
.header("accept-language", language)
.header("origin", "https://open.spotify.com")
.header("referer", "https://open.spotify.com/")
- .header("user-agent", USER_AGENT)
+ .header("user-agent", browserUserAgent ?: USER_AGENT)
// Bytes keep the content type exactly as given (OkHttp appends a charset to String bodies,
// which some Spotify endpoints reject with 400).
builder.method(method, body?.toByteArray()?.toRequestBody(contentType.toMediaType()) ?: if (method == "GET" || method == "DELETE") null else ByteArray(0).toRequestBody(null))
@@ -160,7 +171,7 @@ class SpotifyHttp(
// Bytes, not a String: OkHttp would append "; charset=utf-8", which this endpoint rejects with 400.
.post(body.toString().toByteArray().toRequestBody("application/json".toMediaType()))
.header("accept", "application/json")
- .header("user-agent", USER_AGENT)
+ .header("user-agent", browserUserAgent ?: USER_AGENT)
.build()
val (code, text) = withContext(Dispatchers.IO) { http.newCall(request).execute().use { it.code to it.body.string() } }
val granted = runCatching { Bridge.json.parseToJsonElement(text).jsonObject["granted_token"]?.jsonObject }.getOrNull()
diff --git a/base/api-spotify/src/main/resources/bridge/player-bridge.js b/base/api-spotify/src/main/resources/bridge/player-bridge.js
index 6ca06f48..113b7537 100644
--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js
+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js
@@ -214,6 +214,12 @@
// Not heard, yet not "muted audio" to Chromium (see 'media.mute').
const SILENT = 0.001;
+ // A fade is a list of setTimeout steps: a second fade, a plain volume set or a mute must
+ // cancel the pending ones, or they would override it seconds later (the up-ramp of a
+ // crossfade undone by the tail of its own down-ramp, a restored volume pulled down again).
+ let fadeTimers = [];
+ const cancelFade = () => { fadeTimers.forEach(clearTimeout); fadeTimers = []; };
+
// "Is this page Spotify Connect's active device": a full device-list round trip, so it is
// read at most once every ACTIVE_CACHE_MS and reused (a transfer happens minutes apart).
const ACTIVE_CACHE_MS = 6000;
@@ -242,8 +248,55 @@
return services;
};
+ // --- ads ------------------------------------------------------------------
+ // The page's own ad managers drive the audio ads and their mute. SpotX patches the bundled
+ // web player to force `adsEnabled` off; the very same managers are reachable at runtime through
+ // the service registry, so they are turned off here instead of patching a bundle we do not ship.
+ //
+ // `disable` alone is not enough: the page re-arms its managers at every ad opportunity (a
+ // "Test ad" still came through on a free account, 19/10 02:29). `enable`/`disable` sit on the
+ // prototype and `enabled` is a plain field, so the instance is shadowed here: after this, the
+ // page cannot arm an ad again for the life of the page.
+ let adsLatched = false;
+ const adsOff = () => {
+ if (!services) return 'not ready';
+ if (adsLatched) return 'already off';
+ let audio = null;
+ try { audio = services.resolve('AdManagers').audio; } catch (e) { return 'unresolved'; }
+ if (!audio) return 'no ad manager';
+ const done = [];
+ for (const [label, mgr] of [['audio', audio], ['inStream', audio.inStreamApi]]) {
+ if (!mgr) continue;
+ try {
+ if (typeof mgr.disable === 'function') { mgr.disable(); done.push(label); }
+ // The page's own `enable` is replaced on the instance: it can only ever answer "not on".
+ if (typeof mgr.enable === 'function') {
+ Object.defineProperty(mgr, 'enable', { value: () => false, writable: true, configurable: true });
+ }
+ if ('enabled' in mgr) mgr.enabled = false;
+ } catch (e) { /* already off */ }
+ }
+ return done.length ? (adsLatched = true, done.join(',')) : 'nothing to disable';
+ };
+
+ /**
+ * Ends the ad the in-stream ad manager owns, its own way (a skip of the ad break, not of the
+ * song). The app asks for this before it falls back to reloading the page, which is what a
+ * "Test ad" used to cost: a visible reload of the whole player.
+ */
+ const adsSkip = () => {
+ if (!services) return 'not ready';
+ try {
+ const api = services.resolve('AdManagers').audio.inStreamApi;
+ if (api && typeof api.skipToNext === 'function') { api.skipToNext(); return 'inStream.skipToNext'; }
+ } catch (e) { return 'failed: ' + e; }
+ return 'no lever';
+ };
+
const commands = {
'bridge.version': () => VERSION,
+ 'ads.off': () => adsOff(),
+ 'ads.skip': () => adsSkip(),
'player.state': () => mapState(need().player.getState()),
'player.queue': () => mapQueue(need().player.getQueue()),
@@ -320,6 +373,7 @@
// new song, a restart, a seek) muted or at volume 0, and the song after the ad stayed
// paused. A volume of SILENT is not heard and keeps playback going.
'media.mute': async a => {
+ cancelFade();
window.__mspMuted = !!a.on;
const player = await localPlayer().catch(() => null);
const els = new Set([...(window.__mspMedia || []), ...document.querySelectorAll('audio, video'), ...await playerMedia()]);
@@ -352,6 +406,7 @@
const player = await localPlayer();
const el = player && player._player;
if (!(el instanceof HTMLMediaElement)) return null;
+ cancelFade();
// Never 0: see 'media.mute'.
el.volume = a.restore ? ownLevel(player) : Math.min(1, Math.max(SILENT, Number(a.level) || 0));
return el.volume;
@@ -367,8 +422,11 @@
const steps = (Array.isArray(a.steps) ? a.steps : []).map(Number);
const per = Math.max(1, Number(a.ms) || 12);
const set = v => { el.volume = Math.min(1, Math.max(SILENT, v)); };
- steps.forEach((v, i) => setTimeout(() => set(v), i * per));
- if (a.restore) setTimeout(() => { el.volume = ownLevel(player); }, steps.length * per);
+ // A ramp replaces the one before it (a crossfade's up-ramp must not be pulled back down
+ // by steps still pending from its down-ramp).
+ cancelFade();
+ fadeTimers = steps.map((v, i) => setTimeout(() => set(v), i * per));
+ if (a.restore) fadeTimers.push(setTimeout(() => { el.volume = ownLevel(player); }, steps.length * per));
return true;
},
@@ -454,6 +512,8 @@
const pushState = () => {
if (!services) return;
const state = mapState(services.player.getState());
+ // An ad is on: the page's ad managers are turned off again (it re-arms them per break).
+ if (state && state.track && state.track.kind === 'ad') { try { adsOff(); } catch (e) { /* no service */ } }
const json = JSON.stringify(state);
if (json === lastState) return;
lastState = json;
@@ -468,6 +528,8 @@
const events = services.player.getEvents();
events.addListener('update', pushState);
events.addListener('queue_update', pushQueue);
+ // Ads off from the first moment: a break queued before the bridge attached never starts.
+ try { adsOff(); } catch (e) { /* no service yet */ }
};
// --- boot -----------------------------------------------------------------
@@ -494,7 +556,7 @@
pushState();
};
- window.Myspoti = { version: VERSION, call, announce, methods: Object.keys(commands) };
+ window.Myspoti = { version: VERSION, call, announce, adsOff, adsSkip, methods: Object.keys(commands) };
// The page's own UI is never seen. On the home page a song change redraws ~7000 nodes and
// ~190 images, which held the main thread for ~1 s and delayed the next song's sound; the
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/PlayerStartTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/PlayerStartTest.kt
new file mode 100644
index 00000000..174026d5
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/PlayerStartTest.kt
@@ -0,0 +1,30 @@
+package app.myspoti.spotify
+
+import app.myspoti.spotify.bridge.Bridge
+import app.myspoti.spotify.bridge.BridgeHost
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.flow.MutableSharedFlow
+import org.junit.jupiter.api.Test
+
+/** The app builds the player on the main dispatcher, whose coroutines start at once. */
+class PlayerStartTest {
+ private class SilentHost : BridgeHost {
+ override val messages = MutableSharedFlow<String>()
+ override suspend fun evaluate(script: String) {}
+ }
+
+ @Test fun `the player starts on a dispatcher that runs its coroutines at once`() {
+ val failures = mutableListOf<Throwable>()
+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined +
+ kotlinx.coroutines.CoroutineExceptionHandler { _, e -> failures += e })
+ try {
+ SpotifyPlayer(Bridge(SilentHost(), scope), scope)
+ if (failures.isNotEmpty()) throw failures.first()
+ } finally {
+ scope.cancel()
+ }
+ }
+}
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyWritesTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyWritesTest.kt
index 13fe2edf..db392e00 100644
--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyWritesTest.kt
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyWritesTest.kt
@@ -81,7 +81,7 @@ class SpotifyWritesTest {
}
@Test fun `saving an episode uses the listenlater set that savedEpisodes reads`() = runBridge({ JsonNull }) { host, bridge ->
- val podcasts = SpotifyPodcasts(FakeGql { _, _ -> JsonNull }, bridge)
+ val podcasts = SpotifyPodcasts(FakeGql { _, _ -> JsonNull }, bridge, SpotifyHttp(OkHttpClient(), bridge))
podcasts.setEpisodeSaved("spotify:episode:e", true)
podcasts.setEpisodeSaved("spotify:episode:e", false)
assertEquals(listOf("add", "remove"), host.calls.map { it.method() })
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt
index 85681b8b..9648510a 100644
--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt
@@ -26,6 +26,17 @@ class StallTest {
@Test fun `buffering for long`() = assertEquals("buffering", SpotifyPlayer.stallOf(state(0, 0, buffering = true), 20_000, false))
@Test fun `buffering a moment`() = assertNull(SpotifyPlayer.stallOf(state(0, 0, buffering = true), 5_000, false))
+ private val episode = song.copy(kind = ItemKind.EPISODE, uri = "spotify:episode:e", name = "E")
+ private val nextEpisode = episode.copy(uri = "spotify:episode:f", name = "F")
+ private val ad = song.copy(kind = ItemKind.AD, uri = "spotify:ad:x")
+
+ @Test fun `a song at its end moves on to the next song`() = assertEquals(after.uri, SpotifyPlayer.onwardTarget(state(199_500, 0), emptyList()))
+ @Test fun `an episode at its end moves on to the next episode`() =
+ assertEquals(nextEpisode.uri, SpotifyPlayer.onwardTarget(state(199_500, 0, next = nextEpisode).copy(item = episode), emptyList()))
+ @Test fun `the queue is read when the state names no next item`() =
+ assertEquals(nextEpisode.uri, SpotifyPlayer.onwardTarget(state(199_500, 0, next = null).copy(item = episode), listOf(ad, nextEpisode)))
+ @Test fun `an ad is never a target`() = assertNull(SpotifyPlayer.onwardTarget(state(199_500, 0, next = ad), listOf(ad)))
+
@Test fun `a stuck ad is skipped twice, then the page reloads`() {
assertEquals("next", SpotifyPlayer.adRecovery(1))
assertEquals("next", SpotifyPlayer.adRecovery(2))
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdFormatsTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdFormatsTest.kt
deleted file mode 100644
index 3e511413..00000000
--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdFormatsTest.kt
+++ /dev/null
@@ -1,27 +0,0 @@
-package app.myspoti.spotify.bridge
-
-import org.junit.jupiter.api.Assertions.assertEquals
-import org.junit.jupiter.api.Assertions.assertFalse
-import org.junit.jupiter.api.Assertions.assertTrue
-import org.junit.jupiter.api.Test
-
-class AdFormatsTest {
- private val registration = """{"device":{"brand":"spotify","capabilities":{"change_volume":true,"manifest_formats":["file_ids_mp3","file_urls_mp3","manifest_urls_audio_ad","manifest_ids_video","file_urls_external","file_ids_mp4","file_ids_mp4_dual","manifest_urls_audio_ad"]},"device_id":"x"},"volume":65535}"""
-
- @Test fun `registration loses the ad formats only`() {
- val out = AdBlock.withoutAdFormats(registration)
- assertTrue(""""manifest_formats":["file_ids_mp3","manifest_ids_video","file_urls_external","file_ids_mp4","file_ids_mp4_dual"]""" in out, out)
- assertTrue(""""device_id":"x"""" in out && """"volume":65535""" in out)
- }
-
- @Test fun `other bodies stay as they are`() {
- assertEquals("not json", AdBlock.withoutAdFormats("not json"))
- assertEquals("""{"seq_num":2}""", AdBlock.withoutAdFormats("""{"seq_num":2}"""))
- }
-
- @Test fun `only the registration is rewritten`() {
- assertTrue(AdBlock.isDeviceRegistration("POST", "https://gew4-spclient.spotify.com/track-playback/v1/devices"))
- assertFalse(AdBlock.isDeviceRegistration("PUT", "https://gew4-spclient.spotify.com/track-playback/v1/devices/abc/state"))
- assertFalse(AdBlock.isDeviceRegistration("POST", "https://gew4-spclient.spotify.com/track-playback/v1/devices/abc/state"))
- }
-}
diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/DeviceRegistrationTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/DeviceRegistrationTest.kt
new file mode 100644
index 00000000..50386496
--- /dev/null
+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/DeviceRegistrationTest.kt
@@ -0,0 +1,72 @@
+package app.myspoti.spotify.bridge
+
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.Test
+
+/**
+ * The device registration is the one request where this client tells Spotify what it is. It must
+ * stay byte-for-byte what the real Web Player sends — the capabilities in particular: a device that
+ * declares fewer formats is the only one of its kind (and the prime suspect for the 402 refusals
+ * some accounts get). Only the display name changes, so the phone appears as the phone it is.
+ */
+class DeviceRegistrationTest {
+ // The real payload, as captured from the Web Player: note `manifest_urls_audio_ad` twice.
+ private val registration = """
+ {"device":{"brand":"spotify","capabilities":{"change_volume":true,"enable_play_token":true,
+ "supports_file_media_type":true,"play_token_lost_behavior":"pause","disable_connect":false,
+ "audio_podcasts":true,"video_playback":true,"manifest_formats":["file_ids_mp3","file_urls_mp3",
+ "manifest_urls_audio_ad","manifest_ids_video","file_urls_external","file_ids_mp4","file_ids_mp4_dual",
+ "manifest_urls_audio_ad"],"supports_preferred_media_type":true,"supports_playback_offsets":true,
+ "supports_playback_speed":true},"device_id":"x","device_type":"computer","metadata":{},
+ "model":"web_player","name":"Web Player (Chrome)",
+ "platform_identifier":"web_player linux undefined;chrome 155.0.0.0;desktop","is_group":false,
+ "is_public":false},"client_version":"harmony:4.81.1-1f3d48b7f","volume":65535}
+ """.trimIndent()
+
+ @Test fun `the device name becomes the phone's own`() {
+ val out = AdBlock.withDeviceName(registration, "Test Phone")
+ assertTrue(""""name":"Test Phone"""" in out, out)
+ assertFalse("Web Player (Chrome)" in out, out)
+ }
+
+ @Test fun `nothing else in the registration changes`() {
+ val out = AdBlock.withDeviceName(registration, "Test Phone")
+ // The capability list is the Web Player's own, duplicate entry included: it is the shape
+ // every other client has, and lying about it is what stood out.
+ assertTrue("\"manifest_urls_audio_ad\",\"manifest_ids_video\"" in out, out)
+ assertEquals(2, Regex("manifest_urls_audio_ad").findAll(out).count(), out)
+ assertTrue(""""model":"web_player"""" in out && """"device_type":"computer"""" in out, out)
+ assertTrue(""""platform_identifier":"web_player linux undefined;chrome 155.0.0.0;desktop"""" in out, out)
+ assertTrue(""""client_version":"harmony:4.81.1-1f3d48b7f"""" in out && """"volume":65535""" in out, out)
+ // Same length apart from the name: nothing was re-serialised.
+ assertEquals(registration.length - "Web Player (Chrome)".length + "Test Phone".length, out.length, out)
+ }
+
+ @Test fun `a name with quotes is escaped, an empty one changes nothing`() {
+ val tricky = AdBlock.withDeviceName(registration, "The \"Test\" Phone")
+ val expected = "\"name\":\"The \\\"Test\\\" Phone\""
+ assertTrue(expected in tricky, tricky)
+ assertEquals(registration, AdBlock.withDeviceName(registration, ""))
+ assertEquals(registration, AdBlock.withDeviceName(registration, "Web Player (Chrome)"))
+ }
+
+ @Test fun `other bodies stay as they are`() {
+ assertEquals("not json", AdBlock.withDeviceName("not json", "Test Phone"))
+ assertEquals("""{"seq_num":2}""", AdBlock.withDeviceName("""{"seq_num":2}""", "Test Phone"))
+ }
+
+ @Test fun `only the registration is rewritten`() {
+ assertTrue(AdBlock.isDeviceRegistration("POST", "https://gew4-spclient.spotify.com/track-playback/v1/devices"))
+ assertFalse(AdBlock.isDeviceRegistration("PUT", "https://gew4-spclient.spotify.com/track-playback/v1/devices/abc/state"))
+ assertFalse(AdBlock.isDeviceRegistration("POST", "https://gew4-spclient.spotify.com/track-playback/v1/devices/abc/state"))
+ }
+
+ @Test fun `the ad hosts are still refused`() {
+ assertTrue(AdBlock.isBlocked("https://adstudio-assets.scdn.co/audio/ad.mp3"))
+ assertTrue(AdBlock.isBlocked("https://pubads.g.doubleclick.net/gampad/ads"))
+ assertFalse(AdBlock.isBlocked("https://audio-fa.scdn.co/audio/abc"))
+ assertFalse(AdBlock.isBlocked("https://gew4-spclient.spotify.com/track-playback/v1/devices"))
+ }
+}
diff --git a/base/api/src/main/kotlin/app/myspoti/api/Api.kt b/base/api/src/main/kotlin/app/myspoti/api/Api.kt
index 98435218..8cf32129 100644
--- a/base/api/src/main/kotlin/app/myspoti/api/Api.kt
+++ b/base/api/src/main/kotlin/app/myspoti/api/Api.kt
@@ -16,6 +16,8 @@ interface MyspotiApi {
val extras: TrackExtras
val devices: Devices
val jam: Jam
+ /** The account's "Recently played", as Spotify's own list has it. */
+ val recents: Recents
/** False until the playback engine is ready to take commands. */
val ready: StateFlow<Boolean>
@@ -166,6 +168,14 @@ interface Home {
interface Podcasts {
suspend fun show(uri: Uri): Show
+ /**
+ * The episode's audio, resolved right before a download (the links are signed and expire).
+ *
+ * Spotify serves its own copy only as a Widevine-encrypted MP4; the clear file we can play
+ * offline is the publisher's own upload ("passthrough"). It does not exist for
+ * Spotify-exclusive shows, which report [EpisodeAudio.passthrough] = "NONE".
+ */
+ suspend fun audioUrl(uri: Uri): EpisodeAudio
suspend fun episodes(uri: Uri, offset: Int = 0, limit: Int = 50): Page<Episode>
suspend fun episode(uri: Uri): Episode
suspend fun audiobook(uri: Uri): Audiobook
@@ -228,3 +238,12 @@ interface Jam {
suspend fun setQueueOnly(on: Boolean)
suspend fun setParticipantVolumeControl(on: Boolean)
}
+
+interface Recents {
+ /**
+ * What the account played lately, newest first, as the Web Player lists it: context rows
+ * (playlists, albums, artists, shows) followed by the plays they collected, with the group
+ * keys the page regroups them by (see [groupRecents]).
+ */
+ suspend fun recentEntries(offset: Int = 0, limit: Int = 50): Page<RecentEntry>
+}
diff --git a/base/api/src/main/kotlin/app/myspoti/api/Media.kt b/base/api/src/main/kotlin/app/myspoti/api/Media.kt
index e617f76e..f5d1ac52 100644
--- a/base/api/src/main/kotlin/app/myspoti/api/Media.kt
+++ b/base/api/src/main/kotlin/app/myspoti/api/Media.kt
@@ -36,6 +36,30 @@ data class MediaCard(
val images: List<Image>,
)
+/**
+ * One row of the account's "Recently played", as the Web Player's own list returns it: a track
+ * or a context (playlist, album, artist, show) that was played. Spotify keeps the list, so it
+ * covers every device of the account; the app's own play counter does not.
+ */
+data class RecentItem(
+ val uri: Uri,
+ val kind: MediaKind,
+ val title: String,
+ /** The artists (or the playlist's owner), when the server says. */
+ val subtitle: String?,
+ val images: List<Image>,
+ val durationMs: Long = 0,
+ val explicit: Boolean = false,
+ /** The play's day (epoch ms, local midnight): the list dates its rows, it does not time them. */
+ val playedAtMs: Long? = null,
+ /**
+ * The server's own type word for the entity ("EP", "Playlist", "Artiste"), localised with the
+ * account's language: the recents page prints it between the play count and the creators,
+ * which a [MediaKind] alone cannot say (an EP is an album).
+ */
+ val typeLabel: String? = null,
+)
+
data class Shelf(val uri: Uri?, val title: String?, val items: List<MediaCard>, val total: Int)
// --- Home and browse ---------------------------------------------------------
@@ -126,6 +150,23 @@ data class Episode(
val previewUrl: String?,
)
+/**
+ * A podcast episode's audio, as the Web Player resolves it (soundfinder REST endpoint).
+ *
+ * [url] is the publisher's own file — clear MP3/M4A, no DRM — when Spotify exposes one.
+ * It is null for Spotify-exclusive shows, whose only copy is Widevine-encrypted.
+ */
+data class EpisodeAudio(
+ val url: String?,
+ /** "ALLOWED", "MANDATORY" or "NONE": whether the publisher's file exists. */
+ val passthrough: String,
+ /** Spotify's copy format ("MP4_128", "DO_NOT_USE"…); diagnostic only. */
+ val format: String,
+) {
+ /** A clear file we can store and play ourselves. */
+ val downloadable: Boolean get() = !url.isNullOrBlank() && !passthrough.equals("NONE", ignoreCase = true)
+}
+
data class Audiobook(
val uri: Uri,
val name: String,
diff --git a/base/api/src/main/kotlin/app/myspoti/api/Models.kt b/base/api/src/main/kotlin/app/myspoti/api/Models.kt
index fb026997..f2f7193b 100644
--- a/base/api/src/main/kotlin/app/myspoti/api/Models.kt
+++ b/base/api/src/main/kotlin/app/myspoti/api/Models.kt
@@ -115,6 +115,13 @@ data class NowPlaying(
val explicit: Boolean = false,
/** Where the player took this item from ("context", "queue", "autoplay"...), when it says. */
val provider: String? = null,
+ /**
+ * The item's media kind as the page reports it ("audio", "video"). A **video** ad never
+ * reports a position or a speed the way an audio one does, so the recovery has to treat it as
+ * playing (see the ad branch of the stall watcher) instead of waiting for a state that never
+ * comes.
+ */
+ val mediaType: String? = null,
)
data class PlayerRestrictions(
diff --git a/base/api/src/main/kotlin/app/myspoti/api/Recents.kt b/base/api/src/main/kotlin/app/myspoti/api/Recents.kt
new file mode 100644
index 00000000..45db6b81
--- /dev/null
+++ b/base/api/src/main/kotlin/app/myspoti/api/Recents.kt
@@ -0,0 +1,120 @@
+package app.myspoti.api
+
+/**
+ * One row of the account's recents list, with the group keys Spotify sends beside it.
+ *
+ * The list is not flat. The row of a context (an album, a playlist, an artist, a show) announces
+ * `children_group_id: N`, and every following row that was played from it carries `group_id_N`.
+ * Those two keys are the whole grouping — they are what says which plays belong under which
+ * context, and they are why the page must not guess a play's container from its album: a playlist
+ * plays other albums' tracks, and the list still files them under the playlist.
+ */
+data class RecentEntry(
+ val item: RecentItem,
+ /** On a context row: the group id its plays carry. */
+ val childrenGroup: String? = null,
+ /** On a play row: the group it was played from. */
+ val group: String? = null,
+ /** A context row's own count (`group_metadata`): how many plays it collected. */
+ val groupCount: Int? = null,
+ /** Saved rather than played (Liked Songs): the page says "titres ajoutés", not "lus". */
+ val saved: Boolean = false,
+ /** Music, or a podcast/audiobook: what the two pills of the page split on. */
+ val music: Boolean = true,
+)
+
+/** A context and the plays it collected: one row of the "Récents" page. */
+data class RecentGroup(
+ /** The context row itself: its uri opens the page, its cover and type fill the row. */
+ val context: RecentItem,
+ /** How many plays are counted for the row ("N titres lus"). */
+ val count: Int,
+ val saved: Boolean,
+ val music: Boolean,
+ /** The plays, newest first: the row expands to them. */
+ val plays: List<RecentItem>,
+ /** The day the row sits under (epoch ms, local midnight), from its newest play. */
+ val dayMs: Long?,
+)
+
+/** One date heading ("Aujourd'hui", "Hier", …) and its rows, newest first. */
+data class RecentSection(val dayMs: Long?, val groups: List<RecentGroup>)
+
+/**
+ * Rebuilds the page's rows from the list's raw order.
+ *
+ * Two rules, both taken from the real response:
+ * - a context row opens a group, and the rows tagged with the id it announced fill it;
+ * - a context played on several days is one row, not one per day: the "Classical Bangers" group
+ * of 1 play today and of 8 plays yesterday were a single "9 titres lus" row under the newest
+ * day. Merging on the context uri is what reproduces that, so the same playlist never appears
+ * twice on the page.
+ *
+ * A play row whose group no context announced (a page that starts mid-group) and any row without
+ * group keys stay their own row: nothing the server sent is dropped.
+ */
+fun groupRecents(entries: List<RecentEntry>): List<RecentSection> {
+ val rows = mutableListOf<RecentGroup>()
+ var openContext: RecentEntry? = null
+ var openGroup: String? = null
+ var openPlays = mutableListOf<RecentItem>()
+
+ fun closeOpen() {
+ val context = openContext ?: return
+ // The server's count wins when it is larger: the last group of a page is often cut by the
+ // page size, and its own count still names the plays it really holds.
+ val count = maxOf(context.groupCount ?: 0, openPlays.size)
+ rows += RecentGroup(
+ context = context.item,
+ count = count.coerceAtLeast(1),
+ saved = context.saved,
+ music = context.music,
+ plays = openPlays.toList(),
+ dayMs = context.item.playedAtMs,
+ )
+ openContext = null
+ openGroup = null
+ openPlays = mutableListOf()
+ }
+
+ for (entry in entries) {
+ val children = entry.childrenGroup
+ if (children != null) {
+ closeOpen()
+ openContext = entry
+ openGroup = children
+ continue
+ }
+ val group = entry.group
+ if (group != null && group == openGroup) {
+ openPlays += entry.item
+ continue
+ }
+ // No group key at all: the server gave this row on its own, so it is its own row.
+ if (group == null) {
+ closeOpen()
+ rows += RecentGroup(
+ context = entry.item,
+ count = 1,
+ saved = entry.saved,
+ music = entry.music,
+ plays = listOf(entry.item),
+ dayMs = entry.item.playedAtMs,
+ )
+ }
+ }
+ closeOpen()
+
+ val merged = LinkedHashMap<String, RecentGroup>()
+ for (row in rows) {
+ val seen = merged[row.context.uri]
+ merged[row.context.uri] = if (seen == null) row else seen.copy(
+ count = seen.count + row.count,
+ // A track played twice keeps one entry in the expansion: the row is a context, not a
+ // play log, and the same uri twice under one row reads as a duplicate.
+ plays = seen.plays + row.plays.filter { play -> seen.plays.none { it.uri == play.uri } },
+ )
+ }
+ // groupBy keeps the insertion order, which is the list's own (newest first).
+ return merged.values.groupBy { it.dayMs }.map { (day, groups) -> RecentSection(day, groups) }
+}
diff --git a/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.kt b/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.kt
index f78b09e0..307b3db0 100644
--- a/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.kt
+++ b/base/app/src/debug/java/com/music/spotui/di/TestControlReceiver.kt
@@ -4,24 +4,57 @@ import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
+import kotlinx.coroutines.launch
+import kotlinx.serialization.json.jsonObject
/**
* Debug builds only: the playback test (tools/playback_test.py) sends the app's own
* commands, as a tap would, with
* `adb shell am broadcast -a app.myspoti.TEST -p app.myspoti.dev --es cmd <cmd> ...`.
* cmd: play (--es track <uri> --es context <uri>), resume, pause, next, previous, seek (--el ms <n>).
+ * cmd: screenon (--ez on false to release) holds the screen on for a long run: One UI does not
+ * honour the huge `screen_off_timeout` set over adb, the window flag does.
+ * cmd: gql (--es op <operation> --es vars <json>) runs a persisted operation through the app's own
+ * Gql layer and logs the raw response: learning a server shape from the phone's real account beats
+ * guessing one from a bundle.
*/
class TestControlReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val cmd = intent.getStringExtra("cmd").orEmpty()
Log.i("MspPlayer", "test command $cmd")
when (cmd) {
+ "gql" -> {
+ val op = intent.getStringExtra("op").orEmpty()
+ val variables = intent.getStringExtra("vars").orEmpty().ifBlank { "{}" }
+ app.myspoti.host.android.MyspotiRuntime.scope.launch {
+ runCatching {
+ app.myspoti.host.android.MyspotiRuntime.spotify.raw.gql(
+ op,
+ app.myspoti.spotify.bridge.Bridge.json.parseToJsonElement(variables).jsonObject,
+ )
+ }.onSuccess { Log.i("MspPlayer", "gql $op vars=$variables -> ${it.toString().take(4000)}") }
+ .onFailure { Log.i("MspPlayer", "gql $op vars=$variables failed: $it") }
+ }
+ }
"play" -> SongPlayer.playSong(intent.getStringExtra("track").orEmpty(), contextUri = intent.getStringExtra("context"))
"resume" -> SongPlayer.play()
"pause" -> SongPlayer.pause()
"next" -> SongPlayer.next()
"previous" -> SongPlayer.previous()
"seek" -> SongPlayer.seekTo(intent.getLongExtra("ms", 0L))
+ "screenon" -> context.getSharedPreferences("myspoti_prefs", Context.MODE_PRIVATE)
+ .edit().putBoolean("keep_screen_on", intent.getBooleanExtra("on", true)).apply()
+ // Debug builds: the same report the Settings row writes, so an unattended run can check
+ // that the export really produces a readable file (and where it lands).
+ "diagnose" -> runCatching {
+ val file = app.myspoti.host.android.Logbook.export(context)
+ Log.i("MspPlayer", "diagnostic report: ${file.absolutePath} (${file.length()} bytes)")
+ }.onFailure { Log.i("MspPlayer", "diagnostic report failed: $it") }
+ // Debug: how many local audio files the app would list (Local Files check without the UI).
+ "localfiles" -> Thread {
+ val n = runCatching { kotlinx.coroutines.runBlocking { com.music.spotui.data.local.LocalMusic.tracks(context, refresh = true).size } }
+ Log.i("MspPlayer", "local files: ${n.getOrElse { "failed: $it" }} track(s)")
+ }.start()
}
}
}
diff --git a/base/app/src/main/java/app/myspoti/MainActivity.kt b/base/app/src/main/java/app/myspoti/MainActivity.kt
index 2ff58859..8dcf0dbe 100644
--- a/base/app/src/main/java/app/myspoti/MainActivity.kt
+++ b/base/app/src/main/java/app/myspoti/MainActivity.kt
@@ -28,6 +28,16 @@ import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
+/** Logcat tag, the host's own: playback and session land in one stream (`adb logcat -s Myspoti`). */
+private const val LOG = "Myspoti"
+
+/**
+ * How long the player page is given to prove the session (a non-anonymous token) once it comes back.
+ * The sign-in page stays in front while this runs — the address alone is never taken for a session —
+ * and only a real token hands the screen to the player (see [MainActivity.watchLoginReturn]).
+ */
+private const val SESSION_WAIT_MS = 6_000L
+
/**
* The app's only screen host: the Compose UI, with the Web Player page attached behind it.
* The page comes to the front only to sign in, on Spotify's own login pages.
@@ -38,6 +48,8 @@ class MainActivity : AppCompatActivity() {
private var showingLogin by mutableStateOf(false)
/** Back from Spotify's login, waiting for the session: a native loading screen, not the web page. */
private var connecting by mutableStateOf(false)
+ /** A pending wait for the session to prove itself after the login page came back. */
+ private var loginWait: kotlinx.coroutines.Job? = null
/** The one-time setup screen (permissions, battery) after signing in. */
private var setupNeeded by mutableStateOf(false)
/** SpotiFLAC verification, opened from the setup screen or the settings. */
@@ -105,6 +117,10 @@ class MainActivity : AppCompatActivity() {
override fun onStart() {
super.onStart()
com.music.spotui.video.MusicVideoController.onForeground()
+ // Asked for over adb (TestControlReceiver's "screenon"): One UI ignores the huge
+ // `screen_off_timeout`, so a long unattended run holds the screen on from in here.
+ if (prefs.getBoolean("keep_screen_on", false)) window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ else window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
override fun onStop() {
@@ -145,19 +161,64 @@ class MainActivity : AppCompatActivity() {
}
}
- /** Spotify sent the user back to the player: hide the page now, the session follows. */
+ /**
+ * Spotify sent the user back to the player: the page is hidden now, the session follows.
+ *
+ * The address is not a session. The page comes back to open.spotify.com while its token is
+ * still anonymous when the login never finished (the e-mail step that hangs — the reported
+ * "stuck on the e-mail screen"), and hiding the page on that alone left a spinner that never
+ * stopped. The return is bounded: no token after [SESSION_WAIT_MS], the login page comes back.
+ */
private fun watchLoginReturn() {
lifecycleScope.launch {
MyspotiRuntime.host.url.collect { url ->
val backOnPlayer = url.startsWith("https://open.spotify.com") && !url.contains("/login")
- if (showingLogin && backOnPlayer) {
- hideLogin()
- if (!signedIn) connecting = true
+ if (!(showingLogin && backOnPlayer)) return@collect
+ // The address is not a session — and it comes back to open.spotify.com as soon as the
+ // user leaves the app to read the sign-in e-mail. Hiding the page here showed an
+ // anonymous player: an app that looked signed in with nothing playable (reported).
+ // The login page therefore stays in FRONT until a real token exists.
+ loginWait?.cancel()
+ loginWait = launch {
+ var waited = 0L
+ while (waited < SESSION_WAIT_MS) {
+ if (runCatching { MyspotiRuntime.isSignedIn() }.getOrDefault(false)) {
+ android.util.Log.d(LOG, "session established: player shown")
+ hideLogin()
+ return@launch
+ }
+ // The countdown only runs while the user is looking at the app: away to read
+ // the e-mail, the sign-in page must not be reset under them.
+ if (lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) waited += 500
+ kotlinx.coroutines.delay(500)
+ }
+ android.util.Log.d(LOG, "no session ${SESSION_WAIT_MS / 1000}s after the player came back: sign-in page restored")
+ // The page may now be the anonymous player: send it back to the e-mail step so the
+ // user is not left where nothing plays.
+ if (!showingLogin) showLogin() else MyspotiRuntime.host.openLogin()
}
}
}
}
+ /**
+ * Back from the e-mail app: the session may have been established while away, or the page may
+ * have reloaded into the anonymous player. Only the token decides — never the address.
+ */
+ override fun onResume() {
+ super.onResume()
+ if (!showingLogin) return
+ lifecycleScope.launch {
+ if (MyspotiRuntime.awaitSignedIn(1_500)) {
+ android.util.Log.d(LOG, "back with a session: player shown")
+ hideLogin()
+ } else if (MyspotiRuntime.host.url.value.let { it.startsWith("https://open.spotify.com") && !it.contains("/login") }) {
+ android.util.Log.d(LOG, "back without a session: sign-in page restored")
+ MyspotiRuntime.host.openLogin()
+ }
+ }
+ }
+
/**
* Signed in = the Web Player is ready with a user token. A Spotify login page while
* signed in (expired session) brings the page back to the front.
@@ -188,6 +249,16 @@ class MainActivity : AppCompatActivity() {
}
connecting = false
if (showingLogin) hideLogin()
+ } else if (signedIn) {
+ // The pref said "signed in", the token says anonymous: only the token
+ // counts. This is what left the app on its full UI (or on Spotify's
+ // anonymous page) with nothing playable — reported after leaving the app
+ // to read the sign-in e-mail, where the session never completed.
+ android.util.Log.d(LOG, "anonymous token while the app thought it was signed in: back to the sign-in page")
+ prefs.edit().putBoolean("LoggedIn", false).apply()
+ signedIn = false
+ connecting = false
+ showLogin()
}
}
}
diff --git a/base/app/src/main/java/com/music/spotui/App.kt b/base/app/src/main/java/com/music/spotui/App.kt
index 3a4310a3..2c11d7a7 100644
--- a/base/app/src/main/java/com/music/spotui/App.kt
+++ b/base/app/src/main/java/com/music/spotui/App.kt
@@ -73,6 +73,12 @@ fun App() {
/** The update card is on screen: the donation reminder waits for another launch. */
private val updateCardOpen = mutableStateOf(false)
+/**
+ * The release the update card shows. The launch check fills it; so does the manual check in
+ * Settings, which is why it is not private to [UpdatePrompt].
+ */
+internal val updateRelease = mutableStateOf<com.music.spotui.data.api.UpdateChecker.Release?>(null)
+
/**
* The donation reminder (see SupportReminder): a card a few seconds after launch, only
* when due, signed in, and no update card is open. "No thanks" closes it for 2 weeks.
@@ -176,8 +182,10 @@ private fun SupportDialog(supporter: Boolean, onSupport: () -> Unit, onSponsor:
@Composable
private fun UpdatePrompt() {
val context = androidx.compose.ui.platform.LocalContext.current
- var release by androidx.compose.runtime.remember { mutableStateOf<com.music.spotui.data.api.UpdateChecker.Release?>(null) }
+ var release by updateRelease
androidx.compose.runtime.LaunchedEffect(Unit) {
+ // Turned off in Settings: no check at launch. The manual check there still asks.
+ if (!com.music.spotui.data.preferences.AutoUpdateCheckPref.on) return@LaunchedEffect
kotlinx.coroutines.delay(5_000)
release = com.music.spotui.data.api.UpdateChecker.check(context)
}
diff --git a/base/app/src/main/java/com/music/spotui/data/api/Api.kt b/base/app/src/main/java/com/music/spotui/data/api/Api.kt
index 94d3a272..5a0af27c 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/Api.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/Api.kt
@@ -27,6 +27,7 @@ import com.music.spotui.data.entity.HomeSection
import com.music.spotui.data.entity.LibraryEntry
import com.music.spotui.data.entity.PodcastModel
import com.music.spotui.data.entity.SearchResults
+import com.music.spotui.data.entity.ShowPage
import com.music.spotui.data.entity.SongsModel
import com.music.spotui.di.Graph
import com.music.spotui.di.SongPlayer
@@ -36,6 +37,7 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.withTimeoutOrNull
+import kotlinx.serialization.json.contentOrNull
/**
* The UI's data source, over [MyspotiApi]. Keeps the `Flow<Response<...>>` contract the
@@ -60,6 +62,12 @@ class Api constructor(
const val DOWNLOADS_ID = "downloads"
/** "Your Episodes" (saved podcast episodes). */
const val EPISODES_ID = "your-episodes"
+ /** "Recently played": Spotify's own list for the account, pinned in the library. */
+ const val RECENT_ID = "recently-played"
+ /** Pages of 50 asked for a show's episodes / chapters, at most (500 rows). */
+ const val MAX_EPISODE_PAGES = 10
+ /** The page's collection set behind its "Mark as finished" menu. */
+ private const val MARKED_FINISHED = "markedasfinished"
@Volatile var albums: List<AlbumsModel>? = null
@Volatile var artists: List<ArtistsModel>? = null
@Volatile var home: HomeFeedModel? = null
@@ -173,6 +181,14 @@ class Api constructor(
coverUri = cover(e.images).ifBlank { cover(e.show?.images.orEmpty()) },
url = "episode:$id",
durationMs = e.durationMs.toInt(),
+ // No spotifyTrackId on purpose: an episode is keyed by its "episode:<id>" url
+ // everywhere (download, playback). "playable" is what the downloader refuses on.
+ playable = e.playable,
+ description = e.description.orEmpty(),
+ releaseDate = e.releaseDate.orEmpty(),
+ played = e.played,
+ playedPositionMs = e.playedPositionMs,
+ showId = e.show?.uri?.substringAfterLast(':').orEmpty(),
)
}
@@ -370,6 +386,128 @@ class Api constructor(
}
}
+ /**
+ * The show page: header and rows in one flow, so the screen has a single loading state.
+ *
+ * A podcast answers [app.myspoti.api.Podcasts.episodes]; a book answers nothing there and
+ * only has chapters, which is why its page used to show a cover and a title and nothing
+ * else (B13).
+ */
+ suspend fun getShowPage(showId: String): Flow<Response<ShowPage>> = flow {
+ emit(Response.Loading())
+ if (!ready()) { emit(Response.Error(notSignedIn())); return@flow }
+ val uri = "spotify:show:$showId"
+ val head = runCatching { api.podcasts.show(uri) }.getOrNull()
+ val rows = ArrayList<SongsModel>()
+ var failure: Throwable? = null
+ var audiobook = false
+ var book: app.myspoti.api.Audiobook? = null
+
+ try {
+ var offset = 0
+ loop@ for (page in 0 until MAX_EPISODE_PAGES) {
+ val p = api.podcasts.episodes(uri, offset, 50)
+ if (p.items.isEmpty()) break@loop
+ rows += p.items.map(::episodeSong)
+ emit(Response.Success(pageOf(showId, head, book, rows, audiobook = false)))
+ offset = p.nextOffset ?: break@loop
+ }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ failure = e
+ }
+
+ if (rows.isEmpty()) {
+ // A book: its chapters come from queryBookChapters, not from the episodes query.
+ audiobook = true
+ book = runCatching { api.podcasts.audiobook(uri) }.getOrNull()
+ try {
+ var offset = 0
+ loop@ for (page in 0 until MAX_EPISODE_PAGES) {
+ val p = api.podcasts.chapters(uri, offset, 50)
+ if (p.items.isEmpty()) break@loop
+ rows += p.items.map(::episodeSong)
+ emit(Response.Success(pageOf(showId, head, book, rows, audiobook = true)))
+ offset = p.nextOffset ?: break@loop
+ }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ if (rows.isEmpty()) failure = e
+ }
+ }
+
+ if (rows.isEmpty() && failure != null) {
+ Log.e("Api", "getShowPage failed", failure)
+ emit(Response.Error(failure.message ?: "error"))
+ return@flow
+ }
+ SongPlayer.registerContext(rows.map { it.url }, uri)
+ emit(Response.Success(pageOf(showId, head, book, rows, audiobook)))
+ }
+
+ private fun pageOf(
+ showId: String,
+ head: app.myspoti.api.Show?,
+ book: app.myspoti.api.Audiobook?,
+ rows: List<SongsModel>,
+ audiobook: Boolean,
+ ): ShowPage {
+ val cover = head?.let { big(it.images) }.orEmpty()
+ .ifBlank { book?.images?.let(::big).orEmpty() }
+ .ifBlank { rows.firstOrNull()?.coverUri.orEmpty() }
+ val model = PodcastModel(
+ id = showId,
+ name = head?.name ?: book?.name ?: rows.firstOrNull()?.album.orEmpty(),
+ publisher = head?.publisher?.takeIf { it.isNotBlank() }
+ ?: book?.authors?.joinToString(", ").orEmpty(),
+ coverUri = cover,
+ description = head?.description ?: book?.description.orEmpty(),
+ rating = head?.rating ?: 0.0,
+ saved = head?.saved == true,
+ authors = book?.authors.orEmpty(),
+ narrators = book?.narrators.orEmpty(),
+ audiobook = audiobook,
+ )
+ return ShowPage(model, rows, audiobook, cover)
+ }
+
+ /** One episode (or chapter) by raw Spotify id, for the episode page. */
+ suspend fun getEpisode(episodeId: String): SongsModel? {
+ if (!ready()) return null
+ return runCatching { episodeSong(api.podcasts.episode("spotify:episode:$episodeId")) }.getOrNull()
+ }
+
+ /**
+ * Marks an episode finished, or not started. The page keeps this in its own
+ * "markedasfinished" collection — the set behind its "Mark as finished" menu — so the
+ * change follows the account like Spotify's own menu does.
+ */
+ suspend fun setEpisodePlayed(episodeUri: String, played: Boolean) {
+ if (episodeUri.isBlank()) return
+ MyspotiRuntime.spotify.raw.service(
+ "CollectionPlatformAPI",
+ if (played) "add" else "remove",
+ kotlinx.serialization.json.JsonPrimitive(MARKED_FINISHED),
+ kotlinx.serialization.json.JsonArray(listOf(kotlinx.serialization.json.JsonPrimitive(episodeUri))),
+ )
+ }
+
+ /** Raw uris the page has in its "markedasfinished" set (empty when it refuses). */
+ suspend fun finishedEpisodes(): Set<String> {
+ if (!ready()) return emptySet()
+ // The page's get() throws on an empty set: that simply means nothing is marked.
+ val raw = runCatching {
+ MyspotiRuntime.spotify.raw.service(
+ "CollectionPlatformAPI", "get", kotlinx.serialization.json.JsonPrimitive(MARKED_FINISHED),
+ )
+ }.getOrNull()
+ return (raw as? kotlinx.serialization.json.JsonArray).orEmpty()
+ .mapNotNull { (it as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull }
+ .toSet()
+ }
+
/** "Your Episodes": saved podcast episodes. */
suspend fun getSavedEpisodes(): List<SongsModel> {
if (!ready()) return emptyList()
diff --git a/base/app/src/main/java/com/music/spotui/data/entity/PodcastModel.kt b/base/app/src/main/java/com/music/spotui/data/entity/PodcastModel.kt
index c72d4294..72ae0bce 100644
--- a/base/app/src/main/java/com/music/spotui/data/entity/PodcastModel.kt
+++ b/base/app/src/main/java/com/music/spotui/data/entity/PodcastModel.kt
@@ -11,6 +11,25 @@ data class PodcastModel(
val name: String,
val publisher: String,
val coverUri: String,
+ /** Show description ("About" tab, episode page header). */
+ val description: String = "",
+ /** Average rating and how many people gave it (0 = none shown). */
+ val rating: Double = 0.0,
+ val ratingCount: Int = 0,
+ /** Spotify's own follow state for this show. */
+ val saved: Boolean = false,
+ /** Audiobooks: authors and narrators, empty for a podcast. */
+ val authors: List<String> = emptyList(),
+ val narrators: List<String> = emptyList(),
+ /** The page is a book: its items are chapters, not episodes. */
+ val audiobook: Boolean = false,
) {
constructor() : this("", "", "", "")
+
+ /** "de <author> • lu par <narrator>" for a book, the publisher for a podcast. */
+ val byline: String get() = when {
+ authors.isNotEmpty() && narrators.isNotEmpty() -> authors.joinToString(", ") + " • " + narrators.joinToString(", ")
+ authors.isNotEmpty() -> authors.joinToString(", ")
+ else -> publisher
+ }
}
diff --git a/base/app/src/main/java/com/music/spotui/data/entity/ShowPage.kt b/base/app/src/main/java/com/music/spotui/data/entity/ShowPage.kt
new file mode 100644
index 00000000..c52f2f69
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/entity/ShowPage.kt
@@ -0,0 +1,18 @@
+package com.music.spotui.data.entity
+
+/**
+ * A show page as the screen shows it: the header plus the rows.
+ *
+ * A podcast has episodes; a book has chapters, fetched through another Spotify operation
+ * ([audiobook] = true). Both arrive as [SongsModel] rows so they play through the same
+ * queue as an episode (url = "episode:<raw id>").
+ */
+data class ShowPage(
+ val show: PodcastModel,
+ val items: List<SongsModel> = emptyList(),
+ val audiobook: Boolean = false,
+ /** Spotify's cover for the page: the show's, or the first item's when the header failed. */
+ val coverUri: String = "",
+) {
+ val complete: Boolean get() = items.isNotEmpty()
+}
diff --git a/base/app/src/main/java/com/music/spotui/data/entity/SongsModel.kt b/base/app/src/main/java/com/music/spotui/data/entity/SongsModel.kt
index c9ff7623..e7a65520 100644
--- a/base/app/src/main/java/com/music/spotui/data/entity/SongsModel.kt
+++ b/base/app/src/main/java/com/music/spotui/data/entity/SongsModel.kt
@@ -25,6 +25,21 @@ data class SongsModel(
val playable : Boolean = true,
// Spotify ids of the artists, for "liked songs by this artist". Empty in older caches.
val artistIds : List<String> = emptyList(),
+ // ── Podcast episodes. Empty / false on tracks: the show page and the episode page
+ // read these from the row itself instead of asking Spotify again.
+ /** Episode description, as Spotify publishes it (the row snippet and the episode page). */
+ val description : String = "",
+ /** Release date (ISO 8601), shown as "24 juil." on the episode page. */
+ val releaseDate : String = "",
+ /** Spotify keeps this episode as finished (playedState, or the page's own mark). */
+ val played : Boolean = false,
+ /** Where the user stopped listening, in ms (0 when never started). */
+ val playedPositionMs : Long = 0L,
+ /** Raw Spotify id of the show the episode belongs to. */
+ val showId : String = "",
){
constructor() : this(-1 ,"" ,"" ,"" ,"" ,"", "")
+
+ /** A podcast episode (url = "episode:<raw id>"), not a music track. */
+ val isEpisode : Boolean get() = url.startsWith("episode:")
}
diff --git a/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt b/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt
index ad0d5c83..822e71f7 100644
--- a/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt
+++ b/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt
@@ -56,9 +56,18 @@ object LocalMusic {
MediaStore.Audio.Media.RELATIVE_PATH,
)
val out = ArrayList<LocalTrack>()
+ // Android's index decides what is "music": a phone full of recorded or downloaded audio can
+ // come back empty while another player lists those very files (reported: 29 tracks with a
+ // third-party player, none here). Anything long enough to be a song is therefore listed too,
+ // minus the system folders whose sounds are not music.
+ val notSystem = listOf("Ringtones", "Notifications", "Alarms", "Android")
+ .joinToString(" AND ") { "${MediaStore.Audio.Media.RELATIVE_PATH} NOT LIKE '$it/%'" }
+ val selection = "(${MediaStore.Audio.Media.IS_MUSIC} != 0 AND ${MediaStore.Audio.Media.DURATION} >= 30000)" +
+ " OR (${MediaStore.Audio.Media.DURATION} >= 20000" +
+ " AND ${MediaStore.Audio.Media.RELATIVE_PATH} IS NOT NULL AND $notSystem)"
context.contentResolver.query(
collection, projection,
- "${MediaStore.Audio.Media.IS_MUSIC} != 0 AND ${MediaStore.Audio.Media.DURATION} >= 30000",
+ selection,
null, "${MediaStore.Audio.Media.TITLE} COLLATE NOCASE ASC",
)?.use { c ->
val iId = c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt
index ca47df45..d281611f 100644
--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt
+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt
@@ -76,7 +76,9 @@ object OfflineCollections {
/** Download a song on its own. */
fun downloadSong(song: SongsModel, quality: com.music.spotui.data.preferences.DownloadQuality? = null) {
- if (song.spotifyTrackId.isBlank()) return
+ // Episodes have no track id and their own downloader (PodcastDownloader): sending one
+ // here would only be dropped, or worse, hit the lossless path.
+ if (song.spotifyTrackId.isBlank() || episodeKeyOf(song) != null) return
synchronized(lock) { singles += song.spotifyTrackId }
save()
OfflineDownloader.enqueue(listOf(song), quality)
@@ -96,7 +98,9 @@ object OfflineCollections {
/** Download a list as a whole, and keep it in step from now on. */
fun download(page: ContextPageModel, quality: com.music.spotui.data.preferences.DownloadQuality? = null) {
- val ids = page.tracks.map { it.spotifyTrackId }.filter { it.isNotBlank() }.toSet()
+ // An episode in a list is not a lossless track: it stays out of the collection, and the
+ // list download never enqueues it (its own menu row is the way to download an episode).
+ val ids = page.tracks.map { it.spotifyTrackId }.filter { it.isNotBlank() && !isEpisodeKey(it) }.toSet()
collections[page.uri] = OfflineCollection(page.uri, page.type, page.name, ids, System.currentTimeMillis(), quality?.name.orEmpty())
save()
OfflineDownloader.enqueue(page.tracks, quality)
@@ -122,14 +126,16 @@ object OfflineCollections {
fun sync(page: ContextPageModel) {
val c = collections[page.uri] ?: return
if (!page.complete) return
- val songs = page.tracks.filter { it.spotifyTrackId.isNotBlank() }
+ // Episodes are never part of a downloaded list: they have their own queue and their
+ // downloaded copies are kept by their own key, not by the list that shows them.
+ val songs = page.tracks.filter { it.spotifyTrackId.isNotBlank() && !isEpisodeKey(it.spotifyTrackId) }
val ids = songs.map { it.spotifyTrackId }.toSet()
val gone = c.trackIds - ids
collections[page.uri] = c.copy(name = page.name, trackIds = ids, syncedAt = System.currentTimeMillis())
save()
val missing = songs.filter { !OfflineStore.isDownloaded(it.spotifyTrackId) && OfflineStore.status[it.spotifyTrackId] == null }
if (missing.isNotEmpty()) OfflineDownloader.enqueue(missing, com.music.spotui.data.preferences.DownloadQuality.saved(c.quality), auto = true)
- gone.filterNot { isKept(it) }.forEach { OfflineDownloader.remove(it) }
+ gone.filterNot { isKept(it) || isEpisodeKey(it) }.forEach { OfflineDownloader.remove(it) }
if (missing.isNotEmpty() || gone.isNotEmpty()) Log.i(TAG, "${page.name}: +${missing.size} -${gone.size}")
}
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt
index d0c6dc72..087504d6 100644
--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt
+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineDownloader.kt
@@ -15,6 +15,7 @@ import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
+import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.currentCoroutineContext
@@ -169,13 +170,17 @@ object OfflineDownloader {
return
}
val q = quality?.let { com.music.spotui.data.preferences.DownloadQuality.saved(it.name) }?.name.orEmpty()
- enqueueAll(songs.filter { it.spotifyTrackId.isNotBlank() }.map { Request.of(it).copy(quality = q) })
+ // Episodes go to PodcastDownloader: their id is no track id, so the lossless lookup
+ // would 404 (or worse, match an unrelated recording by title).
+ enqueueAll(songs.filter { it.spotifyTrackId.isNotBlank() && !isEpisodeKey(it.spotifyTrackId) }.map { Request.of(it).copy(quality = q) })
}
private fun enqueueAll(list: List<Request>) {
val added = synchronized(pending) {
list.filter { r ->
- !OfflineStore.isDownloaded(r.trackId) && pending.putIfAbsent(r.trackId, r) == null
+ // Last guard before the lossless path, whatever the caller (resume, retry, list).
+ !isEpisodeKey(r.trackId) &&
+ !OfflineStore.isDownloaded(r.trackId) && pending.putIfAbsent(r.trackId, r) == null
}.also { if (it.isNotEmpty()) savePending() }
}
if (added.isEmpty()) return
@@ -194,6 +199,24 @@ object OfflineDownloader {
requests.remove(trackId)
}
+ /**
+ * Stops every running and queued download and empties the queue. Unlike [removeAll], it
+ * deletes nothing: finished songs stay in [OfflineStore.tracks] and in the index, and a
+ * cancelled download only drops its own partial file in the temp folder.
+ */
+ fun stopAll() {
+ // The queue survives a restart through pending.json: clearing it here is what makes the
+ // stop stick, instead of the downloads resuming at the next launch.
+ val ids = synchronized(pending) { pending.keys.toList().also { pending.clear(); savePending() } }
+ // Running jobs may not all be in `pending` any more; cancel them by their own handle.
+ running.values.forEach { it.cancel() }
+ running.clear()
+ // Snapshot state: the badges and the list are read from the UI, so write them there.
+ scope.launch(Dispatchers.Main) {
+ ids.forEach { OfflineStore.status.remove(it); requests.remove(it) }
+ }
+ }
+
/** Tries a failed song again. */
fun retry(trackId: String) {
val r = requests[trackId] ?: return
@@ -326,18 +349,22 @@ object OfflineDownloader {
out = File(OfflineStore.audioDir, "${r.trackId}.flac")
if (!audioTmp.renameTo(out)) throw IOException("could not move the file")
}
- // Kept encrypted: the file only plays in Myspoti, on this phone.
- runInterruptible(Dispatchers.IO) { OfflineCrypto.encryptInPlace(Graph.app, out) }
- val cover = runCatching {
- val c = File(OfflineStore.coverDir, "${r.trackId}.jpg")
- httpGet(meta.coverUrl, c); c.name
- }.getOrDefault("")
- return OfflineTrack(
- trackId = r.trackId, title = meta.title, artist = meta.artist, album = meta.album,
- albumId = meta.albumId, durationMs = meta.durationMs, coverUrl = meta.coverUrl,
- file = out.name, cover = cover, source = file.provider, verified = file.verified,
- bytes = out.length(), addedAt = System.currentTimeMillis(),
- )
+ // The audio is complete on disk from here on: "stop all" must not interrupt this last
+ // part, or the file would stay out of the index and be swept as a stray at startup.
+ return withContext(NonCancellable) {
+ // Kept encrypted: the file only plays in Myspoti, on this phone.
+ runInterruptible(Dispatchers.IO) { OfflineCrypto.encryptInPlace(Graph.app, out) }
+ val cover = runCatching {
+ val c = File(OfflineStore.coverDir, "${r.trackId}.jpg")
+ httpGet(meta.coverUrl, c); c.name
+ }.getOrDefault("")
+ OfflineTrack(
+ trackId = r.trackId, title = meta.title, artist = meta.artist, album = meta.album,
+ albumId = meta.albumId, durationMs = meta.durationMs, coverUrl = meta.coverUrl,
+ file = out.name, cover = cover, source = file.provider, verified = file.verified,
+ bytes = out.length(), addedAt = System.currentTimeMillis(),
+ )
+ }
} finally {
audioTmp.delete(); previewTmp.delete()
}
@@ -477,7 +504,12 @@ object OfflineDownloader {
}
}
- private fun rangedDownload(url: String, out: File, knownTotal: Long): Boolean {
+ /**
+ * The byte range loop, shared with [PodcastDownloader]: a publisher's MP3 is fetched the
+ * same way (follows the 302s to podtrac/radiofrance/simplecast, restarts from zero when a
+ * server ignores Range, retries each chunk three times).
+ */
+ internal fun rangedDownload(url: String, out: File, knownTotal: Long): Boolean {
val chunk = 4L * 1024 * 1024 // 4 MB: the stream gets its turn between two chunks
var total = knownTotal
java.io.RandomAccessFile(out, "rw").use { output ->
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt
index ee60d777..a2a2f1c1 100644
--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt
+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineStore.kt
@@ -23,26 +23,38 @@ data class OfflineTrack(
val file: String,
/** Cover file name in the covers folder, empty when it could not be fetched. */
val cover: String,
- /** Where the audio came from (YouTube watch URL). */
+ /** Where the audio came from (YouTube watch URL, or the podcast publisher). */
val source: String,
/** The audio was checked against the recording's official preview. */
val verified: Boolean,
val bytes: Long,
val addedAt: Long,
+ /**
+ * Music or podcast episode. Entries written before this field existed are music, so an
+ * older index stays valid (and its files are not swept as strays).
+ */
+ val kind: String = KIND_MUSIC,
) {
+ val isEpisode: Boolean get() = kind == KIND_PODCAST
+
fun toJson(): JSONObject = JSONObject()
.put("id", trackId).put("title", title).put("artist", artist).put("album", album)
.put("albumId", albumId).put("duration", durationMs).put("coverUrl", coverUrl)
.put("file", file).put("cover", cover).put("source", source).put("verified", verified)
- .put("bytes", bytes).put("added", addedAt)
+ .put("bytes", bytes).put("added", addedAt).put("kind", kind)
companion object {
+ const val KIND_MUSIC = "MUSIC"
+ const val KIND_PODCAST = "PODCAST"
+
fun fromJson(o: JSONObject) = OfflineTrack(
trackId = o.getString("id"), title = o.optString("title"), artist = o.optString("artist"),
album = o.optString("album"), albumId = o.optString("albumId"), durationMs = o.optLong("duration"),
coverUrl = o.optString("coverUrl"), file = o.getString("file"), cover = o.optString("cover"),
source = o.optString("source"), verified = o.optBoolean("verified"), bytes = o.optLong("bytes"),
addedAt = o.optLong("added"),
+ // Absent in an index written before podcasts: those entries are all music.
+ kind = o.optString("kind").ifBlank { KIND_MUSIC },
)
}
}
@@ -116,6 +128,8 @@ object OfflineStore {
/** The index before the last write, the fallback when [indexFile] is damaged. */
private val backupFile: File get() = File(root, "index.json.bak")
internal val pendingFile: File get() = File(root, "pending.json")
+ /** The podcast queue: kept apart so a restart resumes episodes without touching music. */
+ internal val podcastPendingFile: File get() = File(root, "podcasts-pending.json")
val tmpDir: File get() = File(root, "tmp").apply { mkdirs() }
fun isDownloaded(trackId: String) = trackId.isNotBlank() && tracks.containsKey(trackId)
@@ -186,7 +200,10 @@ object OfflineStore {
id = "track:${t.trackId}".hashCode() and 0x7fffffff,
title = t.title, album = t.album, singer = t.artist,
coverUri = coverFile(t)?.let { Uri.fromFile(it).toString() } ?: t.coverUrl,
- url = "spotify:track:${t.trackId}", spotifyTrackId = t.trackId,
+ // An episode is keyed "episode:<id>" and must keep that url (playback, download state);
+ // it has no Spotify track id, and giving it one would send it down the track paths.
+ url = if (t.isEpisode) t.trackId else "spotify:track:${t.trackId}",
+ spotifyTrackId = if (t.isEpisode) "" else t.trackId,
durationMs = t.durationMs.toInt(), albumId = t.albumId,
)
diff --git a/base/app/src/main/java/com/music/spotui/data/offline/PodcastDownloader.kt b/base/app/src/main/java/com/music/spotui/data/offline/PodcastDownloader.kt
new file mode 100644
index 00000000..abdafa04
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/offline/PodcastDownloader.kt
@@ -0,0 +1,373 @@
+package com.music.spotui.data.offline
+
+import android.util.Log
+import androidx.compose.runtime.mutableStateMapOf
+import androidx.compose.runtime.snapshots.SnapshotStateMap
+import com.music.spotui.data.entity.SongsModel
+import com.music.spotui.data.preferences.isLosslessEnabled
+import com.music.spotui.di.Graph
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.NonCancellable
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.ensureActive
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runInterruptible
+import kotlinx.coroutines.withContext
+import org.json.JSONArray
+import org.json.JSONObject
+import java.io.File
+import java.io.IOException
+import java.net.HttpURLConnection
+import java.net.URL
+import java.util.concurrent.ConcurrentHashMap
+
+/** Download keys of podcast episodes ("episode:<id>"): never a Spotify track id. */
+internal const val EPISODE_PREFIX = "episode:"
+
+internal fun isEpisodeKey(id: String) = id.startsWith(EPISODE_PREFIX)
+
+/** The download key of an episode row, or null for a music track. */
+internal fun episodeKeyOf(song: SongsModel) = song.url.takeIf { isEpisodeKey(it) }
+
+/**
+ * Downloads podcast episodes for offline listening — a separate path from
+ * [OfflineDownloader], which is the lossless/SpotiFLAC one.
+ *
+ * Spotify never hands out an episode's audio in GraphQL: the Web Player asks
+ * `soundfinder/v1/unauth/episode/<id>/com.widevine.alpha`, which returns either the
+ * publisher's own clear file (`passthroughUrl`, an MP3/M4A behind podtrac/radiofrance
+ * redirects) or only a Widevine-encrypted MP4. Only the clear file is usable here, so:
+ *
+ * - the URL is resolved right before the GET (the links are signed and expire),
+ * - `passthrough = NONE` (Spotify-exclusive shows) is refused, with a message, and no
+ * DRM is ever attempted,
+ * - the file is fetched with the same byte-range loop as music downloads, then checked
+ * (content type, magic bytes, size) before it is kept,
+ * - it is encrypted in place and indexed with [OfflineTrack.KIND_PODCAST], in the same
+ * store as the songs, under an `episode:<id>` key.
+ *
+ * One worker only: episodes run 10–150 MB and three downloads starved the player.
+ */
+object PodcastDownloader {
+ private const val TAG = "PodcastDl"
+ /** Below this, what came back is an error page or a stub, not an episode. */
+ internal const val MIN_BYTES = 100_000L
+
+ data class Request(
+ val trackId: String,
+ val title: String,
+ val artist: String,
+ val album: String,
+ val coverUrl: String,
+ val durationMs: Long,
+ ) {
+ fun toJson(): JSONObject = JSONObject().put("id", trackId).put("title", title)
+ .put("artist", artist).put("album", album).put("duration", durationMs).put("cover", coverUrl)
+
+ companion object {
+ fun of(s: SongsModel) = Request(
+ trackId = s.url, title = s.title, artist = s.singer, album = s.album,
+ coverUrl = s.coverUri, durationMs = s.durationMs.toLong(),
+ )
+ fun fromJson(o: JSONObject) = Request(
+ o.getString("id"), o.optString("title"), o.optString("artist"), o.optString("album"),
+ o.optString("cover"), o.optLong("duration"),
+ )
+ }
+ }
+
+ /** A refusal worth telling the user about; [messageRes] is the localized text. */
+ private class Unavailable(val messageRes: Int, why: String) : Exception(why)
+
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ /** Episode keys queued, downloading, or whose last attempt was refused. */
+ val requests: SnapshotStateMap<String, Request> = mutableStateMapOf()
+ private val queue = Channel<Request>(Channel.UNLIMITED)
+ /** Waiting requests, in order (persisted in podcasts-pending.json: a restart resumes them). */
+ private val pending = LinkedHashMap<String, Request>()
+ private val running = ConcurrentHashMap<String, Job>()
+ @Volatile private var started = false
+
+ private fun start() {
+ if (started) return
+ synchronized(this) {
+ if (started) return
+ started = true
+ scope.launch { for (r in queue) work(r) }
+ }
+ }
+
+ /** Re-queues the episodes that were waiting when the app last stopped. */
+ fun resumePending() {
+ val saved = runCatching {
+ val a = JSONArray(OfflineStore.podcastPendingFile.readText())
+ (0 until a.length()).map { Request.fromJson(a.getJSONObject(it)) }
+ }.getOrDefault(emptyList())
+ if (saved.isNotEmpty()) enqueueAll(saved)
+ }
+
+ /** Downloads [song], which must be an episode row (`url = "episode:<id>"`). */
+ fun enqueue(song: SongsModel) {
+ // A track row has no episode url: it belongs to OfflineDownloader, never here.
+ if (episodeKeyOf(song) == null) return
+ val req = Request.of(song)
+ // "Downloads" off in Settings means no downloads at all, podcasts included.
+ if (!isLosslessEnabled(Graph.app)) {
+ toast(app.myspoti.engine.R.string.downloads_off_toast)
+ return
+ }
+ // Spotify itself marks some episodes unplayable (region, removed, paywall).
+ if (!song.playable) {
+ toast(app.myspoti.engine.R.string.podcast_download_unavailable)
+ return
+ }
+ if (com.music.spotui.data.DataSaver.metered) toast(app.myspoti.engine.R.string.download_on_mobile_data)
+ enqueueAll(listOf(req))
+ }
+
+ private fun enqueueAll(list: List<Request>) {
+ val added = synchronized(pending) {
+ list.filter { r ->
+ isEpisodeKey(r.trackId) && !OfflineStore.isDownloaded(r.trackId) &&
+ pending.putIfAbsent(r.trackId, r) == null
+ }.also { if (it.isNotEmpty()) savePending() }
+ }
+ if (added.isEmpty()) return
+ scope.launch(Dispatchers.Main) {
+ added.forEach { requests[it.trackId] = it; OfflineStore.status[it.trackId] = OfflineStatus.Queued }
+ }
+ start()
+ added.forEach { queue.trySend(it) }
+ }
+
+ /** Stops a queued or running download (and forgets a refused one). */
+ fun cancel(trackId: String) {
+ synchronized(pending) { if (pending.remove(trackId) != null) savePending() }
+ running.remove(trackId)?.cancel()
+ scope.launch(Dispatchers.Main) { OfflineStore.status.remove(trackId); requests.remove(trackId) }
+ }
+
+ /** Deletes a downloaded episode (or stops its download). */
+ fun remove(trackId: String) {
+ cancel(trackId)
+ scope.launch { OfflineStore.remove(trackId) }
+ }
+
+ /** Tries a refused or failed episode again (the URL is resolved again, so a retry can succeed). */
+ fun retry(trackId: String) {
+ val r = requests[trackId] ?: return
+ enqueueAll(listOf(r))
+ }
+
+ private fun savePending() {
+ runCatching {
+ val a = JSONArray()
+ pending.values.forEach { a.put(it.toJson()) }
+ OfflineStore.podcastPendingFile.writeText(a.toString())
+ }
+ }
+
+ private suspend fun setStatus(id: String, s: OfflineStatus?) = withContext(Dispatchers.Main) {
+ if (s == null) OfflineStore.status.remove(id) else OfflineStore.status[id] = s
+ }
+
+ private fun toast(res: Int) = scope.launch(Dispatchers.Main) {
+ android.widget.Toast.makeText(Graph.app, res, android.widget.Toast.LENGTH_LONG).show()
+ }
+
+ private suspend fun work(r: Request) {
+ // Cancelled while it waited in the queue.
+ if (synchronized(pending) { !pending.containsKey(r.trackId) }) return
+ // Data saver on mobile data: like music downloads, wait for Wi-Fi rather than spend data.
+ while (com.music.spotui.data.DataSaver.active) {
+ delay(5_000)
+ if (synchronized(pending) { !pending.containsKey(r.trackId) }) return
+ }
+ val job = scope.launch {
+ val outcome: OfflineStatus? = try {
+ setStatus(r.trackId, OfflineStatus.Downloading(-1f))
+ val t = download(r)
+ OfflineStore.add(t)
+ withContext(Dispatchers.Main) { requests.remove(r.trackId) }
+ null
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Unavailable) {
+ Log.i(TAG, "${r.title}: ${e.message}")
+ toast(e.messageRes)
+ OfflineStatus.Unavailable
+ } catch (t: Throwable) {
+ Log.w(TAG, "${r.title} failed", t)
+ toast(app.myspoti.engine.R.string.podcast_download_failed)
+ OfflineStatus.Failed
+ }
+ synchronized(pending) { pending.remove(r.trackId); savePending() }
+ if (outcome != null) setStatus(r.trackId, outcome)
+ }
+ running[r.trackId] = job
+ job.join()
+ running.remove(r.trackId, job)
+ }
+
+ private suspend fun download(r: Request): OfflineTrack {
+ val episodeId = r.trackId.removePrefix(EPISODE_PREFIX)
+ // Resolved here and not at queue time: a signed publisher URL is only good for hours.
+ val audio = app.myspoti.host.android.MyspotiRuntime.api.podcasts.audioUrl("spotify:episode:$episodeId")
+ if (audio.passthrough.equals("NONE", ignoreCase = true)) {
+ // Spotify-exclusive show: its only copy is Widevine-encrypted. Refuse, never try DRM.
+ throw Unavailable(app.myspoti.engine.R.string.podcast_download_protected, "no publisher file (passthrough NONE, ${audio.format})")
+ }
+ val url = audio.url?.takeIf { it.startsWith("http") }
+ ?: throw Unavailable(app.myspoti.engine.R.string.podcast_download_unavailable, "passthrough ${audio.passthrough} without a url")
+ Log.i(TAG, "${r.title}: publisher file (passthrough ${audio.passthrough}, ${audio.format})")
+
+ // What the server says it is before a byte is fetched: an expired link answers with a
+ // login page or an error page, and that must not end up in the index as an episode.
+ val probe = probe(url)
+ if (!contentTypeOk(probe.type)) {
+ throw Unavailable(app.myspoti.engine.R.string.podcast_download_unavailable, "the server sent ${probe.type}, not audio")
+ }
+
+ val base = safeName(r.trackId)
+ val tmp = File(OfflineStore.tmpDir, "$base.part")
+ val out: File
+ try {
+ val total = probe.bytes
+ val watcher = if (total > 0) scope.launch {
+ while (isActive) {
+ setStatus(r.trackId, OfflineStatus.Downloading((tmp.length().toFloat() / total).coerceIn(0f, 1f)))
+ delay(400)
+ }
+ } else null
+ try {
+ runInterruptible(Dispatchers.IO) { OfflineDownloader.rangedDownload(url, tmp, total) }
+ } finally {
+ watcher?.cancel()
+ setStatus(r.trackId, OfflineStatus.Downloading(-1f))
+ }
+ currentCoroutineContext().ensureActive()
+
+ if (tmp.length() <= MIN_BYTES) throw Unavailable(app.myspoti.engine.R.string.podcast_download_failed, "only ${tmp.length()} bytes")
+ val head = readHead(tmp)
+ if (!audioMagicOk(head)) {
+ throw Unavailable(app.myspoti.engine.R.string.podcast_download_failed, "not an audio file (starts with ${hex(head, 4)})")
+ }
+ out = File(OfflineStore.audioDir, "$base.${audioExtension(url, head)}")
+ if (out.exists()) out.delete()
+ if (!tmp.renameTo(out)) throw IOException("could not move the file")
+ } finally {
+ tmp.delete()
+ }
+
+ // Complete on disk from here on: "stop" must not leave a file outside the index
+ // (it would be swept as a stray at the next start).
+ return withContext(NonCancellable) {
+ // Kept encrypted, like every download: it only plays in Myspoti, on this phone.
+ runInterruptible(Dispatchers.IO) { OfflineCrypto.encryptInPlace(Graph.app, out) }
+ val cover = runCatching {
+ val c = File(OfflineStore.coverDir, "$base.jpg")
+ fetchCover(r.coverUrl, c)
+ c.name
+ }.getOrDefault("")
+ OfflineTrack(
+ trackId = r.trackId, title = r.title, artist = r.artist, album = r.album,
+ albumId = "", durationMs = r.durationMs, coverUrl = r.coverUrl,
+ file = out.name, cover = cover, source = "podcast", verified = false,
+ bytes = out.length(), addedAt = System.currentTimeMillis(),
+ kind = OfflineTrack.KIND_PODCAST,
+ )
+ }
+ }
+
+ private class Probe(val bytes: Long, val type: String)
+
+ /** HEAD with redirects followed: the content type and size, or -1 / "" when unknown. */
+ private fun probe(url: String): Probe = runCatching {
+ val conn = (URL(url).openConnection() as HttpURLConnection).apply {
+ requestMethod = "HEAD"
+ connectTimeout = 20_000
+ readTimeout = 20_000
+ instanceFollowRedirects = true
+ setRequestProperty("User-Agent", OfflineDownloader.LosslessUa)
+ setRequestProperty("Accept", "*/*")
+ }
+ try {
+ Probe(conn.contentLengthLong.takeIf { it > 0 } ?: -1L, conn.contentType.orEmpty())
+ } finally {
+ conn.disconnect()
+ }
+ }.onFailure { Log.w(TAG, "HEAD failed: ${it.message}") }.getOrDefault(Probe(-1L, ""))
+
+ /** The cover, when the publisher has one; a missing cover must not fail the download. */
+ private fun fetchCover(url: String, out: File) {
+ if (!url.startsWith("http")) return
+ val conn = (URL(url).openConnection() as HttpURLConnection).apply {
+ connectTimeout = 15_000
+ readTimeout = 30_000
+ instanceFollowRedirects = true
+ setRequestProperty("User-Agent", OfflineDownloader.LosslessUa)
+ }
+ try {
+ if (conn.responseCode !in 200..299) return
+ conn.inputStream.use { input -> out.outputStream().use { input.copyTo(it) } }
+ } finally {
+ conn.disconnect()
+ }
+ }
+
+ private fun readHead(file: File): ByteArray {
+ val head = ByteArray(12)
+ file.inputStream().use { s ->
+ var off = 0
+ while (off < head.size) {
+ val n = s.read(head, off, head.size - off)
+ if (n < 0) break
+ off += n
+ }
+ }
+ return head
+ }
+
+ private fun hex(bytes: ByteArray, n: Int) =
+ bytes.take(n).joinToString(" ") { "%02x".format(it) }
+
+ // ── Pure helpers (unit-tested) ──
+
+ /**
+ * A publisher file is any `audio` type, an opaque `…octet-stream`, or an MP4 container; anything
+ * else (an HTML or JSON error page served with 200) is a broken link, not an episode.
+ * An unknown type is left to the magic-byte check.
+ */
+ internal fun contentTypeOk(type: String): Boolean {
+ val t = type.substringBefore(';').trim().lowercase()
+ return t.isEmpty() || t.startsWith("audio/") || t.endsWith("octet-stream") ||
+ t == "application/mp4" || t == "video/mp4"
+ }
+
+ /**
+ * An MP3 with an ID3 tag, a bare MPEG frame sync (`0xFF 0xE?`: 0xFB/0xF3/0xF2…), or an
+ * ISO base media file (`ftyp`, an M4A/AAC episode).
+ */
+ internal fun audioMagicOk(head: ByteArray): Boolean {
+ if (head.size >= 3 && head[0] == 'I'.code.toByte() && head[1] == 'D'.code.toByte() && head[2] == '3'.code.toByte()) return true
+ if (head.size >= 2 && (head[0].toInt() and 0xFF) == 0xFF && (head[1].toInt() and 0xE0) == 0xE0) return true
+ return head.size >= 8 && String(head, 4, 4, Charsets.ISO_8859_1) == "ftyp"
+ }
+
+ /** The container decides the extension first: a `.mp3` URL can serve an MP4 (and vice versa). */
+ internal fun audioExtension(url: String, head: ByteArray): String {
+ if (head.size >= 8 && String(head, 4, 4, Charsets.ISO_8859_1) == "ftyp") return "m4a"
+ val fromUrl = url.substringBefore('?').substringAfterLast('/').substringAfterLast('.', "").lowercase()
+ return fromUrl.takeIf { it == "mp3" || it == "m4a" || it == "aac" } ?: "mp3"
+ }
+
+ /** "episode:abc" → "episode_abc": a colon is legal in the index key, not in a file name. */
+ internal fun safeName(trackId: String) = trackId.replace(Regex("[^A-Za-z0-9._-]"), "_")
+}
diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt
index b9f3ecad..72071a2d 100644
--- a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt
@@ -4,13 +4,14 @@ import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
-// Trimmed from Spotui: stream quality, crossfade, YouTube and web-playback settings
-// are gone (the Web Player engine streams Spotify's own audio).
+// Trimmed from Spotui: stream quality, YouTube and web-playback settings are gone (the Web
+// Player engine streams Spotify's own audio). Crossfade is ours: a fade, not an overlap.
private const val PREF = "settings_prefs"
private const val KEY_LIBRARY_GRID = "library_grid_view"
private const val KEY_LYRIC_TRANSLATE_LANG = "lyric_translate_lang"
private const val KEY_LYRICS_EXTRA = "lyrics_extra_sources"
+private const val KEY_CROSSFADE = "crossfade_seconds"
/** Extra lyrics sources (NetEase, Genius) when Spotify and LRCLIB have none. Off by default. */
fun isLyricsExtraSources(c: Context): Boolean = prefs(c).getBoolean(KEY_LYRICS_EXTRA, false)
@@ -42,6 +43,22 @@ object AutoplayPref {
}
}
+/**
+ * The automatic update check at launch (on by default: the app behaved that way before this
+ * option existed). Off means no check when the app starts — a check asked for in Settings still
+ * works, it reads the same release list.
+ */
+object AutoUpdateCheckPref {
+ private const val KEY = "auto_update_check"
+ var on by androidx.compose.runtime.mutableStateOf(prefs(com.music.spotui.di.Graph.app).getBoolean(KEY, true))
+ private set
+
+ fun set(c: Context, value: Boolean) {
+ on = value
+ prefs(c).edit().putBoolean(KEY, value).apply()
+ }
+}
+
/** Screen rotation: portrait (the default), automatic (follows the system), or landscape. */
object OrientationPref {
private const val KEY = "screen_orientation"
@@ -68,6 +85,39 @@ object OrientationPref {
fun isLibraryGridView(c: Context): Boolean = prefs(c).getBoolean(KEY_LIBRARY_GRID, false)
fun setLibraryGridView(c: Context, v: Boolean) = prefs(c).edit().putBoolean(KEY_LIBRARY_GRID, v).apply()
+/**
+ * Crossfade length in seconds, 0 = off (the default: nothing changes unless asked for).
+ *
+ * It is a fade, not an overlap: the page plays one media element, so the next song cannot
+ * start before this one ends. The song fades out over its last N seconds, the next one fades
+ * in. The value is Compose state, so the settings row redraws when it changes.
+ */
+object CrossfadePref {
+ const val MAX = 12
+ var seconds by androidx.compose.runtime.mutableStateOf(
+ prefs(com.music.spotui.di.Graph.app).getInt(KEY_CROSSFADE, 0).coerceIn(0, MAX),
+ )
+ private set
+
+ /** Saves it and hands it to the player: the change applies to the song playing now. */
+ fun set(c: Context, value: Int) {
+ val v = value.coerceIn(0, MAX)
+ seconds = v
+ prefs(c).edit().putInt(KEY_CROSSFADE, v).apply()
+ applyCrossfade(v)
+ }
+}
+
+fun getCrossfadeSeconds(c: Context): Int =
+ prefs(c).getInt(KEY_CROSSFADE, 0).coerceIn(0, CrossfadePref.MAX)
+
+/** Gives the saved length to the player (at start, and at every change); 0 stops a fade at once. */
+fun applyCrossfade(seconds: Int) {
+ val runtime = app.myspoti.host.android.MyspotiRuntime
+ if (!runtime.isStarted) return
+ runtime.spotify.player.crossfadeSeconds = seconds
+}
+
fun getLyricTranslateLang(c: Context): String =
prefs(c).getString(KEY_LYRIC_TRANSLATE_LANG, "").orEmpty()
diff --git a/base/app/src/main/java/com/music/spotui/di/AutoBrowser.kt b/base/app/src/main/java/com/music/spotui/di/AutoBrowser.kt
index 34118049..6d972695 100644
--- a/base/app/src/main/java/com/music/spotui/di/AutoBrowser.kt
+++ b/base/app/src/main/java/com/music/spotui/di/AutoBrowser.kt
@@ -6,12 +6,19 @@ import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat.MediaItem
import android.support.v4.media.MediaDescriptionCompat
import app.myspoti.engine.R
+import app.myspoti.host.android.MyspotiRuntime
import com.music.spotui.data.api.Response
import com.music.spotui.data.entity.ContextPageModel
import com.music.spotui.data.entity.SongsModel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeoutOrNull
+/**
+ * The hidden player did not come up in time (cold start, no network). The browse answer is
+ * an empty folder then — MediaBrowserCompat has no error reply — and the log says why.
+ */
+class AudioNotReady(what: String) : IllegalStateException("player not ready: $what")
+
/**
* Android Auto / media browser tree, built from the app's own data (not the web page):
* Liked Songs, playlists, albums, followed artists, and search. Tapping a track plays it
@@ -23,40 +30,52 @@ import kotlinx.coroutines.withTimeoutOrNull
object AutoBrowser {
const val ROOT = "root"
private const val TIMEOUT_MS = 15_000L
+ /** Cold start: the car binds before the hidden Web Player is up; browse waits this long. */
+ private const val READY_WAIT_MS = 25_000L
// Contexts recently listed, so a tap plays with the right queue.
private val pages = java.util.concurrent.ConcurrentHashMap<String, ContextPageModel>()
- suspend fun children(context: Context, parentId: String): List<MediaItem> = when {
- parentId == ROOT -> listOf(
+ /**
+ * Browse for [parentId]. The root is static and answers at once, so the car draws its
+ * four folders while the page loads; every other node needs the session, and waits for
+ * it instead of returning an empty list, which Android Auto keeps as the folder's
+ * content until it unsubscribes (issue #41, cold start).
+ */
+ suspend fun children(context: Context, parentId: String): List<MediaItem> {
+ if (parentId == ROOT) return listOf(
browsable("liked", context.getString(R.string.collection_liked_songs_title), null, grid = false),
browsable("playlists", context.getString(R.string.aa_playlists), null, grid = false),
browsable("albums", context.getString(R.string.aa_albums), null, grid = false),
browsable("artists", context.getString(R.string.aa_artists), null, grid = false),
)
- parentId == "playlists" || parentId == "albums" -> {
- val wantPlaylists = parentId == "playlists"
- val entries = (firstResult { Graph.api.getLibrary() } ?: emptyList())
- .filter { it.isPlaylist == wantPlaylists && it.spotifyId != com.music.spotui.data.api.Api.HomeCache.LIKED_SONGS_ID }
- entries.map { e ->
- browsable(if (wantPlaylists) "pl:${e.spotifyId}" else "al:${e.spotifyId}", e.name, e.coverUri, subtitle = e.subtitle)
+ if (!awaitPlayer()) throw AudioNotReady("browse $parentId")
+ return when {
+ parentId == "playlists" || parentId == "albums" -> {
+ val wantPlaylists = parentId == "playlists"
+ val entries = (firstResult { Graph.api.getLibrary() } ?: emptyList())
+ .filter { it.isPlaylist == wantPlaylists && it.spotifyId != com.music.spotui.data.api.Api.HomeCache.LIKED_SONGS_ID }
+ entries.map { e ->
+ browsable(if (wantPlaylists) "pl:${e.spotifyId}" else "al:${e.spotifyId}", e.name, e.coverUri, subtitle = e.subtitle)
+ }
}
+ parentId == "artists" -> Graph.api.getFollowedArtists().filter { it.id.isNotBlank() }.map { a ->
+ browsable("ar:${a.id}|${a.name}", a.name, a.coverUri)
+ }
+ parentId == "liked" -> tracksOf(firstResult { Graph.api.getLikedPage() })
+ parentId.startsWith("pl:") -> tracksOf(firstResult { Graph.api.getPlaylistPage(parentId.removePrefix("pl:")) })
+ parentId.startsWith("al:") -> tracksOf(firstResult { Graph.api.getAlbumPage(parentId.removePrefix("al:")) })
+ parentId.startsWith("ar:") -> {
+ val (id, name) = parentId.removePrefix("ar:").split("|", limit = 2).let { it[0] to it.getOrElse(1) { "" } }
+ val overview = firstResult { Graph.api.getArtistOverview(name, id) }
+ overview?.topTracks?.map { playable("spotify:artist:$id", it.song) }.orEmpty()
+ }
+ else -> emptyList()
}
- parentId == "artists" -> Graph.api.getFollowedArtists().filter { it.id.isNotBlank() }.map { a ->
- browsable("ar:${a.id}|${a.name}", a.name, a.coverUri)
- }
- parentId == "liked" -> tracksOf(firstResult { Graph.api.getLikedPage() })
- parentId.startsWith("pl:") -> tracksOf(firstResult { Graph.api.getPlaylistPage(parentId.removePrefix("pl:")) })
- parentId.startsWith("al:") -> tracksOf(firstResult { Graph.api.getAlbumPage(parentId.removePrefix("al:")) })
- parentId.startsWith("ar:") -> {
- val (id, name) = parentId.removePrefix("ar:").split("|", limit = 2).let { it[0] to it.getOrElse(1) { "" } }
- val overview = firstResult { Graph.api.getArtistOverview(name, id) }
- overview?.topTracks?.map { playable("spotify:artist:$id", it.song) }.orEmpty()
- }
- else -> emptyList()
}
suspend fun search(query: String): List<MediaItem> {
+ if (!awaitPlayer()) throw AudioNotReady("search")
val r = firstResult { Graph.api.searchEverything(query) } ?: return emptyList()
return r.songs.take(20).map { playable("", it) } +
r.albums.filter { it.spotifyId.isNotBlank() }.take(8).map { browsable("al:${it.spotifyId}", it.name, it.coverUri, subtitle = it.artists) }
@@ -64,11 +83,22 @@ object AutoBrowser {
/** Voice search ("play X on Myspoti"): the best matching track. */
suspend fun playFromSearch(query: String): Boolean {
+ // A cold start asks before the page is up: waiting gives the answer, returning at
+ // once would tell the driver nothing matched.
+ if (!awaitPlayer()) {
+ android.util.Log.w("Myspoti", "voice search dropped: the player page is not ready")
+ return false
+ }
val song = (firstResult { Graph.api.searchEverything(query) })?.songs?.firstOrNull() ?: return false
play("t||${song.url}")
return true
}
+ /** [MyspotiRuntime.api.ready], waited for (bounded) — the page loads after the car connects. */
+ private suspend fun awaitPlayer(): Boolean =
+ MyspotiRuntime.api.ready.value ||
+ withTimeoutOrNull(READY_WAIT_MS) { MyspotiRuntime.api.ready.first { it } } != null
+
fun play(mediaId: String) {
val parts = mediaId.split("|", limit = 3)
if (parts.size < 3 || parts[0] != "t") return
diff --git a/base/app/src/main/java/com/music/spotui/di/Graph.kt b/base/app/src/main/java/com/music/spotui/di/Graph.kt
index c08bb538..4e2e04f5 100644
--- a/base/app/src/main/java/com/music/spotui/di/Graph.kt
+++ b/base/app/src/main/java/com/music/spotui/di/Graph.kt
@@ -18,6 +18,8 @@ object Graph {
MyspotiRuntime.start(application, loadPage = !com.music.spotui.data.DataSaver.active)
// The streaming quality the user chose, set on the player at every page load.
com.music.spotui.data.preferences.applyStreamingQuality(com.music.spotui.data.preferences.getStreamingQuality(application))
+ // The crossfade length (0 = off), in the player from the first song on.
+ com.music.spotui.data.preferences.applyCrossfade(com.music.spotui.data.preferences.getCrossfadeSeconds(application))
com.music.spotui.data.local.ListenHistory.init(application)
// Downloaded songs (private storage), and the downloads left unfinished last time.
// Supporter thank-yous (accent colour) before any screen draws.
@@ -29,6 +31,8 @@ object Graph {
com.music.spotui.data.local.LibraryOrder.init(application)
runCatching { com.music.spotui.data.DataSaverGlide.install(application) }
com.music.spotui.data.offline.OfflineDownloader.resumePending()
+ // Episodes have their own queue and their own file: resumed the same way.
+ com.music.spotui.data.offline.PodcastDownloader.resumePending()
}
val api: Api by lazy { Api(app) }
diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
index 057a58dd..77592ed1 100644
--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt
@@ -42,6 +42,8 @@ object SongPlayer {
private const val TRANSPORT_TIMEOUT_MS = 15_000L
/** How long a play has to show up in the page's state before it is sent again. */
private const val PLAY_CHECK_MS = 4_000L
+ /** A resume of an episode that the page did not take is asked for again after that. */
+ private const val EPISODE_RESUME_CHECK_MS = 2_500L
/** "Next" taps closer than this are sent as one jump. */
private const val SKIP_BURST_MS = 350L
/** After a local file starts, engine states this recent still predate the pause. */
@@ -57,6 +59,13 @@ object SongPlayer {
private val bufferingState = mutableStateOf(false)
/** Observable startup state: visual lookups wait for the audio transport. */
val isBuffering: Boolean get() = bufferingState.value
+
+ /**
+ * An ad break is on (T4). The page publishes no track while one plays — the song before it
+ * stays in the state, buffering — so the screens show this instead of that stale song.
+ */
+ private val adState = mutableStateOf(false)
+ val adPlaying: Boolean get() = adState.value
@Volatile private var durationMs = 0L
@Volatile private var positionMs = 0L
@Volatile private var positionAt = 0L
@@ -137,20 +146,23 @@ object SongPlayer {
com.music.spotui.data.preferences.isLyricsExtraSources(Graph.app)
restoreLastTrack(state)
scope.launch { api.player.state.collect { s -> if (acceptsSessionUpdates()) applyState(s) } }
- // Another device plays (the phone as a remote): the page does not always report its
- // changes, so the state is read again every few seconds and the notification, the
- // mini player and the slider follow that device.
+ // Another device plays (the phone as a remote), or the app sits in the background while the
+ // page's own reports go quiet: the state is read again every few seconds so the
+ // notification, the mini player and the slider keep up. Reported: the notification stopped
+ // refreshing in the background — this loop waited for _activeDevice, which only a pull-back
+ // sets, so an app started in the background never ran it.
scope.launch {
- androidx.compose.runtime.snapshotFlow { _activeDevice.value }.collectLatest { remote ->
- if (remote == null) return@collectLatest
- while (true) {
- kotlinx.coroutines.delay(REMOTE_REFRESH_MS)
- runCatching { MyspotiRuntime.spotify.player.refresh() }
- }
+ while (true) {
+ kotlinx.coroutines.delay(REMOTE_REFRESH_MS)
+ if (_activeDevice.value == null && !PlaybackService.isRunning) continue
+ runCatching { MyspotiRuntime.spotify.player.refresh() }
}
}
scope.launch { api.player.queue.collect { q -> if (acceptsSessionUpdates()) applyQueue(q) } }
scope.launch { api.library.changes.collect { refreshCurrentLiked() } }
+ // T4: the player keeps the ad out of [api.player.state] on purpose (the last song stays
+ // there, buffering); its own flag is collected here so the UI can say an ad is on.
+ scope.launch { MyspotiRuntime.spotify.player.adPlaying.collect(::onAdPlaying) }
scope.launch {
MyspotiRuntime.spotify.player.refused.collect {
android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.play_refused, android.widget.Toast.LENGTH_LONG).show()
@@ -229,9 +241,9 @@ object SongPlayer {
intentUri = ""; intentUntil = 0L
wantPlayingUntil = 0L; wantPausedUntil = 0L
stateSeen = false
- playing = false; bufferingState.value = false; durationMs = 0L; positionMs = 0L
+ playing = false; bufferingState.value = false; adState.value = false; durationMs = 0L; positionMs = 0L
currentTrackId = ""; currentContextUri = ""
- contextRegistry.clear(); library.clear()
+ contextRegistry.clear(); contextNames.clear(); library.clear()
synchronized(wantedSaved) { wantedSaved.clear() }
_queue.value = EngineQueue(); apiQueue = null; _nowPlaying.value = NowPlaying()
lastTrackPrefs().edit().clear().apply(); savedLast = ""; resumeWhenReady = false
@@ -266,27 +278,40 @@ object SongPlayer {
)
}
+ /** An ad break starts or ends: the notification, the widget and the screens follow (T4). */
+ private fun onAdPlaying(on: Boolean) {
+ if (adState.value == on) return
+ adState.value = on
+ pushNotification(null, boundState?.likeState?.value ?: false)
+ }
+
/** Notification, lock screen, Bluetooth and Android Auto. */
private fun pushNotification(song: SongsModel?, liked: Boolean) {
val st = boundState
+ // T4: during an ad break the page reports no track (the song before it would sit there,
+ // buffering), so the notification and the widget say an ad is on instead of that song.
+ val ad = adState.value
+ val title = if (ad) Graph.app.getString(app.myspoti.engine.R.string.ad_playing) else song?.title ?: st?.title?.value.orEmpty()
+ val artist = if (ad) "" else song?.singer ?: st?.singer?.value.orEmpty()
+ val cover = if (ad) null else song?.coverUri ?: st?.coverUri?.value
PlaybackService.update(Graph.app, NowPlayingInfo(
- id = _nowPlaying.value.uri,
- title = song?.title ?: st?.title?.value.orEmpty(),
- artist = song?.singer ?: st?.singer?.value.orEmpty(),
- album = song?.album ?: st?.album?.value.orEmpty(),
- coverUrl = song?.coverUri ?: st?.coverUri?.value,
- durationMs = getDuration(),
- positionMs = getCurrentPosition(),
- playing = isPlaying(),
- buffering = isBuffering,
- liked = liked,
+ id = if (ad) "spotify:ad" else _nowPlaying.value.uri,
+ title = title,
+ artist = artist,
+ album = if (ad) "" else song?.album ?: st?.album?.value.orEmpty(),
+ coverUrl = cover,
+ durationMs = if (ad) 0L else getDuration(),
+ positionMs = if (ad) 0L else getCurrentPosition(),
+ playing = isPlaying() && !ad,
+ buffering = isBuffering && !ad,
+ liked = !ad && liked,
shuffle = st?.shuffle?.value == true,
))
com.music.spotui.widget.NowPlayingWidget.show(Graph.app,
- title = song?.title ?: st?.title?.value.orEmpty(),
- artist = song?.singer ?: st?.singer?.value.orEmpty(),
- coverUrl = song?.coverUri ?: st?.coverUri?.value,
- playing = isPlaying())
+ title = title,
+ artist = artist,
+ coverUrl = cover,
+ playing = isPlaying() && !ad)
}
/** The autoplay item already paused on, so it is paused once, not on every state. */
@@ -327,7 +352,11 @@ object SongPlayer {
}
val trackChanged = uri != _nowPlaying.value.uri
// Autoplay off: stop once, when the player moves on to a track it picked itself.
- if (item != null && item.provider == "autoplay" && uri != autoplayHandledUri && !com.music.spotui.data.preferences.AutoplayPref.on) {
+ // Tracks only: this is the music setting (similar songs). An episode the page rolls on
+ // to after the previous one belongs to the show, not to that recommendation autoplay —
+ // pausing it there is how a podcast "stopped by itself" (B11).
+ if (item != null && item.provider == "autoplay" && uri.startsWith(SPOTIFY_TRACK_PREFIX) &&
+ uri != autoplayHandledUri && !com.music.spotui.data.preferences.AutoplayPref.on) {
autoplayHandledUri = uri
if (!s.isPaused) pauseSilently()
}
@@ -345,6 +374,8 @@ object SongPlayer {
)
val state = boundState ?: return
state.shuffle.value = s.shuffle
+ // The page reports a speed other than 1 only for episodes: music stays at 1.
+ _speed.value = s.speed.takeIf { it > 0.0 } ?: 1.0
_repeatMode.value = s.repeat.ordinal
state.repeat.value = s.repeat != Repeat.OFF
if (item == null) {
@@ -453,19 +484,23 @@ object SongPlayer {
* song until restarted); one still waiting when a newer one comes is dropped.
*/
/** [pullBack]: playback taken by another device comes back here first (not for a pause). */
- private fun transport(pullBack: Boolean = true, block: suspend (isLatest: () -> Boolean) -> Unit) {
+ /**
+ * [waitReady]: wait for the page when it is loading. Skips do not once a state was seen:
+ * the player keeps them for after the reload (the song the taps point at plays then).
+ */
+ private fun transport(pullBack: Boolean = true, waitReady: Boolean = true, block: suspend (isLatest: () -> Boolean) -> Unit) {
val gen = transportGen.incrementAndGet()
scope.launch {
transportLock.withLock {
if (gen != transportGen.get()) return@withLock
// A tap while the page loads (cold start, a reload): sent once it is there,
// instead of failing at once with "not ready".
- if (!api.ready.value && kotlinx.coroutines.withTimeoutOrNull(READY_WAIT_MS) { api.ready.first { it } } == null) {
+ if (waitReady && !api.ready.value && kotlinx.coroutines.withTimeoutOrNull(READY_WAIT_MS) { api.ready.first { it } } == null) {
Log.w(TAG, "transport dropped: the player page is not ready")
return@withLock
}
if (gen != transportGen.get()) return@withLock
- if (pullBack) takeBackPlayback()
+ if (pullBack && api.ready.value) takeBackPlayback()
// A cancellation of the caller is never swallowed (it must unwind); only the
// transport's own timeout and a real failure are logged here.
try {
@@ -501,6 +536,20 @@ object SongPlayer {
urls.forEach { contextRegistry[it] = contextUri }
}
+ // Names of the lists playback started from, as the app's own pages name them. Spotify's
+ // state carries a context label, but it comes back blank for some lists, and the player
+ // then showed the album name instead of the playlist's (B26). A context the page does not
+ // name is shown with the name the app played it from.
+ private val contextNames = ConcurrentHashMap<String, String>()
+
+ /** [name] of the list at [contextUri], for the player header and the queue sheet. */
+ fun registerContextName(contextUri: String, name: String) {
+ if (contextUri.isNotBlank() && name.isNotBlank()) contextNames[contextUri] = name
+ }
+
+ /** The app's name for [contextUri], "" when the app never played from it (B26). */
+ fun knownContextName(contextUri: String): String = contextNames[contextUri].orEmpty()
+
/** Liked Songs plays as its own context: Spotify maps it to the account's liked list. */
fun registerLikedSongs(urls: List<String>) = registerContext(urls, LIKED_CONTEXT)
@@ -548,7 +597,21 @@ object SongPlayer {
Haptics.click(); intendPlaying(); playing = true; positionAt = SystemClock.elapsedRealtime()
// Tapped on the restored mini player while the Web Player is still loading.
if (!stateSeen) resumeWhenReady = true
+ val uri = _nowPlaying.value.uri
transport { api.player.resume() }
+ // An episode ignored by a plain resume (the page's element stays paused, which is what
+ // "the podcast stopped and the play button does nothing" was — B11) is asked for again
+ // by its uri, where it was. Music keeps the plain resume: it never showed that.
+ if (!uri.startsWith("spotify:episode:")) return
+ scope.launch {
+ kotlinx.coroutines.delay(EPISODE_RESUME_CHECK_MS)
+ if (!playing || LocalPlayer.active.value) return@launch
+ val s = api.player.state.value
+ if (s?.item?.uri == uri && s.isPaused) {
+ Log.i(TAG, "episode resume not taken: playing $uri again")
+ runCatching { api.player.play(uri, positionMs = getCurrentPosition()) }
+ }
+ }
}
fun pause() { Haptics.click(); pauseSilently() }
@@ -575,7 +638,7 @@ object SongPlayer {
burstUpcoming = apiQueue?.let { it.queued + it.nextUp }.orEmpty()
burstTaps = 1
pendingSkips = 0
- transport { api.player.next() }
+ transport(waitReady = !stateSeen) { api.player.next() }
return
}
burstAt = now
@@ -595,9 +658,9 @@ object SongPlayer {
pendingSkips = 0
// The song [burstTaps] after the one playing at the first tap.
val target = burstUpcoming.getOrNull(burstTaps - 1)
- transport { if (target == null) api.player.next() else api.player.skipTo(target) }
+ transport(waitReady = !stateSeen) { if (target == null) api.player.next() else api.player.skipTo(target) }
}
- fun previous() { Haptics.click(); if (LocalPlayer.active.value) { LocalPlayer.previous(); return }; intendPlaying(); transport { api.player.previous() } }
+ fun previous() { Haptics.click(); if (LocalPlayer.active.value) { LocalPlayer.previous(); return }; intendPlaying(); transport(waitReady = !stateSeen) { api.player.previous() } }
/** Tracks shufflePlay plays without a context: the first one, plus up to 49 queued. */
private const val SHUFFLE_QUEUE_MAX = 50
@@ -605,6 +668,12 @@ object SongPlayer {
private const val PULL_BACK_SETTLE_MS = 600L
private const val PULL_BACK_WAIT_MS = 6_000L
private const val DEVICES_WAIT_MS = 2_000L
+
+ /**
+ * How long the device list read by [takeBackPlayback] is trusted. Long enough that a burst of
+ * taps pays for it once, short enough that a device taking playback in between is noticed.
+ */
+ private const val DEVICES_FRESH_MS = 10_000L
/** A transport command waits that long for the page to load before it is dropped. */
private const val READY_WAIT_MS = 30_000L
@@ -651,7 +720,34 @@ object SongPlayer {
fun cycleRepeat() = setRepeatMode((_repeatMode.value + 1) % 3)
/** Podcast playback speed (Spotify refuses it on music). */
- fun setSpeed(speed: Double) = command { api.player.setSpeed(speed) }
+ fun setSpeed(speed: Double) {
+ _speed.value = speed
+ command { api.player.setSpeed(speed) }
+ }
+
+ private val _speed = mutableStateOf(1.0)
+ /** The speed Spotify reports for what plays (podcasts only); 1.0 for music. */
+ val speed: State<Double> get() = _speed
+
+ /** Lands within the episode when skipping: Spotify refuses a position past the end. */
+ fun skipBy(deltaMs: Long) {
+ val duration = getDuration()
+ val target = (getCurrentPosition() + deltaMs).coerceAtLeast(0L)
+ seekTo(if (duration > 0) target.coerceAtMost(duration - 1_000L) else target)
+ }
+
+ /** "Add to queue" for a podcast episode (its uri, not a track id). */
+ fun addEpisodeToQueue(url: String) {
+ val id = url.removePrefix("episode:").takeIf { url.startsWith("episode:") } ?: return
+ Haptics.confirm()
+ command { api.player.addToQueue(listOf("spotify:episode:$id")) }
+ }
+
+ /**
+ * What plays is a podcast episode: the player shows its own controls (30-second-free
+ * skips, speed, no shuffle), not the music ones.
+ */
+ val isEpisode: Boolean get() = _nowPlaying.value.uri.startsWith("spotify:episode:")
fun lyricsTrack(s: SongsModel) = com.music.spotui.data.api.LyricsApi.Track(
trackId = s.spotifyTrackId, title = s.title, artist = s.singer, album = s.album,
@@ -894,18 +990,39 @@ object SongPlayer {
* same account, for instance): Myspoti's play, skip and previous then drove that device,
* where a free account's commands are refused. The music comes back to this phone first.
*/
+ /** When [takeBackPlayback] last read the device list; 0 = never read (read it now). */
+ @Volatile private var devicesFreshUntil = 0L
+
private suspend fun takeBackPlayback() {
// The device list as Spotify has it now: the one kept here is only refreshed on a song
// change, and after a cold start it does not know a device that took playback before.
+ // But this used to run on EVERY tap, i.e. a server round trip before the song was even
+ // asked for: measured 963 ms from tap to sound against 554 ms for a skip, which takes the
+ // same playback path without this call. The list is read again only once the entry is
+ // older than [DEVICES_FRESH_MS] — a takeover within those seconds is still caught by the
+ // play check (the page does not move, the play is sent again) and by the next read.
+ // Measured (15/10 run): this refresh answers from the page's cache in 8-36 ms, so it is not
+ // what makes a tap slower than a skip (963 vs 554 ms then) — keeping it unconditional keeps
+ // "a device that took playback is pulled back at once" (beta.7 behaviour). The timing stays
+ // in the log because the day it becomes slow, that line says so.
+ devicesFreshUntil = 0L
+ val started = System.currentTimeMillis()
kotlinx.coroutines.withTimeoutOrNull(DEVICES_WAIT_MS) { runCatching { api.devices.refresh() } }
+ Log.i(TAG, "device list read in ${System.currentTimeMillis() - started} ms")
val active = api.devices.devices.value.firstOrNull { it.active }
_activeDevice.value = active?.takeIf { !it.local }?.let { ConnectDevice(it.id, it.name, it.type, false, true) }
val remote = _activeDevice.value ?: return
if (remote.id == chosenRemote) return
Log.i(TAG, "playback taken by ${remote.name}: pulled back here")
+ // A pull-back can land on this phone at 0:00 (reported: "sometimes on Connect the sound
+ // starts over"). The position is remembered across the pull and restored only when the same
+ // item really rolled back — a new play right after this call asks for its own position.
+ val before = api.player.state.value?.let { s -> s.item?.uri?.let { uri -> uri to s.positionAt(System.currentTimeMillis()) } }
// Bounded: a transfer from a device that went away can leave the page's promise
// pending for ever, and every later command waiting behind it.
val pulled = kotlinx.coroutines.withTimeoutOrNull(PULL_BACK_WAIT_MS) { runCatching { api.devices.pullHere() } }
+ // Whatever happened, the list just changed under us: read it again next time.
+ devicesFreshUntil = 0L
if (pulled?.isSuccess != true) Log.w(TAG, "pull here failed: ${pulled?.exceptionOrNull()?.message ?: "no answer"}")
// No answer: the page's Connect layer waits on that device and would hold every later
// command. A new page claims playback for itself at the first command.
@@ -916,6 +1033,18 @@ object SongPlayer {
_activeDevice.value = null
PlaybackService.setPlaybackDevice(false, remoteVolume)
kotlinx.coroutines.delay(PULL_BACK_SETTLE_MS)
+ // Same item but an earlier position: the page restarted it. Put the listener back where they
+ // were. Anything else (a different item, a position that did not move back) is left alone.
+ before?.let { (uri, pos) ->
+ val now = api.player.state.value
+ val at = now?.positionAt(System.currentTimeMillis()) ?: return@let
+ if (now.item?.uri == uri && pos > 3_000 && at < pos - 3_000) {
+ Log.i(TAG, "playback came back at $at ms on the same item: back to $pos ms")
+ runCatching { api.player.seek(pos) }
+ } else {
+ Log.i(TAG, "playback came back at $at ms (item ${now.item?.uri})")
+ }
+ }
}
/** Move playback to [device] (Spotify Connect transfer). */
@@ -1015,7 +1144,7 @@ object SongPlayer {
durationMs = item.song.durationMs.toLong()
pushNotification(item.song, false)
val target = apiItem(item) ?: return
- transport { api.player.skipTo(target) }
+ transport(waitReady = !stateSeen) { api.player.skipTo(target) }
}
/** "Clear queue": drops the tracks the user queued (not the context's next ones). */
@@ -1138,7 +1267,9 @@ object SongPlayer {
}
}
- fun isCrossfadeActive(): Boolean = false
+ /** True while a crossfade is fading this song out, or the next one in (see [SpotifyPlayer]). */
+ fun isCrossfadeActive(): Boolean =
+ MyspotiRuntime.isStarted && MyspotiRuntime.spotify.player.isCrossfading()
fun release() {}
// ── Play-key helpers (url = "spotify:track:<id>|<search text>") ──
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AddToPlaylistSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/AddToPlaylistSheet.kt
new file mode 100644
index 00000000..bdcb59f3
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/components/AddToPlaylistSheet.kt
@@ -0,0 +1,172 @@
+package com.music.spotui.ui.components
+
+import android.content.Context
+import android.os.Handler
+import android.os.Looper
+import android.widget.Toast
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Add
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Icon
+import androidx.compose.material3.ModalBottomSheet
+import androidx.compose.material3.Text
+import androidx.compose.material3.rememberModalBottomSheetState
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.res.pluralStringResource
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import app.myspoti.engine.R
+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
+import com.bumptech.glide.integration.compose.GlideImage
+import com.bumptech.glide.integration.compose.placeholder
+import com.music.spotui.data.api.EditablePlaylist
+import com.music.spotui.data.api.EditablePlaylists
+import com.music.spotui.data.api.SpotifySync
+import com.music.spotui.data.entity.SongsModel
+
+/**
+ * "Add to another playlist": one tap copies the track into a playlist the user picks.
+ *
+ * Add-only on purpose — the "Saved in" sheet stays the place where the track is toggled in
+ * and out of several lists; this one is the short path asked for by the testers, with a
+ * search field because a library folds into dozens of rows. The playlist the track is
+ * already shown in is filtered out: adding it there would only make a duplicate entry.
+ */
+@OptIn(ExperimentalMaterial3Api::class, ExperimentalGlideComposeApi::class)
+@Composable
+fun AddToPlaylistSheet(
+ song: SongsModel,
+ context: Context,
+ onDismiss: () -> Unit,
+ excludePlaylistId: String? = null,
+) {
+ val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
+ var playlists by remember { mutableStateOf<List<EditablePlaylist>?>(null) }
+ var query by remember { mutableStateOf("") }
+ LaunchedEffect(Unit) {
+ // Folders flattened: adding to a playlist does not need the folder tree.
+ playlists = EditablePlaylists.load()
+ }
+ // Filtered in one pass; accent-insensitive like the other "find" fields of the app.
+ val shown = remember(playlists, query) {
+ playlists.orEmpty().filter { it.id != excludePlaylistId && matchesFind(query, it.name) }
+ }
+
+ fun addTo(playlist: EditablePlaylist) {
+ onDismiss()
+ SpotifySync.addTrackToPlaylist(context, playlist.id, song.spotifyTrackId) { ok ->
+ // The write runs on the main dispatcher already; posted anyway so the toast
+ // survives the sheet's teardown.
+ Handler(Looper.getMainLooper()).post {
+ val text = if (ok) context.getString(R.string.local_added_to, playlist.name)
+ else context.getString(R.string.playlist_change_refused)
+ Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
+ }
+ }
+ }
+
+ ModalBottomSheet(
+ onDismissRequest = onDismiss,
+ sheetState = sheetState,
+ containerColor = androidx.compose.ui.graphics.Color(0xFF1A1A1A),
+ ) {
+ Column(modifier = Modifier.navigationBarsPadding().imePadding()) {
+ Text(
+ stringResource(R.string.context_menu_add_to_another_playlist),
+ color = androidx.compose.ui.graphics.Color.White,
+ fontSize = 20.sp,
+ fontWeight = FontWeight.Bold,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(20.dp, 4.dp, 20.dp, 12.dp),
+ )
+ FindInListField(
+ query = query,
+ onQuery = { query = it },
+ hint = stringResource(R.string.add_to_playlist_search_hint),
+ modifier = Modifier.padding(horizontal = 20.dp),
+ )
+ val list = playlists
+ when {
+ list == null -> Text(
+ stringResource(R.string.loading_playlists),
+ color = androidx.compose.ui.graphics.Color.Gray, fontSize = 14.sp,
+ modifier = Modifier.padding(20.dp, 12.dp),
+ )
+ shown.isEmpty() -> Text(
+ stringResource(if (list.isEmpty()) R.string.add_to_playlist_empty else R.string.add_to_playlist_no_match, query.trim()),
+ color = androidx.compose.ui.graphics.Color.Gray, fontSize = 14.sp,
+ modifier = Modifier.padding(20.dp, 12.dp),
+ )
+ else -> LazyColumn(modifier = Modifier.heightIn(max = 420.dp).padding(top = 4.dp)) {
+ items(shown.size) { i ->
+ val pl = shown[i]
+ PickRow(pl) { addTo(pl) }
+ }
+ }
+ }
+ Spacer(Modifier.height(16.dp))
+ }
+ }
+}
+
+@OptIn(ExperimentalGlideComposeApi::class)
+@Composable
+private fun PickRow(playlist: EditablePlaylist, onClick: () -> Unit) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(horizontal = 20.dp, vertical = 8.dp),
+ ) {
+ GlideImage(
+ transition = CrossFade,
+ modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)),
+ model = playlist.imageUrl,
+ contentScale = ContentScale.Crop,
+ failure = placeholder(R.drawable.placeholder),
+ loading = placeholder(R.drawable.placeholder),
+ contentDescription = "",
+ )
+ Column(Modifier.weight(1f).padding(start = 14.dp)) {
+ Text(playlist.name, color = androidx.compose.ui.graphics.Color.White, fontSize = 15.sp, fontWeight = FontWeight.Medium,
+ maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(
+ pluralStringResource(R.plurals.liked_songs_header_metadata_text, playlist.trackCount, playlist.trackCount),
+ color = androidx.compose.ui.graphics.Color.Gray, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,
+ )
+ }
+ Spacer(Modifier.width(8.dp))
+ Icon(
+ Icons.Default.Add,
+ contentDescription = null,
+ tint = androidx.compose.ui.graphics.Color(0xFFB3B3B3),
+ modifier = Modifier.size(22.dp),
+ )
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt b/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt
index 6958a259..cc5b7bb2 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt
@@ -22,6 +22,8 @@ import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
+import androidx.compose.material.icons.filled.BluetoothAudio
+import androidx.compose.material.icons.filled.Headphones
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Slider
@@ -53,6 +55,7 @@ import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import app.myspoti.engine.R
@@ -137,6 +140,15 @@ fun MiniPlayer(navController: NavHostController) {
val liked = vm.likeState.value
val np by SongPlayer.nowPlaying
val context = LocalContext.current
+ // A29: where the sound goes when it is not this phone's speaker. rememberAudioRoute
+ // follows devices coming and going, so plugging a headset or getting in the car
+ // updates the label without the screen reopening.
+ val route = rememberAudioRoute()
+ val routeLabel = when (route.kind) {
+ AudioRoute.Kind.SPEAKER -> null
+ AudioRoute.Kind.BLUETOOTH -> route.name.ifBlank { stringResource(R.string.label_bluetooth) }
+ AudioRoute.Kind.WIRED -> stringResource(R.string.headphones)
+ }
// Card tint from the cover — extracted once per cover, not on every recomposition.
var tint by remember { mutableStateOf(Palette.cachedFirst(songCoverUri) ?: Color(0xFF2A2A2A)) }
@@ -148,6 +160,9 @@ fun MiniPlayer(navController: NavHostController) {
}
}
+ // A new song cross-fades the card's colour instead of snapping to it.
+ val animatedTint by androidx.compose.animation.animateColorAsState(tint, androidx.compose.animation.core.tween(400), label = "miniTint")
+
// The Canvas of the song playing is looked up and loaded now, so the full player
// opens on it directly instead of showing the cover first.
val energy by app.myspoti.power.EnergySettings.state.collectAsStateWithLifecycle()
@@ -182,8 +197,7 @@ fun MiniPlayer(navController: NavHostController) {
modifier = Modifier.pressable(0.96f) { com.music.spotui.ui.navigation.PlayerSheet.show() }
.padding(horizontal = 8.dp)
.clip(RoundedCornerShape(8.dp))
- .background(tint)
-
+ .background(animatedTint)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -197,8 +211,12 @@ fun MiniPlayer(navController: NavHostController) {
modifier = Modifier.weight(1f),
) { page ->
val s = when (page) { 0 -> np.prev; 2 -> np.next; else -> null }
+ // T4: during an ad break the page publishes no track, so the song before it
+ // would sit in the mini player; an explicit ad state is shown instead.
+ val adPlaying = com.music.spotui.di.SongPlayer.adPlaying
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.size(40.dp)
.clip(RoundedCornerShape(4.dp)),
@@ -211,8 +229,28 @@ fun MiniPlayer(navController: NavHostController) {
val remote = SongPlayer.activeDevice.value
Column(modifier = Modifier.padding(start = 12.dp, end = 8.dp)) {
if (remote == null) {
- Text(text = s?.title ?: songTitle, color = Color.White, fontSize = 13.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)
- Text(text = s?.singer ?: songSinger, color = Color.White.copy(alpha = 0.7f), fontSize = 13.sp, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)
+ Text(text = if (adPlaying) stringResource(R.string.ad_playing) else (s?.title ?: songTitle), color = Color.White, fontSize = 13.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)
+ if (!adPlaying) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ // The artist yields the width: the output's name stays whole.
+ Text(
+ text = s?.singer ?: songSinger, color = Color.White.copy(alpha = 0.7f), fontSize = 13.sp,
+ maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f, fill = false),
+ )
+ if (routeLabel != null) {
+ Icon(
+ imageVector = if (route.kind == AudioRoute.Kind.BLUETOOTH) Icons.Filled.BluetoothAudio else Icons.Filled.Headphones,
+ contentDescription = stringResource(R.string.playing_on),
+ tint = Color.White.copy(alpha = 0.55f),
+ modifier = Modifier.padding(start = 6.dp).size(12.dp),
+ )
+ Text(
+ text = routeLabel, color = Color.White.copy(alpha = 0.55f), fontSize = 11.sp,
+ maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
+ modifier = Modifier.padding(start = 3.dp).widthIn(max = 110.dp),
+ )
+ }
+ }
} else {
// Playing on another device: "Title • Artist", then the device in green.
Text(
@@ -248,9 +286,8 @@ fun MiniPlayer(navController: NavHostController) {
Spacer(modifier = Modifier.width(20.dp))
if (!com.music.spotui.di.LocalPlayer.active.value) com.music.spotui.ui.screens.AddButton(song = { com.music.spotui.ui.screens.nowPlayingSong(vm) }, liked = liked, size = 24.dp) { vm.updateLikeState(true) }
Spacer(modifier = Modifier.width(20.dp))
- Icon(
- painter = if (songPlayingState) painterResource(id = R.drawable.ic_playing)
- else painterResource(id = R.drawable.play_svgrepo_com),
+ com.music.spotui.ui.components.PlayPauseIcon(
+ playing = songPlayingState,
contentDescription = if (songPlayingState) stringResource(R.string.content_description_pause_button) else stringResource(R.string.content_description_play_button),
tint = Color.White,
modifier = Modifier.pressable(0.96f) {
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/ArtistOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/ArtistOptionsSheet.kt
new file mode 100644
index 00000000..07749c08
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/components/ArtistOptionsSheet.kt
@@ -0,0 +1,114 @@
+package com.music.spotui.ui.components
+
+import android.content.Intent
+import android.widget.Toast
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Block
+import androidx.compose.material.icons.filled.Share
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.Icon
+import androidx.compose.material3.ModalBottomSheet
+import androidx.compose.material3.Text
+import androidx.compose.material3.rememberModalBottomSheetState
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.produceState
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import app.myspoti.engine.R
+import kotlinx.coroutines.launch
+
+/**
+ * B27: the ⋮ of an artist page's action row had no `clickable` and did nothing. It now opens
+ * the artist's own menu, with the actions the app can really do for an artist: share its link,
+ * and keep it out of (or back in) radios and mixes — the same taste-profile call the track
+ * menu's "Don't play this artist" uses.
+ */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun ArtistOptionsSheet(artistId: String, artistName: String, onDismiss: () -> Unit) {
+ val context = LocalContext.current
+ val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
+ val uri = "spotify:artist:$artistId"
+ // null = not known yet (or the call failed): the ban row stays disabled rather than lying.
+ val banned by produceState<Boolean?>(null, uri) {
+ if (artistId.isBlank()) return@produceState
+ value = runCatching {
+ app.myspoti.host.android.MyspotiRuntime.api.extras.isArtistBanned(listOf(uri)).single()
+ }.getOrNull()
+ }
+ ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState, containerColor = Color(0xFF282828)) {
+ Column(Modifier.navigationBarsPadding().verticalScroll(rememberScrollState())) {
+ Text(
+ artistName, color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold,
+ maxLines = 1, overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 12.dp),
+ )
+ HorizontalDivider(color = Color(0xFF3E3E3E), thickness = 0.5.dp)
+ Spacer(Modifier.height(8.dp))
+ ArtistMenuRow(Icons.Default.Share, stringResource(R.string.share_link), enabled = artistId.isNotBlank()) {
+ val send = Intent(Intent.ACTION_SEND).apply {
+ type = "text/plain"
+ putExtra(Intent.EXTRA_TEXT, "https://open.spotify.com/artist/$artistId")
+ }
+ context.startActivity(Intent.createChooser(send, context.getString(R.string.action_share_label)))
+ onDismiss()
+ }
+ ArtistMenuRow(
+ Icons.Default.Block,
+ stringResource(if (banned == true) R.string.artist_unban else R.string.artist_ban),
+ enabled = banned != null,
+ ) {
+ // The button shows the action it will do, so the flip is derived from the state.
+ val keepOut = banned != true
+ app.myspoti.host.android.MyspotiRuntime.scope.launch {
+ runCatching { app.myspoti.host.android.MyspotiRuntime.api.extras.setArtistBanned(uri, keepOut) }
+ }
+ Toast.makeText(
+ context,
+ context.getString(if (keepOut) R.string.artist_banned else R.string.artist_unbanned, artistName),
+ Toast.LENGTH_SHORT,
+ ).show()
+ com.music.spotui.di.Haptics.confirm()
+ onDismiss()
+ }
+ Spacer(Modifier.height(12.dp))
+ }
+ }
+}
+
+/** One row of the artist menu, laid out like the track menu's rows. */
+@Composable
+private fun ArtistMenuRow(icon: ImageVector, label: String, enabled: Boolean = true, onClick: () -> Unit) {
+ val tint = if (enabled) Color.White else Color(0xFF6A6A6A)
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable(enabled = enabled) { onClick() }
+ .padding(horizontal = 20.dp, vertical = 14.dp),
+ ) {
+ Icon(icon, contentDescription = null, tint = if (enabled) Color(0xFFB3B3B3) else Color(0xFF6A6A6A), modifier = Modifier.size(22.dp))
+ Text(label, color = tint, fontSize = 15.sp, modifier = Modifier.padding(start = 16.dp))
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AudioRoute.kt b/base/app/src/main/java/com/music/spotui/ui/components/AudioRoute.kt
index 74ea0424..32473081 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/AudioRoute.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/AudioRoute.kt
@@ -17,14 +17,19 @@ data class AudioRoute(val kind: Kind, val name: String) {
enum class Kind { SPEAKER, BLUETOOTH, WIRED }
companion object {
- /** The output media plays on now. Product names need no Bluetooth permission. */
+ /**
+ * The output media plays on now. Each name is read on its own: without
+ * BLUETOOTH_CONNECT the product name throws, and the route must still be known
+ * (the mini player then says "Bluetooth" instead of showing nothing).
+ */
fun current(context: Context): AudioRoute = runCatching {
val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
val outs = am.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
+ fun nameOf(device: AudioDeviceInfo) = runCatching { device.productName?.toString().orEmpty() }.getOrDefault("")
outs.firstOrNull { it.type == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP || it.type == AudioDeviceInfo.TYPE_BLE_HEADSET || it.type == AudioDeviceInfo.TYPE_BLE_SPEAKER }
- ?.let { return@runCatching AudioRoute(Kind.BLUETOOTH, it.productName?.toString().orEmpty()) }
+ ?.let { return@runCatching AudioRoute(Kind.BLUETOOTH, nameOf(it)) }
outs.firstOrNull { it.type == AudioDeviceInfo.TYPE_WIRED_HEADPHONES || it.type == AudioDeviceInfo.TYPE_WIRED_HEADSET || it.type == AudioDeviceInfo.TYPE_USB_HEADSET }
- ?.let { return@runCatching AudioRoute(Kind.WIRED, it.productName?.toString().orEmpty()) }
+ ?.let { return@runCatching AudioRoute(Kind.WIRED, nameOf(it)) }
AudioRoute(Kind.SPEAKER, "")
}.getOrDefault(AudioRoute(Kind.SPEAKER, ""))
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/EpisodeSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/EpisodeSheets.kt
new file mode 100644
index 00000000..185868fa
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/components/EpisodeSheets.kt
@@ -0,0 +1,289 @@
+package com.music.spotui.ui.components
+
+import android.content.Context
+import android.content.Intent
+import android.widget.Toast
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Check
+import androidx.compose.material.icons.filled.PlayArrow
+import androidx.compose.material.icons.outlined.Add
+import androidx.compose.material.icons.outlined.ArrowCircleDown
+import androidx.compose.material.icons.outlined.DeleteOutline
+import androidx.compose.material.icons.outlined.Done
+import androidx.compose.material.icons.outlined.Download
+import androidx.compose.material.icons.outlined.Info
+import androidx.compose.material.icons.outlined.PlaylistAdd
+import androidx.compose.material.icons.outlined.Share
+import androidx.compose.material.icons.outlined.Undo
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Icon
+import androidx.compose.material3.ModalBottomSheet
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import app.myspoti.engine.R
+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
+import com.bumptech.glide.integration.compose.GlideImage
+import com.music.spotui.data.entity.SongsModel
+import com.music.spotui.data.offline.OfflineStatus
+import com.music.spotui.data.offline.OfflineStore
+import com.music.spotui.data.offline.PodcastDownloader
+import com.music.spotui.data.offline.episodeKeyOf
+import com.music.spotui.di.SongPlayer
+
+private val Accent: Color get() = com.music.spotui.ui.theme.AppAccent
+private val Sheet: Color get() = Color(0xFF1F1F1F)
+
+/** "episode:<id>" — an episode has no track id; the downloader and the library key on this. */
+val SongsModel.episodeKey: String? get() = episodeKeyOf(this)
+
+/** Spotify's episode uri, as the page's own menu hands it around. */
+val SongsModel.spotifyUri: String get() = "spotify:$url"
+
+/**
+ * The row's download control: outlined arrow, progress ring, green disc when kept. A tap
+ * downloads, cancels or removes — as the button in the official row does.
+ */
+@Composable
+fun EpisodeDownloadButton(song: SongsModel, size: Dp = 26.dp) {
+ val context = LocalContext.current
+ val key = song.episodeKey ?: return
+ val status = OfflineStore.statusOf(key)
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier.size(size + 14.dp).clip(CircleShape).clickable {
+ when (status) {
+ OfflineStatus.Done -> {
+ PodcastDownloader.remove(key)
+ Toast.makeText(context, context.getString(R.string.toast_undownload), Toast.LENGTH_SHORT).show()
+ }
+ OfflineStatus.Queued, is OfflineStatus.Downloading -> PodcastDownloader.cancel(key)
+ else -> PodcastDownloader.enqueue(song)
+ }
+ },
+ ) {
+ when (status) {
+ null -> Icon(Icons.Outlined.Download, stringResource(R.string.episode_download), tint = Color.White.copy(alpha = 0.85f), modifier = Modifier.size(size))
+ else -> DownloadBadge(status, size = size)
+ }
+ }
+}
+
+/** The episode's own "…" menu, as the official app has it (no like, no lyrics, played marks). */
+@OptIn(ExperimentalMaterial3Api::class, ExperimentalGlideComposeApi::class)
+@Composable
+fun EpisodeOptionsSheet(
+ song: SongsModel,
+ finished: Boolean,
+ onPlay: () -> Unit,
+ onMarkFinished: (Boolean) -> Unit,
+ /** The episode page: shown only where there is a page to open. */
+ onOpen: (() -> Unit)? = null,
+ onDismiss: () -> Unit,
+) {
+ val context = LocalContext.current
+ val key = song.episodeKey
+ val status = key?.let { OfflineStore.statusOf(it) }
+ // The + / ✓ follows Spotify's library: ask once for this episode's saved state.
+ androidx.compose.runtime.LaunchedEffect(song.url) { SongPlayer.requestSaved(song.spotifyUri) }
+ val saved = SongPlayer.library[song.spotifyUri] == true
+ ModalBottomSheet(onDismissRequest = onDismiss, containerColor = Sheet) {
+ Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(20.dp, 4.dp, 20.dp, 16.dp)) {
+ GlideImage(
+ transition = CrossFade,
+ model = song.coverUri,
+ contentDescription = "",
+ contentScale = ContentScale.Crop,
+ modifier = Modifier.size(52.dp).clip(RoundedCornerShape(4.dp)),
+ )
+ Column(Modifier.weight(1f).padding(start = 12.dp)) {
+ Text(song.title, color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.Bold, maxLines = 2, overflow = TextOverflow.Ellipsis)
+ Text(song.singer, color = Color.White.copy(alpha = 0.65f), fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ }
+ SheetAction(Icons.Outlined.Share, stringResource(R.string.a11y_share)) {
+ onDismiss()
+ shareEpisode(context, song)
+ }
+ SheetAction(
+ if (saved) Icons.Default.Check else Icons.Outlined.Add,
+ stringResource(if (saved) R.string.episode_unsave else R.string.episode_save),
+ ) {
+ SongPlayer.setSaved(song.spotifyUri, !saved)
+ onDismiss()
+ }
+ when {
+ status == OfflineStatus.Done -> SheetAction(Icons.Outlined.DeleteOutline, stringResource(R.string.episode_download_remove)) {
+ key?.let { PodcastDownloader.remove(it) }
+ Toast.makeText(context, context.getString(R.string.toast_undownload), Toast.LENGTH_SHORT).show()
+ onDismiss()
+ }
+ status == OfflineStatus.Queued || status is OfflineStatus.Downloading ->
+ SheetAction(Icons.Outlined.ArrowCircleDown, stringResource(R.string.download_cancel)) {
+ key?.let { PodcastDownloader.cancel(it) }
+ onDismiss()
+ }
+ else -> SheetAction(Icons.Outlined.ArrowCircleDown, stringResource(R.string.episode_download)) {
+ PodcastDownloader.enqueue(song)
+ onDismiss()
+ }
+ }
+ // The mark the official episode menu carries and the music menu does not.
+ if (finished) {
+ SheetAction(Icons.Outlined.Undo, stringResource(R.string.episode_mark_unplayed)) {
+ onMarkFinished(false)
+ Toast.makeText(context, context.getString(R.string.episode_marked_unplayed), Toast.LENGTH_SHORT).show()
+ onDismiss()
+ }
+ } else {
+ SheetAction(Icons.Outlined.Done, stringResource(R.string.episode_mark_played)) {
+ onMarkFinished(true)
+ Toast.makeText(context, context.getString(R.string.episode_marked_played), Toast.LENGTH_SHORT).show()
+ onDismiss()
+ }
+ }
+ SheetAction(Icons.Outlined.PlaylistAdd, stringResource(R.string.episode_add_queue)) {
+ SongPlayer.addEpisodeToQueue(song.url)
+ onDismiss()
+ }
+ SheetAction(Icons.Default.PlayArrow, stringResource(R.string.episode_play)) {
+ onDismiss()
+ onPlay()
+ }
+ if (onOpen != null) SheetAction(Icons.Outlined.Info, stringResource(R.string.episode_open)) {
+ onDismiss()
+ onOpen()
+ }
+ }
+ }
+}
+
+@Composable
+private fun SheetAction(icon: ImageVector, label: String, onClick: () -> Unit) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(horizontal = 20.dp, vertical = 14.dp),
+ ) {
+ Icon(icon, contentDescription = null, tint = Color.White.copy(alpha = 0.9f), modifier = Modifier.size(22.dp))
+ Spacer(Modifier.width(16.dp))
+ Text(label, color = Color.White, fontSize = 15.sp)
+ }
+}
+
+/** Shares the episode's own link (the official app opens the same page). */
+fun shareEpisode(context: Context, song: SongsModel) {
+ val id = song.url.removePrefix("episode:")
+ val send = Intent(Intent.ACTION_SEND).apply {
+ type = "text/plain"
+ putExtra(Intent.EXTRA_TEXT, "https://open.spotify.com/episode/$id")
+ }
+ runCatching { context.startActivity(Intent.createChooser(send, context.getString(R.string.a11y_share))) }
+}
+
+/** "24 juil." from Spotify's ISO date; "" when the date is missing. */
+fun episodeDateLabel(iso: String): String {
+ if (iso.isBlank()) return ""
+ return runCatching {
+ val date = java.time.LocalDate.parse(iso.take(10))
+ date.format(java.time.format.DateTimeFormatter.ofPattern("d MMM", java.util.Locale.getDefault()))
+ }.getOrDefault("")
+}
+
+/** "12 min" for a row's meta line. */
+@Composable
+fun episodeMinutes(durationMs: Int): String =
+ stringResource(R.string.episode_duration_min, ((durationMs + 30_000) / 60_000).coerceAtLeast(1))
+
+/** "m:ss" for the player's clocks. */
+fun episodeClock(ms: Long): String {
+ val total = (ms / 1000).coerceAtLeast(0)
+ val h = total / 3600
+ val m = (total % 3600) / 60
+ val s = total % 60
+ return if (h > 0) String.format(java.util.Locale.US, "%d:%02d:%02d", h, m, s)
+ else String.format(java.util.Locale.US, "%d:%02d", m, s)
+}
+
+/** "1", "1,2", "1,5"… as the speed sheet shows them, in the phone's language. */
+fun speedLabel(speed: Double): String =
+ if (speed == Math.floor(speed)) speed.toInt().toString()
+ else String.format(java.util.Locale.getDefault(), "%.2f", speed).trimEnd('0').trimEnd('.')
+
+/** The stock app's speed sheet: the current value, its scale, then the presets. */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun PodcastSpeedSheet(onDismiss: () -> Unit) {
+ val current = SongPlayer.speed.value
+ ModalBottomSheet(onDismissRequest = onDismiss, containerColor = Sheet) {
+ Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 20.dp)) {
+ Text(
+ stringResource(R.string.playback_speed),
+ color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp),
+ )
+ Text(
+ text = stringResource(R.string.player_speed_chip, speedLabel(current)),
+ color = Accent, fontSize = 40.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.fillMaxWidth().padding(vertical = 12.dp),
+ textAlign = androidx.compose.ui.text.style.TextAlign.Center,
+ )
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp),
+ ) {
+ // The presets of the official sheet: 3× exists for podcasts.
+ listOf(1.0, 1.2, 1.5, 2.0, 3.0).forEach { speed ->
+ val selected = kotlin.math.abs(current - speed) < 0.01
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .weight(1f)
+ .height(44.dp)
+ .clip(CircleShape)
+ .background(if (selected) Color.White else Color.White.copy(alpha = 0.12f))
+ .clickable {
+ SongPlayer.setSpeed(speed)
+ onDismiss()
+ },
+ ) {
+ Text(
+ text = speedLabel(speed),
+ color = if (selected) Color.Black else Color.White,
+ fontSize = 15.sp,
+ fontWeight = FontWeight.Bold,
+ )
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/Motion.kt b/base/app/src/main/java/com/music/spotui/ui/components/Motion.kt
index 74c66637..023048af 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/Motion.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/Motion.kt
@@ -1,6 +1,19 @@
package com.music.spotui.ui.components
import androidx.compose.animation.core.Spring
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.scaleIn
+import androidx.compose.animation.scaleOut
+import androidx.compose.animation.togetherWith
+import androidx.compose.animation.core.tween
+import androidx.compose.material3.Icon
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.painterResource
+import app.myspoti.engine.R
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.foundation.clickable
@@ -62,3 +75,33 @@ fun Modifier.pressScale(source: MutableInteractionSource, pressedScale: Float =
)
graphicsLayer { scaleX = scale; scaleY = scale }
}
+
+/**
+ * The play/pause glyph of the official app: the new one springs in from a smaller size
+ * while the old one fades out, instead of swapping in a single frame. [playing] picks
+ * the pause glyph.
+ */
+@Composable
+fun PlayPauseIcon(
+ playing: Boolean,
+ contentDescription: String?,
+ tint: Color,
+ modifier: Modifier = Modifier,
+) {
+ AnimatedContent(
+ targetState = playing,
+ transitionSpec = {
+ (scaleIn(spring(dampingRatio = 0.55f, stiffness = Spring.StiffnessMediumLow), initialScale = 0.6f) + fadeIn(tween(120))) togetherWith
+ (scaleOut(tween(120), targetScale = 0.6f) + fadeOut(tween(90)))
+ },
+ contentAlignment = Alignment.Center,
+ label = "playPause",
+ ) { isPlaying ->
+ Icon(
+ painter = painterResource(if (isPlaying) R.drawable.ic_playing else R.drawable.play_svgrepo_com),
+ contentDescription = contentDescription,
+ tint = tint,
+ modifier = modifier,
+ )
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/MusicVideo.kt b/base/app/src/main/java/com/music/spotui/ui/components/MusicVideo.kt
index 1b6a4dd3..1e646086 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/MusicVideo.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/MusicVideo.kt
@@ -205,8 +205,8 @@ fun VideoFullscreenOverlay() {
.background(Color.White)
.clickable { touch++; if (playing) SongPlayer.pause() else SongPlayer.play() },
) {
- Icon(
- painterResource(if (playing) R.drawable.ic_playing else R.drawable.play_svgrepo_com),
+ PlayPauseIcon(
+ playing = playing,
contentDescription = if (playing) stringResource(R.string.content_description_pause_button) else stringResource(R.string.content_description_play_button),
tint = Color.Black,
modifier = Modifier.size(30.dp),
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
index 69b4120e..32772e60 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
@@ -4,10 +4,15 @@ import androidx.compose.ui.res.stringResource
import app.myspoti.engine.R
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
-import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectDragGestures
+import androidx.compose.foundation.gestures.scrollBy
+import androidx.compose.foundation.lazy.LazyListState
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.background
import androidx.compose.material.icons.filled.DragHandle
import androidx.compose.material.icons.filled.Delete
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import androidx.compose.runtime.collectAsState
import androidx.compose.material.icons.filled.RemoveCircleOutline
@@ -62,7 +67,9 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
+import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -74,6 +81,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.music.spotui.data.entity.SongsModel
import com.music.spotui.di.Graph
@@ -413,6 +421,10 @@ fun QueueSheet(contextName: String, onDismiss: () -> Unit) {
var editing by remember { mutableStateOf(false) }
if (showTimer) SleepTimerSheet { showTimer = false }
+ // The queue rows are all ONE LazyColumn item, so a drag can only scroll the sheet
+ // through this state.
+ val listState = rememberLazyListState()
+
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),
@@ -434,7 +446,7 @@ fun QueueSheet(contextName: String, onDismiss: () -> Unit) {
}
PillButton(if (editing) "OK" else stringResource(R.string.curation_actions_edit_button_title)) { editing = !editing }
}
- LazyColumn(modifier = Modifier.weight(1f)) {
+ LazyColumn(state = listState, modifier = Modifier.weight(1f)) {
q.current?.let { cur ->
item(key = "current") {
QueueSheetRow(cur, current = true, trailing = {
@@ -455,7 +467,7 @@ fun QueueSheet(contextName: String, onDismiss: () -> Unit) {
}, onClick = {})
}
}
- item(key = "queue") { QueueList(q, contextName, editing) }
+ item(key = "queue") { QueueList(q, contextName, editing, listState) }
}
Row(
horizontalArrangement = Arrangement.spacedBy(10.dp),
@@ -490,6 +502,48 @@ private fun PillButton(label: String, onClick: () -> Unit) {
private val QueueHeaderHeight = 48.dp
+/** Strip at each end of the list where a drag starts scrolling it. */
+private val QueueEdgeZone = 72.dp
+
+/** Scroll distance per frame at the very edge; it fades to 0 at the zone's inner border. */
+private val QueueEdgeMaxStep = 14.dp
+
+/**
+ * Pixels to scroll this frame for a drag whose row centre is at [pointerY] (viewport
+ * space): negative near the top edge, positive near the bottom, 0 in the middle. The
+ * speed ramps up as the row gets closer to the edge, so a song crosses a long queue fast.
+ */
+internal fun queueEdgeScrollStep(
+ pointerY: Float,
+ viewportTop: Float,
+ viewportBottom: Float,
+ edgePx: Float,
+ maxStepPx: Float,
+): Float {
+ if (viewportBottom <= viewportTop || edgePx <= 0f) return 0f
+ val up = ((viewportTop + edgePx) - pointerY) / edgePx
+ if (up > 0f) return -maxStepPx * up.coerceIn(0f, 1f)
+ val down = (pointerY - (viewportBottom - edgePx)) / edgePx
+ return if (down > 0f) maxStepPx * down.coerceIn(0f, 1f) else 0f
+}
+
+/**
+ * Top of the queue block in viewport pixels (negative once scrolled past the top).
+ * The sheet's list holds the current track (optional) and the queue block, so
+ * [queueContentTop] is that first item's height; [firstVisibleIndex] / [firstVisibleScrollOffset]
+ * are [LazyListState]'s own numbers, which keeps this in step with the scroll.
+ */
+internal fun queueTopInViewport(
+ totalItems: Int,
+ firstVisibleIndex: Int,
+ firstVisibleScrollOffset: Int,
+ queueContentTop: Float,
+): Float {
+ if (totalItems == 0) return 0f
+ val firstItemTop = if (firstVisibleIndex > 0 && totalItems > 1) queueContentTop else 0f
+ return queueContentTop - (firstItemTop + firstVisibleScrollOffset)
+}
+
private sealed class QEntry {
data class Header(val queuedSection: Boolean) : QEntry()
data class Row(val item: SongPlayer.QueueItem, val queued: Boolean) : QEntry()
@@ -501,17 +555,26 @@ private sealed class QEntry {
* the queue (official behaviour). Drag handle on every row; swipe right removes.
*/
@Composable
-private fun QueueList(q: SongPlayer.EngineQueue, contextName: String, editing: Boolean) {
+private fun QueueList(
+ q: SongPlayer.EngineQueue,
+ contextName: String,
+ editing: Boolean,
+ listState: LazyListState,
+) {
val haptic = androidx.compose.ui.platform.LocalHapticFeedback.current
val density = androidx.compose.ui.platform.LocalDensity.current
+ val scope = rememberCoroutineScope()
val rowPx = with(density) { QueueRowHeight.toPx() }
val headerPx = with(density) { QueueHeaderHeight.toPx() }
+ val edgePx = with(density) { QueueEdgeZone.toPx() }
+ val maxStepPx = with(density) { QueueEdgeMaxStep.toPx() }
var queued by remember(q.queued) { mutableStateOf(q.queued) }
var nextUp by remember(q.nextUp) { mutableStateOf(q.nextUp) }
var dragging by remember { mutableStateOf<SongPlayer.QueueItem?>(null) }
var dragOffset by remember { mutableStateOf(0f) }
var lastSlot by remember { mutableStateOf(-1) }
+ var autoScrollJob by remember { mutableStateOf<Job?>(null) }
val entries = buildList {
if (queued.isNotEmpty()) add(QEntry.Header(true))
@@ -529,6 +592,70 @@ private fun QueueList(q: SongPlayer.EngineQueue, contextName: String, editing: B
return entries.lastIndex
}
+ /**
+ * Top of the queue block in viewport coordinates (negative once scrolled past the
+ * top). Computing it from the scroll state instead of measuring the composable
+ * guarantees it matches the scroll the drag itself is doing.
+ */
+ fun queueBlockTop(): Float {
+ val total = listState.layoutInfo.totalItemsCount
+ return queueTopInViewport(
+ totalItems = total,
+ firstVisibleIndex = listState.firstVisibleItemIndex,
+ firstVisibleScrollOffset = listState.firstVisibleItemScrollOffset,
+ queueContentTop = if (total > 1) rowPx else 0f,
+ )
+ }
+
+ /** Pixels to scroll this frame: negative near the top edge, positive near the bottom. */
+ fun edgeScrollStep(pointerY: Float): Float {
+ val info = listState.layoutInfo
+ return queueEdgeScrollStep(
+ pointerY,
+ info.viewportStartOffset.toFloat(),
+ info.viewportEndOffset.toFloat(),
+ edgePx,
+ maxStepPx,
+ )
+ }
+
+ /** Recomputes the hovered entry after the list moved; ticks only when it changes. */
+ fun syncHoveredSlot(itemIndex: Int) {
+ val slot = entryAt(topOf(itemIndex) + dragOffset + rowPx / 2)
+ if (slot != lastSlot) {
+ lastSlot = slot
+ haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.SegmentTick)
+ }
+ }
+
+ /** Scrolls the list once per frame while the dragged row stays in an edge zone. */
+ fun startAutoScroll(itemIndex: Int) {
+ autoScrollJob?.cancel()
+ autoScrollJob = scope.launch {
+ while (isActive) {
+ val top = queueBlockTop()
+ val pointerY = top + topOf(itemIndex) + dragOffset + rowPx / 2
+ val step = edgeScrollStep(pointerY)
+ if (step != 0f) {
+ val moved = listState.scrollBy(step)
+ if (moved != 0f) {
+ // The rows live in list CONTENT space: the content slid under a
+ // still finger, so the drag has to slide by the same amount or
+ // the row escapes the finger and the hovered slot stops matching.
+ dragOffset += moved
+ syncHoveredSlot(itemIndex)
+ }
+ }
+ withFrameNanos { }
+ }
+ }
+ }
+
+ fun stopAutoScroll() {
+ autoScrollJob?.cancel()
+ autoScrollJob = null
+ }
+
fun drop(item: SongPlayer.QueueItem, fromQueued: Boolean, centerY: Float) {
val nextHeaderIndex = entries.indexOfFirst { it is QEntry.Header && !it.queuedSection }
val nextHeaderMid = if (nextHeaderIndex >= 0) topOf(nextHeaderIndex) + headerPx / 2 else Float.MAX_VALUE
@@ -626,22 +753,23 @@ private fun QueueList(q: SongPlayer.EngineQueue, contextName: String, editing: B
onDragStart = {
dragging = item; dragOffset = 0f; lastSlot = index
haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
+ startAutoScroll(index)
},
onDragEnd = {
+ stopAutoScroll()
val center = topOf(entries.indexOf(e)) + dragOffset + rowPx / 2
drop(item, e.queued, center)
haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.GestureEnd)
dragging = null; dragOffset = 0f
},
- onDragCancel = { dragging = null; dragOffset = 0f },
+ onDragCancel = {
+ stopAutoScroll()
+ dragging = null; dragOffset = 0f
+ },
) { change, amount ->
change.consume()
dragOffset += amount.y
- val slot = entryAt(topOf(entries.indexOf(e)) + dragOffset + rowPx / 2)
- if (slot != lastSlot) {
- lastSlot = slot
- haptic.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.SegmentTick)
- }
+ syncHoveredSlot(index)
}
},
)
@@ -739,6 +867,7 @@ private fun QueueSheetRow(
) {
leading()
GlideImage(
+ transition = CrossFade,
model = song.coverUri, contentDescription = "", contentScale = ContentScale.Crop,
modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)),
)
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.kt
index 314bc1fa..c0cb5940 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/SavedInSheet.kt
@@ -55,6 +55,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import app.myspoti.engine.R
@@ -236,6 +237,7 @@ fun SavedInSheet(
saved = saved,
cover = {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.size(48.dp)
.clip(RoundedCornerShape(4.dp)),
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt
index aa27bc6f..11425180 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt
@@ -38,6 +38,7 @@ import androidx.compose.material.icons.outlined.Share
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.Block
import androidx.compose.material.icons.outlined.Bookmark
+import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Speed
import kotlinx.coroutines.launch
import androidx.compose.material3.ExperimentalMaterial3Api
@@ -63,6 +64,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.music.spotui.data.entity.SongsModel
import com.music.spotui.di.SongPlayer
@@ -87,12 +89,18 @@ fun SongOptionsSheet(
onDismiss: () -> Unit,
nowPlaying: Boolean = false,
onOpenQueue: (() -> Unit)? = null,
+ // Removing a track only makes sense where it is listed in a playlist: the screen that
+ // owns that playlist passes this, and handles the write plus its undo (it has the list).
+ onRemoveFromPlaylist: (() -> Unit)? = null,
+ // The playlist the track is shown in, so the "Add to another playlist" picker can hide it.
+ currentPlaylistId: String? = null,
) {
val playerViewModel: com.music.spotui.ui.viewmodel.PlayerViewModel =
androidx.lifecycle.viewmodel.compose.viewModel()
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val liked = com.music.spotui.di.rememberTrackSaved(song.spotifyTrackId)
var showSavedIn by remember { mutableStateOf(false) }
+ var showAddTo by remember { mutableStateOf(false) }
var showSleep by remember { mutableStateOf(false) }
var showCredits by remember { mutableStateOf(false) }
var showSpeed by remember { mutableStateOf(false) }
@@ -108,11 +116,19 @@ fun SongOptionsSheet(
SavedInSheet(song = song, context = context, onDismiss = { showSavedIn = false; onDismiss() })
return
}
+ if (showAddTo) {
+ AddToPlaylistSheet(song = song, context = context, onDismiss = { showAddTo = false; onDismiss() }, excludePlaylistId = currentPlaylistId)
+ return
+ }
if (showSleep) {
SleepTimerSheet(onDismiss = { showSleep = false; onDismiss() })
return
}
val hasId = song.spotifyTrackId.isNotBlank()
+ // An episode is keyed by its url ("episode:<id>") and has no track id: the Download row
+ // (and only it) follows that key, everything else in this menu stays on the track id.
+ val episodeKey = com.music.spotui.data.offline.episodeKeyOf(song)
+ val downloadKey = episodeKey ?: song.spotifyTrackId
fun toast(text: String) = Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
ModalBottomSheet(
@@ -126,6 +142,7 @@ fun SongOptionsSheet(
modifier = Modifier.fillMaxWidth().padding(16.dp, 0.dp, 16.dp, 16.dp),
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)),
model = song.coverUri,
contentScale = ContentScale.Crop,
@@ -151,6 +168,16 @@ fun SongOptionsSheet(
onDismiss()
}
MenuRow(Icons.AutoMirrored.Filled.PlaylistAdd, stringResource(R.string.context_menu_add_to_playlist), enabled = hasId) { showSavedIn = true }
+ // Copy into another playlist: one tap, one target, said out loud by the toast.
+ MenuRow(Icons.AutoMirrored.Filled.PlaylistAdd, stringResource(R.string.context_menu_add_to_another_playlist), enabled = hasId) { showAddTo = true }
+ // Only where a playlist is on screen (A11): the row disappears at once, the
+ // screen tells the user and offers Undo.
+ if (onRemoveFromPlaylist != null) {
+ MenuRow(Icons.Outlined.Delete, stringResource(R.string.context_menu_remove_from_playlist), enabled = hasId) {
+ onDismiss()
+ onRemoveFromPlaylist()
+ }
+ }
if (!nowPlaying) {
MenuRow(Icons.AutoMirrored.Filled.PlaylistPlay, stringResource(R.string.context_menu_play_next), enabled = hasId) {
playerViewModel.playNext(song)
@@ -170,24 +197,40 @@ fun SongOptionsSheet(
onOpenQueue()
}
}
- val offline = com.music.spotui.data.offline.OfflineStore.statusOf(song.spotifyTrackId)
- when (offline) {
- com.music.spotui.data.offline.OfflineStatus.Done -> MenuRow(
+ val offline = com.music.spotui.data.offline.OfflineStore.statusOf(downloadKey)
+ when {
+ offline == com.music.spotui.data.offline.OfflineStatus.Done -> MenuRow(
null, stringResource(R.string.context_menu_undownload),
leading = { DownloadBadge(offline, size = 22.dp) },
) {
- toast(context.getString(if (com.music.spotui.data.offline.OfflineCollections.removeSong(song.spotifyTrackId)) R.string.toast_undownload else R.string.download_kept_by_list))
+ // An episode is kept by its own key (no list holds it): it goes straight.
+ val gone = if (episodeKey != null) {
+ com.music.spotui.data.offline.PodcastDownloader.remove(downloadKey)
+ true
+ } else com.music.spotui.data.offline.OfflineCollections.removeSong(downloadKey)
+ toast(context.getString(if (gone) R.string.toast_undownload else R.string.download_kept_by_list))
onDismiss()
}
- com.music.spotui.data.offline.OfflineStatus.Queued, is com.music.spotui.data.offline.OfflineStatus.Downloading -> MenuRow(
+ offline == com.music.spotui.data.offline.OfflineStatus.Queued ||
+ offline is com.music.spotui.data.offline.OfflineStatus.Downloading -> MenuRow(
null, stringResource(R.string.download_cancel),
leading = { DownloadBadge(offline, size = 22.dp) },
) {
- com.music.spotui.data.offline.OfflineDownloader.cancel(song.spotifyTrackId)
+ if (episodeKey != null) com.music.spotui.data.offline.PodcastDownloader.cancel(downloadKey)
+ else com.music.spotui.data.offline.OfflineDownloader.cancel(downloadKey)
onDismiss()
}
- else -> MenuRow(Icons.Outlined.ArrowCircleDown, stringResource(R.string.context_menu_download), enabled = hasId) {
- com.music.spotui.ui.components.DownloadAsk.start(context) { q ->
+ // Enabled for episodes too: refused ones keep the error badge, and a tap tries
+ // again (the audio URL is resolved at that moment, so a retry can succeed).
+ else -> MenuRow(
+ Icons.Outlined.ArrowCircleDown, stringResource(R.string.context_menu_download),
+ enabled = downloadKey.isNotBlank(),
+ leading = if (offline != null) ({ DownloadBadge(offline, size = 22.dp) }) else null,
+ ) {
+ if (episodeKey != null) {
+ // No quality dialog: it is the publisher's own file, encoded once.
+ com.music.spotui.data.offline.PodcastDownloader.enqueue(song)
+ } else com.music.spotui.ui.components.DownloadAsk.start(context) { q ->
com.music.spotui.data.offline.OfflineCollections.downloadSong(song, q)
com.music.spotui.di.Haptics.confirm()
toast(context.getString(R.string.download_notification_downloading))
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SpotifyImages.kt b/base/app/src/main/java/com/music/spotui/ui/components/SpotifyImages.kt
new file mode 100644
index 00000000..e1556a4f
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/components/SpotifyImages.kt
@@ -0,0 +1,15 @@
+package com.music.spotui.ui.components
+
+/**
+ * B25: the `user-profile-view` endpoints hand out `spotify:image:<id>` URIs (the form their
+ * protobuf payload carries) instead of an https URL. Nothing in the app turned those into a
+ * URL, so Glide was given a string it cannot fetch and kept its grey placeholder: the profile
+ * picture and the covers of a user's public playlists never loaded, while the same covers
+ * appeared as soon as the playlist page itself was opened (it builds https URLs).
+ * A real URL passes through untouched.
+ */
+fun spotifyImageUrl(url: String?): String? = when {
+ url.isNullOrBlank() -> null
+ url.startsWith("spotify:image:") -> "https://i.scdn.co/image/" + url.removePrefix("spotify:image:")
+ else -> url
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/MainBottomNavigation.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/MainBottomNavigation.kt
index 97e82c19..ae33acb5 100644
--- a/base/app/src/main/java/com/music/spotui/ui/navigation/MainBottomNavigation.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/MainBottomNavigation.kt
@@ -19,20 +19,25 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.RowScope
+import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.material3.Icon
-import androidx.compose.material3.NavigationBar
-import androidx.compose.material3.NavigationBarItem
-import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
@@ -43,6 +48,38 @@ import kotlinx.coroutines.flow.emptyFlow
import androidx.compose.foundation.layout.navigationBarsPadding
+/**
+ * What re-tapping the tab you are already on does in the official app: Home and Library
+ * scroll their list back to the top without reloading anything, Search focuses its field.
+ * The bar only sees the tap; the list state and the text field live inside the screens,
+ * so the tap is published here and each screen collects its own event.
+ */
+object TabReselect {
+ // replay = 0 + a one-slot buffer: a tap is never held back, and a tap that lands while
+ // the screen is not composed is simply dropped rather than replayed on the next visit.
+ private val _home = kotlinx.coroutines.flow.MutableSharedFlow<Unit>(
+ extraBufferCapacity = 1, onBufferOverflow = kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST,
+ )
+ private val _library = kotlinx.coroutines.flow.MutableSharedFlow<Unit>(
+ extraBufferCapacity = 1, onBufferOverflow = kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST,
+ )
+ private val _search = kotlinx.coroutines.flow.MutableSharedFlow<Unit>(
+ extraBufferCapacity = 1, onBufferOverflow = kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST,
+ )
+
+ val home: kotlinx.coroutines.flow.SharedFlow<Unit> = _home
+ val library: kotlinx.coroutines.flow.SharedFlow<Unit> = _library
+ val search: kotlinx.coroutines.flow.SharedFlow<Unit> = _search
+
+ fun emit(route: String) {
+ when (route) {
+ Routes.Home.route -> _home.tryEmit(Unit)
+ Routes.Library.route -> _library.tryEmit(Unit)
+ Routes.Search.route -> _search.tryEmit(Unit)
+ }
+ }
+}
+
class NoRippleInteractionSource : MutableInteractionSource {
override val interactions: Flow<Interaction> = emptyFlow()
@@ -80,7 +117,14 @@ fun MainBottomNavigation(navController: NavHostController, bottomBarState: Mutab
// Settings, Display: the fade over the list (the default), or solid black (from #15).
.then(
if (com.music.spotui.data.preferences.SolidNavBar.on) Modifier.background(Color.Black)
- else Modifier.background(Brush.verticalGradient(colors = listOf(Color.Transparent, Color.Black), startY = 0f))
+ // Like the official bar: clear above the mini player, near-opaque by the tab icons,
+ // so covers scrolling underneath never compete with the labels.
+ else Modifier.background(Brush.verticalGradient(
+ 0f to Color.Transparent,
+ 0.3f to Color.Black.copy(alpha = 0.7f),
+ 0.6f to Color.Black.copy(alpha = 0.92f),
+ 1f to Color.Black,
+ ))
)
) {
@@ -98,47 +142,36 @@ fun MainBottomNavigation(navController: NavHostController, bottomBarState: Mutab
Spacer(modifier = Modifier.height(4.dp))
- NavigationBar(
+ val navStack by navController.currentBackStackEntryAsState()
+ val currentRoute = navStack?.destination?.route
+ // The tab the user is in, even on one of its sub-pages (album, artist…).
+ var selectedTab by androidx.compose.runtime.saveable.rememberSaveable { androidx.compose.runtime.mutableStateOf(Routes.Home.route) }
+ if (currentRoute in navItems.map { it.route }) selectedTab = currentRoute!!
+
+ // Official bar proportions: a 58 dp strip (the gesture inset is added by
+ // navigationBarsPadding above), three equal thirds edge to edge, so the
+ // tabs spread over the full width instead of clustering in the middle.
+ Row(
modifier = Modifier
- .height(60.dp)
- .padding(30.dp, 0.dp)
- .fillMaxWidth(),
- containerColor = Color.Transparent,
- windowInsets = androidx.compose.foundation.layout.WindowInsets(0, 0, 0, 0)
+ .fillMaxWidth()
+ .height(NavBarHeight),
+ verticalAlignment = Alignment.CenterVertically,
) {
- val navStack by navController.currentBackStackEntryAsState()
- val currentRoute = navStack?.destination?.route
- // The tab the user is in, even on one of its sub-pages (album, artist…).
- var selectedTab by androidx.compose.runtime.saveable.rememberSaveable { androidx.compose.runtime.mutableStateOf(Routes.Home.route) }
- if (currentRoute in navItems.map { it.route }) selectedTab = currentRoute!!
-
navItems.forEach { item ->
- NavigationBarItem(
+ NavBarTab(
+ iconRes = item.icon,
+ label = if (item.labelRes != 0) stringResource(item.labelRes) else item.label,
selected = selectedTab == item.route,
- icon = {
- Icon(
- painter = painterResource(
- id = item.icon
- ), contentDescription = "home"
- )
- },
- label = {
- if (currentRoute == item.route) {
- Text(color = Color.White, text = if (item.labelRes != 0) stringResource(item.labelRes) else item.label, fontSize = 11.sp)
- } else {
- Text(
- color = Color.Gray,
- text = if (item.labelRes != 0) stringResource(item.labelRes) else item.label,
- fontSize = 11.sp
- )
- }
- },
onClick = {
// Standard bottom-tab navigation: each tab keeps its
// state (no reload, scroll kept) when you come back.
if (item.route == selectedTab) {
- // Same tab again: back to its root page (Spotify behaviour).
- if (currentRoute != item.route && !navController.popBackStack(item.route, inclusive = false)) {
+ if (currentRoute == item.route) {
+ // Already on the tab's own page: nothing to reload, only
+ // the re-tap shortcut (scroll to top, or focus search).
+ TabReselect.emit(item.route)
+ } else if (!navController.popBackStack(item.route, inclusive = false)) {
+ // On one of its sub-pages: back to its root page first.
navController.navigate(item.route) { launchSingleTop = true }
}
} else {
@@ -152,15 +185,7 @@ fun MainBottomNavigation(navController: NavHostController, bottomBarState: Mutab
}
}
},
- alwaysShowLabel = true,
- interactionSource = NoRippleInteractionSource(),
- colors = NavigationBarItemDefaults.colors(
- selectedIconColor = Color.White,
- unselectedIconColor = Color.Gray,
- indicatorColor = Color.Transparent
- )
)
-
}
}
@@ -174,3 +199,59 @@ fun MainBottomNavigation(navController: NavHostController, bottomBarState: Mutab
}
)
}
+
+// Official app metrics. Material3's NavigationBarItem measures its icon slot at a
+// fixed 24 dp, so a 28 dp Icon there was clipped back down: the bar is drawn by hand.
+private val NavBarHeight = 58.dp
+private val NavIconSize = 28.dp
+
+/**
+ * One tab of the bottom bar: a 28 dp glyph above an 11 sp medium label, the two
+ * centred as a single block inside an equal third of the bar's width.
+ */
+@Composable
+private fun RowScope.NavBarTab(
+ iconRes: Int,
+ label: String,
+ selected: Boolean,
+ onClick: () -> Unit,
+) {
+ // Spotify's idle grey, lighter than Color.Gray which read as "disabled".
+ val tint = if (selected) Color.White else Color(0xFFB3B3B3)
+ Box(
+ modifier = Modifier
+ .weight(1f)
+ .fillMaxHeight()
+ // No ripple: the bar is a plain strip of tabs, and the tint is the feedback.
+ .clickable(
+ interactionSource = remember { MutableInteractionSource() },
+ indication = null,
+ onClickLabel = label,
+ onClick = onClick,
+ ),
+ contentAlignment = Alignment.Center,
+ ) {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.Center,
+ ) {
+ Icon(
+ painter = painterResource(id = iconRes),
+ // The label right below already names the tab for TalkBack.
+ contentDescription = null,
+ tint = tint,
+ modifier = Modifier.size(NavIconSize),
+ )
+ Spacer(modifier = Modifier.height(4.dp))
+ Text(
+ text = label,
+ color = tint,
+ fontSize = 11.sp,
+ lineHeight = 12.sp,
+ fontWeight = FontWeight.Medium,
+ letterSpacing = 0.2.sp,
+ maxLines = 1,
+ )
+ }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt
index b6a4c833..ab619988 100644
--- a/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt
@@ -166,6 +166,15 @@ fun MyNavHost(
com.music.spotui.ui.screens.RecapScreen(navHostController)
}
+ // Spotify's own list for the account (every device), not this phone's counter.
+ page(Routes.Recent.route) {
+ LaunchedEffect(playerState) {
+ bottomBarState.value = true
+ bottomBarPlayerState.value = playerState != ""
+ }
+ com.music.spotui.ui.screens.RecentlyPlayedScreen(navHostController)
+ }
+
page(Routes.Liked.route){
LaunchedEffect(playerState) {
bottomBarState.value = true
@@ -289,6 +298,19 @@ fun MyNavHost(
sId?.let { ShowScreen(navHostController, showId = it, showName = name) }
}
+ page(
+ "${Routes.Episode.route}/{eId}?name={name}",
+ arguments = listOf(navArgument("name") { defaultValue = "" }),
+ ) { navBackStackEntry ->
+ LaunchedEffect(playerState) {
+ bottomBarState.value = true
+ bottomBarPlayerState.value = playerState != ""
+ }
+ val eId = navBackStackEntry.arguments?.getString("eId")
+ val name = navBackStackEntry.arguments?.getString("name").orEmpty()
+ eId?.let { com.music.spotui.ui.screens.EpisodeScreen(navHostController, episodeId = it, fallbackName = name) }
+ }
+
page(
"${Routes.Folder.route}/{uri}?name={name}",
arguments = listOf(navArgument("name") { defaultValue = "" }),
diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/PlayerSheet.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/PlayerSheet.kt
index e7577563..a98514a2 100644
--- a/base/app/src/main/java/com/music/spotui/ui/navigation/PlayerSheet.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/PlayerSheet.kt
@@ -41,7 +41,13 @@ fun PlayerOverlay(navController: NavController) {
BackHandler { PlayerSheet.close() }
val settled = remember { derivedStateOf { transition.currentState == transition.targetState } }
CompositionLocalProvider(LocalPageSettled provides settled) {
- PlayerScreen(navController)
+ // A podcast episode gets the podcast player (±15 s, speed, sleep timer, no shuffle);
+ // everything else keeps the music player.
+ if (com.music.spotui.di.SongPlayer.isEpisode) {
+ com.music.spotui.ui.screens.PodcastPlayerScreen(navController)
+ } else {
+ PlayerScreen(navController)
+ }
}
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt
index fb3e5383..e3925925 100644
--- a/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt
@@ -19,6 +19,7 @@ sealed class Routes(
object ArtistReleases : Routes(0, "ArtistReleases", "artistreleases")
object Playlist : Routes(0, "Playlist", "playlist")
object Show : Routes(0, "Show", "show")
+ object Episode : Routes(0, "Episode", "episode")
object Queue : Routes(0, "Queue", "queue")
object Liked : Routes(0, "Liked", "liked")
object LocalFiles : Routes(0, "LocalFiles", "localfiles")
@@ -29,6 +30,7 @@ sealed class Routes(
object NewReleases : Routes(0, "NewReleases", "newreleases")
object Episodes : Routes(0, "Episodes", "episodes")
object Recap : Routes(0, "Recap", "recap")
+ object Recent : Routes(0, "Recent", "recent")
object Spotiflac : Routes(0, "SpotiFLAC", "spotiflac")
object Settings : Routes(0, "Settings", "settings")
object Profile : Routes(0, "Profile", "profile")
@@ -62,6 +64,10 @@ fun localPlaylistRoute(id: String): String = "${Routes.LocalPlaylist.route}/${an
fun showRoute(id: String, name: String = ""): String =
"${Routes.Show.route}/${android.net.Uri.encode(id)}?name=${android.net.Uri.encode(name)}"
+/** A podcast episode (or a book chapter), by raw Spotify id. */
+fun episodeRoute(id: String, name: String = ""): String =
+ "${Routes.Episode.route}/${android.net.Uri.encode(id)}?name=${android.net.Uri.encode(name)}"
+
/**
* Builds an artist route. When the exact Spotify artist id is known it is
* carried along so the artist page opens the exact artist instead of
diff --git a/base/app/src/main/java/com/music/spotui/ui/repository/AppRepository.kt b/base/app/src/main/java/com/music/spotui/ui/repository/AppRepository.kt
index f09aa780..88f0bce1 100644
--- a/base/app/src/main/java/com/music/spotui/ui/repository/AppRepository.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/repository/AppRepository.kt
@@ -31,6 +31,12 @@ class AppRepository constructor(private val api: Api = Graph.api) {
suspend fun provideShow(showId: String) = api.getShow(showId)
+ /** Show (or book) page: header plus episodes / chapters in one flow. */
+ suspend fun provideShowPage(showId: String) = api.getShowPage(showId)
+
+ /** One episode by raw id, for the episode page. */
+ suspend fun provideEpisode(episodeId: String) = api.getEpisode(episodeId)
+
suspend fun provideLibrary() = api.getLibraryRoot()
suspend fun provideLibraryFolder(uri: String) = api.getLibraryFolder(uri)
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt
index 18c4ff4e..7d6e080e 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt
@@ -63,6 +63,7 @@ import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import app.myspoti.engine.R
@@ -142,6 +143,15 @@ private fun ArtistOverviewContent(
)
}
+ // B27: the ⋮ of the action row below used to do nothing (no clickable at all); it now
+ // opens the artist's own menu.
+ var showArtistMenu by remember { mutableStateOf(false) }
+ if (showArtistMenu) com.music.spotui.ui.components.ArtistOptionsSheet(
+ artistId = overview.id,
+ artistName = displayName,
+ onDismiss = { showArtistMenu = false },
+ )
+
// Follow + liked tracks straight from the user's Spotify library.
var following by remember(overview.id) { mutableStateOf(false) }
var saved by remember(overview.id) { mutableStateOf<Set<String>>(emptySet()) }
@@ -193,6 +203,7 @@ private fun ArtistOverviewContent(
.height(340.dp)
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier.fillMaxSize(),
model = overview.headerImage.ifBlank { overview.avatarImage },
contentScale = ContentScale.Crop,
@@ -277,6 +288,7 @@ private fun ArtistOverviewContent(
Row(verticalAlignment = Alignment.CenterVertically) {
overview.popularReleases.firstOrNull()?.let { latest ->
GlideImage(
+ transition = CrossFade,
model = latest.coverUri,
contentDescription = latest.name,
contentScale = ContentScale.Crop,
@@ -306,11 +318,15 @@ private fun ArtistOverviewContent(
)
}
Spacer(Modifier.width(16.dp))
+ // B27: this ⋮ had neither `clickable` nor `onClick` — the artist menu is
+ // opened with the same pressable feedback as the row's other buttons.
Icon(
Icons.Default.MoreVert,
contentDescription = stringResource(R.string.content_description_context_menu),
tint = Color.White.copy(alpha = 0.7f),
- modifier = Modifier.size(24.dp),
+ modifier = Modifier
+ .pressable(0.96f) { showArtistMenu = true }
+ .size(24.dp),
)
}
@@ -449,6 +465,7 @@ private fun ArtistOverviewContent(
Column {
if (overview.avatarImage.isNotBlank()) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.fillMaxWidth()
.height(200.dp),
@@ -575,6 +592,7 @@ private fun PopularTrackRow(
modifier = Modifier.width(24.dp),
)
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.padding(8.dp, 0.dp, 12.dp, 0.dp)
.size(48.dp)
@@ -628,6 +646,7 @@ private fun ReleaseCard(album: AlbumsModel, onClick: () -> Unit) {
,
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.size(132.dp)
.clip(RoundedCornerShape(6.dp)),
@@ -659,6 +678,7 @@ private fun ReleaseRow(album: AlbumsModel, onClick: () -> Unit) {
,
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.size(88.dp)
.clip(RoundedCornerShape(4.dp)),
@@ -853,6 +873,7 @@ private fun RelatedArtistCard(artist: ArtistsModel, onClick: () -> Unit) {
,
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.size(122.dp)
.clip(CircleShape),
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/CategoryScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/CategoryScreen.kt
index 000c6449..5f58fce4 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/CategoryScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/CategoryScreen.kt
@@ -42,6 +42,7 @@ import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import app.myspoti.engine.R
@@ -121,6 +122,7 @@ private fun CategoryGrid(entries: List<LibraryEntry>, navController: NavControll
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
index 164d0f4a..7ee7847a 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt
@@ -65,8 +65,10 @@ import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.music.spotui.data.api.Api
+import com.music.spotui.data.api.EditablePlaylists
import com.music.spotui.data.api.Response
import com.music.spotui.data.entity.ContextPageModel
import com.music.spotui.data.entity.SongsModel
@@ -155,6 +157,8 @@ class ContextViewModel(
val page: StateFlow<Response<ContextPageModel>> = _page
val savedUris = mutableStateOf<Set<String>>(emptySet())
val contextSaved = mutableStateOf(false)
+ /** The page is a playlist the user may change: only there can a track be removed. */
+ val editableContext = mutableStateOf(false)
private var key: String? = null
private var savedChecked = 0
@@ -230,6 +234,11 @@ class ContextViewModel(
val saved = SongPlayer.libraryContains(uris)
savedUris.value = saved
contextSaved.value = p.uri in saved
+ // A11: Spotify refuses an edit to a list the user cannot change, so the entry is only
+ // offered where it would work (own and collaborative playlists, as Spotify itself).
+ if (p.type == "playlist") editableContext.value = withContext(Dispatchers.IO) {
+ runCatching { EditablePlaylists.load().any { it.id == p.uri.substringAfterLast(':') } }.getOrDefault(false)
+ }
}
fun toggleContextSaved(p: ContextPageModel) {
@@ -239,6 +248,19 @@ class ContextViewModel(
SongPlayer.setSaved(p.uri, on)
}
+ /**
+ * The track left this page's playlist: its row goes at once, so the list answers the tap
+ * without waiting for Spotify (the write reads every page of the playlist first). A
+ * failure puts the page back from the server.
+ */
+ fun dropTrack(song: SongsModel) {
+ val k = key ?: return
+ val current = (_page.value as? Response.Success)?.data ?: return
+ val updated = Response.Success(current.copy(tracks = current.tracks.filterNot { it.id == song.id }))
+ _page.value = updated
+ recent[k] = updated
+ }
+
/**
* Smart shuffle (Spotify keeps its own for Premium): the playlist shuffled, with one of
* Spotify's recommendations for it after every [SmartShuffle.EVERY] songs.
@@ -261,6 +283,9 @@ class ContextViewModel(
return
}
state.updateQueue(p.tracks)
+ // B26: keep the list's own name — the player header falls back to it when Spotify's
+ // context label comes back blank (it then showed the album's name).
+ SongPlayer.registerContextName(p.uri, p.name)
if (p.type == "liked" || p.type == "liked-artist") SongPlayer.registerLikedSongs(p.tracks.map { it.url })
// Sorted by the user: Spotify plays the list in that order, not the playlist's. An
// artist's liked songs are a part of Liked Songs: always given, so only they play.
@@ -317,6 +342,37 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
var sort by remember(p.uri) { mutableStateOf(TrackOrder.load(ctx, p.uri)) }
var askRemoveDownloads by remember { mutableStateOf(false) }
var playlistMenu by remember { mutableStateOf(false) }
+ // A11: confirmations (and their Undo) float above the list, not inside a menu that closes.
+ val snackbar = remember { androidx.compose.material3.SnackbarHostState() }
+ val scope = androidx.compose.runtime.rememberCoroutineScope()
+
+ // A11: the row goes at once, then the removal is written to Spotify. The snackbar keeps
+ // the mistake reversible: Undo adds the track back and the page is read again.
+ fun removeFromThisPlaylist(song: SongsModel) {
+ val playlistId = p.uri.substringAfterLast(':')
+ vm.dropTrack(song)
+ com.music.spotui.data.api.SpotifySync.removeTrackFromPlaylist(context, playlistId, song.spotifyTrackId) { ok ->
+ if (!ok) {
+ vm.reload()
+ android.widget.Toast.makeText(context, context.getString(R.string.playlist_change_refused), android.widget.Toast.LENGTH_SHORT).show()
+ } else scope.launch {
+ val chosen = snackbar.showSnackbar(
+ message = context.getString(R.string.removed_from, p.name),
+ actionLabel = context.getString(R.string.undo),
+ withDismissAction = false,
+ // Long: the write has just gone through, the mistake deserves time to be undone.
+ duration = androidx.compose.material3.SnackbarDuration.Long,
+ )
+ if (chosen == androidx.compose.material3.SnackbarResult.ActionPerformed) {
+ com.music.spotui.data.api.SpotifySync.addTrackToPlaylist(context, playlistId, song.spotifyTrackId) { back ->
+ if (back) vm.reload()
+ else android.widget.Toast.makeText(context, context.getString(R.string.playlist_change_refused), android.widget.Toast.LENGTH_SHORT).show()
+ }
+ }
+ }
+ }
+ }
+
if (playlistMenu) com.music.spotui.ui.components.PlaylistOptionsSheet(
page = p,
onDismiss = { playlistMenu = false },
@@ -343,11 +399,17 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
},
)
menuSong?.let { sel ->
+ val inPlaylist = p.type == "playlist"
+ val canRemove = inPlaylist && vm.editableContext.value
com.music.spotui.ui.components.SongOptionsSheet(
song = sel,
navController = navController,
context = context,
onDismiss = { menuSong = null },
+ // The removal entry only exists on a playlist page the user may change: nowhere else
+ // is there a list to take the track out of.
+ onRemoveFromPlaylist = if (canRemove) ({ removeFromThisPlaylist(sel) }) else null,
+ currentPlaylistId = if (inPlaylist) p.uri.substringAfterLast(':') else null,
)
}
@@ -402,6 +464,7 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth()) {
if (p.type == "liked" || p.type == "liked-artist") LikedCover(Modifier.fillMaxWidth(0.66f).aspectRatio(1f).shadow(16.dp, RoundedCornerShape(4.dp))) else
GlideImage(
+ transition = CrossFade,
model = p.coverUri,
contentDescription = "",
contentScale = ContentScale.Crop,
@@ -433,6 +496,7 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
) {
if (p.ownerAvatar.isNotBlank()) {
GlideImage(
+ transition = CrossFade,
model = p.ownerAvatar,
contentDescription = "",
contentScale = ContentScale.Crop,
@@ -463,6 +527,7 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
) {
if (p.type != "liked") {
GlideImage(
+ transition = CrossFade,
model = p.coverUri,
contentDescription = "",
contentScale = ContentScale.Crop,
@@ -602,9 +667,23 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p
item { Spacer(Modifier.height(com.music.spotui.ui.components.bottomBarsSpace())) }
}
com.music.spotui.ui.components.FastScrollbar(listState, Modifier.align(Alignment.CenterEnd))
+ androidx.compose.material3.SnackbarHost(
+ hostState = snackbar,
+ modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = com.music.spotui.ui.components.bottomBarsSpace()),
+ ) { data ->
+ androidx.compose.material3.Snackbar(
+ snackbarData = data,
+ containerColor = Color(0xFF282828),
+ contentColor = Color.White,
+ actionContentColor = SpotifyGreen,
+ )
+ }
}
}
+/** How long a greyed track is given to start before the app says why it did not. */
+private const val UNAVAILABLE_CHECK_MS = 4_000L
+
@OptIn(ExperimentalGlideComposeApi::class)
@Composable
private fun TrackRow(
@@ -616,17 +695,38 @@ private fun TrackRow(
onClick: () -> Unit,
onMore: () -> Unit,
) {
+ // A greyed row is still tried (see the click): the tap is followed by a check, not a refusal.
+ val scope = androidx.compose.runtime.rememberCoroutineScope()
+ val appContext = androidx.compose.ui.platform.LocalContext.current
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start,
modifier = Modifier
.fillMaxWidth()
.then(if (song.playable) Modifier else Modifier.alpha(0.4f))
- .clickable(onClick = onClick)
+ .clickable {
+ onClick()
+ // Spotify's playability flag is per market and can be wrong (testers heard greyed
+ // "region" tracks play in the official app), so a greyed row is still tried. If the
+ // player has not moved to it a few seconds later, the reason is said — a tap that
+ // appears to do nothing is what makes the app look broken.
+ if (!song.playable) scope.launch {
+ kotlinx.coroutines.delay(UNAVAILABLE_CHECK_MS)
+ val playing = SongPlayer.nowPlaying.value.uri
+ if (song.spotifyTrackId.isNotBlank() && !playing.endsWith(song.spotifyTrackId)) {
+ android.widget.Toast.makeText(
+ appContext,
+ app.myspoti.engine.R.string.track_unavailable_region,
+ android.widget.Toast.LENGTH_LONG,
+ ).show()
+ }
+ }
+ }
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
if (showCover) {
GlideImage(
+ transition = CrossFade,
model = song.coverUri,
contentDescription = "",
contentScale = ContentScale.Crop,
@@ -854,7 +954,7 @@ private fun SimilarAlbums(navController: NavController, firstTrackId: String, al
Column(Modifier.width(140.dp).pressable(0.96f) {
navController.navigate(com.music.spotui.ui.navigation.albumRoute(a.name, artists, a.uri.substringAfterLast(':')))
}) {
- GlideImage(model = a.images.maxByOrNull { it.width ?: 0 }?.url, contentDescription = null, contentScale = ContentScale.Crop,
+ GlideImage(transition = CrossFade, model = a.images.maxByOrNull { it.width ?: 0 }?.url, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.size(140.dp).clip(RoundedCornerShape(4.dp)))
Text(a.name, color = Color.White, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 6.dp))
Text(artists, color = Color(0xFFB3B3B3), fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.kt b/base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.kt
index d9181a0a..dcff5b9a 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.kt
@@ -51,6 +51,7 @@ import app.myspoti.api.best
import app.myspoti.engine.R
import app.myspoti.host.android.MyspotiRuntime
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.music.spotui.data.local.ListenHistory
import com.music.spotui.di.Graph
@@ -124,7 +125,7 @@ fun NewReleasesScreen(navController: NavController) {
}
else -> items(list, key = { "$title:${it.id}" }) { t ->
Column(Modifier.clickable { navController.navigate(albumRoute(t.name, t.artists, t.id)) }) {
- GlideImage(model = t.cover, contentDescription = null, contentScale = ContentScale.Crop,
+ GlideImage(transition = CrossFade, model = t.cover, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxWidth().aspectRatio(1f).clip(RoundedCornerShape(6.dp)))
Text(t.name, color = Color.White, fontSize = 13.sp, fontWeight = FontWeight.Bold, lineHeight = 16.sp, minLines = 2, maxLines = 2,
overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 6.dp))
@@ -158,7 +159,7 @@ fun EpisodesScreen(navController: NavController) {
SongPlayer.playSong(e.url)
}.padding(16.dp, 8.dp),
) {
- GlideImage(model = e.coverUri, contentDescription = null, contentScale = ContentScale.Crop,
+ GlideImage(transition = CrossFade, model = e.coverUri, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.size(56.dp).clip(RoundedCornerShape(6.dp)))
Column(Modifier.padding(start = 12.dp).weight(1f)) {
Text(e.title, color = Color.White, fontSize = 15.sp, maxLines = 2, overflow = TextOverflow.Ellipsis)
@@ -224,7 +225,7 @@ fun RecapScreen(navController: NavController) {
val r = list[i]
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(16.dp, 6.dp)) {
Text("${i + 1}", color = Subtle, fontSize = 16.sp, modifier = Modifier.width(28.dp))
- GlideImage(model = r.cover, contentDescription = null, contentScale = ContentScale.Crop,
+ GlideImage(transition = CrossFade, model = r.cover, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)))
Column(Modifier.padding(start = 12.dp).weight(1f)) {
Text(r.name, color = Color.White, fontSize = 15.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/DownloadsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/DownloadsScreen.kt
index ae8ee60f..933a227f 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/DownloadsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/DownloadsScreen.kt
@@ -49,6 +49,7 @@ import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import app.myspoti.engine.R
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import com.music.spotui.data.entity.SongsModel
@@ -70,6 +71,11 @@ fun DownloadsScreen(navController: NavController) {
// Snapshot reads: the list follows downloads as they finish.
val tracks = OfflineStore.tracks.values.sortedByDescending { it.addedAt }
val waiting = OfflineDownloader.requests.values.filter { !OfflineStore.isDownloaded(it.trackId) }
+ // A25: only queued or running songs can be stopped; a failed one has nothing left to cancel.
+ val stoppable = waiting.count {
+ val s = OfflineStore.status[it.trackId]
+ s == OfflineStatus.Queued || s is OfflineStatus.Downloading
+ }
val np by SongPlayer.nowPlaying
val playingHere = LocalPlayer.active.value && LocalPlayer.contextName == title
var menuSong by remember { mutableStateOf<SongsModel?>(null) }
@@ -143,6 +149,24 @@ fun DownloadsScreen(navController: NavController) {
.padding(14.dp),
)
}
+ // A25: one tap empties the queue; the songs already downloaded stay untouched.
+ if (stoppable > 0) item(key = "stop_all") {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)
+ .clip(RoundedCornerShape(8.dp)).background(Color(0xFF2A2A2A))
+ .pressable(0.98f) { OfflineDownloader.stopAll() }
+ .padding(horizontal = 14.dp, vertical = 10.dp),
+ ) {
+ Column(Modifier.weight(1f)) {
+ Text(stringResource(R.string.downloads_stop_all_title), color = Color.White, fontSize = 14.sp)
+ Text(stringResource(R.string.downloads_stop_all_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
+ }
+ Spacer(Modifier.width(12.dp))
+ Icon(Icons.Default.Close, stringResource(R.string.downloads_stop_all_title),
+ tint = Color.White.copy(alpha = 0.7f), modifier = Modifier.size(20.dp))
+ }
+ }
// Songs still on their way (or that could not be downloaded).
items(waiting, key = { "w:" + it.trackId }) { r ->
val status = OfflineStore.status[r.trackId]
@@ -154,6 +178,7 @@ fun DownloadsScreen(navController: NavController) {
.padding(horizontal = 16.dp, vertical = 8.dp),
) {
GlideImage(
+ transition = CrossFade,
model = r.coverUrl, contentDescription = null, contentScale = ContentScale.Crop,
loading = placeholder(R.drawable.placeholder), failure = placeholder(R.drawable.placeholder),
modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)),
@@ -183,6 +208,7 @@ fun DownloadsScreen(navController: NavController) {
modifier = Modifier.fillMaxWidth().pressable(0.97f) { play(i) }.padding(horizontal = 16.dp, vertical = 8.dp),
) {
GlideImage(
+ transition = CrossFade,
model = OfflineStore.coverFile(t) ?: t.coverUrl, contentDescription = null, contentScale = ContentScale.Crop,
loading = placeholder(R.drawable.placeholder), failure = placeholder(R.drawable.downloads_cover),
modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)),
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/EpisodeScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/EpisodeScreen.kt
new file mode 100644
index 00000000..519805ad
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/EpisodeScreen.kt
@@ -0,0 +1,306 @@
+package com.music.spotui.ui.screens
+
+import androidx.compose.animation.animateContentSize
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material.icons.filled.Check
+import androidx.compose.material.icons.filled.MoreVert
+import androidx.compose.material.icons.filled.PlayArrow
+import androidx.compose.material.icons.filled.Share
+import androidx.compose.material.icons.outlined.Add
+import androidx.compose.material3.Icon
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.lifecycle.viewmodel.compose.viewModel
+import androidx.navigation.NavController
+import app.myspoti.engine.R
+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
+import com.bumptech.glide.integration.compose.GlideImage
+import com.bumptech.glide.integration.compose.placeholder
+import com.music.spotui.data.entity.SongsModel
+import com.music.spotui.di.SongPlayer
+import com.music.spotui.ui.components.EpisodeDownloadButton
+import com.music.spotui.ui.components.EpisodeOptionsSheet
+import com.music.spotui.ui.components.Loader
+import com.music.spotui.ui.components.episodeClock
+import com.music.spotui.ui.components.episodeDateLabel
+import com.music.spotui.ui.components.episodeMinutes
+import com.music.spotui.ui.components.pressable
+import com.music.spotui.ui.components.shareEpisode
+import com.music.spotui.ui.components.spotifyUri
+import com.music.spotui.ui.navigation.showRoute
+import com.music.spotui.ui.theme.AppAccent
+import com.music.spotui.ui.theme.AppBackground
+import com.music.spotui.ui.viewmodel.EpisodeViewModel
+
+/**
+ * One podcast episode (or book chapter), as the official page shows it: cover, title, the show
+ * it belongs to, date and length, the action row, then the description.
+ */
+@OptIn(ExperimentalGlideComposeApi::class)
+@Composable
+fun EpisodeScreen(navController: NavController, episodeId: String, fallbackName: String = "") {
+ val vm: EpisodeViewModel = viewModel()
+ val context = LocalContext.current
+ LaunchedEffect(episodeId) { vm.load(episodeId) }
+
+ val episode by vm.episode.collectAsState()
+ val finished = vm.finished.value
+ var menuOpen by remember { mutableStateOf(false) }
+ var expanded by remember { mutableStateOf(false) }
+ val np by SongPlayer.nowPlaying
+ val uri = "spotify:episode:$episodeId"
+ val playing = np.uri == uri && SongPlayer.isPlaying()
+ val saved = SongPlayer.library[uri] == true
+
+ fun play() {
+ val ep = episode ?: return
+ SongPlayer.playSong(ep.url, context)
+ // The mini player and the notification show it before Spotify reports it.
+ com.music.spotui.di.Graph.currentSongState.updateSongState(ep.coverUri, ep.title, ep.singer, true, ep.id, 0, ep.album)
+ }
+
+ episode?.let { ep ->
+ if (menuOpen) EpisodeOptionsSheet(
+ song = ep,
+ finished = finished,
+ onPlay = ::play,
+ onMarkFinished = { vm.setFinished(ep, it) },
+ onDismiss = { menuOpen = false },
+ )
+ }
+
+ Box(Modifier.fillMaxSize().background(AppBackground)) {
+ LazyColumn(
+ contentPadding = PaddingValues(bottom = com.music.spotui.ui.components.bottomBarsSpace()),
+ modifier = Modifier.fillMaxSize(),
+ ) {
+ item {
+ Column(
+ Modifier
+ .fillMaxWidth()
+ .background(Brush.verticalGradient(listOf(Color(0xFF34302B), AppBackground)))
+ .statusBarsPadding(),
+ ) {
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .padding(12.dp)
+ .size(40.dp)
+ .clip(CircleShape)
+ .background(Color.Black.copy(alpha = 0.35f))
+ .clickable { navController.navigateUp() },
+ ) {
+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.accessibility_navigate_back), tint = Color.White)
+ }
+ GlideImage(
+ transition = CrossFade,
+ model = episode?.coverUri,
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ failure = placeholder(R.drawable.placeholder),
+ modifier = Modifier
+ .fillMaxWidth(0.62f)
+ .aspectRatio(1f)
+ .align(Alignment.CenterHorizontally)
+ .clip(RoundedCornerShape(6.dp)),
+ )
+ Spacer(Modifier.height(18.dp))
+ Text(
+ text = episode?.title?.takeIf { it.isNotBlank() } ?: fallbackName,
+ color = Color.White,
+ fontSize = 24.sp,
+ fontWeight = FontWeight.Bold,
+ maxLines = 3,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(horizontal = 16.dp),
+ )
+ // The show, as the page links it.
+ val showId = episode?.showId.orEmpty()
+ if (showId.isNotBlank()) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .padding(horizontal = 16.dp, vertical = 8.dp)
+ .clickable { navController.navigate(showRoute(showId, episode?.singer.orEmpty())) },
+ ) {
+ GlideImage(
+ transition = CrossFade,
+ model = episode?.coverUri,
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ modifier = Modifier.size(22.dp).clip(RoundedCornerShape(3.dp)),
+ )
+ Spacer(Modifier.width(8.dp))
+ Text(
+ text = episode?.singer.orEmpty(),
+ color = Color.White,
+ fontSize = 13.sp,
+ fontWeight = FontWeight.Bold,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+ val date = episodeDateLabel(episode?.releaseDate.orEmpty())
+ val minutes = episodeMinutes(episode?.durationMs ?: 0)
+ Text(
+ text = if (date.isBlank()) minutes else "$date • $minutes",
+ color = Color.White.copy(alpha = 0.65f),
+ fontSize = 13.sp,
+ modifier = Modifier.padding(horizontal = 16.dp),
+ )
+ // Action row: save, download, share, "…", then Play.
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 10.dp),
+ ) {
+ SaveEpisodeButton(saved) {
+ val ep = episode ?: return@SaveEpisodeButton
+ SongPlayer.setSaved(ep.spotifyUri, !saved)
+ }
+ episode?.let { EpisodeDownloadButton(it, size = 26.dp) }
+ Icon(
+ Icons.Default.Share,
+ contentDescription = stringResource(R.string.a11y_share),
+ tint = Color.White.copy(alpha = 0.85f),
+ modifier = Modifier.size(26.dp).pressable(0.9f) { episode?.let { shareEpisode(context, it) } },
+ )
+ Spacer(Modifier.width(20.dp))
+ Icon(
+ Icons.Default.MoreVert,
+ contentDescription = stringResource(R.string.episode_options),
+ tint = Color.White.copy(alpha = 0.85f),
+ modifier = Modifier.size(26.dp).pressable(0.9f) { menuOpen = true },
+ )
+ Spacer(Modifier.weight(1f))
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .height(36.dp)
+ .clip(RoundedCornerShape(18.dp))
+ .background(AppAccent)
+ .pressable(0.95f) { if (playing) SongPlayer.pause() else play() }
+ .padding(horizontal = 20.dp),
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ com.music.spotui.ui.components.PlayPauseIcon(
+ playing = playing,
+ contentDescription = null,
+ tint = Color.Black,
+ modifier = Modifier.size(18.dp),
+ )
+ Spacer(Modifier.width(6.dp))
+ Text(stringResource(if (playing) R.string.notif_action_pause else R.string.episode_play), color = Color.Black, fontSize = 14.sp, fontWeight = FontWeight.Bold)
+ }
+ }
+ }
+ }
+ }
+ if (vm.loading.value) item { Loader() }
+ if (vm.failed.value) item {
+ Text(
+ stringResource(R.string.episode_not_found),
+ color = Color.White.copy(alpha = 0.7f),
+ fontSize = 14.sp,
+ modifier = Modifier.padding(16.dp),
+ )
+ }
+ episode?.let { ep ->
+ if (ep.playedPositionMs > 0 && !finished) item {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
+ ) {
+ Text(
+ stringResource(R.string.episode_remaining, episodeClock(ep.durationMs - ep.playedPositionMs)),
+ color = AppAccent,
+ fontSize = 12.sp,
+ )
+ }
+ }
+ if (ep.description.isNotBlank()) item {
+ Column(Modifier.fillMaxWidth().animateContentSize(androidx.compose.animation.core.tween(250)).padding(16.dp)) {
+ Text(
+ text = ep.description,
+ color = Color.White.copy(alpha = 0.78f),
+ fontSize = 14.sp,
+ maxLines = if (expanded) Int.MAX_VALUE else 4,
+ overflow = TextOverflow.Ellipsis,
+ )
+ Spacer(Modifier.height(6.dp))
+ Text(
+ text = stringResource(if (expanded) R.string.episode_show_less else R.string.episode_show_more),
+ color = Color.White,
+ fontSize = 13.sp,
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier.clickable { expanded = !expanded },
+ )
+ }
+ }
+ }
+ }
+ }
+}
+
+/** ✓ disc when the episode is saved, outlined + otherwise (same shape as the player's). */
+@Composable
+private fun SaveEpisodeButton(saved: Boolean, onClick: () -> Unit) {
+ if (saved) {
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .size(26.dp)
+ .clip(CircleShape)
+ .background(AppAccent)
+ .pressable(0.9f, onClick = onClick),
+ ) {
+ Icon(Icons.Default.Check, contentDescription = stringResource(R.string.episode_unsave), tint = Color.Black, modifier = Modifier.size(17.dp))
+ }
+ } else {
+ Icon(
+ Icons.Outlined.Add,
+ contentDescription = stringResource(R.string.episode_save),
+ tint = Color.White.copy(alpha = 0.85f),
+ modifier = Modifier.size(28.dp).pressable(0.9f, onClick = onClick),
+ )
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/FollowListScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/FollowListScreen.kt
index d253d685..97ceaf07 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/FollowListScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/FollowListScreen.kt
@@ -40,6 +40,7 @@ import app.myspoti.api.UserRef
import app.myspoti.engine.R
import app.myspoti.host.android.MyspotiRuntime
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import com.music.spotui.ui.components.pressable
@@ -100,7 +101,8 @@ fun FollowListScreen(navController: NavController, userId: String, followers: Bo
.padding(16.dp, 8.dp),
) {
GlideImage(
- model = u.imageUrl, contentDescription = null, contentScale = ContentScale.Crop,
+ transition = CrossFade,
+ model = com.music.spotui.ui.components.spotifyImageUrl(u.imageUrl), contentDescription = null, contentScale = ContentScale.Crop,
failure = placeholder(R.drawable.placeholder), loading = placeholder(R.drawable.placeholder),
modifier = Modifier.size(52.dp).clip(CircleShape),
)
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt
index 05cf99ec..349fc73c 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt
@@ -67,6 +67,7 @@ import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import app.myspoti.engine.R
@@ -181,7 +182,19 @@ fun HomeFeedContent(navController: NavController, feed: HomeFeedModel, facet: St
if (top.isNotEmpty()) ContextViewModel.prefetchSoon(top)
}
+ // Re-tapping the Home tab while on Home scrolls this list back to its top (official
+ // behaviour): an animation over the existing items, so nothing is fetched again.
+ val listState = androidx.compose.foundation.lazy.rememberLazyListState()
+ androidx.compose.runtime.LaunchedEffect(Unit) {
+ com.music.spotui.ui.navigation.TabReselect.home.collect {
+ if (listState.firstVisibleItemIndex != 0 || listState.firstVisibleItemScrollOffset != 0) {
+ listState.animateScrollToItem(0)
+ }
+ }
+ }
+
LazyColumn(
+ state = listState,
contentPadding = PaddingValues(bottom = com.music.spotui.ui.components.bottomBarsSpace()),
modifier = Modifier
.fillMaxSize()
@@ -248,6 +261,7 @@ private fun HomeHeaderRow(navController: NavController, facet: String, onFacet:
) {
if (avatarUrl != null) {
GlideImage(
+ transition = CrossFade,
model = avatarUrl,
contentScale = ContentScale.Crop,
contentDescription = stringResource(R.string.recently_played_user_profile),
@@ -262,6 +276,14 @@ private fun HomeHeaderRow(navController: NavController, facet: String, onFacet:
)
}
}
+ // B31: a separator between the profile and the options, reported missing from this
+ // header (the sheets already carry one).
+ Box(
+ modifier = Modifier
+ .padding(start = 10.dp)
+ .size(width = 1.dp, height = 22.dp)
+ .background(Color(0xFF3E3E3E)),
+ )
// Scrolls sideways if the pills don't fit, like Spotify's.
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -318,6 +340,7 @@ private fun HomeShortcutGrid(navController: NavController, items: List<HomeItem>
,
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier.size(48.dp),
contentScale = ContentScale.Crop,
model = item.imageUrl,
@@ -378,6 +401,7 @@ private fun HomeFeedCard(item: HomeItem, onClick: () -> Unit) {
,
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.size(150.dp)
.clip(if (isArtist) CircleShape else RoundedCornerShape(8.dp)),
@@ -428,6 +452,7 @@ private fun ProfileSheet(onOpen: (route: String) -> Unit = {}, onDismiss: () ->
.clickable(enabled = myId != null) { myId?.let { onOpen(com.music.spotui.ui.navigation.profileRoute(it, name)) } }
.padding(horizontal = 20.dp, vertical = 8.dp)) {
if (avatar != null) GlideImage(
+ transition = CrossFade,
model = avatar, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.size(48.dp).clip(CircleShape),
)
@@ -455,6 +480,15 @@ private fun ProfileSheet(onOpen: (route: String) -> Unit = {}, onDismiss: () ->
Text(stringResource(R.string.recap_title), color = Color.White, fontSize = 16.sp)
Text(stringResource(R.string.recap_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
}
+ // The account's own listening history, as Spotify keeps it: it belongs beside the
+ // recap (the local counter) because both answer "what did I listen to".
+ androidx.compose.foundation.layout.Column(
+ Modifier.fillMaxWidth().clickable { onOpen(com.music.spotui.ui.navigation.Routes.Recent.route) }
+ .padding(horizontal = 20.dp, vertical = 10.dp),
+ ) {
+ Text(stringResource(R.string.recents_title), color = Color.White, fontSize = 16.sp)
+ Text(stringResource(R.string.recents_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
+ }
// The Spotify account page (plan, privacy, devices), in the app's signed-in browser.
androidx.compose.foundation.layout.Column(
Modifier.fillMaxWidth().clickable {
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt
index 90c996e3..f166302e 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt
@@ -68,6 +68,7 @@ import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import app.myspoti.engine.R
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import com.music.spotui.data.api.LibraryFolders
@@ -269,6 +270,7 @@ private fun LocalItemRow(item: LocalItem, current: Boolean, onClick: () -> Unit)
modifier = Modifier.fillMaxWidth().pressable(0.97f, onClick = onClick).padding(horizontal = 16.dp, vertical = 8.dp),
) {
GlideImage(
+ transition = CrossFade,
model = item.artUri, contentDescription = null, contentScale = ContentScale.Crop,
loading = placeholder(R.drawable.placeholder), failure = placeholder(R.drawable.local_files_cover),
modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)),
@@ -404,7 +406,7 @@ private fun PickRow(name: String, detail: String, cover: String?, onClick: () ->
modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(horizontal = 20.dp, vertical = 8.dp),
) {
if (cover == null) Image(painterResource(R.drawable.local_files_cover), null, modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)))
- else GlideImage(model = cover, contentDescription = null, contentScale = ContentScale.Crop,
+ else GlideImage(transition = CrossFade, model = cover, contentDescription = null, contentScale = ContentScale.Crop,
loading = placeholder(R.drawable.placeholder), failure = placeholder(R.drawable.placeholder),
modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)))
Column(Modifier.padding(start = 12.dp)) {
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
index bb94f65a..f5c89cb8 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
@@ -80,6 +80,7 @@ import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.music.spotui.data.api.Api
import com.music.spotui.data.api.Response
@@ -155,7 +156,14 @@ fun LibraryScreen(navController: NavController) {
fontWeight = FontWeight.Bold,
color = Color.White,
fontSize = 22.sp,
- modifier = Modifier.weight(1f),
+ // The title itself scrolls the list to its top in the official app
+ // ("Appuyez pour faire défiler jusqu'en haut de la liste").
+ modifier = Modifier
+ .weight(1f)
+ .clickable(
+ interactionSource = remember { MutableInteractionSource() },
+ indication = null,
+ ) { com.music.spotui.ui.navigation.TabReselect.emit(Routes.Library.route) },
)
var creating by remember { mutableStateOf(false) }
if (creating) LibraryCreateSheet(navController, onDismiss = { creating = false }, onLibraryChanged = { libraryViewModel.load() })
@@ -275,7 +283,9 @@ fun LibraryScreen(navController: NavController) {
val hasDownloads = com.music.spotui.data.offline.OfflineStore.tracks.isNotEmpty() ||
com.music.spotui.data.offline.OfflineDownloader.requests.isNotEmpty()
val likedName = stringResource(R.string.collection_liked_songs_title)
- // Liked Songs, Local Files and Downloaded stay on top; the rest follows the chosen sort.
+ // Liked Songs, Local Files and Downloaded stay on top; the rest follows the
+ // chosen sort. "Récents" is not here: it lives on the profile panel, as in the
+ // official app (it is the account's history, not a library folder).
val rootPinned = ((entries as? Response.Success)?.data ?: emptyList())
.indexOfFirst { it.spotifyId == Api.HomeCache.LIKED_SONGS_ID } + 2 + (if (hasDownloads) 1 else 0)
val allEntries = ((entries as? Response.Success)?.data ?: emptyList()).map {
@@ -325,6 +335,7 @@ fun LibraryScreen(navController: NavController) {
@Composable
private fun AccountAvatar(url: String, size: androidx.compose.ui.unit.Dp) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier.size(size).clip(CircleShape),
model = url,
contentScale = ContentScale.Crop,
@@ -353,6 +364,15 @@ fun SumUpLibraryScreen(
return
}
val listState = androidx.compose.foundation.lazy.rememberLazyListState()
+ // Re-tap on the Library tab (or on the "Bibliothèque" title): animated scroll back to
+ // the top of the rows already loaded, exactly like the official app.
+ androidx.compose.runtime.LaunchedEffect(Unit) {
+ com.music.spotui.ui.navigation.TabReselect.library.collect {
+ if (listState.firstVisibleItemIndex != 0 || listState.firstVisibleItemScrollOffset != 0) {
+ listState.animateScrollToItem(0)
+ }
+ }
+ }
val haptic = androidx.compose.ui.platform.LocalHapticFeedback.current
val density = androidx.compose.ui.platform.LocalDensity.current
// The rows as shown, moved live under the finger; saved when the finger lifts.
@@ -496,6 +516,7 @@ fun SumUpLibraryScreen(
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.size(55.dp)
.clip(CircleShape),
@@ -527,7 +548,7 @@ fun LibraryEntryCover(entry: LibraryEntry, modifier: Modifier) {
}
// Vector drawables are drawn directly (Glide left them blank).
if (drawn != 0) androidx.compose.foundation.Image(painterResource(drawn), contentDescription = null, modifier = modifier)
- else GlideImage(model = entry.coverUri, contentScale = ContentScale.Crop, contentDescription = "", modifier = modifier)
+ else GlideImage(transition = CrossFade, model = entry.coverUri, contentScale = ContentScale.Crop, contentDescription = "", modifier = modifier)
}
/** Library ids of the phone's own playlists (see LocalPlaylists). */
@@ -574,6 +595,14 @@ fun LibraryGridScreen(
return
}
val gridState = androidx.compose.foundation.lazy.grid.rememberLazyGridState()
+ // Same re-tap shortcut as the list view: the grid animates back to its first tile.
+ androidx.compose.runtime.LaunchedEffect(Unit) {
+ com.music.spotui.ui.navigation.TabReselect.library.collect {
+ if (gridState.firstVisibleItemIndex != 0 || gridState.firstVisibleItemScrollOffset != 0) {
+ gridState.animateScrollToItem(0)
+ }
+ }
+ }
val haptic = androidx.compose.ui.platform.LocalHapticFeedback.current
val density = androidx.compose.ui.platform.LocalDensity.current
// Same as the list view, in two dimensions: the tile follows the finger and takes
@@ -706,6 +735,7 @@ fun LibraryGridScreen(
modifier = Modifier.pressable(0.96f) { navController.navigate(artistRoute(artist.name, artist.id)) }
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LocalFilesScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LocalFilesScreen.kt
index 3c091aa1..dbeadbde 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/LocalFilesScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LocalFilesScreen.kt
@@ -55,6 +55,7 @@ import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.navigation.NavController
import app.myspoti.engine.R
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import com.music.spotui.data.local.LocalMusic
@@ -165,6 +166,7 @@ fun LocalFilesScreen(navController: NavController) {
.padding(horizontal = 16.dp, vertical = 8.dp),
) {
GlideImage(
+ transition = CrossFade,
model = t.artUri, contentDescription = null, contentScale = ContentScale.Crop,
loading = placeholder(R.drawable.placeholder), failure = placeholder(R.drawable.local_files_cover),
modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)),
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt
index 2caae634..0ee5fc47 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt
@@ -1,5 +1,6 @@
package com.music.spotui.ui.screens
+import com.music.spotui.ui.components.pressable
import androidx.compose.ui.res.stringResource
import android.content.Context
@@ -110,7 +111,10 @@ private fun paletteFor(lyrics: Lyrics?, accent: Color): LyricsPalette {
lyrics?.colors?.let { return LyricsPalette(Color(it.background), Color(it.text), Color(it.highlight)) }
// No Spotify colours (fallback source): the artwork colour, like Spotify's own fallback.
val bg = lerp(accent, Color.Black, 0.15f)
- val text = if (bg.luminance() > 0.35f) Color.Black.copy(alpha = 0.8f) else Color.Black.copy(alpha = 0.55f)
+ // B23: upcoming lines were black at 55 % — invisible on a dark (AMOLED) card. On a dark
+ // background they are drawn in a slightly dimmed white instead, the sung lines staying
+ // the full highlight colour.
+ val text = if (bg.luminance() > 0.35f) Color.Black.copy(alpha = 0.8f) else Color.White.copy(alpha = 0.72f)
return LyricsPalette(bg, text, Color.White)
}
@@ -481,10 +485,10 @@ private fun LyricsControls(
.size(60.dp)
.clip(CircleShape)
.background(palette.highlight)
- .clickable { if (SongPlayer.isPlaying()) SongPlayer.pause() else SongPlayer.play() },
+ .pressable(0.92f) { if (SongPlayer.isPlaying()) SongPlayer.pause() else SongPlayer.play() },
) {
- Icon(
- painter = painterResource(if (playing) R.drawable.ic_playing else R.drawable.play_svgrepo_com),
+ com.music.spotui.ui.components.PlayPauseIcon(
+ playing = playing,
contentDescription = if (playing) stringResource(R.string.content_description_pause_button) else stringResource(R.string.content_description_play_button),
tint = palette.background,
modifier = Modifier.size(30.dp),
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
index ad8c423f..ea04bf96 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
@@ -2,6 +2,7 @@ package com.music.spotui.ui.screens
import androidx.compose.material.icons.filled.Check
import androidx.compose.ui.draw.drawWithContent
+import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
@@ -57,6 +58,7 @@ import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.PlayArrow
+import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
@@ -116,6 +118,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import app.myspoti.power.EnergySettings
import androidx.navigation.NavController
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import app.myspoti.engine.R
import com.music.spotui.data.api.Response
@@ -148,6 +151,8 @@ fun PlayerScreen(navController: NavController) {
val songCoverUri = playerViewModel.currentSongCoverUri.value
val songPlayingState = playerViewModel.currentSongPlayingState.value
val audioBuffering = SongPlayer.isBuffering
+ // T4: the page shows no track during an ad break; an explicit ad state is shown instead.
+ val adPlaying = SongPlayer.adPlaying
val songId = playerViewModel.currentSongId.value
val context = LocalContext.current
val energy by EnergySettings.state.collectAsStateWithLifecycle()
@@ -158,15 +163,23 @@ fun PlayerScreen(navController: NavController) {
var showSavedIn by remember { mutableStateOf(false) }
var showDevices by remember { mutableStateOf(false) }
var showQueue by remember { mutableStateOf(false) }
+ // Immersive view (official app: a tap on the artwork): artwork full-bleed, no top bar,
+ // no title / controls block, only one compact strip. A second tap leaves it.
+ var immersive by remember { mutableStateOf(false) }
if (showDevices) com.music.spotui.ui.components.DevicesSheet { showDevices = false }
if (showQueue) com.music.spotui.ui.components.QueueSheet(
- contextName = SongPlayer.nowPlaying.value.contextName.ifBlank { playerViewModel.currentSongAlbum.value },
+ // B26: the list's own name (the page's label is blank for some lists), not the album's.
+ contextName = playerContextName(playerViewModel),
onDismiss = { showQueue = false },
)
BackHandler(enabled = showLyrics) {
showLyrics = false
}
+ // Back leaves the immersive view first; the lyrics (handled above) keep priority.
+ BackHandler(enabled = immersive && !showLyrics) {
+ immersive = false
+ }
if (showMenu) {
PlayerOptionsSheet(
@@ -262,11 +275,8 @@ fun PlayerScreen(navController: NavController) {
}
val canvasAlpha = canvasProgress.value
val coverAlpha = 1f - canvasProgress.value
- // A tap on the Canvas hides the player (title, controls, progress) to watch the clip,
- // brighter; another tap anywhere brings everything back.
- var canvasOnly by remember(canvasUrl) { mutableStateOf(false) }
- val chrome by androidx.compose.animation.core.animateFloatAsState(
- if (canvasOnly) 0f else 1f, androidx.compose.animation.core.tween(CANVAS_FADE_MS / 2), label = "chrome")
+ // A tap on the Canvas no longer needs its own mode: the immersive view below handles both
+ // cases (Canvas playing or plain cover), so the Canvas-only fade ("chrome") is gone.
// Music video (YouTube, synced to the Spotify playback): looked up for every track
// shown here, offered once its time map is known, shown in place of the artwork.
val mv = com.music.spotui.video.MusicVideoController
@@ -302,8 +312,11 @@ fun PlayerScreen(navController: NavController) {
.graphicsLayer { translationY = pullToClose.offset }
.fillMaxSize()
.background(
+ // The tint follows the cover in BOTH modes: AMOLED used to be pure black, and the
+ // colour was asked for anyway (that replaces the halo idea). The screen keeps its
+ // gradient, the toggle still governs the rest of the app.
Brush.verticalGradient(
- colors = if (energy.policy.oledBlack) listOf(Color.Black, Color.Black) else listOf(
+ colors = listOf(
androidx.compose.ui.graphics.lerp(dominentColor, Color.Black, 0.35f),
Color(0xFF121212),
),
@@ -324,7 +337,9 @@ fun PlayerScreen(navController: NavController) {
Box(
modifier = Modifier
.fillMaxSize()
- .alpha(canvasAlpha * chrome)
+ // Lighter dim in the immersive view: the clip is the page there, only the
+ // compact strip needs something to sit on.
+ .alpha(canvasAlpha * if (immersive) 0.35f else 1f)
.background(
Brush.verticalGradient(
colors = listOf(
@@ -340,7 +355,6 @@ fun PlayerScreen(navController: NavController) {
androidx.compose.foundation.lazy.LazyColumn(
modifier = Modifier
.fillMaxSize()
- .graphicsLayer { alpha = chrome }
.nestedScroll(pullToClose.connection)
.statusBarsPadding(),
horizontalAlignment = Alignment.CenterHorizontally
@@ -357,7 +371,9 @@ fun PlayerScreen(navController: NavController) {
// Height budget from the screen, as before (the list item is shorter than the screen and
// gave a smaller cover); the width cap only matters on wide windows.
val screenHeight = androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp
- val artSide = minOf(contentWidth, screenHeight - PLAYER_CONTROLS_DP.dp).coerceAtLeast(160.dp)
+ // Immersive: the artwork takes the whole height instead of leaving room for controls.
+ val artSide = if (immersive) screenHeight
+ else minOf(contentWidth, screenHeight - PLAYER_CONTROLS_DP.dp).coerceAtLeast(160.dp)
Column(
modifier = Modifier
.fillMaxHeight()
@@ -365,39 +381,48 @@ fun PlayerScreen(navController: NavController) {
.navigationBarsPadding(),
horizontalAlignment = Alignment.CenterHorizontally
) {
- PlayerTopBar(
- navController,
- onMenuClick = { showMenu = true },
- np = np,
- fallbackName = playerViewModel.currentSongAlbum.value,
- )
- Spacer(modifier = Modifier.height(28.dp))
+ // Immersive mode has no top bar: only the artwork and the compact strip remain.
+ if (!immersive) {
+ PlayerTopBar(
+ navController,
+ onMenuClick = { showMenu = true },
+ np = np,
+ fallbackName = playerViewModel.currentSongAlbum.value,
+ )
+ Spacer(modifier = Modifier.height(28.dp))
+ }
// Media area: artwork (swipe to change track) or the music video, with
// Spotify's "Passer à la vidéo" pill over it (black, like the official app).
// Square, but never taller than what the controls leave (foldables, landscape-ish
// screens): otherwise play / pause ends up under the lyrics card.
// A clear upward drag on the artwork opens the lyrics (observed on the initial pass,
// never consumed, so the pager and the pull-to-close keep working).
- Box(modifier = Modifier.size(artSide).pointerInput(canvasUrl, videoOn) {
+ Box(modifier = Modifier.size(artSide).pointerInput(immersive, videoOn) {
detectTapGestures(onTap = {
- if (canvasUrl != null && !videoOn) canvasOnly = true
+ // Plain tap on the artwork: the immersive toggle, with or without a Canvas
+ // (it used to depend on the Canvas being there, and only ever turned on).
+ if (!videoOn) immersive = !immersive
})
}.pointerInput(Unit) {
val threshold = 80.dp.toPx()
+ // A deliberate flick, judged on release: an upward drag that crosses the threshold in
+ // under [maxMs]. Reported bug: scrolling up through the player opened the lyrics —
+ // that gesture crosses a distance threshold too, but never that fast, so distance
+ // alone was not a gesture.
+ val maxMs = 350L
while (true) awaitPointerEventScope {
val down = awaitFirstDown(requireUnconsumed = false, pass = androidx.compose.ui.input.pointer.PointerEventPass.Initial)
var dx = 0f
var dy = 0f
- var fired = false
while (true) {
val event = awaitPointerEvent(androidx.compose.ui.input.pointer.PointerEventPass.Initial)
val change = event.changes.firstOrNull { it.id == down.id } ?: break
- if (!change.pressed) break
val d = change.positionChange()
dx += d.x; dy += d.y
- if (!fired && -dy > threshold && -dy > kotlin.math.abs(dx) * 2f) {
- fired = true
- showLyrics = true
+ if (!change.pressed) {
+ val quick = change.uptimeMillis - down.uptimeMillis <= maxMs
+ if (quick && -dy > threshold && -dy > kotlin.math.abs(dx) * 2f) showLyrics = true
+ break
}
}
}
@@ -409,9 +434,9 @@ fun PlayerScreen(navController: NavController) {
com.music.spotui.ui.components.VideoSurface(onTap = { mv.fullscreen.value = true })
} else HorizontalPager(
state = artworkPagerState,
- modifier = Modifier
- .fillMaxWidth()
- .aspectRatio(1f),
+ // Immersive: the artwork fills the screen instead of sitting in a square.
+ modifier = if (immersive) Modifier.fillMaxSize()
+ else Modifier.fillMaxWidth().aspectRatio(1f),
) { page ->
val cover = when (page) {
0 -> np.prev?.coverUri
@@ -420,10 +445,10 @@ fun PlayerScreen(navController: NavController) {
} ?: songCoverUri
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
GlideImage(
- modifier = Modifier
- .padding(horizontal = 24.dp)
- .aspectRatio(1f)
- .clip(RoundedCornerShape(8.dp))
+ transition = CrossFade,
+ modifier = (if (immersive) Modifier.fillMaxSize()
+ // Normal layout keeps the inset, rounded cover.
+ else Modifier.padding(horizontal = 24.dp).aspectRatio(1f).clip(RoundedCornerShape(8.dp)))
.graphicsLayer {
alpha = coverAlpha
val grow = 1f + (1f - coverAlpha) * 0.06f
@@ -436,99 +461,107 @@ fun PlayerScreen(navController: NavController) {
}
// Over the artwork / video; with a Canvas the artwork is hidden, so the
// pill sits above the title instead of floating mid-screen.
- if ((videoReady || videoOn) && !pillAboveTitle) {
+ if (!immersive && (videoReady || videoOn) && !pillAboveTitle) {
com.music.spotui.ui.components.VideoSwitchPill(
on = videoOn,
modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 36.dp),
)
}
- if (showVideo) {
+ if (showVideo && !immersive) {
com.music.spotui.ui.components.VideoFullscreenButton(
modifier = Modifier.align(Alignment.BottomEnd).padding(end = 36.dp, bottom = 36.dp),
)
}
}
Spacer(modifier = Modifier.weight(1f))
- if ((videoReady || videoOn) && pillAboveTitle) {
+ if (!immersive && (videoReady || videoOn) && pillAboveTitle) {
com.music.spotui.ui.components.VideoSwitchPill(
on = videoOn,
modifier = Modifier.padding(bottom = 20.dp),
)
}
- PlayerInfo(
- songTitle = songTitle,
- songSinger = songSinger,
- explicit = np.explicit || currentTrack?.explicit == true,
- liked = isLiked.value,
- onLikeClick = { playerViewModel.updateLikeState(!isLiked.value) },
- likeSong = { nowPlayingSong(playerViewModel) },
- onTitleClick = {
- val albumId = np.albumUri.substringAfterLast(":")
- if (albumId.isNotBlank()) navController.navigate(albumRoute(playerViewModel.currentSongAlbum.value, songSinger, albumId))
- },
- onArtistClick = {
- playerViewModel.goToArtist(SongPlayer.currentTrackId, songSinger) { route ->
- navController.navigate(route)
- }
- },
- )
+ // Immersive mode keeps none of this: the compact strip at the bottom of
+ // the screen replaces the title block and every control.
+ if (!immersive) {
+ PlayerInfo(
+ songTitle = songTitle,
+ songSinger = songSinger,
+ explicit = np.explicit || currentTrack?.explicit == true,
+ liked = isLiked.value,
+ onLikeClick = { playerViewModel.updateLikeState(!isLiked.value) },
+ likeSong = { nowPlayingSong(playerViewModel) },
+ adPlaying = adPlaying,
+ onTitleClick = {
+ val albumId = np.albumUri.substringAfterLast(":")
+ if (albumId.isNotBlank()) navController.navigate(albumRoute(playerViewModel.currentSongAlbum.value, songSinger, albumId))
+ },
+ onArtistClick = {
+ playerViewModel.goToArtist(SongPlayer.currentTrackId, songSinger) { route ->
+ navController.navigate(route)
+ }
+ },
+ )
- // Seek bar: follows the finger while dragging, seeks once on release.
- var isDragging by remember { mutableStateOf(false) }
- var dragValue by remember { mutableStateOf(0f) }
- val duration = mv.duration()
- SpotifySeekBar(
- fraction = {
- frame.value // redraw each frame
- if (isDragging) dragValue else {
- val d = mv.duration()
- if (d > 0) (mv.position().toFloat() / d).coerceIn(0f, 1f) else 0f
+ // Seek bar: follows the finger while dragging, seeks once on release.
+ var isDragging by remember { mutableStateOf(false) }
+ var dragValue by remember { mutableStateOf(0f) }
+ val duration = mv.duration()
+ SpotifySeekBar(
+ fraction = {
+ frame.value // redraw each frame
+ if (isDragging) dragValue else {
+ val d = mv.duration()
+ if (d > 0) (mv.position().toFloat() / d).coerceIn(0f, 1f) else 0f
+ }
+ },
+ onDrag = { isDragging = true; dragValue = it },
+ onRelease = {
+ val target = (dragValue * mv.duration()).toLong()
+ mv.seekTo(target)
+ isDragging = false
+ },
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 24.dp)
+ .padding(top = 14.dp),
+ )
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 24.dp),
+ horizontalArrangement = Arrangement.SpaceBetween
+ ) {
+ ElapsedLabel(songPlayingState, if (isDragging) (dragValue * duration).toLong() else null) {
+ playerViewModel.formatDuration(it)
}
- },
- onDrag = { isDragging = true; dragValue = it },
- onRelease = {
- val target = (dragValue * mv.duration()).toLong()
- mv.seekTo(target)
- isDragging = false
- },
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 24.dp)
- .padding(top = 14.dp),
- )
- Row(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 24.dp),
- horizontalArrangement = Arrangement.SpaceBetween
- ) {
- ElapsedLabel(songPlayingState, if (isDragging) (dragValue * duration).toLong() else null) {
- playerViewModel.formatDuration(it)
+ Text(
+ text = playerViewModel.formatDuration(duration.coerceAtLeast(0)),
+ color = Color.White.copy(alpha = 0.7f),
+ fontSize = 12.sp,
+ )
}
- Text(
- text = playerViewModel.formatDuration(duration.coerceAtLeast(0)),
- color = Color.White.copy(alpha = 0.7f),
- fontSize = 12.sp,
- )
- }
- PlayerFull(songPlayingState, playerViewModel, context, isLiked, shuffle, repeat, queueSongs)
+ PlayerFull(songPlayingState, playerViewModel, context, isLiked, shuffle, repeat, queueSongs)
- PlayerConnectRow(
- context = context,
- title = songTitle,
- artist = songSinger,
- coverUri = songCoverUri,
- onDevices = { showDevices = true },
- onQueue = { showQueue = true },
- )
- Spacer(modifier = Modifier.height(20.dp))
+ PlayerConnectRow(
+ context = context,
+ title = songTitle,
+ artist = songSinger,
+ coverUri = songCoverUri,
+ onDevices = { showDevices = true },
+ onQueue = { showQueue = true },
+ )
+ Spacer(modifier = Modifier.height(20.dp))
+ }
}
}
}
- item {
- if (!audioBuffering) InlineLyrics(
+ // The lyrics card belongs to the scrolled layout; in immersive mode the list holds the
+ // artwork only, so a swipe there cannot pull a card up under the compact strip.
+ if (!immersive) item {
+ // T4: no lyrics card during an ad break — the song it belongs to is not what plays.
+ if (!audioBuffering && !adPlaying) InlineLyrics(
title = songTitle,
artist = songSinger,
album = playerViewModel.currentSongAlbum.value,
@@ -537,12 +570,23 @@ fun PlayerScreen(navController: NavController) {
)
}
}
- // The Canvas alone: any tap brings the player back.
- if (canvasOnly) Box(
- modifier = Modifier
- .fillMaxSize()
- .pointerInput(Unit) { detectTapGestures(onTap = { canvasOnly = false }) }
- )
+ // Immersive: one compact strip at the bottom of the full-bleed artwork, the official
+ // app's collapsed layout. It swallows taps, so only the artwork leaves the mode.
+ if (immersive) {
+ ImmersiveStrip(
+ modifier = Modifier.align(Alignment.BottomCenter).navigationBarsPadding(),
+ coverUri = songCoverUri,
+ title = songTitle,
+ artists = songSinger,
+ liked = isLiked.value,
+ onLike = { playerViewModel.updateLikeState(!isLiked.value) },
+ fraction = {
+ frame.value // redraw each frame
+ val d = mv.duration()
+ if (d > 0) (mv.position().toFloat() / d).coerceIn(0f, 1f) else 0f
+ },
+ )
+ }
AnimatedVisibility(
visible = showLyrics,
@@ -568,6 +612,80 @@ fun PlayerScreen(navController: NavController) {
}
}
+/**
+ * The immersive player's single control strip (official app): cover, title, artists, like
+ * and a thin progress line. No transport row, no timestamps, no Connect/Share/Queue — those
+ * disappear with the rest of the player when the artwork is tapped.
+ */
+@OptIn(ExperimentalGlideComposeApi::class)
+@Composable
+private fun ImmersiveStrip(
+ modifier: Modifier = Modifier,
+ coverUri: String,
+ title: String,
+ artists: String,
+ liked: Boolean,
+ onLike: () -> Unit,
+ fraction: () -> Float,
+) {
+ Column(
+ modifier = modifier
+ .fillMaxWidth()
+ // Swallows taps: the strip is not the artwork, so hitting it must not close the
+ // mode (its own like button still works).
+ .pointerInput(Unit) { detectTapGestures(onTap = {}) }
+ .background(
+ // Scrim only under the strip: the artwork above stays untouched.
+ Brush.verticalGradient(listOf(Color.Transparent, Color.Black.copy(alpha = 0.72f)))
+ )
+ .padding(horizontal = 16.dp, vertical = 10.dp),
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ GlideImage(
+ transition = CrossFade,
+ model = coverUri,
+ contentDescription = "",
+ contentScale = ContentScale.Crop,
+ modifier = Modifier.size(44.dp).clip(RoundedCornerShape(4.dp)),
+ )
+ Column(modifier = Modifier.weight(1f).padding(horizontal = 12.dp)) {
+ Text(
+ text = title,
+ color = Color.White,
+ fontSize = 14.sp,
+ fontWeight = FontWeight.Bold,
+ maxLines = 1,
+ overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
+ )
+ if (artists.isNotBlank()) Text(
+ text = artists,
+ color = Color.White.copy(alpha = 0.75f),
+ fontSize = 12.sp,
+ maxLines = 1,
+ overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
+ )
+ }
+ LikeButton(liked = liked, size = 26.dp, onClick = onLike)
+ }
+ Spacer(modifier = Modifier.height(10.dp))
+ // Read in the draw phase, so the line follows playback without recomposing.
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(2.dp)
+ .clip(RoundedCornerShape(1.dp))
+ .drawBehind {
+ drawRect(Color.White.copy(alpha = 0.3f))
+ val played = fraction().coerceIn(0f, 1f)
+ drawRect(
+ color = Color.White,
+ size = androidx.compose.ui.geometry.Size(size.width * played, size.height),
+ )
+ },
+ )
+ }
+}
+
/** The clip filling the screen, landscape while it shows; back or the exit button leaves. */
@Composable
private fun VideoFullscreen() {
@@ -598,12 +716,21 @@ private fun VideoFullscreen() {
+/** B26: the list the music plays from — the page's own label, else the name the app knows
+ * (the list the play started from), else the album's name. */
+private fun contextDisplayName(np: SongPlayer.NowPlaying, fallbackName: String): String =
+ np.contextName.ifBlank { SongPlayer.knownContextName(np.contextUri) }.ifBlank { fallbackName }
+
+/** The list name both the header and the queue sheet show (B26). */
+private fun playerContextName(playerViewModel: PlayerViewModel): String =
+ contextDisplayName(SongPlayer.nowPlaying.value, playerViewModel.currentSongAlbum.value)
+
/** "Lecture à partir de <type>" + context name, or the queue (like the official app). */
@Composable
private fun playingFromLabels(np: SongPlayer.NowPlaying, fallbackName: String): Pair<String, String> {
if (np.provider == "queue") return stringResource(R.string.context_type_description_play_queue) to ""
val type = np.contextUri.split(":").getOrNull(1).orEmpty()
- val name = np.contextName.ifBlank { fallbackName }
+ val name = contextDisplayName(np, fallbackName)
return when {
np.contextUri.contains(":collection") -> stringResource(R.string.context_type_description_collection_your_library) to stringResource(R.string.collection_liked_songs_title)
type == "playlist" -> stringResource(R.string.context_type_description_playlist) to name
@@ -619,11 +746,13 @@ private fun playingFromLabels(np: SongPlayer.NowPlaying, fallbackName: String):
private fun contextRoute(np: SongPlayer.NowPlaying): String? {
val parts = np.contextUri.split(":")
val id = parts.getOrNull(2).orEmpty()
+ // B26: opening that page again must carry the name the header shows.
+ val name = contextDisplayName(np, "")
return when {
np.contextUri.contains(":collection") -> Routes.Liked.route
- parts.getOrNull(1) == "playlist" && id.isNotBlank() -> com.music.spotui.ui.navigation.playlistRoute(id, np.contextName)
- parts.getOrNull(1) == "album" && id.isNotBlank() -> albumRoute(np.contextName, "", id)
- parts.getOrNull(1) == "artist" && id.isNotBlank() -> com.music.spotui.ui.navigation.artistRoute(np.contextName, id)
+ parts.getOrNull(1) == "playlist" && id.isNotBlank() -> com.music.spotui.ui.navigation.playlistRoute(id, name)
+ parts.getOrNull(1) == "album" && id.isNotBlank() -> albumRoute(name, "", id)
+ parts.getOrNull(1) == "artist" && id.isNotBlank() -> com.music.spotui.ui.navigation.artistRoute(name, id)
else -> null
}
}
@@ -762,6 +891,8 @@ fun PlayerInfo(
likeSong: (() -> SongsModel)? = null,
onArtistClick: (() -> Unit)? = null,
onTitleClick: (() -> Unit)? = null,
+ /** T4: an ad break is on: what the caller passes is the song from before it, not what plays. */
+ adPlaying: Boolean = false,
) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -774,18 +905,21 @@ fun PlayerInfo(
modifier = Modifier
// A few passes, after the sheet has settled (not an endless 120 Hz animation).
.basicMarquee(iterations = 3, initialDelayMillis = 1_500, repeatDelayMillis = 2_500)
- .then(if (onTitleClick != null) Modifier.clickable(
+ // Nothing to open during an ad: the title would lead to the previous song.
+ .then(if (onTitleClick != null && !adPlaying) Modifier.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
) { onTitleClick() } else Modifier),
- text = songTitle,
+ text = if (adPlaying) stringResource(R.string.ad_playing) else songTitle,
color = Color.White,
fontSize = 22.sp,
fontWeight = FontWeight.Bold,
maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
softWrap = false,
)
- Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {
+ // The artist row belongs to the song: during an ad the previous one's artist is
+ // what the state still holds, so it is not shown as if it were playing.
+ if (!adPlaying) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {
if (explicit) {
ExplicitBadge()
Spacer(modifier = Modifier.width(6.dp))
@@ -803,8 +937,9 @@ fun PlayerInfo(
)
}
}
- // No like for a local file (not in the Spotify library).
- if (!com.music.spotui.di.LocalPlayer.active.value) {
+ // No like for a local file (not in the Spotify library), and none during an ad break:
+ // the + would save the song from before the break.
+ if (!adPlaying && !com.music.spotui.di.LocalPlayer.active.value) {
if (likeSong != null) AddButton(song = likeSong, liked = liked, onLike = onLikeClick)
else LikeButton(liked = liked, onClick = onLikeClick)
}
@@ -1016,17 +1151,10 @@ fun PlayerFull(
,
contentAlignment = Alignment.Center
) {
- Icon(
- modifier = Modifier
- .size(30.dp)
-
- ,
+ com.music.spotui.ui.components.PlayPauseIcon(
+ modifier = Modifier.size(30.dp),
tint = Color.Black,
- painter = if (songPlayingState)
- painterResource(id = R.drawable.ic_playing)
- else
- painterResource(id = R.drawable.play_svgrepo_com)
- ,
+ playing = songPlayingState,
contentDescription = stringResource(if (songPlayingState) R.string.notif_action_pause else R.string.notif_action_play))
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PodcastPlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PodcastPlayerScreen.kt
new file mode 100644
index 00000000..bdc50cc1
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PodcastPlayerScreen.kt
@@ -0,0 +1,373 @@
+package com.music.spotui.ui.screens
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.MoreVert
+import androidx.compose.material.icons.filled.PlayArrow
+import androidx.compose.material.icons.filled.RotateLeft
+import androidx.compose.material.icons.filled.RotateRight
+import androidx.compose.material.icons.outlined.Timer
+import androidx.compose.material3.Icon
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.navigation.NavController
+import app.myspoti.engine.R
+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
+import com.bumptech.glide.integration.compose.GlideImage
+import com.music.spotui.data.entity.SongsModel
+import com.music.spotui.di.Graph
+import com.music.spotui.di.SongPlayer
+import com.music.spotui.ui.components.DevicesSheet
+import com.music.spotui.ui.components.EpisodeOptionsSheet
+import com.music.spotui.ui.components.PodcastSpeedSheet
+import com.music.spotui.ui.components.QueueSheet
+import com.music.spotui.ui.components.SleepTimerSheet
+import com.music.spotui.ui.components.episodeClock
+import com.music.spotui.ui.components.pressable
+import com.music.spotui.ui.components.speedLabel
+import com.music.spotui.ui.theme.AppAccent
+import com.music.spotui.ui.theme.AppBackground
+import kotlinx.coroutines.launch
+
+/**
+ * The player, when a podcast episode plays: Spotify gives it its own controls — ±15 s instead
+ * of previous / next, a speed selector, a sleep timer and no shuffle or repeat. Music keeps
+ * the music player ([PlayerScreen]).
+ */
+@OptIn(ExperimentalGlideComposeApi::class)
+@Composable
+fun PodcastPlayerScreen(navController: NavController) {
+ val context = LocalContext.current
+ val state = Graph.currentSongState
+ val np by SongPlayer.nowPlaying
+ val title = state.title.value
+ val showName = state.singer.value.ifBlank { np.contextName }
+ val cover = state.coverUri.value
+ val playing = state.playingState.value
+ val episodeId = np.uri.removePrefix("spotify:episode:")
+ val uri = "spotify:episode:$episodeId"
+ val saved = SongPlayer.library[uri] == true
+ androidx.compose.runtime.LaunchedEffect(uri) { SongPlayer.requestSaved(uri) }
+
+ var showSpeed by remember { mutableStateOf(false) }
+ var showSleep by remember { mutableStateOf(false) }
+ var showDevices by remember { mutableStateOf(false) }
+ var showQueue by remember { mutableStateOf(false) }
+ var showMenu by remember { mutableStateOf(false) }
+ // Tapping the time flips it, as in the official player (it opens on what is left).
+ var showRemaining by remember { mutableStateOf(true) }
+ var drag by remember { mutableStateOf<Float?>(null) }
+ var position by remember { mutableStateOf(SongPlayer.getCurrentPosition()) }
+ val scope = androidx.compose.runtime.rememberCoroutineScope()
+
+ val duration = SongPlayer.getDuration()
+ LaunchedEffect(playing, np.uri) {
+ while (true) {
+ position = SongPlayer.getCurrentPosition()
+ if (!playing) break
+ kotlinx.coroutines.delay(500)
+ }
+ }
+ val fraction = when {
+ drag != null -> drag!!
+ duration > 0 -> (position.toFloat() / duration).coerceIn(0f, 1f)
+ else -> 0f
+ }
+
+ val song = SongsModel(
+ id = ("uri:$uri").hashCode() and 0x7fffffff,
+ title = title,
+ album = showName,
+ singer = showName,
+ coverUri = cover,
+ url = "episode:$episodeId",
+ durationMs = duration.toInt(),
+ )
+
+ if (showSpeed) PodcastSpeedSheet { showSpeed = false }
+ if (showSleep) SleepTimerSheet { showSleep = false }
+ if (showDevices) DevicesSheet { showDevices = false }
+ if (showQueue) QueueSheet(contextName = showName) { showQueue = false }
+ if (showMenu) EpisodeOptionsSheet(
+ song = song,
+ finished = false,
+ onPlay = { SongPlayer.play() },
+ onMarkFinished = { played ->
+ scope.launch {
+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ runCatching { Graph.api.setEpisodePlayed(uri, played) }
+ }
+ }
+ },
+ onOpen = { navController.navigate(com.music.spotui.ui.navigation.episodeRoute(episodeId, title)) },
+ onDismiss = { showMenu = false },
+ )
+
+ // The background takes the cover's colour like the music player, cross-faded on change.
+ var coverColor by remember { mutableStateOf(com.music.spotui.di.Palette.cachedSecond(cover) ?: Color(0xFF3A3630)) }
+ LaunchedEffect(cover) {
+ if (cover.isNotBlank()) com.music.spotui.di.Palette().extractSecondColorFromCoverUrl(context, cover) { coverColor = it }
+ }
+ val tint by androidx.compose.animation.animateColorAsState(coverColor, androidx.compose.animation.core.tween(450), label = "cover")
+
+ Box(
+ Modifier
+ .fillMaxSize()
+ .background(Brush.verticalGradient(listOf(tint, AppBackground))),
+ ) {
+ Column(Modifier.fillMaxSize().statusBarsPadding()) {
+ // Top bar: down chevron, "playing from the podcast", the episode's own menu.
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.SpaceBetween,
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 12.dp),
+ ) {
+ Icon(
+ painter = painterResource(id = R.drawable.ic_down),
+ contentDescription = stringResource(R.string.a11y_close_player),
+ tint = Color.White,
+ modifier = Modifier.size(26.dp).clickable(
+ interactionSource = remember { MutableInteractionSource() },
+ indication = null,
+ ) { com.music.spotui.ui.navigation.PlayerSheet.close() },
+ )
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ modifier = Modifier
+ .weight(1f)
+ .padding(horizontal = 12.dp)
+ .clickable(
+ interactionSource = remember { MutableInteractionSource() },
+ indication = null,
+ ) {
+ val showId = episodeShowId(np.contextUri)
+ if (showId.isNotBlank()) navController.navigate(com.music.spotui.ui.navigation.showRoute(showId, showName))
+ },
+ ) {
+ Text(
+ stringResource(R.string.podcast_playing_from),
+ color = Color.White.copy(alpha = 0.7f),
+ fontSize = 12.sp,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ Text(
+ showName,
+ color = Color.White,
+ fontSize = 13.sp,
+ fontWeight = FontWeight.Bold,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ Icon(
+ Icons.Default.MoreVert,
+ contentDescription = stringResource(R.string.episode_options),
+ tint = Color.White,
+ modifier = Modifier.size(24.dp).pressable(0.9f) { showMenu = true },
+ )
+ }
+
+ Spacer(Modifier.weight(1f))
+ GlideImage(
+ transition = CrossFade,
+ model = cover,
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ modifier = Modifier
+ .fillMaxWidth(0.82f)
+ .aspectRatio(1f)
+ .align(Alignment.CenterHorizontally)
+ .clip(RoundedCornerShape(8.dp)),
+ )
+ Spacer(Modifier.weight(1f))
+
+ // Episode title and the show it comes from.
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp),
+ ) {
+ Column(Modifier.weight(1f)) {
+ Text(
+ text = title,
+ color = Color.White,
+ fontSize = 21.sp,
+ fontWeight = FontWeight.Bold,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ )
+ Text(
+ text = showName,
+ color = Color.White.copy(alpha = 0.7f),
+ fontSize = 14.sp,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.clickable(
+ interactionSource = remember { MutableInteractionSource() },
+ indication = null,
+ ) {
+ val showId = episodeShowId(np.contextUri)
+ if (showId.isNotBlank()) navController.navigate(com.music.spotui.ui.navigation.showRoute(showId, showName))
+ },
+ )
+ }
+ LikeButton(liked = saved, size = 28.dp) { SongPlayer.setSaved(uri, !saved) }
+ }
+
+ SpotifySeekBar(
+ fraction = { fraction },
+ onDrag = { f -> drag = f },
+ onRelease = {
+ val f = drag ?: return@SpotifySeekBar
+ drag = null
+ if (duration > 0) {
+ position = (f * duration).toLong()
+ SongPlayer.seekTo(position)
+ }
+ },
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 4.dp),
+ )
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.SpaceBetween,
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp),
+ ) {
+ Text(episodeClock(if (drag != null) (drag!! * duration).toLong() else position), color = Color.White.copy(alpha = 0.7f), fontSize = 12.sp)
+ // The stock player's right-hand clock is a button: elapsed ↔ remaining.
+ Text(
+ text = if (showRemaining) episodeClock((duration - if (drag != null) (drag!! * duration).toLong() else position).coerceAtLeast(0))
+ else episodeClock(if (drag != null) (drag!! * duration).toLong() else position),
+ color = Color.White.copy(alpha = 0.7f),
+ fontSize = 12.sp,
+ modifier = Modifier.clickable(
+ interactionSource = remember { MutableInteractionSource() },
+ indication = null,
+ ) { showRemaining = !showRemaining },
+ )
+ }
+
+ // Podcast transport: speed, −15 s, play, +15 s, sleep timer. No shuffle, no repeat:
+ // the official app does not put them on an episode.
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.SpaceBetween,
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 12.dp).height(64.dp),
+ ) {
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .size(width = 44.dp, height = 28.dp)
+ .clip(RoundedCornerShape(14.dp))
+ .border(1.dp, Color.White.copy(alpha = 0.5f), RoundedCornerShape(14.dp))
+ .pressable(0.92f) { showSpeed = true },
+ ) {
+ Text(
+ stringResource(R.string.player_speed_chip, speedLabel(SongPlayer.speed.value)),
+ color = Color.White,
+ fontSize = 12.sp,
+ fontWeight = FontWeight.Bold,
+ )
+ }
+ SkipIcon(back = true)
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .size(64.dp)
+ .clip(CircleShape)
+ .background(Color.White)
+ .pressable(0.92f) {
+ if (playing) SongPlayer.pause() else SongPlayer.play()
+ },
+ ) {
+ com.music.spotui.ui.components.PlayPauseIcon(
+ playing = playing,
+ contentDescription = stringResource(if (playing) R.string.notif_action_pause else R.string.notif_action_play),
+ tint = Color.Black,
+ modifier = Modifier.size(30.dp),
+ )
+ }
+ SkipIcon(back = false)
+ Icon(
+ Icons.Outlined.Timer,
+ contentDescription = stringResource(R.string.player_sleep_timer),
+ tint = if (SongPlayer.sleepEndsAt.value != null) AppAccent else Color.White,
+ modifier = Modifier.size(26.dp).pressable(0.9f) { showSleep = true },
+ )
+ }
+
+ PlayerConnectRow(
+ context = context,
+ title = title,
+ artist = showName,
+ coverUri = cover,
+ onDevices = { showDevices = true },
+ onQueue = { showQueue = true },
+ )
+ Spacer(Modifier.height(16.dp))
+ }
+ }
+}
+
+/** ±15 s: the circular arrow with the number inside, as the official player draws it. */
+@Composable
+private fun SkipIcon(back: Boolean) {
+ Box(contentAlignment = Alignment.Center, modifier = Modifier.size(40.dp).pressable(0.9f) {
+ SongPlayer.skipBy(if (back) -15_000L else 15_000L)
+ }) {
+ Icon(
+ imageVector = if (back) Icons.Default.RotateLeft else Icons.Default.RotateRight,
+ contentDescription = stringResource(if (back) R.string.player_back_15 else R.string.player_forward_15),
+ tint = Color.White,
+ modifier = Modifier.size(34.dp),
+ )
+ Text(
+ text = "15",
+ color = Color.White,
+ fontSize = 10.sp,
+ fontWeight = FontWeight.Bold,
+ textAlign = TextAlign.Center,
+ )
+ }
+}
+
+/** The show id carried by the played context ("spotify:show:<id>"), "" when there is none. */
+private fun episodeShowId(contextUri: String): String =
+ contextUri.takeIf { it.startsWith("spotify:show:") }?.removePrefix("spotify:show:").orEmpty()
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt
index c0a7296f..917c58d0 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt
@@ -47,9 +47,11 @@ import app.myspoti.api.best
import app.myspoti.engine.R
import app.myspoti.host.android.MyspotiRuntime
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import com.music.spotui.ui.components.pressable
+import com.music.spotui.ui.components.spotifyImageUrl
import com.music.spotui.ui.navigation.playlistRoute
import com.music.spotui.ui.theme.AppAccent
import com.music.spotui.ui.theme.AppBackground
@@ -89,7 +91,8 @@ fun ProfileScreen(navController: NavController, userId: String, userName: String
item {
Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth().padding(16.dp)) {
GlideImage(
- model = p?.images?.best(300)?.url,
+ transition = CrossFade,
+ model = spotifyImageUrl(p?.images?.best(300)?.url),
contentDescription = null,
contentScale = ContentScale.Crop,
failure = placeholder(R.drawable.placeholder),
@@ -161,7 +164,8 @@ fun ProfileScreen(navController: NavController, userId: String, userName: String
.padding(16.dp, 8.dp),
) {
GlideImage(
- model = pl.images.best(160)?.url, contentDescription = null, contentScale = ContentScale.Crop,
+ transition = CrossFade,
+ model = spotifyImageUrl(pl.images.best(160)?.url), contentDescription = null, contentScale = ContentScale.Crop,
failure = placeholder(R.drawable.placeholder), loading = placeholder(R.drawable.placeholder),
modifier = Modifier.size(56.dp).clip(RoundedCornerShape(4.dp)),
)
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/QueueScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/QueueScreen.kt
index 4bcbd42f..d7814d96 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/QueueScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/QueueScreen.kt
@@ -54,6 +54,7 @@ import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import app.myspoti.engine.R
@@ -196,6 +197,7 @@ private fun QueueRow(
.padding(16.dp, 8.dp)
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.size(48.dp)
.clip(RoundedCornerShape(4.dp)),
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/RecentlyPlayedScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/RecentlyPlayedScreen.kt
new file mode 100644
index 00000000..ab69383b
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/RecentlyPlayedScreen.kt
@@ -0,0 +1,413 @@
+package com.music.spotui.ui.screens
+
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.itemsIndexed
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material.icons.filled.Favorite
+import androidx.compose.material.icons.filled.KeyboardArrowDown
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.Icon
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.derivedStateOf
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.rotate
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.navigation.NavController
+import app.myspoti.api.MediaKind
+import app.myspoti.api.RecentEntry
+import app.myspoti.api.RecentGroup
+import app.myspoti.api.RecentItem
+import app.myspoti.api.RecentSection
+import app.myspoti.api.best
+import app.myspoti.api.groupRecents
+import app.myspoti.engine.R
+import app.myspoti.host.android.MyspotiRuntime
+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
+import com.bumptech.glide.integration.compose.GlideImage
+import com.music.spotui.di.SongPlayer
+import com.music.spotui.ui.navigation.Routes
+import com.music.spotui.ui.navigation.albumRoute
+import com.music.spotui.ui.navigation.artistRoute
+import com.music.spotui.ui.navigation.playlistRoute
+import com.music.spotui.ui.navigation.showRoute
+import java.time.Instant
+import java.time.LocalDate
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+import java.util.Locale
+
+private val Background: Color get() = com.music.spotui.ui.theme.AppBackground
+private val Subtle = Color(0xFFB3B3B3)
+/** The pill and chevron greys of Spotify's own page. */
+private val ChipIdle = Color(0xFF282828)
+private val ChevronRing = Color(0xFF8A8A8A)
+
+/** Rows per request: what the Web Player asks for its own list page. */
+private const val PAGE = 50
+
+/** The Liked Songs collection's uri, the row Spotify badges with a heart. */
+private const val LIKED_URI = "spotify:collection:tracks"
+
+/** The saved-episodes collection: a podcast context whose page is the app's own Episodes screen. */
+private const val YOUR_EPISODES_URI = "spotify:collection:your-episodes"
+
+/**
+ * "Récents", from Spotify's own list for the account (see [app.myspoti.api.Recents]): the plays of
+ * every device, grouped by context the way the official page groups them — one row per album,
+ * playlist, artist or show, dated, with the plays behind an expand chevron.
+ */
+@Composable
+fun RecentlyPlayedScreen(navController: NavController) {
+ var entries by remember { mutableStateOf<List<RecentEntry>?>(null) }
+ var failure by remember { mutableStateOf<String?>(null) }
+ // Spotify's list holds thousands of rows: the next pages load as the end comes into view.
+ var nextOffset by remember { mutableStateOf<Int?>(null) }
+ var loadingMore by remember { mutableStateOf(false) }
+ var podcasts by remember { mutableStateOf(false) }
+ var expanded by remember { mutableStateOf(emptySet<String>()) }
+ val listState = rememberLazyListState()
+
+ LaunchedEffect(Unit) {
+ runCatching { MyspotiRuntime.api.recents.recentEntries(0, PAGE) }
+ .onSuccess { page ->
+ entries = page.items
+ nextOffset = page.nextOffset
+ }
+ .onFailure { failure = it.message ?: it.toString() }
+ }
+
+ val atEnd by remember {
+ derivedStateOf {
+ val last = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: return@derivedStateOf false
+ last >= (entries?.size ?: 0) - 5
+ }
+ }
+ LaunchedEffect(atEnd, nextOffset) {
+ val offset = nextOffset ?: return@LaunchedEffect
+ if (!atEnd || loadingMore) return@LaunchedEffect
+ loadingMore = true
+ runCatching { MyspotiRuntime.api.recents.recentEntries(offset, PAGE) }
+ .onSuccess { page ->
+ entries = entries.orEmpty() + page.items
+ nextOffset = page.nextOffset
+ }
+ loadingMore = false
+ }
+
+ // Grouping runs on the raw rows, then the pill drops what the tab does not show: a heading
+ // whose rows are all gone disappears with them.
+ val sections = remember(entries, podcasts) {
+ groupRecents(entries.orEmpty()).mapNotNull { section ->
+ val groups = section.groups.filter { it.music != podcasts }
+ if (groups.isEmpty()) null else RecentSection(section.dayMs, groups)
+ }
+ }
+
+ Column(Modifier.fillMaxSize().background(Background).statusBarsPadding()) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 16.dp, top = 8.dp),
+ ) {
+ Icon(
+ imageVector = Icons.AutoMirrored.Filled.ArrowBack,
+ contentDescription = stringResource(R.string.accessibility_navigate_back),
+ tint = Color.White,
+ modifier = Modifier.size(40.dp).clip(RoundedCornerShape(20.dp))
+ .clickable { navController.popBackStack() }.padding(8.dp),
+ )
+ Text(
+ stringResource(R.string.recents_title),
+ fontWeight = FontWeight.Bold, color = Color.White, fontSize = 24.sp, maxLines = 1,
+ overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(start = 4.dp),
+ )
+ }
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp),
+ ) {
+ Pill(stringResource(R.string.recents_filter_music), selected = !podcasts) { podcasts = false }
+ Pill(stringResource(R.string.recents_filter_podcasts), selected = podcasts) { podcasts = true }
+ }
+ when {
+ entries == null && failure != null -> Text(
+ stringResource(R.string.recently_played_failed, failure.orEmpty()),
+ color = Subtle, fontSize = 14.sp, modifier = Modifier.padding(20.dp),
+ )
+ entries == null -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ CircularProgressIndicator(color = com.music.spotui.ui.theme.AppAccent)
+ }
+ sections.isEmpty() -> Text(
+ stringResource(R.string.recently_played_empty),
+ color = Subtle, fontSize = 14.sp, modifier = Modifier.padding(20.dp),
+ )
+ else -> LazyColumn(
+ state = listState,
+ contentPadding = PaddingValues(bottom = com.music.spotui.ui.components.bottomBarsSpace()),
+ ) {
+ sections.forEach { section ->
+ item(key = "day:${section.dayMs}") { DayHeader(section.dayMs) }
+ section.groups.forEach { group ->
+ val key = group.context.uri
+ item(key = "row:$key") {
+ GroupRow(
+ modifier = Modifier.animateItem(),
+ group = group,
+ expanded = key in expanded,
+ onToggle = {
+ expanded = if (key in expanded) expanded - key else expanded + key
+ },
+ onOpen = { openContext(group.context, navController) },
+ )
+ }
+ if (key in expanded) {
+ itemsIndexed(
+ group.plays,
+ key = { index, play -> "play:$key:$index:${play.uri}" },
+ ) { _, play ->
+ // Unfolded plays fade in and push the rows below down, as in the official app.
+ PlayRow(play, Modifier.animateItem()) {
+ SongPlayer.playSong(playUri(play), contextUri = group.context.uri)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun DayHeader(dayMs: Long?) {
+ Text(
+ dayLabel(dayMs),
+ color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, top = 20.dp, bottom = 6.dp),
+ )
+}
+
+@Composable
+private fun Pill(label: String, selected: Boolean, onClick: () -> Unit) {
+ Box(
+ Modifier.clip(RoundedCornerShape(50))
+ .background(if (selected) Color.White else ChipIdle)
+ .clickable(onClick = onClick)
+ .padding(horizontal = 14.dp, vertical = 7.dp),
+ ) {
+ Text(
+ label,
+ color = if (selected) Color.Black else Color.White,
+ fontSize = 13.sp, fontWeight = FontWeight.Medium, maxLines = 1,
+ )
+ }
+}
+
+/**
+ * One context of the list: its cover, its count, its type and creators, and the round chevron
+ * that expands it in place. The row itself opens the context, as in the official app.
+ */
+@Composable
+private fun GroupRow(group: RecentGroup, expanded: Boolean, onToggle: () -> Unit, onOpen: () -> Unit, modifier: Modifier = Modifier) {
+ val artist = group.context.kind == MediaKind.ARTIST
+ val rotation by animateFloatAsState(if (expanded) 180f else 0f, label = "recentChevron")
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = modifier.fillMaxWidth().clickable(onClick = onOpen)
+ .padding(horizontal = 16.dp, vertical = 6.dp),
+ ) {
+ RecentCover(group.context, 56.dp)
+ Column(Modifier.padding(start = 12.dp).weight(1f)) {
+ // A context the server could not name (a withdrawn album) still reads: its count is
+ // the only thing left to title the row with, and Spotify then drops the subtitle
+ // line instead of repeating the count there.
+ val count = countLabel(group.count, group.saved)
+ Text(
+ group.context.title.ifBlank { count },
+ color = Color.White, fontSize = 16.sp, fontWeight = FontWeight.Bold,
+ maxLines = 1, overflow = TextOverflow.Ellipsis,
+ )
+ if (group.context.title.isNotBlank()) {
+ Text(
+ groupSubtitle(group),
+ color = Subtle, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+ Box(
+ Modifier.padding(start = 8.dp).size(28.dp).clip(CircleShape)
+ .border(1.dp, ChevronRing, CircleShape)
+ .clickable(onClick = onToggle),
+ contentAlignment = Alignment.Center,
+ ) {
+ Icon(
+ Icons.Filled.KeyboardArrowDown,
+ contentDescription = stringResource(
+ if (expanded) R.string.recents_collapse else R.string.recents_expand,
+ ),
+ tint = Color.White,
+ modifier = Modifier.size(18.dp).rotate(rotation),
+ )
+ }
+ }
+}
+
+/** A play of an expanded context: tapping it plays that track with the context as its queue. */
+@OptIn(ExperimentalGlideComposeApi::class)
+@Composable
+private fun PlayRow(item: RecentItem, modifier: Modifier = Modifier, onClick: () -> Unit) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = modifier.fillMaxWidth().clickable(onClick = onClick)
+ .padding(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 4.dp),
+ ) {
+ GlideImage(
+ transition = CrossFade,
+ model = item.images.best(300)?.url.orEmpty(),
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ modifier = Modifier.size(40.dp).clip(RoundedCornerShape(3.dp)),
+ )
+ Column(Modifier.padding(start = 12.dp).weight(1f)) {
+ Text(item.title, color = Color.White, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ item.subtitle?.let {
+ Text(it, color = Subtle, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ }
+ }
+}
+
+/**
+ * The context's artwork. Artists are round, everything else is a square with the page's corners;
+ * Liked Songs carries the heart badge Spotify draws over its cover.
+ */
+@OptIn(ExperimentalGlideComposeApi::class)
+@Composable
+private fun RecentCover(context: RecentItem, size: Dp) {
+ Box(Modifier.size(size)) {
+ GlideImage(
+ transition = CrossFade,
+ model = context.images.best(300)?.url.orEmpty(),
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ modifier = Modifier.size(size).clip(
+ if (context.kind == MediaKind.ARTIST) CircleShape else RoundedCornerShape(4.dp),
+ ),
+ )
+ if (context.uri == LIKED_URI || context.kind == MediaKind.COLLECTION) {
+ Box(
+ Modifier.align(Alignment.BottomStart).size(22.dp).clip(RoundedCornerShape(6.dp))
+ .background(Brush.linearGradient(listOf(Color(0xFF8E7CFF), Color(0xFFC9B8FF)))),
+ contentAlignment = Alignment.Center,
+ ) {
+ Icon(
+ Icons.Filled.Favorite,
+ contentDescription = stringResource(R.string.collection_liked_songs_title),
+ tint = Color.White,
+ modifier = Modifier.size(13.dp),
+ )
+ }
+ }
+ }
+}
+
+/** "[N] titres lus • [Type] • [creators]", with Spotify's own wording for saved rows. */
+@Composable
+private fun groupSubtitle(group: RecentGroup): String {
+ val parts = buildList {
+ add(countLabel(group.count, group.saved))
+ add(group.context.typeLabel?.takeIf { it.isNotBlank() } ?: kindLabel(group.context.kind))
+ // Liked Songs and artists show no creator line on Spotify's own rows.
+ if (!group.saved && group.context.kind != MediaKind.ARTIST) group.context.subtitle?.let { add(it) }
+ }
+ return parts.filter { it.isNotBlank() }.joinToString(" • ")
+}
+
+@Composable
+private fun countLabel(count: Int, saved: Boolean): String = when {
+ saved && count == 1 -> stringResource(R.string.recents_saved_one)
+ saved -> stringResource(R.string.recents_saved_many, count)
+ count == 1 -> stringResource(R.string.recents_played_one)
+ else -> stringResource(R.string.recents_played_many, count)
+}
+
+@Composable
+private fun dayLabel(dayMs: Long?): String {
+ if (dayMs == null) return ""
+ val date = Instant.ofEpochMilli(dayMs).atZone(ZoneId.systemDefault()).toLocalDate()
+ val today = LocalDate.now()
+ return when (date) {
+ today -> stringResource(R.string.recents_today)
+ today.minusDays(1) -> stringResource(R.string.recents_yesterday)
+ // Older days print as the official page does: day and short month, in the phone's language.
+ else -> date.format(DateTimeFormatter.ofPattern("d MMM", Locale.getDefault()))
+ }
+}
+
+@Composable
+private fun kindLabel(kind: MediaKind): String = when (kind) {
+ MediaKind.PLAYLIST -> stringResource(R.string.assisted_curation_search_playlist)
+ MediaKind.ALBUM -> stringResource(R.string.album_type_album)
+ MediaKind.ARTIST -> stringResource(R.string.artist_subtitle)
+ MediaKind.SHOW -> stringResource(R.string.ad_category_title_podcasts)
+ MediaKind.EPISODE -> stringResource(R.string.your_episodes_title)
+ else -> ""
+}
+
+/** The uri a play row hands the player: episodes are queued by id, tracks by their own uri. */
+private fun playUri(item: RecentItem): String =
+ if (item.kind == MediaKind.EPISODE) "episode:" + item.uri.substringAfterLast(':') else item.uri
+
+/**
+ * Opens the context the row stands for. Liked Songs and Your Episodes are collections with their
+ * own pages, the rest go to their playlist, album, artist or show page; a lone track (a row with
+ * no context) plays.
+ */
+private fun openContext(context: RecentItem, navController: NavController) {
+ val id = context.uri.substringAfterLast(':')
+ when {
+ context.uri == LIKED_URI || context.kind == MediaKind.COLLECTION -> navController.navigate(Routes.Liked.route)
+ context.uri == YOUR_EPISODES_URI -> navController.navigate(Routes.Episodes.route)
+ context.kind == MediaKind.PLAYLIST -> navController.navigate(playlistRoute(id, context.title))
+ context.kind == MediaKind.ALBUM -> navController.navigate(albumRoute(context.title, context.subtitle.orEmpty(), id))
+ context.kind == MediaKind.ARTIST -> navController.navigate(artistRoute(context.title, id))
+ context.kind == MediaKind.SHOW -> navController.navigate(showRoute(id, context.title))
+ context.kind == MediaKind.TRACK || context.kind == MediaKind.EPISODE ->
+ SongPlayer.playSong(playUri(context), contextUri = null)
+ else -> Unit
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt
index 81829e34..6c3b6ea4 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt
@@ -49,6 +49,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.focus.onFocusChanged
+import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.layout.ContentScale
@@ -62,6 +63,7 @@ import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import app.myspoti.engine.R
@@ -122,6 +124,21 @@ fun SumUpSearchScreen(
mutableStateOf(com.music.spotui.data.preferences.getRecentItems(context).filter { com.music.spotui.data.api.Features.PODCASTS || it.type != "show" })
}
var menuSong by remember { mutableStateOf<SongsModel?>(null) }
+ // Re-tapping the Search tab while already on it focuses the field (official behaviour)
+ // and shows the recents again; no query is re-run. The field lives in the sticky bar,
+ // so a focus requester is handed down to it.
+ val listState = androidx.compose.foundation.lazy.rememberLazyListState()
+ val searchFieldFocus = remember { androidx.compose.ui.focus.FocusRequester() }
+ LaunchedEffect(Unit) {
+ com.music.spotui.ui.navigation.TabReselect.search.collect {
+ // Focus first: the keyboard should be up as soon as the tab is tapped.
+ // Not attached yet (screen being torn down): the tap is simply dropped.
+ runCatching { searchFieldFocus.requestFocus() }
+ if (listState.firstVisibleItemIndex != 0 || listState.firstVisibleItemScrollOffset != 0) {
+ listState.animateScrollToItem(0)
+ }
+ }
+ }
// Spotify's filter chips: Top (mixed), or one kind of result.
val filter = searchViewModel.filter
menuSong?.let { sel ->
@@ -158,6 +175,7 @@ fun SumUpSearchScreen(
}
LazyColumn(
+ state = listState,
contentPadding = androidx.compose.foundation.layout.PaddingValues(bottom = com.music.spotui.ui.components.bottomBarsSpace()),
modifier = Modifier
.fillMaxSize()
@@ -172,6 +190,7 @@ fun SumUpSearchScreen(
SearchStickyBar(
text,
onFocusChange = { searchFocused = it },
+ focusRequester = searchFieldFocus,
) {
searchViewModel.search(it)
}
@@ -486,6 +505,7 @@ fun RecentItemRow(
.padding(16.dp, 8.dp),
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.size(48.dp)
.clip(RoundedCornerShape(if (item.type == "artist") 100.dp else 6.dp)),
@@ -570,6 +590,7 @@ fun SearchSongRow(
modifier = Modifier.weight(1f).padding(end = 8.dp),
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.padding(0.dp, 0.dp, 10.dp, 0.dp)
.size(48.dp)
@@ -618,6 +639,7 @@ fun SearchShowRow(show: com.music.spotui.data.entity.PodcastModel, onClick: () -
,
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.padding(0.dp, 0.dp, 10.dp, 0.dp)
.size(48.dp)
@@ -649,6 +671,7 @@ fun SearchArtistRow(artist: com.music.spotui.data.entity.ArtistsModel, onClick:
,
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.padding(0.dp, 0.dp, 10.dp, 0.dp)
.size(48.dp)
@@ -677,6 +700,7 @@ fun SearchAlbumRow(album: com.music.spotui.data.entity.AlbumsModel, onClick: ()
,
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier
.padding(0.dp, 0.dp, 10.dp, 0.dp)
.size(48.dp)
@@ -702,6 +726,7 @@ fun SearchPlaylistRow(playlist: com.music.spotui.data.entity.LibraryEntry, onCli
modifier = Modifier.pressable(0.96f) { onClick() }.fillMaxWidth().padding(16.dp, 8.dp),
) {
GlideImage(
+ transition = CrossFade,
modifier = Modifier.padding(0.dp, 0.dp, 10.dp, 0.dp).size(48.dp).clip(RoundedCornerShape(6.dp)),
model = playlist.coverUri,
contentScale = ContentScale.Crop,
@@ -782,6 +807,7 @@ private fun BrowseCategoryTile(
) {
if (cover.isNotBlank()) {
GlideImage(
+ transition = CrossFade,
model = cover,
contentScale = ContentScale.Crop,
contentDescription = null,
@@ -823,6 +849,7 @@ fun SearchTopBar() {
fun SearchStickyBar(
text: String,
onFocusChange: (Boolean) -> Unit = {},
+ focusRequester: androidx.compose.ui.focus.FocusRequester? = null,
onTextChange: (String) -> Unit,
) {
@@ -842,7 +869,9 @@ fun SearchStickyBar(
TextField(
enabled = true,
- modifier = Modifier.onFocusChanged { onFocusChange(it.isFocused) },
+ modifier = Modifier
+ .then(if (focusRequester != null) Modifier.focusRequester(focusRequester) else Modifier)
+ .onFocusChanged { onFocusChange(it.isFocused) },
value = text,
textStyle = TextStyle.Default.copy(fontSize = 16.sp, color = Color.Black, fontWeight = FontWeight(500)),
colors = TextFieldDefaults.colors(
@@ -879,6 +908,7 @@ private fun SearchProfileRow(name: String, image: String?, onClick: () -> Unit)
modifier = Modifier.fillMaxWidth().pressable(0.98f, onClick = onClick).padding(16.dp, 8.dp),
) {
com.bumptech.glide.integration.compose.GlideImage(
+ transition = CrossFade,
model = image, contentDescription = null, contentScale = androidx.compose.ui.layout.ContentScale.Crop,
failure = com.bumptech.glide.integration.compose.placeholder(R.drawable.placeholder),
modifier = Modifier.size(52.dp).clip(androidx.compose.foundation.shape.CircleShape),
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
index 348dccda..07d46cf9 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt
@@ -45,6 +45,7 @@ import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import app.myspoti.engine.R
+import kotlinx.coroutines.launch
import com.music.spotui.ui.components.DownloadQualityPicker
import com.music.spotui.ui.components.StreamingQualityPicker
import com.music.spotui.ui.theme.AppBackground
@@ -73,6 +74,7 @@ fun SettingsScreen(navController: NavController) {
checked = com.music.spotui.data.preferences.AutoplayPref.on,
onChecked = { com.music.spotui.data.preferences.AutoplayPref.set(ctx, it) },
)
+ CrossfadeRow()
Divider()
Section(R.string.settings_section_downloads)
@@ -149,6 +151,14 @@ fun SettingsScreen(navController: NavController) {
Divider()
Section(R.string.settings_section_app)
+ // A18: the launch check can be turned off; the manual check below keeps working.
+ OptionRow(
+ label = stringResource(R.string.settings_auto_update_title),
+ detail = stringResource(R.string.settings_auto_update_detail),
+ checked = com.music.spotui.data.preferences.AutoUpdateCheckPref.on,
+ onChecked = { com.music.spotui.data.preferences.AutoUpdateCheckPref.set(ctx, it) },
+ )
+ CheckUpdateRow()
// The hidden Web Player stuck or crashed: rebuild it without leaving the app.
Column(
Modifier.fillMaxWidth().clickable { app.myspoti.host.android.MyspotiRuntime.host.reload() }
@@ -157,6 +167,19 @@ fun SettingsScreen(navController: NavController) {
Text(stringResource(R.string.restart_player_title), color = Color.White, fontSize = 16.sp)
Text(stringResource(R.string.restart_player_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
}
+ // The report a tester hands us. The engine's log is otherwise reachable only through
+ // adb logcat, which the person reporting the bug cannot run: the label is a literal
+ // rather than a string resource so this change stays out of the shared string files.
+ Column(
+ Modifier.fillMaxWidth().clickable {
+ val file = runCatching { app.myspoti.host.android.Logbook.export(ctx) }.getOrNull()
+ if (file != null) shareDiagnosticReport(ctx, file)
+ else android.widget.Toast.makeText(ctx, ctx.getString(R.string.diagnostic_export_failed), android.widget.Toast.LENGTH_SHORT).show()
+ }.padding(horizontal = 20.dp, vertical = 10.dp),
+ ) {
+ Text(stringResource(R.string.diagnostic_export_title), color = Color.White, fontSize = 16.sp)
+ Text(stringResource(R.string.diagnostic_export_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
+ }
Spacer(Modifier.height(96.dp))
}
}
@@ -199,6 +222,42 @@ private fun AccentRow() {
}
}
+/**
+ * "Crossfade": the length of the fade at the end of a song. The label says what it is: the two
+ * songs never overlap (the page plays one media element), so this is a fade, not a true
+ * crossfade. The default is 0: off, as before.
+ */
+@Composable
+private fun CrossfadeRow() {
+ val ctx = androidx.compose.ui.platform.LocalContext.current
+ val pref = com.music.spotui.data.preferences.CrossfadePref
+ androidx.compose.foundation.layout.Column(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 10.dp)) {
+ Text(stringResource(R.string.settings_crossfade_title), color = Color.White, fontSize = 16.sp)
+ Text(
+ stringResource(R.string.settings_crossfade_detail),
+ color = Color(0xFFB3B3B3), fontSize = 12.sp,
+ modifier = Modifier.padding(top = 2.dp),
+ )
+ Row(
+ horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp),
+ modifier = Modifier.padding(top = 10.dp),
+ ) {
+ for (v in listOf(0, 3, 6, 9, 12)) {
+ val selected = pref.seconds == v
+ Text(
+ if (v == 0) stringResource(R.string.settings_crossfade_off)
+ else stringResource(R.string.settings_crossfade_seconds, v),
+ color = if (selected) Color.Black else Color.White, fontSize = 14.sp,
+ modifier = Modifier.clip(androidx.compose.foundation.shape.RoundedCornerShape(50))
+ .background(if (selected) com.music.spotui.ui.theme.AppAccent else Color(0xFF2A2A2A))
+ .clickable { pref.set(ctx, v) }
+ .padding(horizontal = 14.dp, vertical = 8.dp),
+ )
+ }
+ }
+ }
+}
+
/** Screen rotation: portrait (default), automatic or landscape. */
@Composable
private fun OrientationRow() {
@@ -326,3 +385,53 @@ private fun OptionRow(label: String, detail: String, checked: Boolean,
androidx.compose.material3.Switch(checked = checked, enabled = enabled, onCheckedChange = null)
}
}
+
+/** "Check for updates now": the launch check can be off; this one always asks. */
+@Composable
+private fun CheckUpdateRow() {
+ val ctx = androidx.compose.ui.platform.LocalContext.current
+ val scope = androidx.compose.runtime.rememberCoroutineScope()
+ var checking by remember { androidx.compose.runtime.mutableStateOf(false) }
+ androidx.compose.foundation.layout.Column(
+ Modifier.fillMaxWidth().clickable(enabled = !checking) {
+ if (checking) return@clickable
+ checking = true
+ scope.launch {
+ val found = runCatching { com.music.spotui.data.api.UpdateChecker.check(ctx) }.getOrNull()
+ checking = false
+ // The card is the app's one update UI: fill it, it shows itself.
+ if (found != null) com.music.spotui.updateRelease.value = found
+ else android.widget.Toast.makeText(ctx, ctx.getString(R.string.settings_update_check_latest), android.widget.Toast.LENGTH_SHORT).show()
+ }
+ }.padding(horizontal = 20.dp, vertical = 10.dp),
+ ) {
+ Text(
+ stringResource(if (checking) R.string.settings_update_checking else R.string.settings_check_update_title),
+ color = Color.White, fontSize = 16.sp,
+ )
+ Text(stringResource(R.string.settings_check_update_detail), color = Color(0xFFB3B3B3), fontSize = 12.sp)
+ }
+}
+
+/**
+ * Hands the exported report to the share sheet. The file goes through the app's FileProvider;
+ * if the provider refuses the path (external storage absent), the report's own path is shared
+ * instead, so the tester still has something to send.
+ */
+private fun shareDiagnosticReport(context: android.content.Context, file: java.io.File) {
+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
+ type = "text/plain"
+ putExtra(android.content.Intent.EXTRA_SUBJECT, "Myspoti diagnostic report")
+ }
+ val uri = runCatching {
+ androidx.core.content.FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
+ }.getOrNull()
+ if (uri != null) {
+ send.type = "application/octet-stream"
+ send.putExtra(android.content.Intent.EXTRA_STREAM, uri)
+ send.addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ } else {
+ send.putExtra(android.content.Intent.EXTRA_TEXT, "Myspoti diagnostic report: ${file.absolutePath}")
+ }
+ context.startActivity(android.content.Intent.createChooser(send, null).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ShowScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ShowScreen.kt
index 41faf4bd..cc031bb6 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/ShowScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ShowScreen.kt
@@ -1,27 +1,32 @@
package com.music.spotui.ui.screens
-import androidx.compose.ui.res.stringResource
-
-import com.music.spotui.ui.components.pressable
-import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
-import androidx.compose.foundation.combinedClickable
-import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material.icons.filled.Check
+import androidx.compose.material.icons.filled.MoreVert
+import androidx.compose.material.icons.filled.PlayArrow
+import androidx.compose.material.icons.filled.Star
+import androidx.compose.material.icons.filled.Tune
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@@ -34,134 +39,428 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
+import app.myspoti.engine.R
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
-import com.music.spotui.data.entity.SongsModel
-import com.music.spotui.ui.components.SongOptionsSheet
+import com.bumptech.glide.integration.compose.CrossFade
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
-import app.myspoti.engine.R
import com.music.spotui.data.api.Response
+import com.music.spotui.data.entity.PodcastModel
+import com.music.spotui.data.entity.SongsModel
import com.music.spotui.di.SongPlayer
+import com.music.spotui.ui.components.EpisodeDownloadButton
+import com.music.spotui.ui.components.EpisodeOptionsSheet
import com.music.spotui.ui.components.Loader
+import com.music.spotui.ui.components.episodeClock
+import com.music.spotui.ui.components.episodeDateLabel
+import com.music.spotui.ui.components.episodeMinutes
+import com.music.spotui.ui.components.pressable
+import com.music.spotui.ui.components.spotifyUri
+import com.music.spotui.ui.navigation.episodeRoute
+import com.music.spotui.ui.theme.AppAccent
import com.music.spotui.ui.theme.AppBackground
import com.music.spotui.ui.viewmodel.ShowViewModel
-@OptIn(ExperimentalGlideComposeApi::class, ExperimentalFoundationApi::class)
+/**
+ * A show page, laid out like the official app: cover and name, follow, the episodes (or the
+ * chapters of a book) with their own play / download / "…" controls, and an About tab.
+ */
+@OptIn(ExperimentalGlideComposeApi::class)
@Composable
fun ShowScreen(navController: NavController, showId: String, showName: String = "") {
val vm: ShowViewModel = viewModel()
val context = LocalContext.current
LaunchedEffect(showId) { vm.loadShow(showId) }
- val episodesState by vm.episodes.collectAsState()
- val show by vm.show.collectAsState()
- val episodes = (episodesState as? Response.Success)?.data.orEmpty()
+ val pageState by vm.page.collectAsState()
+ val page = (pageState as? Response.Success)?.data
+ val show = page?.show
+ val audiobook = page?.audiobook == true
+ val items = page?.items.orEmpty()
+ var tab by remember { mutableStateOf(0) }
+ var oldestFirst by remember { mutableStateOf(false) }
var menuSong by remember { mutableStateOf<SongsModel?>(null) }
+ val np by SongPlayer.nowPlaying
+
+ fun playAt(index: Int) {
+ val song = items.getOrNull(index) ?: return
+ vm.updateQueue(items)
+ SongPlayer.playSong(song.url, context, contextUri = "spotify:show:$showId")
+ vm.updateSongState(song.coverUri, song.title, song.singer, true, song.id, index, song.album)
+ }
+
+ val rows = remember(items, oldestFirst) { if (oldestFirst) items.reversed() else items }
+
menuSong?.let { sel ->
- SongOptionsSheet(
+ EpisodeOptionsSheet(
song = sel,
- navController = navController,
- context = context,
+ finished = vm.isFinished(sel),
+ onPlay = {
+ val index = items.indexOfFirst { it.url == sel.url }
+ if (index >= 0) playAt(index)
+ },
+ onMarkFinished = { vm.setFinished(sel, it) },
+ onOpen = { navController.navigate(episodeRoute(sel.url.removePrefix("episode:"), sel.title)) },
onDismiss = { menuSong = null },
)
}
- LazyColumn(
- contentPadding = androidx.compose.foundation.layout.PaddingValues(bottom = com.music.spotui.ui.components.bottomBarsSpace()),
+ Box(Modifier.fillMaxSize().background(AppBackground)) {
+ LazyColumn(
+ contentPadding = PaddingValues(bottom = com.music.spotui.ui.components.bottomBarsSpace()),
+ modifier = Modifier.fillMaxSize(),
+ ) {
+ item {
+ Header(
+ navController = navController,
+ show = show,
+ fallbackName = showName,
+ cover = page?.coverUri.orEmpty(),
+ audiobook = audiobook,
+ following = vm.following.value,
+ onFollow = { vm.setFollow(showId, it) },
+ )
+ }
+ item {
+ Row(
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ TabLabel(
+ text = stringResource(if (audiobook) R.string.show_tab_chapters else R.string.show_tab_episodes),
+ selected = tab == 0,
+ modifier = Modifier.weight(1f),
+ ) { tab = 0 }
+ TabLabel(stringResource(R.string.show_tab_about), selected = tab == 1, modifier = Modifier.weight(1f)) { tab = 1 }
+ }
+ }
+ if (tab == 0 && rows.isNotEmpty()) {
+ item {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable { oldestFirst = !oldestFirst }
+ .padding(horizontal = 16.dp, vertical = 12.dp),
+ ) {
+ Icon(Icons.Default.Tune, contentDescription = null, tint = Color.White.copy(alpha = 0.8f), modifier = Modifier.size(18.dp))
+ Spacer(Modifier.width(10.dp))
+ Text(
+ text = stringResource(
+ when {
+ audiobook && oldestFirst -> R.string.show_sort_chapters_oldest
+ audiobook -> R.string.show_sort_chapters_newest
+ oldestFirst -> R.string.show_sort_oldest
+ else -> R.string.show_sort_newest
+ },
+ ),
+ color = Color.White.copy(alpha = 0.8f),
+ fontSize = 13.sp,
+ )
+ }
+ }
+ }
+ if (pageState is Response.Loading && page == null) item { Loader() }
+ if (pageState is Response.Error && items.isEmpty()) item {
+ Text(
+ (pageState as Response.Error).error,
+ color = Color.White.copy(alpha = 0.7f),
+ fontSize = 14.sp,
+ modifier = Modifier.padding(16.dp),
+ )
+ }
+ if (tab == 1) item { About(show) }
+ if (tab == 0 && page != null && items.isEmpty() && pageState !is Response.Loading) item {
+ Text(
+ stringResource(R.string.show_empty),
+ color = Color.White.copy(alpha = 0.6f),
+ fontSize = 14.sp,
+ modifier = Modifier.padding(16.dp),
+ )
+ }
+ if (tab == 0) items(rows, key = { it.url }) { ep ->
+ EpisodeRow(
+ episode = ep,
+ playing = np.uri == "spotify:episode:${ep.url.removePrefix("episode:")}" && SongPlayer.isPlaying(),
+ finished = vm.isFinished(ep),
+ onPlay = {
+ val index = items.indexOfFirst { it.url == ep.url }
+ if (index >= 0) playAt(index)
+ },
+ onOpen = { navController.navigate(episodeRoute(ep.url.removePrefix("episode:"), ep.title)) },
+ onMenu = { menuSong = ep },
+ )
+ }
+ }
+ }
+}
+
+@OptIn(ExperimentalGlideComposeApi::class)
+@Composable
+private fun Header(
+ navController: NavController,
+ show: PodcastModel?,
+ fallbackName: String,
+ cover: String,
+ audiobook: Boolean,
+ following: Boolean,
+ onFollow: (Boolean) -> Unit,
+) {
+ Column(
modifier = Modifier
- .fillMaxSize()
- .background(Color(AppBackground.toArgb()))
+ .fillMaxWidth()
+ .background(Brush.verticalGradient(listOf(Color(0xFF33322F), AppBackground)))
.statusBarsPadding(),
) {
- item {
- Icon(
- imageVector = Icons.AutoMirrored.Filled.ArrowBack,
- tint = Color.White,
- contentDescription = stringResource(R.string.accessibility_navigate_back),
- modifier = Modifier.pressable(0.96f) { navController.navigateUp() }
- .padding(16.dp)
- .size(26.dp)
- ,
- )
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .padding(12.dp)
+ .size(40.dp)
+ .clip(CircleShape)
+ .background(Color.Black.copy(alpha = 0.35f))
+ .clickable { navController.navigateUp() },
+ ) {
+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.accessibility_navigate_back), tint = Color.White)
}
- item {
- Column(
- horizontalAlignment = Alignment.CenterHorizontally,
- modifier = Modifier.fillMaxWidth().padding(16.dp),
- ) {
- GlideImage(
- model = show?.coverUri ?: episodes.firstOrNull()?.coverUri,
- contentScale = ContentScale.Crop,
- failure = placeholder(R.drawable.placeholder),
- modifier = Modifier.size(180.dp).clip(RoundedCornerShape(8.dp)),
- contentDescription = null,
- )
- Spacer(Modifier.height(12.dp))
+ Row(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp)) {
+ GlideImage(
+ transition = CrossFade,
+ model = cover,
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ failure = placeholder(R.drawable.placeholder),
+ modifier = Modifier
+ .size(128.dp)
+ .clip(RoundedCornerShape(6.dp)),
+ )
+ Column(Modifier.weight(1f).padding(start = 16.dp)) {
Text(
- text = show?.name ?: showName,
+ text = show?.name?.takeIf { it.isNotBlank() } ?: fallbackName,
color = Color.White,
- fontSize = 22.sp,
+ fontSize = 24.sp,
fontWeight = FontWeight.Bold,
- maxLines = 2,
+ maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
- show?.publisher?.takeIf { it.isNotBlank() }?.let {
- Text(it, color = Color(0xFFB3B3B3), fontSize = 13.sp)
+ val authors = show?.authors.orEmpty().joinToString(", ")
+ val narrators = show?.narrators.orEmpty().joinToString(", ")
+ if (authors.isNotBlank()) {
+ Spacer(Modifier.height(6.dp))
+ Text(stringResource(R.string.show_authors, authors), color = Color.White.copy(alpha = 0.8f), fontSize = 13.sp, maxLines = 2, overflow = TextOverflow.Ellipsis)
+ }
+ if (narrators.isNotBlank()) {
+ Spacer(Modifier.height(2.dp))
+ Text(stringResource(R.string.show_narrators, narrators), color = Color.White.copy(alpha = 0.65f), fontSize = 12.sp, maxLines = 2, overflow = TextOverflow.Ellipsis)
+ }
+ if (authors.isBlank() && show != null && show.publisher.isNotBlank()) {
+ Spacer(Modifier.height(6.dp))
+ Text(show.publisher, color = Color.White.copy(alpha = 0.8f), fontSize = 13.sp, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
}
}
-
- if (episodesState is Response.Loading) {
- item { Loader() }
- }
-
- items(episodes.size) { i ->
- val ep = episodes[i]
+ // Rating, as the official header shows it under the cover.
+ val rating = show?.rating ?: 0.0
+ if (rating > 0.0) {
Row(
verticalAlignment = Alignment.CenterVertically,
- modifier = Modifier
- .fillMaxWidth()
- .combinedClickable(
- interactionSource = remember { MutableInteractionSource() },
- indication = null,
- onLongClick = { menuSong = ep },
- onClick = {
- vm.updateQueue(listOf(ep))
- SongPlayer.playSong(ep.url, context)
- vm.updateSongState(ep.coverUri, ep.title, ep.singer, true, ep.id, 0, ep.album)
- },
- )
- .padding(16.dp, 10.dp),
+ modifier = Modifier.padding(start = 16.dp, top = 12.dp),
) {
- GlideImage(
- model = ep.coverUri,
- contentScale = ContentScale.Crop,
- failure = placeholder(R.drawable.placeholder),
- modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)),
- contentDescription = null,
+ Icon(Icons.Default.Star, contentDescription = null, tint = Color.White.copy(alpha = 0.8f), modifier = Modifier.size(16.dp))
+ Spacer(Modifier.width(6.dp))
+ Text(
+ text = String.format(java.util.Locale.getDefault(), "%.1f", rating),
+ color = Color.White.copy(alpha = 0.8f),
+ fontSize = 13.sp,
+ )
+ }
+ }
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 14.dp),
+ ) {
+ FollowPill(following) { onFollow(!following) }
+ }
+ }
+}
+
+@Composable
+private fun FollowPill(following: Boolean, onClick: () -> Unit) {
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .height(32.dp)
+ .clip(RoundedCornerShape(16.dp))
+ .background(if (following) Color.White.copy(alpha = 0.12f) else Color.Transparent)
+ .pressable(0.96f, onClick = onClick)
+ .padding(horizontal = 16.dp),
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ if (following) {
+ Icon(Icons.Default.Check, contentDescription = null, tint = Color.White, modifier = Modifier.size(16.dp))
+ Spacer(Modifier.width(6.dp))
+ }
+ Text(
+ text = stringResource(if (following) R.string.show_following else R.string.show_follow),
+ color = Color.White,
+ fontSize = 13.sp,
+ fontWeight = FontWeight.Bold,
+ )
+ }
+ }
+}
+
+@Composable
+private fun TabLabel(text: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ modifier = modifier.clickable(onClick = onClick).padding(vertical = 10.dp),
+ ) {
+ Text(
+ text = text,
+ color = if (selected) Color.White else Color.White.copy(alpha = 0.6f),
+ fontSize = 14.sp,
+ fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,
+ )
+ Spacer(Modifier.height(6.dp))
+ Box(
+ Modifier
+ .height(2.dp)
+ .width(if (selected) 40.dp else 0.dp)
+ .background(AppAccent),
+ )
+ }
+}
+
+@Composable
+private fun About(show: PodcastModel?) {
+ val authors = show?.authors.orEmpty().joinToString(", ")
+ val narrators = show?.narrators.orEmpty().joinToString(", ")
+ Column(Modifier.fillMaxWidth().padding(16.dp)) {
+ Text(
+ text = show?.description.orEmpty(),
+ color = Color.White.copy(alpha = 0.75f),
+ fontSize = 14.sp,
+ )
+ if (authors.isNotBlank()) {
+ Spacer(Modifier.height(12.dp))
+ Text(stringResource(R.string.show_authors, authors), color = Color.White.copy(alpha = 0.6f), fontSize = 13.sp)
+ }
+ if (narrators.isNotBlank()) {
+ Spacer(Modifier.height(4.dp))
+ Text(stringResource(R.string.show_narrators, narrators), color = Color.White.copy(alpha = 0.6f), fontSize = 13.sp)
+ }
+ }
+}
+
+/** One episode (or chapter): cover, title, snippet, date • length, then its own controls. */
+@OptIn(ExperimentalGlideComposeApi::class)
+@Composable
+private fun EpisodeRow(
+ episode: SongsModel,
+ playing: Boolean,
+ finished: Boolean,
+ onPlay: () -> Unit,
+ onOpen: () -> Unit,
+ onMenu: () -> Unit,
+) {
+ val date = episodeDateLabel(episode.releaseDate)
+ val minutes = episodeMinutes(episode.durationMs)
+ Column(Modifier.fillMaxWidth().clickable(onClick = onOpen).padding(horizontal = 16.dp, vertical = 10.dp)) {
+ Row {
+ GlideImage(
+ transition = CrossFade,
+ model = episode.coverUri,
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ failure = placeholder(R.drawable.placeholder),
+ modifier = Modifier.size(56.dp).clip(RoundedCornerShape(4.dp)),
+ )
+ Column(Modifier.weight(1f).padding(start = 12.dp)) {
+ Text(
+ text = episode.title,
+ color = if (playing) AppAccent else Color.White,
+ fontSize = 15.sp,
+ fontWeight = FontWeight.SemiBold,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
)
- Column(modifier = Modifier.padding(start = 12.dp).weight(1f)) {
+ if (episode.description.isNotBlank()) {
+ Spacer(Modifier.height(4.dp))
Text(
- ep.title,
- color = if (ep.id == vm.currentSongId.value) com.music.spotui.ui.theme.AppAccent else Color.White,
- fontSize = 15.sp,
- fontWeight = FontWeight.SemiBold,
+ text = episode.description,
+ color = Color.White.copy(alpha = 0.65f),
+ fontSize = 12.sp,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
- Text(ep.singer, color = Color(0xFFB3B3B3), fontSize = 12.sp, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)
}
+ Spacer(Modifier.height(4.dp))
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ if (finished) {
+ Text(stringResource(R.string.episode_marked_played), color = Color.White.copy(alpha = 0.6f), fontSize = 12.sp)
+ Spacer(Modifier.width(6.dp))
+ Text("•", color = Color.White.copy(alpha = 0.4f), fontSize = 12.sp)
+ Spacer(Modifier.width(6.dp))
+ }
+ val started = episode.playedPositionMs > 0 && !finished
+ Text(
+ text = when {
+ date.isBlank() -> minutes
+ else -> "$date • $minutes"
+ },
+ color = Color.White.copy(alpha = 0.6f),
+ fontSize = 12.sp,
+ )
+ if (started) {
+ Spacer(Modifier.width(8.dp))
+ Text(
+ text = stringResource(R.string.episode_remaining, episodeClock(episode.durationMs - episode.playedPositionMs)),
+ color = AppAccent,
+ fontSize = 12.sp,
+ )
+ }
+ }
+ }
+ }
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.End,
+ modifier = Modifier.fillMaxWidth().padding(top = 6.dp),
+ ) {
+ Icon(
+ Icons.Default.MoreVert,
+ contentDescription = stringResource(R.string.episode_options),
+ tint = Color.White.copy(alpha = 0.8f),
+ modifier = Modifier.size(22.dp).pressable(0.9f, onClick = onMenu),
+ )
+ Spacer(Modifier.weight(1f))
+ EpisodeDownloadButton(episode, size = 24.dp)
+ Spacer(Modifier.width(6.dp))
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier.size(40.dp).clip(CircleShape).background(Color.White).pressable(0.92f, onClick = onPlay),
+ ) {
+ com.music.spotui.ui.components.PlayPauseIcon(
+ playing = playing,
+ contentDescription = stringResource(R.string.episode_play),
+ tint = Color.Black,
+ modifier = Modifier.size(20.dp),
+ )
}
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/theme/Color.kt b/base/app/src/main/java/com/music/spotui/ui/theme/Color.kt
index 4e55a795..22b7db59 100644
--- a/base/app/src/main/java/com/music/spotui/ui/theme/Color.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/theme/Color.kt
@@ -2,13 +2,6 @@ package com.music.spotui.ui.theme
import androidx.compose.ui.graphics.Color
-val Purple80 = Color(0xFFD0BCFF)
-val PurpleGrey80 = Color(0xFFCCC2DC)
-val Pink80 = Color(0xFFEFB8C8)
-
-val Purple40 = Color(0xFF6650a4)
-val PurpleGrey40 = Color(0xFF625b71)
-val Pink40 = Color(0xFF7D5260)
val AppBackground: Color get() = if (app.myspoti.power.EnergySettings.oledBlack) Color.Black else Color(0xFF121212)
val GridBackground = Color(0xFF2A2A2A)
/** The accent (Spotify green, or the colour a supporter chose). */
diff --git a/base/app/src/main/java/com/music/spotui/ui/theme/Theme.kt b/base/app/src/main/java/com/music/spotui/ui/theme/Theme.kt
index a3541932..f2a4486b 100644
--- a/base/app/src/main/java/com/music/spotui/ui/theme/Theme.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/theme/Theme.kt
@@ -2,52 +2,63 @@ package com.music.spotui.ui.theme
import android.app.Activity
import android.graphics.Color.toArgb
-import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
-import androidx.compose.material3.dynamicDarkColorScheme
-import androidx.compose.material3.dynamicLightColorScheme
-import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
-import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.unit.sp
import androidx.core.view.WindowCompat
-private val DarkColorScheme = darkColorScheme(
- primary = Purple80,
- secondary = PurpleGrey80,
- tertiary = Pink80,
+/**
+ * Spotify's dark palette, so the Material components that read the scheme (switches,
+ * sliders, dialogs, spinners, text fields, menus) look like the official app: accent
+ * green on black, #121212 background, #1F1F1F/#282828 raised surfaces, #B3B3B3
+ * secondary text, and no tonal tint on elevated surfaces.
+ */
+private fun spotifyColorScheme(accent: Color) = darkColorScheme(
+ primary = accent,
+ onPrimary = Color.Black,
+ primaryContainer = accent,
+ onPrimaryContainer = Color.Black,
+ secondary = Color.White,
+ onSecondary = Color.Black,
+ secondaryContainer = Color(0xFF2A2A2A),
+ onSecondaryContainer = Color.White,
+ tertiary = accent,
+ onTertiary = Color.Black,
background = AppBackground,
-)
-
-private val LightColorScheme = lightColorScheme(
- primary = Purple40,
- secondary = PurpleGrey40,
- tertiary = Pink40 ,
- background = AppBackground,
- /* Other default colors to override
-
- surface = Color(0xFFFFFBFE),
- onPrimary = Color.White,
- onSecondary = Color.White,
- onTertiary = Color.White,
- onBackground = Color(0xFF1C1B1F),
- onSurface = Color(0xFF1C1B1F),
- */
+ onBackground = Color.White,
+ surface = AppBackground,
+ onSurface = Color.White,
+ surfaceVariant = Color(0xFF2A2A2A),
+ onSurfaceVariant = Color(0xFFB3B3B3),
+ surfaceTint = Color.Transparent,
+ surfaceDim = AppBackground,
+ surfaceBright = Color(0xFF2A2A2A),
+ surfaceContainerLowest = AppBackground,
+ surfaceContainerLow = Color(0xFF181818),
+ surfaceContainer = Color(0xFF1F1F1F),
+ surfaceContainerHigh = Color(0xFF282828),
+ surfaceContainerHighest = Color(0xFF3E3E3E),
+ inverseSurface = Color.White,
+ inverseOnSurface = Color.Black,
+ inversePrimary = accent,
+ outline = Color(0xFF727272),
+ outlineVariant = Color(0xFF3E3E3E),
+ error = Color(0xFFF3727F),
+ onError = Color.Black,
+ scrim = Color.Black,
)
@Composable
fun SpotuiTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
- // Dynamic color is available on Android 12+
- dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val energy by app.myspoti.power.EnergySettings.state.collectAsStateWithLifecycle()
@@ -57,11 +68,7 @@ fun SpotuiTheme(
}
// The app is always dark, like Spotify: a phone in light mode must not turn the
// surfaces white (an empty or failed page then showed white text on white).
- val colorScheme = when {
- dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> dynamicDarkColorScheme(LocalContext.current)
- else -> DarkColorScheme
- }
- val visualScheme = colorScheme.copy(background = AppBackground, surface = AppBackground)
+ val visualScheme = spotifyColorScheme(AppAccent)
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
@@ -69,6 +76,10 @@ fun SpotuiTheme(
window.attributes = window.attributes.apply { preferredRefreshRate = policy.displayRefreshCap }
window.statusBarColor = Color.Transparent.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = false // always-dark app: white status bar icons
+ // B19: the navigation bar was left to the system — a white band under the always-dark
+ // UI (reported in the modal sheets, where the bar was opaque) with dark icons on it.
+ window.navigationBarColor = Color.Transparent.toArgb()
+ WindowCompat.getInsetsController(window, view).isAppearanceLightNavigationBars = false
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/EpisodeViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/EpisodeViewModel.kt
new file mode 100644
index 00000000..41a7c24c
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/EpisodeViewModel.kt
@@ -0,0 +1,68 @@
+package com.music.spotui.ui.viewmodel
+
+import androidx.compose.runtime.mutableStateOf
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import com.music.spotui.data.api.Api
+import com.music.spotui.data.entity.SongsModel
+import com.music.spotui.di.Graph
+import com.music.spotui.di.SongPlayer
+import com.music.spotui.ui.repository.AppRepository
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.launch
+
+/** One episode page: the episode itself plus the two marks a listener can change on it. */
+class EpisodeViewModel constructor(
+ private val repository: AppRepository = Graph.repository,
+ private val api: Api = Graph.api,
+) : ViewModel() {
+
+ private val _episode = MutableStateFlow<SongsModel?>(null)
+ val episode: StateFlow<SongsModel?> = _episode
+
+ /** False once Spotify answered nothing: the page says so instead of staying empty. */
+ val failed = mutableStateOf(false)
+
+ val loading = mutableStateOf(true)
+
+ /** Finished, as the episode page's own menu shows it. */
+ val finished = mutableStateOf(false)
+
+ private var key: String? = null
+
+ fun load(episodeId: String) {
+ if (key == episodeId) return
+ key = episodeId
+ viewModelScope.launch(Dispatchers.IO) {
+ val loaded = runCatching { repository.provideEpisode(episodeId) }.getOrNull()
+ kotlinx.coroutines.withContext(Dispatchers.Main) {
+ loading.value = false
+ failed.value = loaded == null
+ if (loaded != null) {
+ _episode.value = loaded
+ finished.value = loaded.played
+ SongPlayer.requestSaved("spotify:episode:$episodeId")
+ }
+ }
+ }
+ // The page's own "markedasfinished" set wins over the playedState when it holds the id.
+ viewModelScope.launch(Dispatchers.IO) {
+ val uri = "spotify:episode:$episodeId"
+ if (runCatching { api.finishedEpisodes() }.getOrDefault(emptySet()).contains(uri)) {
+ kotlinx.coroutines.withContext(Dispatchers.Main) { finished.value = true }
+ }
+ }
+ }
+
+ /** "Marquer comme terminé" / "Marquer comme non commencé". */
+ fun setFinished(episode: SongsModel, played: Boolean) {
+ finished.value = played
+ _episode.value = episode.copy(played = played)
+ viewModelScope.launch(Dispatchers.IO) {
+ runCatching { api.setEpisodePlayed("spotify:episode:${episode.url.removePrefix("episode:")}", played) }
+ .onFailure { kotlinx.coroutines.withContext(Dispatchers.Main) { finished.value = episode.played } }
+ }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/ShowViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/ShowViewModel.kt
index 6ffddcae..f1100fb8 100644
--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/ShowViewModel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/ShowViewModel.kt
@@ -1,32 +1,47 @@
package com.music.spotui.ui.viewmodel
-import com.music.spotui.di.Graph
import androidx.compose.runtime.State
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.snapshots.SnapshotStateMap
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.music.spotui.data.api.Api
import com.music.spotui.data.api.Response
-import com.music.spotui.data.entity.PodcastModel
import com.music.spotui.data.entity.SongsModel
+import com.music.spotui.data.entity.ShowPage
import com.music.spotui.di.CurrentSongState
+import com.music.spotui.di.Graph
+import com.music.spotui.di.SongPlayer
import com.music.spotui.ui.repository.AppRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
+/**
+ * A show page (podcast) or a book page (audiobook): one flow for the header and the rows, plus
+ * the states a row can change on its own (followed, finished).
+ */
class ShowViewModel constructor(
private val repository: AppRepository = Graph.repository,
+ private val api: Api = Graph.api,
private val currentSongState: CurrentSongState = Graph.currentSongState,
) : ViewModel() {
val currentSongPlayingState: State<Boolean> get() = currentSongState.playingState
val currentSongId: State<Int> get() = currentSongState.songId
- private val _episodes: MutableStateFlow<Response<List<SongsModel>>> = MutableStateFlow(Response.Loading())
- val episodes: StateFlow<Response<List<SongsModel>>> = _episodes
+ private val _page = MutableStateFlow<Response<ShowPage>>(Response.Loading())
+ val page: StateFlow<Response<ShowPage>> = _page
+
+ /** Following the show (the pill's state), updated on tap before Spotify answers. */
+ val following = mutableStateOf(false)
- private val _show: MutableStateFlow<PodcastModel?> = MutableStateFlow(null)
- val show: StateFlow<PodcastModel?> = _show
+ /**
+ * Episode uri → finished. Spotify's per-episode state comes with the rows; this holds what
+ * the user just changed (and the page's own "markedasfinished" set).
+ */
+ val finished: SnapshotStateMap<String, Boolean> = androidx.compose.runtime.mutableStateMapOf()
val queue: State<List<SongsModel>> get() = currentSongState.queue
@@ -42,10 +57,41 @@ class ShowViewModel constructor(
if (showKey == showId) return
showKey = showId
viewModelScope.launch(Dispatchers.IO) {
- _show.value = repository.provideShow(showId)
+ repository.provideShowPage(showId).collect { response ->
+ _page.value = response
+ val loaded = (response as? Response.Success)?.data ?: return@collect
+ following.value = loaded.show.saved || SongPlayer.library["spotify:show:$showId"] == true
+ }
+ }
+ // The page's own "finished" marks are a separate set: read once, then the rows carry
+ // Spotify's playedState.
+ viewModelScope.launch(Dispatchers.IO) {
+ val marked = runCatching { api.finishedEpisodes() }.getOrDefault(emptySet())
+ if (marked.isEmpty()) return@launch
+ marked.forEach { uri ->
+ val id = uri.substringAfterLast(':')
+ finished["episode:$id"] = true
+ }
}
+ }
+
+ /** True when [episode] is finished: the last tap wins over what the row said. */
+ fun isFinished(episode: SongsModel): Boolean = finished[episode.url] ?: episode.played
+
+ /** "Marquer comme terminé" / "Marquer comme non commencé". */
+ fun setFinished(episode: SongsModel, played: Boolean) {
+ finished[episode.url] = played
viewModelScope.launch(Dispatchers.IO) {
- repository.provideShowEpisodes(showId).collect { _episodes.value = it }
+ runCatching { api.setEpisodePlayed("spotify:episode:${episode.url.removePrefix("episode:")}", played) }
+ .onFailure {
+ // Spotify refused: back to what the row said, the row is the truth.
+ kotlinx.coroutines.withContext(Dispatchers.Main) { finished.remove(episode.url) }
+ }
}
}
+
+ fun setFollow(showId: String, on: Boolean) {
+ following.value = on
+ SongPlayer.setSaved("spotify:show:$showId", on)
+ }
}
diff --git a/base/app/src/main/res/drawable/recent_cover.xml b/base/app/src/main/res/drawable/recent_cover.xml
new file mode 100644
index 00000000..41fdc3ca
--- /dev/null
+++ b/base/app/src/main/res/drawable/recent_cover.xml
@@ -0,0 +1,21 @@
+<!-- "Recently played" (the app's own pinned library entry): a clock, drawn like the other covers. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="64dp"
+ android:height="64dp"
+ android:viewportWidth="64"
+ android:viewportHeight="64">
+ <path
+ android:fillColor="#333333"
+ android:pathData="M0,0h64v64h-64z" />
+ <path
+ android:fillColor="@android:color/transparent"
+ android:pathData="M32,18a14,14 0 1,1 -0.01,0z"
+ android:strokeColor="#FFFFFF"
+ android:strokeWidth="3" />
+ <path
+ android:fillColor="@android:color/transparent"
+ android:pathData="M32,25v8l6,4"
+ android:strokeColor="#FFFFFF"
+ android:strokeLineCap="round"
+ android:strokeWidth="3" />
+</vector>
diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xml
index 09e42517..191fd6fa 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -3,7 +3,7 @@
<resources>
<string name="welcome_tagline">Ta musique, avec les paroles synchronisées et les clips officiels.</string>
<string name="welcome_login">Se connecter avec Spotify</string>
- <string name="welcome_privacy">Tu te connectes sur la page officielle de Spotify. Myspoti ne voit jamais ton mot de passe.</string>
+ <string name="welcome_privacy">Vous vous connectez sur la page officielle de Spotify. Myspoti ne voit jamais votre mot de passe.</string>
<string name="crash_heading">Myspoti s\'est arrêté</string>
<string name="crash_explanation">Un problème est survenu. Relance l\'app ; si ça recommence, copie le rapport et partage-le dans une issue GitHub.</string>
<string name="crash_restart_app">Relancer Myspoti</string>
@@ -36,7 +36,7 @@
<string name="lyrics_reload">Recharger les paroles</string>
<string name="lyrics_fullscreen">Ouvrir les paroles en plein écran</string>
<string name="browse_all">Parcourir tout</string>
- <string name="home_error">Impossible de charger l\'accueil.\nVérifie ta connexion et réessaie.</string>
+ <string name="home_error">Impossible de charger l\'accueil.\nVérifiez votre connexion et réessayez.</string>
<string name="home_retry">Réessayer</string>
<string name="home_empty">Rien à afficher pour le moment.</string>
<string name="spotify_account">Compte Spotify</string>
@@ -61,6 +61,9 @@
<string name="download_unavailable">Aucun enregistrement correspondant trouvé</string>
<string name="download_retry">Réessayer</string>
<string name="download_cancel">Annuler le téléchargement</string>
+ <string name="podcast_download_protected">Cet épisode est protégé (exclusivité Spotify) : non téléchargeable, il ne se lit que dans l’application Spotify.</string>
+ <string name="podcast_download_unavailable">Cet épisode n’est pas téléchargeable : le fichier audio de l’éditeur est introuvable.</string>
+ <string name="podcast_download_failed">Le téléchargement a échoué. Réessayez.</string>
<string name="not_signed_in">Vous êtes déconnecté de Spotify. Reconnectez-vous pour voir ceci.</string>
<string name="artist_not_found">Artiste introuvable</string>
<string name="playlist_not_found">Playlist introuvable</string>
@@ -73,6 +76,11 @@
<string name="language_partial_note">Autres langues : les libellés de Spotify sont traduits, les textes de Myspoti restent en anglais.</string>
<string name="restart_player_title">Redémarrer le lecteur</string>
<string name="restart_player_detail">Si la musique ne répond plus : recharge le lecteur Spotify</string>
+ <string name="ad_playing">Publicité</string>
+ <string name="track_unavailable_region">Indisponible dans votre région</string>
+ <string name="diagnostic_export_title">Exporter un rapport de diagnostic</string>
+ <string name="diagnostic_export_detail">Partage le journal récent de l\'app et les détails de l\'appareil</string>
+ <string name="diagnostic_export_failed">Impossible d\'écrire le rapport de diagnostic</string>
<string name="local_playlist_subtitle">Sur cet appareil</string>
<string name="local_playlist_new">Playlist sur cet appareil</string>
<string name="local_added_section">Ajoutés sur cet appareil</string>
@@ -134,6 +142,21 @@
<string name="recap_listens">%1$d écoutes</string>
<string name="recap_sources">Spotify %1$d min • Téléchargements %2$d min • Fichiers locaux %3$d min</string>
<string name="recap_empty">Écoutez un peu : vos titres et artistes préférés apparaîtront ici.</string>
+ <string name="recently_played_title">Écoutés récemment</string>
+ <string name="recently_played_empty">Ce que vous écoutez sur ce compte apparaît ici.</string>
+ <string name="recently_played_failed">Impossible de charger les écoutes récentes (%1$s)</string>
+ <string name="recents_title">Récents</string>
+ <string name="recents_detail">Ce que vous avez écouté, sur tous vos appareils</string>
+ <string name="recents_filter_music">Musique</string>
+ <string name="recents_filter_podcasts">Podcasts</string>
+ <string name="recents_today">Aujourd\'hui</string>
+ <string name="recents_yesterday">Hier</string>
+ <string name="recents_played_one">1 titre lu</string>
+ <string name="recents_played_many">%1$d titres lus</string>
+ <string name="recents_saved_one">1 titre ajouté</string>
+ <string name="recents_saved_many">%1$d titres ajoutés</string>
+ <string name="recents_expand">Afficher les titres</string>
+ <string name="recents_collapse">Masquer les titres</string>
<string name="recap_plays">%1$d écoutes</string>
<string name="recap_top_tracks">Titres les plus écoutés</string>
<string name="recap_top_artists">Artistes les plus écoutés</string>
@@ -172,13 +195,13 @@
<string name="track_sort_album">Album</string>
<string name="track_sort_duration">Durée</string>
<string name="setup_title">Configurer Myspoti</string>
- <string name="setup_subtitle">Autorise ce que tu veux ; tu pourras changer plus tard dans les réglages du téléphone.</string>
+ <string name="setup_subtitle">Autorisez ce que vous voulez ; vous pourrez changer plus tard dans les réglages du téléphone.</string>
<string name="setup_notifications_title">Notifications</string>
<string name="setup_notifications_detail">Contrôles sur l\'écran verrouillé et dans les notifications</string>
<string name="setup_local_title">Sons locaux</string>
<string name="setup_local_detail">Lire les fichiers de musique du téléphone</string>
<string name="setup_bluetooth_title">Bluetooth</string>
- <string name="setup_bluetooth_detail">Afficher le nom de ton casque ou de ton enceinte dans le lecteur</string>
+ <string name="setup_bluetooth_detail">Afficher le nom de votre casque ou de votre enceinte dans le lecteur</string>
<string name="setup_battery_title">Batterie sans restriction</string>
<string name="setup_battery_detail">La musique continue écran éteint</string>
<string name="setup_enable">Autoriser</string>
@@ -255,8 +278,25 @@
<string name="update_allow">Autoriser</string>
<string name="update_failed">La mise à jour a échoué : %1$s</string>
<string name="update_retry">Réessayer</string>
+ <!-- A18 : la vérification automatique peut être coupée, la vérification manuelle reste. -->
+ <string name="settings_auto_update_title">Vérifier les mises à jour au lancement</string>
+ <string name="settings_auto_update_detail">Désactivé : aucune vérification au démarrage. La vérification manuelle ci-dessous fonctionne toujours.</string>
+ <string name="settings_check_update_title">Vérifier les mises à jour maintenant</string>
+ <string name="settings_check_update_detail">Cherche une version plus récente et propose de l\'installer</string>
+ <string name="settings_update_checking">Vérification…</string>
+ <string name="settings_update_check_latest">Myspoti est à jour</string>
+ <!-- A25 : arrêter la file, garder les titres déjà téléchargés. -->
+ <string name="downloads_stop_all_title">Arrêter tous les téléchargements</string>
+ <string name="downloads_stop_all_detail">Annule ce qui reste ; les titres déjà téléchargés sont conservés</string>
<string name="downloads_verify_banner">Les téléchargements demandent la vérification SpotiFLAC une fois dans cette app. Touchez ici pour la faire.</string>
<string name="removed_from">Retiré de %1$s</string>
+ <!-- Options d'un titre dans une playlist (A11/A12). -->
+ <string name="context_menu_remove_from_playlist">Retirer de cette playlist</string>
+ <string name="context_menu_add_to_another_playlist">Ajouter à une autre playlist</string>
+ <string name="add_to_playlist_search_hint">Rechercher une playlist</string>
+ <string name="add_to_playlist_empty">Vous n\'avez aucune playlist où ajouter ce titre</string>
+ <string name="add_to_playlist_no_match">Aucune playlist ne correspond à « %1$s »</string>
+ <string name="undo">Annuler</string>
<string name="done">OK</string>
<string name="playlist_edit_details">Modifier les infos</string>
<string name="playlist_name_label">Nom</string>
@@ -301,15 +341,15 @@
<string name="more_like_this">Dans le même style</string>
<string name="library_sort_recents">Récents</string>
<string name="library_sort_recently_added">Ajoutés récemment</string>
- <string name="library_change_failed">Impossible de mettre à jour ta bibliothèque, réessaie</string>
+ <string name="library_change_failed">Impossible de mettre à jour votre bibliothèque, réessayez</string>
<string name="a11y_close_player">Fermer le lecteur</string>
<string name="a11y_devices">Appareils</string>
<string name="a11y_share">Partager</string>
- <string name="search_failed">La recherche a échoué. Vérifie ta connexion.</string>
+ <string name="search_failed">La recherche a échoué. Vérifiez votre connexion.</string>
<string name="retry_button">Réessayer</string>
- <string name="page_load_failed">Impossible de charger cette page.\nVérifie ta connexion et réessaie.</string>
+ <string name="page_load_failed">Impossible de charger cette page.\nVérifiez votre connexion et réessayez.</string>
<string name="jam_paste_link">Rejoindre avec un lien copié</string>
- <string name="play_refused">Spotify a refusé cette lecture sur ton compte. Dans certains pays, un compte gratuit ne joue qu’en aléatoire : essaie le bouton aléatoire.</string>
+ <string name="play_refused">Spotify a refusé cette lecture sur votre compte. Dans certains pays, un compte gratuit ne joue qu’en aléatoire : essayez le bouton aléatoire.</string>
<string name="artist_liked_songs">Titres likés</string>
<plurals name="artist_liked_songs_count">
<item quantity="one">%1$d titre de %2$s</item>
@@ -318,12 +358,59 @@
<string name="share_link">Partager le lien</string>
<string name="share_as_image">Partager en image</string>
<string name="settings_autoplay_title">Lecture automatique</string>
- <string name="settings_autoplay_detail">Quand ta musique se termine, continuer avec des titres similaires</string>
+ <string name="settings_autoplay_detail">Quand votre musique se termine, continuer avec des titres similaires</string>
+ <string name="settings_crossfade_title">Fondu enchaîné (sans chevauchement)</string>
+ <string name="settings_crossfade_detail">Un morceau s\'efface sur ses dernières secondes, le suivant remonte. Les deux ne jouent jamais en même temps : un seul lecteur, un seul flux audio.</string>
+ <string name="settings_crossfade_off">Désactivé</string>
+ <string name="settings_crossfade_seconds">%1$d s</string>
<string name="settings_rotation_title">Rotation de l\'écran</string>
<string name="settings_rotation_portrait">Portrait</string>
<string name="settings_rotation_auto">Automatique</string>
<string name="settings_rotation_landscape">Paysage</string>
<string name="support_github_action">Sponsor sur GitHub</string>
<string name="spotiflac_verify_again">La vérification SpotiFLAC a expiré : refais-la dans les Réglages pour télécharger en lossless</string>
- <string name="download_on_mobile_data">Téléchargement en données mobiles : il utilise ton forfait</string>
+ <string name="download_on_mobile_data">Téléchargement en données mobiles : il utilise votre forfait</string>
+
+ <!-- Page émission, page épisode et lecteur de podcast -->
+ <string name="show_follow">S\'abonner</string>
+ <string name="show_following">Abonné</string>
+ <string name="show_tab_episodes">Épisodes</string>
+ <string name="show_tab_chapters">Chapitres</string>
+ <string name="show_tab_about">À propos</string>
+ <string name="show_sort_newest">Tous les épisodes • Plus récents</string>
+ <string name="show_sort_oldest">Tous les épisodes • Plus anciens</string>
+ <string name="show_sort_chapters_newest">Tous les chapitres • Plus récents</string>
+ <string name="show_sort_chapters_oldest">Tous les chapitres • Plus anciens</string>
+ <string name="show_empty">Rien à écouter pour le moment</string>
+ <string name="show_rating">%1$s (%2$s)</string>
+ <string name="show_authors">De %1$s</string>
+ <string name="show_narrators">Lu par %1$s</string>
+ <string name="show_followed">Abonnement ajouté</string>
+ <string name="show_unfollowed">Abonnement retiré</string>
+ <string name="episode_duration_min">%1$d min</string>
+ <string name="episode_remaining">encore %1$s</string>
+ <string name="episode_mark_played">Marquer comme terminé</string>
+ <string name="episode_mark_unplayed">Marquer comme non commencé</string>
+ <string name="episode_marked_played">Marqué comme terminé</string>
+ <string name="episode_marked_unplayed">Marqué comme non commencé</string>
+ <string name="episode_play">Lire</string>
+ <string name="episode_open">Ouvrir l\'épisode</string>
+ <string name="episode_add_queue">Ajouter à la file d\'attente</string>
+ <string name="episode_show_more">afficher plus</string>
+ <string name="episode_show_less">afficher moins</string>
+ <string name="episode_download">Télécharger</string>
+ <string name="episode_downloading">Téléchargement…</string>
+ <string name="episode_downloaded">Téléchargé</string>
+ <string name="episode_download_remove">Supprimer le téléchargement</string>
+ <string name="episode_options">Options de l\'épisode</string>
+ <string name="episode_not_found">Épisode introuvable</string>
+ <string name="show_not_found">Émission introuvable</string>
+ <string name="podcast_playing_from">Lecture à partir du podcast</string>
+ <string name="player_speed_chip">%1$s×</string>
+ <string name="player_back_15">Reculer de 15 secondes</string>
+ <string name="player_forward_15">Avancer de 15 secondes</string>
+ <string name="player_show_remaining">Afficher le temps restant</string>
+ <string name="player_show_elapsed">Afficher le temps écoulé</string>
+ <string name="player_sleep_timer">Minuteur de veille</string>
+ <string name="player_speed_a11y">Vitesse de lecture, %1$s×</string>
</resources>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index 3d9bc374..0ae97d13 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -61,6 +61,9 @@
<string name="download_unavailable">No matching recording found</string>
<string name="download_retry">Try again</string>
<string name="download_cancel">Cancel download</string>
+ <string name="podcast_download_protected">This episode is a Spotify exclusive: it can only be played in the Spotify app, not downloaded.</string>
+ <string name="podcast_download_unavailable">This episode cannot be downloaded: the publisher audio file is missing.</string>
+ <string name="podcast_download_failed">Download failed. Try again.</string>
<string name="not_signed_in">You\'re signed out of Spotify. Sign in again to see this.</string>
<string name="artist_not_found">Artist not found</string>
<string name="playlist_not_found">Playlist not found</string>
@@ -73,6 +76,11 @@
<string name="language_partial_note">Other languages: Spotify\'s own labels are translated, Myspoti\'s texts stay in English.</string>
<string name="restart_player_title">Restart the player</string>
<string name="restart_player_detail">If the music stops responding: reloads Spotify\'s player</string>
+ <string name="ad_playing">Advertisement</string>
+ <string name="track_unavailable_region">Not available in your region</string>
+ <string name="diagnostic_export_title">Export a diagnostic report</string>
+ <string name="diagnostic_export_detail">Shares the app\'s recent log and device details</string>
+ <string name="diagnostic_export_failed">Could not write the diagnostic report</string>
<string name="local_playlist_subtitle">On this device</string>
<string name="local_playlist_new">Playlist on this device</string>
<string name="local_added_section">Added on this device</string>
@@ -134,6 +142,21 @@
<string name="recap_listens">%1$d listens</string>
<string name="recap_sources">Spotify %1$d min • Downloads %2$d min • Local files %3$d min</string>
<string name="recap_empty">Listen for a while: your top tracks and artists will show up here.</string>
+ <string name="recently_played_title">Recently played</string>
+ <string name="recently_played_empty">What you play on this account shows up here.</string>
+ <string name="recently_played_failed">Could not load the recently played list (%1$s)</string>
+ <string name="recents_title">Recents</string>
+ <string name="recents_detail">What you played, on every device</string>
+ <string name="recents_filter_music">Music</string>
+ <string name="recents_filter_podcasts">Podcasts</string>
+ <string name="recents_today">Today</string>
+ <string name="recents_yesterday">Yesterday</string>
+ <string name="recents_played_one">1 track played</string>
+ <string name="recents_played_many">%1$d tracks played</string>
+ <string name="recents_saved_one">1 track added</string>
+ <string name="recents_saved_many">%1$d tracks added</string>
+ <string name="recents_expand">Show the tracks</string>
+ <string name="recents_collapse">Hide the tracks</string>
<string name="recap_plays">%1$d plays</string>
<string name="recap_top_tracks">Top tracks</string>
<string name="recap_top_artists">Top artists</string>
@@ -255,8 +278,25 @@
<string name="update_allow">Allow</string>
<string name="update_failed">The update failed: %1$s</string>
<string name="update_retry">Try again</string>
+ <!-- A18: the automatic update check can be turned off; the manual check stays. -->
+ <string name="settings_auto_update_title">Check for updates at launch</string>
+ <string name="settings_auto_update_detail">Off: no check when the app starts. The manual check below still works.</string>
+ <string name="settings_check_update_title">Check for updates now</string>
+ <string name="settings_check_update_detail">Looks for a newer version and offers to install it</string>
+ <string name="settings_update_checking">Checking…</string>
+ <string name="settings_update_check_latest">Myspoti is up to date</string>
+ <!-- A25: stop the queue, keep the songs already downloaded. -->
+ <string name="downloads_stop_all_title">Stop all downloads</string>
+ <string name="downloads_stop_all_detail">Cancels what is left; songs already downloaded are kept</string>
<string name="downloads_verify_banner">Downloads need the SpotiFLAC verification once on this app. Tap here to do it.</string>
<string name="removed_from">Removed from %1$s</string>
+ <!-- Track options inside a playlist (A11/A12). -->
+ <string name="context_menu_remove_from_playlist">Remove from this playlist</string>
+ <string name="context_menu_add_to_another_playlist">Add to another playlist</string>
+ <string name="add_to_playlist_search_hint">Find a playlist</string>
+ <string name="add_to_playlist_empty">You have no playlist to add this track to</string>
+ <string name="add_to_playlist_no_match">No playlist matches \"%1$s\"</string>
+ <string name="undo">Undo</string>
<string name="done">Done</string>
<string name="playlist_edit_details">Edit details</string>
<string name="playlist_name_label">Name</string>
@@ -319,6 +359,10 @@
<string name="share_as_image">Share as image</string>
<string name="settings_autoplay_title">Autoplay</string>
<string name="settings_autoplay_detail">When your music ends, keep playing similar songs</string>
+ <string name="settings_crossfade_title">Crossfade (tracks fade, they do not overlap)</string>
+ <string name="settings_crossfade_detail">A track fades out over its last seconds, the next one fades in. They never play at once: one player, one audio stream.</string>
+ <string name="settings_crossfade_off">Off</string>
+ <string name="settings_crossfade_seconds">%1$ds</string>
<string name="settings_rotation_title">Screen rotation</string>
<string name="settings_rotation_portrait">Portrait</string>
<string name="settings_rotation_auto">Automatic</string>
@@ -326,4 +370,47 @@
<string name="support_github_action">Sponsor on GitHub</string>
<string name="spotiflac_verify_again">SpotiFLAC verification expired: verify again in Settings to download in lossless</string>
<string name="download_on_mobile_data">Downloading on mobile data: it uses your data plan</string>
+
+ <!-- Podcast show page, episode page and podcast player -->
+ <string name="show_follow">Follow</string>
+ <string name="show_following">Following</string>
+ <string name="show_tab_episodes">Episodes</string>
+ <string name="show_tab_chapters">Chapters</string>
+ <string name="show_tab_about">About</string>
+ <string name="show_sort_newest">All episodes • Newest</string>
+ <string name="show_sort_oldest">All episodes • Oldest</string>
+ <string name="show_sort_chapters_newest">All chapters • Newest</string>
+ <string name="show_sort_chapters_oldest">All chapters • Oldest</string>
+ <string name="show_empty">Nothing to play here yet</string>
+ <string name="show_rating">%1$s (%2$s)</string>
+ <string name="show_authors">By %1$s</string>
+ <string name="show_narrators">Read by %1$s</string>
+ <string name="show_followed">Followed</string>
+ <string name="show_unfollowed">Unfollowed</string>
+ <string name="episode_duration_min">%1$d min</string>
+ <string name="episode_remaining">%1$s left</string>
+ <string name="episode_mark_played">Mark as played</string>
+ <string name="episode_mark_unplayed">Mark as not started</string>
+ <string name="episode_marked_played">Marked as played</string>
+ <string name="episode_marked_unplayed">Marked as not started</string>
+ <string name="episode_play">Play</string>
+ <string name="episode_open">Open episode</string>
+ <string name="episode_add_queue">Add to queue</string>
+ <string name="episode_show_more">show more</string>
+ <string name="episode_show_less">show less</string>
+ <string name="episode_download">Download</string>
+ <string name="episode_downloading">Downloading…</string>
+ <string name="episode_downloaded">Downloaded</string>
+ <string name="episode_download_remove">Remove download</string>
+ <string name="episode_options">Episode options</string>
+ <string name="episode_not_found">Episode not found</string>
+ <string name="show_not_found">Show not found</string>
+ <string name="podcast_playing_from">Playing from the podcast</string>
+ <string name="player_speed_chip">%1$s×</string>
+ <string name="player_back_15">Back 15 seconds</string>
+ <string name="player_forward_15">Forward 15 seconds</string>
+ <string name="player_show_remaining">Show the time remaining</string>
+ <string name="player_show_elapsed">Show the time elapsed</string>
+ <string name="player_sleep_timer">Sleep timer</string>
+ <string name="player_speed_a11y">Playback speed, %1$s×</string>
</resources>
diff --git a/base/app/src/main/res/xml/file_paths.xml b/base/app/src/main/res/xml/file_paths.xml
index 24427d04..f5a584c2 100644
--- a/base/app/src/main/res/xml/file_paths.xml
+++ b/base/app/src/main/res/xml/file_paths.xml
@@ -2,4 +2,6 @@
<paths>
<!-- Share-as-image cards (ShareCard.kt). -->
<cache-path name="shared" path="shared/" />
+ <!-- Diagnostic reports (Logbook.export writes to getExternalFilesDir). -->
+ <external-files-path name="diagnostics" path="." />
</paths>
diff --git a/base/app/src/test/java/com/music/spotui/data/offline/PodcastDownloadTest.kt b/base/app/src/test/java/com/music/spotui/data/offline/PodcastDownloadTest.kt
new file mode 100644
index 00000000..7570d885
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/data/offline/PodcastDownloadTest.kt
@@ -0,0 +1,83 @@
+package com.music.spotui.data.offline
+
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The pure checks that decide whether a publisher's file is kept (no network, no Android). */
+class PodcastDownloadTest {
+
+ private fun bytes(vararg b: Int) = ByteArray(b.size) { b[it].toByte() }
+
+ private fun ascii(s: String) = s.toByteArray(Charsets.ISO_8859_1)
+
+ @Test fun mp3WithId3TagIsAccepted() {
+ assertTrue(PodcastDownloader.audioMagicOk(ascii("ID3") + bytes(4, 0, 0)))
+ }
+
+ @Test fun bareMpegFrameSyncIsAccepted() {
+ assertTrue(PodcastDownloader.audioMagicOk(bytes(0xFF, 0xFB, 0x90, 0x64)))
+ assertTrue(PodcastDownloader.audioMagicOk(bytes(0xFF, 0xF3, 0x00, 0x00)))
+ assertTrue(PodcastDownloader.audioMagicOk(bytes(0xFF, 0xF2, 0x00, 0x00)))
+ }
+
+ @Test fun mp4ContainerIsAccepted() {
+ assertTrue(PodcastDownloader.audioMagicOk(bytes(0, 0, 0, 0x20) + ascii("ftypM4A ")))
+ }
+
+ @Test fun htmlErrorPageIsRefused() {
+ assertFalse(PodcastDownloader.audioMagicOk(ascii("<!DOCTYPE ht")))
+ assertFalse(PodcastDownloader.audioMagicOk(ascii("<htm")))
+ }
+
+ @Test fun contentTypes() {
+ assertTrue(PodcastDownloader.contentTypeOk("audio/mpeg"))
+ assertTrue(PodcastDownloader.contentTypeOk("audio/mpeg; charset=utf-8"))
+ assertTrue(PodcastDownloader.contentTypeOk("audio/mp4"))
+ assertTrue(PodcastDownloader.contentTypeOk("application/octet-stream"))
+ assertTrue(PodcastDownloader.contentTypeOk("audio/x-m4a"))
+ // Unknown: the magic bytes decide (some podcast hosts send no type at all).
+ assertTrue(PodcastDownloader.contentTypeOk(""))
+ // A page or a JSON error served with 200 is a broken link, not an episode.
+ assertFalse(PodcastDownloader.contentTypeOk("text/html; charset=utf-8"))
+ assertFalse(PodcastDownloader.contentTypeOk("application/json"))
+ }
+
+ @Test fun extensionFollowsTheContainerNotTheUrl() {
+ val mp3 = ascii("ID3")
+ val m4a = bytes(0, 0, 0, 0x20) + ascii("ftypM4A ")
+ // A ".mp3" URL that actually serves an MP4 is stored as .m4a.
+ assertEquals("m4a", PodcastDownloader.audioExtension("https://x/y/episode.mp3?token=1", m4a))
+ assertEquals("mp3", PodcastDownloader.audioExtension("https://dts.podtrac.com/redirect.mp3/a/b?x=1", mp3))
+ assertEquals("m4a", PodcastDownloader.audioExtension("https://x/y.m4a", mp3))
+ // No usable extension: MP3 is the publisher default.
+ assertEquals("mp3", PodcastDownloader.audioExtension("https://radiofrance.fr/stream", mp3))
+ }
+
+ @Test fun keyGuardSeparatesEpisodesFromTracks() {
+ assertTrue(isEpisodeKey("episode:2dKPfHhKH0NgXGPKdCa0lA"))
+ assertFalse(isEpisodeKey("3n3Ppam7vgaVa1iaRUc9Lp"))
+ assertEquals("episode_2dKPfHhKH0NgXGPKdCa0lA", PodcastDownloader.safeName("episode:2dKPfHhKH0NgXGPKdCa0lA"))
+ assertEquals("episode_abc", PodcastDownloader.safeName("episode:abc"))
+ }
+
+ @Test fun queuedEpisodePersistsAndComesBack() {
+ val r = PodcastDownloader.Request("episode:abc", "Title", "Show", "Show", "https://c/1.jpg", 1_800_000L)
+ val back = PodcastDownloader.Request.fromJson(JSONObject(r.toJson().toString()))
+ assertEquals(r, back)
+ }
+
+ @Test fun podcastIndexEntriesAreTaggedAndOldOnesAreMusic() {
+ val json = JSONObject().put("id", "episode:abc").put("file", "episode_abc.mp3")
+ val fresh = OfflineTrack.fromJson(json.put("kind", OfflineTrack.KIND_PODCAST))
+ assertTrue(fresh.isEpisode)
+ assertEquals(OfflineTrack.KIND_PODCAST, fresh.kind)
+ // An index written before podcasts has no "kind": those entries must stay music.
+ val old = OfflineTrack.fromJson(JSONObject().put("id", "abc").put("file", "abc.flac"))
+ assertFalse(old.isEpisode)
+ assertEquals(OfflineTrack.KIND_MUSIC, old.kind)
+ assertEquals(OfflineTrack.KIND_PODCAST, fresh.toJson().getString("kind"))
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/ui/components/QueueEdgeScrollTest.kt b/base/app/src/test/java/com/music/spotui/ui/components/QueueEdgeScrollTest.kt
new file mode 100644
index 00000000..a0f8de8d
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/ui/components/QueueEdgeScrollTest.kt
@@ -0,0 +1,83 @@
+package com.music.spotui.ui.components
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The queue drag auto-scroll: direction and ramp of the per-frame scroll step. */
+class QueueEdgeScrollTest {
+ private val top = 200f
+ private val bottom = 1400f // 1200 px viewport, as on a phone in dp-ish units
+ private val zone = 72f
+ private val maxStep = 14f
+
+ private fun step(pointerY: Float) = queueEdgeScrollStep(pointerY, top, bottom, zone, maxStep)
+
+ @Test fun middleOfTheListDoesNotScroll() {
+ assertEquals(0f, step((top + bottom) / 2), 0f)
+ assertEquals(0f, step(top + zone), 0f) // inner border of the top zone
+ assertEquals(0f, step(bottom - zone), 0f) // inner border of the bottom zone
+ }
+
+ @Test fun nearTheTopScrollsUpAndNearTheBottomScrollsDown() {
+ assertTrue(step(top + 10f) < 0f)
+ assertTrue(step(bottom - 10f) > 0f)
+ }
+
+ @Test fun speedGrowsTowardsTheEdge() {
+ val shallow = step(top + zone / 2)
+ val deep = step(top + 1f)
+ assertTrue("deeper in the top zone must scroll faster", deep < shallow)
+ assertEquals(-maxStep, step(top), 0f)
+ assertEquals(maxStep, step(bottom), 0f)
+ }
+
+ @Test fun speedIsCappedOutsideTheViewport() {
+ // A row dragged past the ends (already scrolled to the boundary) must not accelerate.
+ assertEquals(-maxStep, step(top - 500f), 0f)
+ assertEquals(maxStep, step(bottom + 500f), 0f)
+ }
+
+ @Test fun zonesAreSymmetric() {
+ for (d in listOf(1f, 20f, 50f, 71f)) {
+ assertEquals(-step(top + d), step(bottom - d), 0.0001f)
+ }
+ }
+
+ @Test fun aDegenerateViewportNeverScrolls() {
+ assertEquals(0f, queueEdgeScrollStep(top, top, top, zone, maxStep), 0f)
+ assertEquals(0f, queueEdgeScrollStep(top, bottom, top, zone, maxStep), 0f)
+ assertEquals(0f, queueEdgeScrollStep(top, top, bottom, 0f, maxStep), 0f)
+ }
+
+ @Test fun queueBlockOffsetFollowsTheListScroll() {
+ val row = 64f
+ // At rest: the queue block starts one row below the current track.
+ assertEquals(row, queueTopInViewport(2, 0, 0, row), 0f)
+ // Current track half scrolled off.
+ assertEquals(32f, queueTopInViewport(2, 0, 32, row), 0f)
+ // Current track gone: the queue block starts at the viewport top.
+ assertEquals(0f, queueTopInViewport(2, 1, 0, row), 0f)
+ // Queue block scrolled up by 500 px.
+ assertEquals(-500f, queueTopInViewport(2, 1, 500, row), 0f)
+ // No current track: the queue block is the list's only item.
+ assertEquals(-120f, queueTopInViewport(1, 0, 120, 0f), 0f)
+ assertEquals(0f, queueTopInViewport(0, 0, 0, 0f), 0f)
+ }
+
+ @Test fun theDraggedRowKeepsItsPlaceOnScreenWhileTheListScrolls() {
+ // One auto-scroll step: the list content moves by `scrolled` and the drag offset
+ // is compensated by the same amount (QueueList.startAutoScroll), so the row stays
+ // under the finger and the drop target is the row the user actually sees.
+ val row = 64f
+ val itemTopInQueue = 3 * row
+ var dragOffset = 0f
+ var firstOffset = 300
+ val before = queueTopInViewport(2, 1, firstOffset, row) + itemTopInQueue + dragOffset + row / 2
+ val scrolled = 14
+ firstOffset += scrolled
+ dragOffset += scrolled
+ val after = queueTopInViewport(2, 1, firstOffset, row) + itemTopInQueue + dragOffset + row / 2
+ assertEquals(before, after, 0.001f)
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/ui/components/SpotifyImagesTest.kt b/base/app/src/test/java/com/music/spotui/ui/components/SpotifyImagesTest.kt
new file mode 100644
index 00000000..c266a937
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/ui/components/SpotifyImagesTest.kt
@@ -0,0 +1,28 @@
+package com.music.spotui.ui.components
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+/**
+ * B25: the profile endpoints hand out `spotify:image:<id>` identifiers rather than a picture's
+ * address; the image loader was given them as they were and kept its grey placeholder, so a user's
+ * profile picture and their public playlists never showed. These cases pin what the fix promises:
+ * an identifier becomes the URL it stands for, and anything already usable is left alone.
+ */
+class SpotifyImagesTest {
+ @Test fun identifierBecomesTheUrlItStandsFor() =
+ assertEquals("https://i.scdn.co/image/ab67616d0000b273", spotifyImageUrl("spotify:image:ab67616d0000b273"))
+
+ @Test fun aRealUrlPassesThrough() =
+ assertEquals("https://i.scdn.co/image/abc123", spotifyImageUrl("https://i.scdn.co/image/abc123"))
+
+ @Test fun missingStaysMissing() {
+ assertNull(spotifyImageUrl(null))
+ assertNull(spotifyImageUrl(""))
+ assertNull(spotifyImageUrl(" "))
+ }
+
+ @Test fun anythingElseIsUntouched() =
+ assertEquals("spotify:track:4cOdK2wGLETKBW3PvgPWqT", spotifyImageUrl("spotify:track:4cOdK2wGLETKBW3PvgPWqT"))
+}
diff --git a/base/app/src/test/java/com/music/spotui/ui/screens/RecentsGroupingTest.kt b/base/app/src/test/java/com/music/spotui/ui/screens/RecentsGroupingTest.kt
new file mode 100644
index 00000000..c993e8e8
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/ui/screens/RecentsGroupingTest.kt
@@ -0,0 +1,165 @@
+package com.music.spotui.ui.screens
+
+import app.myspoti.api.MediaKind
+import app.myspoti.api.RecentEntry
+import app.myspoti.api.RecentItem
+import app.myspoti.api.groupRecents
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * The grouping of the "Récents" page, checked against the shapes the real `recents` response
+ * sends: a context row announcing `children_group_id`, its plays tagged `group_id_N`, and the
+ * `group_metadata` count on the context.
+ */
+class RecentsGroupingTest {
+ private val today = 1_000_000L
+ private val yesterday = 0L
+
+ private fun item(
+ uri: String,
+ kind: MediaKind = MediaKind.TRACK,
+ title: String = uri,
+ day: Long? = today,
+ ) = RecentItem(uri = uri, kind = kind, title = title, subtitle = "artist", images = emptyList(), playedAtMs = day)
+
+ private fun context(
+ uri: String,
+ kind: MediaKind,
+ group: String,
+ count: Int? = null,
+ saved: Boolean = false,
+ day: Long? = today,
+ ) = RecentEntry(
+ item = item(uri, kind, title = uri, day = day),
+ childrenGroup = group,
+ groupCount = count,
+ saved = saved,
+ )
+
+ private fun play(uri: String, group: String, day: Long? = today) =
+ RecentEntry(item = item(uri, day = day), group = group)
+
+ @Test
+ fun aContextAndItsPlaysMakeOneRow() {
+ val sections = groupRecents(
+ listOf(
+ context("spotify:album:ep", MediaKind.ALBUM, "1", count = 3),
+ play("spotify:track:a", "1"),
+ play("spotify:track:b", "1"),
+ play("spotify:track:c", "1"),
+ ),
+ )
+ assertEquals(1, sections.size)
+ val group = sections.single().groups.single()
+ assertEquals("spotify:album:ep", group.context.uri)
+ assertEquals(3, group.count)
+ assertEquals(listOf("spotify:track:a", "spotify:track:b", "spotify:track:c"), group.plays.map { it.uri })
+ }
+
+ @Test
+ fun onePlaylistPlayedOnTwoDaysIsOneRowWithTheSum() {
+ // The real list had "Classical Bangers" as a 1-play group of today and an 8-play group of
+ // yesterday; Spotify's page showed a single "9 titres lus" row under today.
+ val entries = buildList {
+ add(context("spotify:playlist:bangers", MediaKind.PLAYLIST, "2", count = 1))
+ add(play("spotify:track:s", "2"))
+ add(context("spotify:playlist:bangers", MediaKind.PLAYLIST, "3", count = 4, day = yesterday))
+ repeat(4) { add(play("spotify:track:y$it", "3", day = yesterday)) }
+ }
+ val sections = groupRecents(entries)
+ assertEquals(1, sections.size)
+ val group = sections.single().groups.single()
+ assertEquals(5, group.count)
+ assertEquals(5, group.plays.size)
+ assertEquals(today, group.dayMs)
+ }
+
+ @Test
+ fun theSameTrackTwiceIsListedOnceWhenGroupsMerge() {
+ val entries = listOf(
+ context("spotify:playlist:bangers", MediaKind.PLAYLIST, "2", count = 1),
+ play("spotify:track:same", "2"),
+ context("spotify:playlist:bangers", MediaKind.PLAYLIST, "3", count = 1, day = yesterday),
+ play("spotify:track:same", "3", day = yesterday),
+ )
+ val group = groupRecents(entries).single().groups.single()
+ assertEquals(2, group.count)
+ assertEquals(listOf("spotify:track:same"), group.plays.map { it.uri })
+ }
+
+ @Test
+ fun aSavedContextIsTheLikedSongsRow() {
+ val entries = buildList {
+ add(
+ RecentEntry(
+ item = item("spotify:collection:tracks", MediaKind.PLAYLIST, "Titres likés", day = yesterday),
+ childrenGroup = "4",
+ groupCount = 2,
+ saved = true,
+ ),
+ )
+ add(RecentEntry(item = item("spotify:track:x", day = yesterday), group = "4"))
+ add(RecentEntry(item = item("spotify:track:y", day = yesterday), group = "4"))
+ }
+ val group = groupRecents(entries).single().groups.single()
+ assertTrue(group.saved)
+ assertEquals(2, group.count)
+ assertEquals("spotify:collection:tracks", group.context.uri)
+ }
+
+ @Test
+ fun aContextCutByThePageKeepsTheServersCount() {
+ // The last group of a page can arrive with fewer plays than it holds: group_metadata is
+ // the count the row must print.
+ val sections = groupRecents(listOf(context("spotify:playlist:blend", MediaKind.PLAYLIST, "6", count = 43)))
+ assertEquals(43, sections.single().groups.single().count)
+ assertTrue(sections.single().groups.single().plays.isEmpty())
+ }
+
+ @Test
+ fun aRowWithoutGroupKeysStaysItsOwnRow() {
+ val sections = groupRecents(
+ listOf(
+ context("spotify:album:ep", MediaKind.ALBUM, "1", count = 1),
+ play("spotify:track:a", "1"),
+ RecentEntry(item = item("spotify:track:lonely")),
+ ),
+ )
+ val groups = sections.single().groups
+ assertEquals(2, groups.size)
+ assertEquals("spotify:track:lonely", groups[1].context.uri)
+ assertEquals(1, groups[1].count)
+ }
+
+ @Test
+ fun daysAreSectionsNewestFirst() {
+ val sections = groupRecents(
+ listOf(
+ context("spotify:album:ep", MediaKind.ALBUM, "1", count = 1),
+ play("spotify:track:a", "1"),
+ context("spotify:artist:someone", MediaKind.ARTIST, "5", count = 1, day = yesterday),
+ play("spotify:track:b", "5", day = yesterday),
+ ),
+ )
+ assertEquals(listOf(today, yesterday), sections.map { it.dayMs })
+ assertEquals(1, sections[0].groups.size)
+ assertEquals(1, sections[1].groups.size)
+ }
+
+ @Test
+ fun thePillSplitFollowsTheEntryFlag() {
+ val entries = listOf(
+ context("spotify:album:ep", MediaKind.ALBUM, "1", count = 1),
+ RecentEntry(
+ item = item("spotify:show:pod", MediaKind.SHOW, "A show"),
+ childrenGroup = "7",
+ groupCount = 1,
+ music = false,
+ ),
+ )
+ val groups = groupRecents(entries).single().groups
+ assertEquals(listOf(true, false), groups.map { it.music })
+ }
+}
diff --git a/base/host-android/build.gradle.kts b/base/host-android/build.gradle.kts
index 20e8bd36..0a6686c8 100644
--- a/base/host-android/build.gradle.kts
+++ b/base/host-android/build.gradle.kts
@@ -25,4 +25,8 @@ dependencies {
implementation(libs.serialization.json)
implementation(libs.okhttp)
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
+
+ testImplementation("junit:junit:4.13.2")
+ // The real org.json in unit tests (android.jar only has stubs).
+ testImplementation("org.json:json:20240303")
}
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
index f9049194..c1bd4b3c 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt
@@ -5,7 +5,10 @@ import android.os.Looper
import android.webkit.WebView
import okhttp3.Call
import okhttp3.Callback
+import okhttp3.Cookie
+import okhttp3.CookieJar
import okhttp3.Headers
+import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
@@ -28,26 +31,93 @@ import java.util.concurrent.TimeUnit
* `MyspotiNet.postMessage` ([exposeToPlayer]), which repeats them with OkHttp using the page's own headers (its token,
* client token, connection id), then hands the response back to the page.
*/
-internal class ControlRelay(private val view: WebView) {
+internal class ControlRelay(private val view: WebView, private val fingerprint: Fingerprint) {
private val main = Handler(Looper.getMainLooper())
+
+ /**
+ * The WebView's own cookies. The page's `fetch` sends them, this app's OkHttp does not: a
+ * relayed request without them is not the shape of the real Web Player's request, which
+ * Spotify can tell apart (a `402 COMMAND_FAILED` on a free account is one such refusal).
+ */
+ private val cookies = object : CookieJar {
+ override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) = Unit
+ override fun loadForRequest(url: HttpUrl): List<Cookie> = runCatching {
+ val raw = android.webkit.CookieManager.getInstance().getCookie(url.toString()) ?: return emptyList()
+ raw.split(';').mapNotNull { part ->
+ val at = part.indexOf('=')
+ if (at <= 0) null
+ else Cookie.Builder()
+ .name(part.take(at).trim())
+ .value(part.substring(at + 1).trim())
+ .domain(url.host)
+ .path("/")
+ .build()
+ }
+ }.getOrDefault(emptyList())
+ }
+
private val http = OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
+ .cookieJar(cookies)
.build()
fun install() {
view.exposeToPlayer("MyspotiNet", ::onMessage)
val documentStart = androidx.webkit.WebViewFeature.isFeatureSupported(androidx.webkit.WebViewFeature.DOCUMENT_START_SCRIPT)
if (documentStart) androidx.webkit.WebViewCompat.addDocumentStartJavaScript(view, SCRIPT, setOf("https://open.spotify.com"))
- android.util.Log.d(WebPlayerHost.LOG, "control relay installed (document start: $documentStart)")
+ Logbook.log("control relay installed (document start: $documentStart)")
}
/** Fallback for WebViews without document-start scripts; harmless when already installed. */
fun injectNow() = view.evaluateJavascript(SCRIPT, null)
+ /**
+ * The identity the page presents, as its own requests carry it (user agent, client hints,
+ * accepted languages). The relay echoes these instead of hand-written constants, so a relayed
+ * request cannot contradict the page it comes from. Sent from the page at document start; the
+ * [WebPlayerHost] constants are only the fallback for the moment before it arrives.
+ */
+ @Volatile private var identity: JSONObject? = null
+
+ /**
+ * Until the page has said which identity it presents, the relay presents the one the WebView
+ * was given ([Fingerprint]) and the phone's languages, so even the first requests agree with it.
+ */
+ private val fallbackLanguage: String by lazy {
+ Fingerprint.acceptLanguage(android.os.LocaleList.getDefault().toLanguageTags().split(','))
+ }
+
+ /** The page's identity, for the audio proxy: the user agent and language it presents itself. */
+ internal fun identityPair(): Pair<String, String>? {
+ val page = identity ?: return null
+ val userAgent = page.optString("userAgent").takeIf { it.isNotEmpty() } ?: return null
+ return userAgent to page.optString("acceptLanguage")
+ }
+
+ /**
+ * The name this device shows in Spotify's device lists: the one its owner gave the phone
+ * (Paramètres → À propos → Nom de l'appareil), the same string Bluetooth and Quick Share show.
+ * A phone appearing as "Web Player (Chrome)" on every other device is a phone that stands out;
+ * under its own name it looks like what it is. Falls back to the model, then to a neutral name.
+ */
+ private val deviceName: String by lazy {
+ val resolver = view.context.contentResolver
+ fun setting(key: String): String? = runCatching {
+ android.provider.Settings.Global.getString(resolver, key)
+ ?: android.provider.Settings.Secure.getString(resolver, key)
+ }.getOrNull()?.takeIf { it.isNotBlank() }
+ setting("device_name") ?: setting("bluetooth_name") ?: android.os.Build.MODEL.ifBlank { "Spotify" }
+ }
+
/** `{id, url, method, headers, body}` from the page's wrapped `fetch`. */
private fun onMessage(json: String) {
val m = runCatching { JSONObject(json) }.getOrNull() ?: return
+ if (m.optString("type") == "identity") {
+ identity = m.optJSONObject("value")
+ Logbook.log("page identity: ${identity.toString().take(320)}")
+ return
+ }
val id = m.optInt("id", -1).takeIf { it >= 0 } ?: return
val body = if (m.isNull("body")) null else m.optString("body")
send(id, m.optString("url"), m.optString("method", "GET"), m.optJSONObject("headers") ?: JSONObject(), body)
@@ -64,19 +134,41 @@ internal class ControlRelay(private val view: WebView) {
if (key.lowercase() !in setOf("host", "content-length", "connection", "accept-encoding", "x-requested-with"))
runCatching { headers.add(key, given.getString(key)) }
}
- headers["User-Agent"] = WebPlayerHost.DESKTOP_UA
+ val page = identity
+ fun fromPage(name: String, fallback: String) = page?.optString(name)?.takeIf { it.isNotEmpty() } ?: fallback
+ headers["User-Agent"] = fromPage("userAgent", fingerprint.userAgent)
headers["Origin"] = "https://open.spotify.com"
headers["Referer"] = "https://open.spotify.com/"
+ // The transport headers Chromium adds by itself, which the page's `fetch` cannot set
+ // (forbidden header names in JS) and OkHttp does not add either: without them the
+ // relayed request carries a shape the real Web Player's request never has.
+ headers["Sec-Fetch-Site"] = "same-site"
+ headers["Sec-Fetch-Mode"] = "cors"
+ headers["Sec-Fetch-Dest"] = "empty"
+ // Values taken from the page, not written by hand: whichever language and client hints it
+ // presents, the relayed request presents the same.
+ headers["Accept-Language"] = fromPage("acceptLanguage", fallbackLanguage)
+ headers["sec-ch-ua"] = fromPage("brands", fingerprint.secChUa)
+ headers["sec-ch-ua-mobile"] = fromPage("mobile", "?0")
+ headers["sec-ch-ua-platform"] = "\"${fromPage("platform", "Linux")}\""
val built = headers.build()
- // The player's registration leaves out the ad formats (see AdBlock).
- val sent = if (body != null && app.myspoti.spotify.bridge.AdBlock.isDeviceRegistration(method, url)) app.myspoti.spotify.bridge.AdBlock.withoutAdFormats(body) else body
+ // The registration goes out as the real Web Player sends it, except for its name: the phone's
+ // own (see [deviceName]) replaces "Web Player (Chrome)".
+ val registration = body != null && app.myspoti.spotify.bridge.AdBlock.isDeviceRegistration(method, url)
+ if (debuggable && body != null && url.contains("/connect-state/"))
+ Logbook.log("connect-state body: ${body.take(500)}")
+ val sent = if (registration) {
+ val rewritten = app.myspoti.spotify.bridge.AdBlock.withDeviceName(body!!, deviceName)
+ if (debuggable && rewritten != body) Logbook.log("device registered as \"$deviceName\"")
+ rewritten
+ } else body
// Bytes, not a String body: OkHttp would append "; charset=utf-8" to the content type.
val payload = if (method == "GET" || method == "HEAD") null else (sent ?: "").toByteArray().toRequestBody(null)
val request = Request.Builder().url(url).headers(built).method(method, payload).build()
val asked = android.os.SystemClock.uptimeMillis()
http.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
- android.util.Log.d(WebPlayerHost.LOG, "relay $method ${shortPath(url)} failed: ${e.message}")
+ Logbook.log("relay $method ${shortPath(url)} failed: ${e.message}")
reply(id, 0, "{}", "")
}
@@ -86,8 +178,9 @@ internal class ControlRelay(private val view: WebView) {
it.headers.names().forEach { name -> out.put(name, it.header(name)) }
val text = it.body.string()
val net = android.os.SystemClock.uptimeMillis() - asked
- android.util.Log.d(WebPlayerHost.LOG, "relay $method ${shortPath(url)} -> ${it.code} in $net ms")
- if (it.code >= 400) android.util.Log.d(WebPlayerHost.LOG, "relay error body: ${text.take(400)}")
+ Logbook.log("relay $method ${shortPath(url)} -> ${it.code} in $net ms")
+ if (it.code >= 400) Logbook.log("relay error body: ${text.take(400)}")
+ if (debuggable && registration) Logbook.log("registration answered: ${text.take(500)}")
if (debuggable && AD_MARK.containsMatchIn(text)) keepAdSample(method, url, body, text)
reply(id, it.code, out.toString(), text)
}
@@ -102,7 +195,7 @@ internal class ControlRelay(private val view: WebView) {
private fun replyNow(id: Int, status: Int, headersJson: String, body: String, posted: Long) {
val waited = android.os.SystemClock.uptimeMillis() - posted
- if (waited > 30) android.util.Log.d(WebPlayerHost.LOG, "relay reply #$id waited $waited ms for the main thread")
+ if (waited > 30) Logbook.log("relay reply #$id waited $waited ms for the main thread")
view.evaluateJavascript(
"window.__mspNetDone && window.__mspNetDone($id, $status, ${JSONObject.quote(headersJson)}, ${JSONObject.quote(body)})",
null,
@@ -116,15 +209,27 @@ internal class ControlRelay(private val view: WebView) {
val dir = java.io.File(view.context.cacheDir, "ad-samples").apply { mkdirs() }
java.io.File(dir, "${System.currentTimeMillis()}.json").writeText(
JSONObject().put("method", method).put("url", url.substringBefore('?')).put("sent", sent ?: "").put("received", received).toString())
- android.util.Log.d(WebPlayerHost.LOG, "relay: ad in $method ${shortPath(url)} (sample kept)")
+ Logbook.log("relay: ad in $method ${shortPath(url)} (sample kept)")
}
private fun shortPath(url: String) = url.substringBefore('?').substringAfter(".com").replace(Regex("[0-9a-f]{20,}"), "…")
companion object {
+ /**
+ * The page's own API calls. Every request the WebView makes carries
+ * "X-Requested-With: <our package>" — no browser does that, and it was measured on the wire
+ * riding on the telemetry and on the audio files themselves. Relaying through OkHttp is what
+ * removes it; the playback commands were only the first ones (that header alone was enough to
+ * silence them). One rule on Spotify's side is all it takes to flag every install, so the
+ * whole API goes through here now.
+ *
+ * Login and consent hosts stay out: their flows post forms and redirect, and a relay would
+ * have to reproduce every step exactly to sign in.
+ */
private val RELAYED = Regex("^https://[a-z0-9-]+(\\.[a-z0-9-]+)*\\.spotify\\.com/(connect-state|track-playback)/v1/")
+ private val NOT_RELAYED = Regex("^https://(accounts|challenge|www)\\.spotify\\.com/")
- fun isRelayed(url: String) = RELAYED.containsMatchIn(url)
+ fun isRelayed(url: String) = RELAYED.containsMatchIn(url) && !NOT_RELAYED.containsMatchIn(url)
private val AD_MARK = Regex("\"is_advertisement\"\\s*:\\s*\"?true|spotify:ad:|\"ad_id\"")
@@ -133,6 +238,23 @@ internal class ControlRelay(private val view: WebView) {
(() => {
if (window.__mspNetInstalled || !window.MyspotiNet) return;
window.__mspNetInstalled = true;
+ // The identity this page really presents, read from the browser itself and handed to
+ // the host, which echoes it on every relayed request. Written by hand before, the
+ // relayed headers contradicted the page's own (a grease brand that read
+ // "Not:A-Brand" against the page's "Not?A_Brand", and "en" against its "fr-CH"):
+ // a client whose headers disagree with its page is what a server-side gate can spot.
+ try {
+ const d = navigator.userAgentData || {};
+ const langs = (navigator.languages && navigator.languages.length) ? navigator.languages : [navigator.language];
+ window.MyspotiNet.postMessage(JSON.stringify({ type: 'identity', value: {
+ userAgent: navigator.userAgent,
+ brands: (d.brands || []).map(b => '"' + b.brand + '";v="' + b.version + '"').join(', '),
+ mobile: d.mobile === true ? '?1' : '?0',
+ platform: d.platform || 'Linux',
+ // Chromium's own shape: the first language plain, then q=0.9, 0.8, ...
+ acceptLanguage: langs.map((l, i) => i === 0 ? l : l + ';q=0.' + Math.max(1, 10 - i)).join(','),
+ }}));
+ } catch (e) { /* the host keeps its fallback identity */ }
// The player's media elements, often never added to the document: the bridge
// silences them during an ad ("media.mute"); one started then starts silent.
// Silent is a tiny volume, never muted: Chromium pauses muted media of a hidden page.
@@ -144,7 +266,8 @@ internal class ControlRelay(private val view: WebView) {
if (window.__mspMuted) { this.muted = false; this.volume = 0.001; }
return play.apply(this, arguments);
};
- const relayed = /^https:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*\.spotify\.com\/(connect-state|track-playback)\/v1\//;
+ const relayed = /^https:\/\/([a-z0-9-]+\.)*spotify\.com\/(connect-state|track-playback)\/v1\//;
+ const notRelayed = /^https:\/\/(accounts|challenge|www)\.spotify\.com\//;
const pending = new Map();
let seq = 0;
window.__mspNetDone = (id, status, headers, body) => {
@@ -163,7 +286,7 @@ internal class ControlRelay(private val view: WebView) {
window.fetch = function (input, init) {
const url = typeof input === 'string' ? input : (input instanceof URL ? input.href : null);
const body = init && init.body;
- if (!url || !relayed.test(url) || (body != null && typeof body !== 'string')) return original.apply(this, arguments);
+ if (!url || !relayed.test(url) || notRelayed.test(url) || (body != null && typeof body !== 'string')) return original.apply(this, arguments);
const headers = {};
new Headers((init && init.headers) || {}).forEach((v, k) => { headers[k] = v; });
const method = ((init && init.method) || 'GET').toUpperCase();
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/Fingerprint.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/Fingerprint.kt
new file mode 100644
index 00000000..91fcc848
--- /dev/null
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/Fingerprint.kt
@@ -0,0 +1,153 @@
+package app.myspoti.host.android
+
+import android.content.Context
+import org.json.JSONObject
+import java.io.File
+import kotlin.random.Random
+
+/**
+ * The browser this install pretends to be.
+ *
+ * Every install used to announce the very same user agent and client hints — the same Chrome build,
+ * the same Linux version. That is a **group** signature: one rule on Spotify's side would have
+ * covered every Myspoti at once, and blocking one profile would have blocked them all. Each install
+ * draws its own values once and keeps them; within a run nothing changes (no browser changes its own
+ * version between two requests).
+ *
+ * The version follows the WebView: what is kept is how far behind it this install claims to be
+ * ([lag], at most [BACK_RELEASES]), not a frozen number. A real Chrome updates itself, and a version
+ * drawn once and kept for ever would have drifted further back at every WebView update.
+ */
+internal data class Fingerprint(val major: Int, val build: Int, val patch: Int, val kernel: String) {
+
+ /**
+ * The user agent the WebView presents, and the one the app's own HTTP calls use. Reduced, like
+ * every desktop Chrome since the user-agent reduction: `Chrome/<major>.0.0.0`. The full version
+ * only exists in the client hints ([fullVersion]); a build number in this string is something no
+ * real Chrome sends, so it would have marked every install instead of hiding it.
+ */
+ val userAgent: String
+ get() = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " +
+ "Chrome/$major.0.0.0 Safari/537.36"
+
+ /** What the client hints announce as this browser's full version. */
+ val fullVersion: String get() = "$major.0.$build.$patch"
+
+ /** The brand list, in the order and with the grease brand Chromium itself derives from [major]. */
+ val brands: List<Brand> get() = brandsOf(major, fullVersion)
+
+ /** The `sec-ch-ua` header these brands make, as Chromium writes it. */
+ val secChUa: String get() = brands.joinToString(", ") { "\"${it.name}\";v=\"${it.major}\"" }
+
+ data class Brand(val name: String, val major: String, val fullVersion: String)
+
+ /** What is kept on disk: the draw, never the version itself (that one comes from the WebView). */
+ data class Draw(val lag: Int, val patch: Int, val kernel: String)
+
+ companion object {
+ /** How many Chrome releases back this install may claim (two: recent, and still plausible). */
+ const val BACK_RELEASES = 2
+
+ /** Linux versions a desktop Chrome would report (kernel 6.x, the versions in the wild). */
+ val KERNELS = listOf("6.8.0", "6.7.2", "6.6.9", "6.5.7", "6.9.1", "6.4.12")
+
+ /**
+ * Chrome's build number grows by about this much per release (130 → 6723, 140 → 7339,
+ * 143 → 7499): the estimate for a release behind the WebView, whose real build is unknown here.
+ */
+ const val BUILDS_PER_MAJOR = 55
+
+ /** Used only when the WebView's version cannot be read. */
+ private const val FALLBACK_ENGINE = "155.0.8160.0"
+
+ // Chromium's GREASE (components/embedder_support/user_agent_utils.cc): the fake brand, its
+ // version and the order of the three brands all follow from the major version. A fixed
+ // grease brand next to a varying major is a combination no real Chrome produces.
+ private val GREASE_CHARS = listOf(" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_")
+ private val GREASE_VERSIONS = listOf("8", "99", "24")
+ private val ORDERS = listOf(
+ intArrayOf(0, 1, 2), intArrayOf(0, 2, 1), intArrayOf(1, 0, 2),
+ intArrayOf(1, 2, 0), intArrayOf(2, 0, 1), intArrayOf(2, 1, 0),
+ )
+
+ fun brandsOf(major: Int, fullVersion: String): List<Brand> {
+ val greaseVersion = GREASE_VERSIONS[major % GREASE_VERSIONS.size]
+ val grease = Brand(
+ "Not${GREASE_CHARS[major % GREASE_CHARS.size]}A${GREASE_CHARS[(major + 1) % GREASE_CHARS.size]}Brand",
+ greaseVersion,
+ "$greaseVersion.0.0.0",
+ )
+ val order = ORDERS[major % ORDERS.size]
+ val out = arrayOfNulls<Brand>(3)
+ out[order[0]] = grease
+ out[order[1]] = Brand("Chromium", "$major", fullVersion)
+ out[order[2]] = Brand("Google Chrome", "$major", fullVersion)
+ return out.map { it!! }
+ }
+
+ /** A Chrome version string ("141.0.7390.122") as (major, build, patch); null if it is not one. */
+ fun parseEngine(version: String?): Triple<Int, Int, Int>? {
+ val parts = version?.trim()?.split('.')?.map { it.toIntOrNull() } ?: return null
+ if (parts.size != 4 || parts.any { it == null }) return null
+ val (major, _, build, patch) = parts.map { it!! }
+ return if (major in 100..300 && build > 0) Triple(major, build, patch) else null
+ }
+
+ /**
+ * `Accept-Language` as Chromium writes it from a language list: the first plain, then
+ * q=0.9, 0.8… down to 0.1, joined by a bare comma ("fr-CH,fr;q=0.9,en;q=0.8").
+ */
+ fun acceptLanguage(tags: List<String>): String = tags.filter { it.isNotBlank() }
+ .mapIndexed { i, tag -> if (i == 0) tag else "$tag;q=0.${maxOf(1, 10 - i)}" }
+ .joinToString(",")
+
+ fun draw(random: Random = Random.Default) = Draw(
+ lag = random.nextInt(0, BACK_RELEASES + 1),
+ patch = random.nextInt(1, 200),
+ kernel = KERNELS[random.nextInt(KERNELS.size)],
+ )
+
+ /**
+ * This install's browser on the WebView [engineVersion]. With no lag it is exactly the
+ * WebView's own version; behind it, the build is estimated and the patch is the drawn one.
+ */
+ fun resolve(engineVersion: String?, draw: Draw): Fingerprint {
+ val (engineMajor, engineBuild, enginePatch) = parseEngine(engineVersion) ?: parseEngine(FALLBACK_ENGINE)!!
+ val lag = draw.lag.coerceIn(0, BACK_RELEASES)
+ return if (lag == 0) Fingerprint(engineMajor, engineBuild, enginePatch, draw.kernel)
+ else Fingerprint(engineMajor - lag, engineBuild - lag * BUILDS_PER_MAJOR, draw.patch, draw.kernel)
+ }
+
+ /**
+ * A draw read back from [json]. The file of earlier versions held the claimed version
+ * itself (major, build, patch): its lag is recovered against the current WebView, so an
+ * install keeps its place behind it rather than drawing a new identity.
+ */
+ fun drawFrom(json: JSONObject, engineVersion: String?): Draw? {
+ val kernel = json.optString("kernel").takeIf { it in KERNELS } ?: return null
+ val patch = json.optInt("patch", 0).takeIf { it > 0 } ?: return null
+ if (json.has("lag")) return Draw(json.optInt("lag", 0).coerceIn(0, BACK_RELEASES), patch, kernel)
+ val major = json.optInt("major", 0).takeIf { it > 0 } ?: return null
+ val engineMajor = (parseEngine(engineVersion) ?: parseEngine(FALLBACK_ENGINE)!!).first
+ return Draw((engineMajor - major).coerceIn(0, BACK_RELEASES), patch, kernel)
+ }
+
+ fun of(context: Context): Fingerprint {
+ val engine = runCatching {
+ androidx.webkit.WebViewCompat.getCurrentWebViewPackage(context)?.versionName
+ }.getOrNull()
+ val file = File(context.filesDir, "spotify/browser.json")
+ val json = runCatching { JSONObject(file.readText()) }.getOrNull()
+ val saved = json?.let { runCatching { drawFrom(it, engine) }.getOrNull() }
+ val draw = saved ?: draw()
+ // Written once, or once more to move a file of the old shape to the new one.
+ if (saved == null || json?.has("lag") != true) {
+ runCatching {
+ file.parentFile?.mkdirs()
+ file.writeText(JSONObject().put("lag", draw.lag).put("patch", draw.patch).put("kernel", draw.kernel).toString())
+ }
+ }
+ return resolve(engine, draw)
+ }
+ }
+}
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt
new file mode 100644
index 00000000..aa3e9ac2
--- /dev/null
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt
@@ -0,0 +1,80 @@
+package app.myspoti.host.android
+
+import android.content.Context
+import java.io.File
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+/**
+ * The engine's own log, kept in memory so a tester can hand it back as a file.
+ *
+ * The WebView bridge is invisible on a phone: the only evidence of a refused playback
+ * command (`402 COMMAND_FAILED`) or of a sign-in that stalls is these lines, and until now
+ * they were reachable only through `adb logcat` ([WebPlayerHost.LOG]) — which the person
+ * reporting the bug cannot run. Every line is mirrored to Logcat with the very same text
+ * ([log]) and kept in a bounded ring buffer that [export] writes to a shareable file, so
+ * the report a tester sends is the app's own log and nothing else has to change.
+ */
+object Logbook {
+ /**
+ * Only the tail is kept: a report is read from the end, and an unbounded buffer would
+ * grow for the whole life of the process (the page can run for hours).
+ */
+ private const val MAX_LINES = 1500
+
+ /** Guarded by its own monitor: [log] is called from the main thread, OkHttp threads and coroutines. */
+ private val lines = ArrayDeque<String>(MAX_LINES)
+ private val stamp = SimpleDateFormat("HH:mm:ss.SSS", Locale.US)
+ private val fileStamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US)
+
+ /**
+ * Records [line] and mirrors it to Logcat with the same message, so the exported report
+ * and `adb logcat -s Myspoti` show the same thing. Safe from any thread.
+ */
+ fun log(line: String) {
+ android.util.Log.d(WebPlayerHost.LOG, line)
+ synchronized(lines) {
+ lines.addLast("${stamp.format(Date())} $line")
+ while (lines.size > MAX_LINES) lines.removeFirst()
+ }
+ }
+
+ /** The buffered lines, oldest first. */
+ fun recent(): String = synchronized(lines) { lines.joinToString("\n") }
+
+ /**
+ * Writes the report (device and version header, then [recent]) to the app's own external
+ * files directory, so it can be handed to the share sheet through the FileProvider.
+ * Returns the file for the caller to share.
+ */
+ fun export(context: Context): File {
+ // The external dir is what a FileProvider can expose; the internal one is the
+ // fallback for a device with no external storage.
+ val dir = context.getExternalFilesDir(null) ?: context.filesDir
+ val file = File(dir, "diagnostic-${fileStamp.format(Date())}.txt")
+ file.writeText(report(context))
+ return file
+ }
+
+ private fun report(context: Context): String {
+ val info = runCatching { context.packageManager.getPackageInfo(context.packageName, 0) }.getOrNull()
+ val versionName = info?.versionName ?: "?"
+ val versionCode = info?.let { androidx.core.content.pm.PackageInfoCompat.getLongVersionCode(it) } ?: 0L
+ // The player's page URL tells which Spotify screen the app was on; read only when the
+ // runtime started, or the not-yet-initialized host would crash the export.
+ val pageUrl = if (MyspotiRuntime.isStarted) runCatching { MyspotiRuntime.host.url.value }.getOrNull() else null
+ val tail = recent()
+ return buildString {
+ appendLine("Myspoti diagnostic report")
+ appendLine("app : $versionName ($versionCode)")
+ appendLine("android : ${android.os.Build.VERSION.RELEASE} (SDK ${android.os.Build.VERSION.SDK_INT})")
+ appendLine("device : ${android.os.Build.MANUFACTURER} ${android.os.Build.MODEL}")
+ appendLine("locale : ${Locale.getDefault().toLanguageTag()}")
+ if (!pageUrl.isNullOrEmpty()) appendLine("page : $pageUrl")
+ appendLine()
+ appendLine("--- log ---")
+ appendLine(tail)
+ }
+ }
+}
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/MediaProxy.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/MediaProxy.kt
new file mode 100644
index 00000000..adc91a30
--- /dev/null
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/MediaProxy.kt
@@ -0,0 +1,102 @@
+package app.myspoti.host.android
+
+import android.webkit.WebResourceRequest
+import android.webkit.WebResourceResponse
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.Response
+import java.io.FilterInputStream
+import java.io.InputStream
+import java.util.concurrent.TimeUnit
+
+/**
+ * Fetches Spotify's audio files for the WebView, instead of letting the WebView fetch them.
+ *
+ * Every request a WebView makes carries `X-Requested-With: <package name>` — measured on the wire,
+ * it rode on the music files themselves and on Spotify's telemetry. No browser sends that header,
+ * so it is the one thing that names this client wherever it goes; the telemetry and the API calls
+ * are relayed (see [ControlRelay]), and the audio is the bulk of what is left: it is fetched from
+ * here, so those requests never leave the WebView at all.
+ *
+ * Range requests are forwarded as they arrive, so seeking, buffering and the CDN's own caching
+ * behave exactly as before; the response travels back as a live stream, never buffered.
+ */
+internal class MediaProxy(private val client: OkHttpClient, private val identity: () -> Pair<String, String>?) {
+
+ /** A Spotify audio file (tracks, podcast episodes). */
+ fun handles(url: String) = ENABLED && AUDIO.containsMatchIn(url)
+
+ fun fetch(request: WebResourceRequest): WebResourceResponse? = runCatching {
+ val builder = Request.Builder().url(request.url.toString())
+ // The method comes from the page (HEAD probes included): asking for something else would
+ // hand back a body where Chromium expects none.
+ builder.method(request.method?.uppercase() ?: "GET", null)
+ request.requestHeaders.forEach { (key, value) ->
+ // The transport headers are the client's own, and `accept-encoding` must not be copied:
+ // OkHttp asks for what it can undo, and a copy Chromium cannot read would be corruption.
+ if (key.lowercase() !in SKIP) builder.header(key, value)
+ }
+ // The page's identity, so the CDN sees the same client the page claims to be.
+ identity()?.let { (userAgent, language) ->
+ builder.header("User-Agent", userAgent)
+ if (language.isNotEmpty()) builder.header("Accept-Language", language)
+ }
+ val response = client.newCall(builder.build()).execute()
+ val body = response.body
+ if (body == null || (response.code != 200 && response.code != 206)) {
+ response.close()
+ return null
+ }
+ // Everything the CDN said, minus what the hop replaces. A whitelist looked safer and was
+ // wrong: the Web Player's audio element goes through CORS, and dropping
+ // `access-control-allow-origin` made the media fail — the player threw and playback died.
+ val headers = response.headers.toMultimap()
+ .filterKeys { it.lowercase() !in DROP }
+ .mapValues { (_, values) -> values.joinToString(",") }
+ WebResourceResponse(
+ body.contentType()?.toString()?.substringBefore(';') ?: "audio/mpeg",
+ null,
+ response.code,
+ response.message.ifBlank { "OK" },
+ headers,
+ ClosingStream(body.byteStream(), response),
+ )
+ }.getOrNull()
+
+ companion object {
+ /**
+ * Off while the regression it was meant to fix is being worked out: the header it removes is
+ * the fingerprint, but a proxy that breaks playback is worse than a fingerprint. Flipped back
+ * on once the test battery passes with it.
+ */
+ const val ENABLED = false
+
+ /** Spotify's audio CDNs. Images and fonts (also on these hosts) stay with the WebView. */
+ private val AUDIO = Regex("^https://[a-z0-9-]+\\.(scdn\\.co|spotifycdn\\.com)/audio/")
+
+ /** Never copied from the incoming request; the transport sets them (or must not copy them). */
+ private val SKIP = setOf(
+ "host", "connection", "accept-encoding", "content-length", "x-requested-with",
+ "user-agent", "accept-language", "origin", "referer",
+ )
+
+ /**
+ * What the hop replaces, and nothing else: every other header the CDN sent travels through
+ * untouched (CORS above all — see the comment in [fetch]).
+ */
+ private val DROP = setOf("content-encoding", "transfer-encoding", "connection", "keep-alive", "set-cookie")
+ /** A connection of its own: audio streams are long, and one kept alive per track is enough. */
+ fun client(): OkHttpClient = OkHttpClient.Builder()
+ .connectTimeout(15, TimeUnit.SECONDS)
+ .readTimeout(30, TimeUnit.SECONDS)
+ .build()
+ }
+}
+
+/** Closes the whole HTTP response once Chromium has finished with the body it was handed. */
+private class ClosingStream(stream: InputStream, private val response: Response) : FilterInputStream(stream) {
+ override fun close() {
+ runCatching { super.close() }
+ runCatching { response.close() }
+ }
+}
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
index 95a5a42e..98e5d087 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
@@ -30,8 +30,8 @@ object MyspotiRuntime {
if (isStarted) return
val updater = app.myspoti.spotify.gql.GqlOpsUpdater(okhttp3.OkHttpClient(), java.io.File(context.filesDir, "spotify/gql-ops.json"))
host = WebPlayerHost(context)
- spotify = SpotifyApi(host, scope, language = Locale.getDefault().language, ops = updater.load())
- spotify.bridge.logger = { line -> android.util.Log.d(WebPlayerHost.LOG, line) }
+ spotify = SpotifyApi(host, scope, language = Locale.getDefault().language, ops = updater.load(), deviceId = clientDeviceId(context), userAgent = host.userAgent)
+ spotify.bridge.logger = { line -> Logbook.log(line) }
host.onPageLoaded = { scope.launch { spotify.onPageLoaded() } }
host.onPageStarting = { spotify.onPageStarting() }
spotify.player.reloadHost = { host.reload() }
@@ -42,11 +42,18 @@ object MyspotiRuntime {
while (true) {
kotlinx.coroutines.delay(10_000)
val s = spotify.player.state.value
- val line = "status ready=${spotify.ready.value} login=${host.loginRequired.value} " +
+ // "login" alone said nothing (it only meant "the page is on a login URL"): a bug
+ // report needs the session itself — a token that is anonymous means no account.
+ val session = when {
+ host.loginRequired.value -> "login-page"
+ runCatching { isSignedIn() }.getOrDefault(false) -> "signed-in"
+ else -> "anonymous"
+ }
+ val line = "status ready=${spotify.ready.value} session=$session " +
"track=${s?.item?.name} paused=${s?.isPaused} buffering=${s?.isBuffering} url=${host.url.value.take(60)}"
if (line != last) {
last = line
- android.util.Log.d(WebPlayerHost.LOG, line)
+ Logbook.log(line)
}
}
}
@@ -61,7 +68,33 @@ object MyspotiRuntime {
/** True when the Web Player holds a signed-in user's token (not an anonymous one). */
suspend fun isSignedIn(): Boolean = spotify.isSignedIn()
+ /**
+ * Waits for a signed-in session (a non-anonymous token) up to [timeoutMs]. The login flow is
+ * bounded by this: the page returning to open.spotify.com is not a session, and waiting on
+ * it for ever is what left the spinner running (see MainActivity.watchLoginReturn).
+ */
+ suspend fun awaitSignedIn(timeoutMs: Long): Boolean {
+ val deadline = System.currentTimeMillis() + timeoutMs
+ while (System.currentTimeMillis() < deadline) {
+ if (runCatching { isSignedIn() }.getOrDefault(false)) return true
+ kotlinx.coroutines.delay(500)
+ }
+ return runCatching { isSignedIn() }.getOrDefault(false)
+ }
+
/** Data saver: frees the page; [resume] loads it again. */
fun suspendPlayer() = host.unload()
fun resume() = host.load()
+
+ /**
+ * The client's device id, kept across launches: a client token is issued per (client, device)
+ * pair, and a fresh id at every start made the app look like a brand-new client each time.
+ */
+ private fun clientDeviceId(context: Context): String {
+ val file = java.io.File(context.filesDir, "spotify/device-id")
+ runCatching { file.readText().trim() }.getOrNull()?.takeIf { it.isNotEmpty() }?.let { return it }
+ val id = java.util.UUID.randomUUID().toString()
+ runCatching { file.parentFile?.mkdirs(); file.writeText(id) }
+ return id
+ }
}
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt
index 34c0ad6b..556b84e0 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt
@@ -89,6 +89,13 @@ class PlaybackService : MediaBrowserServiceCompat() {
session = MediaSessionCompat(this, "Myspoti").apply {
setCallback(callback)
setSessionActivity(launchIntent())
+ // Android Auto binds on a cold start, before the app has pushed any state: a
+ // session without a playback state gives the car no play button, and no command
+ // is ever sent (issue #41). Paused with the full action set: the car can play.
+ setPlaybackState(PlaybackStateCompat.Builder()
+ .setActions(ACTIONS)
+ .setState(PlaybackStateCompat.STATE_PAUSED, 0L, 0f)
+ .build())
isActive = true
}
sessionToken = session.sessionToken
@@ -163,12 +170,7 @@ class PlaybackService : MediaBrowserServiceCompat() {
else -> PlaybackStateCompat.STATE_PAUSED
}
session.setPlaybackState(PlaybackStateCompat.Builder()
- .setActions(
- PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_PLAY_PAUSE or
- PlaybackStateCompat.ACTION_SKIP_TO_NEXT or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or
- PlaybackStateCompat.ACTION_SEEK_TO or PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID or
- PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
- )
+ .setActions(ACTIONS)
// Like on the left of previous / play / next, shuffle on the right: five buttons, so
// play / pause sits in the middle (lock screen, Samsung Now Bar, Android 13+ shade).
.addCustomAction(ACTION_LIKE, if (info.liked) "Unlike" else "Like",
@@ -311,14 +313,30 @@ class PlaybackService : MediaBrowserServiceCompat() {
if (parentId == EMPTY_ROOT_ID || !callerMayBrowse()) return result.sendResult(mutableListOf())
val lib = library ?: return result.sendResult(mutableListOf())
result.detach()
- scope.launch { result.sendResult(runCatching { lib.children(this@PlaybackService, parentId).toMutableList() }.getOrElse { mutableListOf() }) }
+ scope.launch {
+ val outcome = runCatching { lib.children(this@PlaybackService, parentId).toMutableList() }
+ val items = outcome.getOrNull()
+ if (items == null) {
+ // The library waits for the player itself; reaching here means it never came
+ // up. MediaBrowserCompat has no error reply on API 26+ (sendError throws), so
+ // an empty list is the only answer: the log names the cause of a cold start
+ // that failed (#41), and the folder loads on the next browse.
+ android.util.Log.w("Myspoti", "browse $parentId: ${outcome.exceptionOrNull()?.message}")
+ }
+ result.sendResult(items ?: mutableListOf())
+ }
}
override fun onSearch(query: String, extras: Bundle?, result: Result<MutableList<MediaBrowserCompat.MediaItem>>) {
if (!callerMayBrowse()) return result.sendResult(mutableListOf())
val lib = library ?: return result.sendResult(mutableListOf())
result.detach()
- scope.launch { result.sendResult(runCatching { lib.search(query).toMutableList() }.getOrElse { mutableListOf() }) }
+ scope.launch {
+ val outcome = runCatching { lib.search(query).toMutableList() }
+ val items = outcome.getOrNull()
+ if (items == null) android.util.Log.w("Myspoti", "search: ${outcome.exceptionOrNull()?.message}")
+ result.sendResult(items ?: mutableListOf())
+ }
}
/** The app itself, the listed browsers, and system apps may browse the library. */
@@ -343,11 +361,19 @@ class PlaybackService : MediaBrowserServiceCompat() {
private const val NOTIFICATION_ID = 1
private const val ACTION_LIKE = "like"
private const val ACTION_SHUFFLE = "shuffle"
+ /** Everything the car, the lock screen and the notification may ask for. */
+ private val ACTIONS = PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_PLAY_PAUSE or
+ PlaybackStateCompat.ACTION_SKIP_TO_NEXT or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or
+ PlaybackStateCompat.ACTION_SEEK_TO or PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID or
+ PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
private val http = OkHttpClient()
@Volatile private var instance: PlaybackService? = null
@Volatile private var current: NowPlayingInfo? = null
+ /** True while the service runs (its notification is up): the app may be in the background. */
+ val isRunning: Boolean get() = instance != null
+
private const val PAUSE_GRACE_MS = 60_000L
/** A state that did not change is republished at most that often (see [update]). */
private const val POSITION_REPUSH_MS = 10_000L
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
index 2ee71a4e..b94cc7be 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
@@ -14,6 +14,7 @@ import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebView
+import android.webkit.RenderProcessGoneDetail
import android.webkit.WebViewClient
import app.myspoti.spotify.bridge.AdBlock
import app.myspoti.spotify.bridge.BridgeHost
@@ -34,7 +35,7 @@ import java.io.ByteArrayInputStream
* - [loginRequired] turns true on Spotify's login pages: the UI then shows [view] so the
* user signs in on Spotify's own page.
*/
-class WebPlayerHost(context: Context) : BridgeHost {
+class WebPlayerHost(private val context: Context) : BridgeHost {
private val main = Handler(Looper.getMainLooper())
// DROP_OLDEST: tryEmit under a main-thread stall must not drop the newest
@@ -55,38 +56,68 @@ class WebPlayerHost(context: Context) : BridgeHost {
/** Fires when a Web Player page load starts: the old page and its bridge are gone. */
var onPageStarting: (() -> Unit)? = null
+ /** Debug builds: extra logging (a proxy that fails, a device name rewritten…) — and CDP. */
+ private val debuggable = context.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0
+
+ /**
+ * This install's browser identity, drawn once (see [Fingerprint]) and handed to the API as
+ * well: the page and the app's own calls must present the *same* browser, or the difference
+ * between them is itself the tell.
+ */
+ internal val fingerprint = Fingerprint.of(context)
+ val userAgent: String get() = fingerprint.userAgent
+
init {
// Debug builds only: lets desktop tools (chrome://inspect, CDP) look at the page.
- val debuggable = context.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0
if (debuggable) WebView.setWebContentsDebuggingEnabled(true)
}
private lateinit var relay: ControlRelay
+ /** Fetches the audio files itself: the last request the WebView would stamp with its package. */
+ private val media = MediaProxy(MediaProxy.client()) { relay.identityPair() }
+
@SuppressLint("SetJavaScriptEnabled")
- val view: WebView = WebView(context.applicationContext).apply {
+ var view: WebView = createView()
+
+ /**
+ * Builds the page view. Called once at startup, and again after a renderer crash: a WebView
+ * whose renderer died can never be reused, and Android kills the process if one is used after
+ * [onRenderProcessGone] returns false (see [rebuild]).
+ */
+ @SuppressLint("SetJavaScriptEnabled")
+ private fun createView(): WebView = WebView(context.applicationContext).apply {
settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
mediaPlaybackRequiresUserGesture = false
- userAgentString = DESKTOP_UA
+ userAgentString = fingerprint.userAgent
cacheMode = WebSettings.LOAD_DEFAULT
loadWithOverviewMode = true
useWideViewPort = true
}
+ // The WebView stamps every request the page makes with "X-Requested-With: <our package>".
+ // No browser does that, and it is measured on the wire ([tools/cdp.py] --trace --headers):
+ // it rode on the audio files themselves and on Spotify's telemetry, so a single rule on
+ // Spotify's side would flag every Myspoti install. The androidx API was made to allow that
+ // header for a few origins; an empty allowlist is what suppresses it everywhere.
+ if (androidx.webkit.WebViewFeature.isFeatureSupported(androidx.webkit.WebViewFeature.REQUESTED_WITH_HEADER_ALLOW_LIST)) {
+ androidx.webkit.WebSettingsCompat.setRequestedWithHeaderOriginAllowList(settings, emptySet())
+ Logbook.log("x-requested-with: off for every origin")
+ } else {
+ Logbook.log("x-requested-with: cannot be turned off on this WebView")
+ }
// Client hints must agree with the desktop user agent: by default the WebView announces
// "Android WebView" / mobile in Sec-CH-UA headers and navigator.userAgentData.
if (androidx.webkit.WebViewFeature.isFeatureSupported(androidx.webkit.WebViewFeature.USER_AGENT_METADATA)) {
- val brands = listOf(
- androidx.webkit.UserAgentMetadata.BrandVersion.Builder().setBrand("Chromium").setMajorVersion("155").setFullVersion("155.0.0.0").build(),
- androidx.webkit.UserAgentMetadata.BrandVersion.Builder().setBrand("Google Chrome").setMajorVersion("155").setFullVersion("155.0.0.0").build(),
- androidx.webkit.UserAgentMetadata.BrandVersion.Builder().setBrand("Not?A_Brand").setMajorVersion("24").setFullVersion("24.0.0.0").build(),
- )
+ val brands = fingerprint.brands.map {
+ androidx.webkit.UserAgentMetadata.BrandVersion.Builder().setBrand(it.name).setMajorVersion(it.major).setFullVersion(it.fullVersion).build()
+ }
androidx.webkit.WebSettingsCompat.setUserAgentMetadata(settings, androidx.webkit.UserAgentMetadata.Builder()
.setBrandVersionList(brands)
- .setFullVersion("155.0.0.0")
+ .setFullVersion(fingerprint.fullVersion)
.setPlatform("Linux")
- .setPlatformVersion("6.8.0")
+ .setPlatformVersion(fingerprint.kernel)
.setArchitecture("x86")
.setBitness(64)
.setMobile(false)
@@ -97,7 +128,7 @@ class WebPlayerHost(context: Context) : BridgeHost {
// The page plays the audio: its renderer keeps its priority when the screen is off.
setRendererPriorityPolicy(WebView.RENDERER_PRIORITY_IMPORTANT, false)
// Playback control requests leave from the app, without the WebView's X-Requested-With.
- relay = ControlRelay(this).also { it.install() }
+ relay = ControlRelay(this, fingerprint).also { it.install() }
val webView = this
CookieManager.getInstance().apply {
setAcceptCookie(true)
@@ -108,26 +139,46 @@ class WebPlayerHost(context: Context) : BridgeHost {
override fun onConsoleMessage(message: android.webkit.ConsoleMessage): Boolean {
if (message.messageLevel() == android.webkit.ConsoleMessage.MessageLevel.ERROR ||
message.messageLevel() == android.webkit.ConsoleMessage.MessageLevel.WARNING)
- android.util.Log.d(LOG, "console ${message.messageLevel()}: ${message.message().take(300)}")
+ Logbook.log("console ${message.messageLevel()}: ${message.message().take(300)}")
return true
}
override fun onPermissionRequest(request: PermissionRequest) {
- android.util.Log.d(LOG, "permission request: ${request.resources.joinToString()}")
+ Logbook.log("permission request: ${request.resources.joinToString()}")
val allowed = request.resources.filter { it == PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID }
if (allowed.isNotEmpty()) request.grant(allowed.toTypedArray()) else request.deny()
}
}
webViewClient = object : WebViewClient() {
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
- if (!AdBlock.isBlocked(request.url.toString())) return null
- android.util.Log.d(LOG, "blocked ad request ${request.url.toString().take(120)}")
- // Refused like a blocked request: the player reports a failed ad and moves on.
- return WebResourceResponse("text/plain", "utf-8", 403, "Blocked", emptyMap(), ByteArrayInputStream(ByteArray(0)))
+ val url = request.url.toString()
+ if (AdBlock.isBlocked(url)) {
+ Logbook.log("blocked ad request ${url.take(120)}")
+ // Refused like a blocked request: the player reports a failed ad and moves on.
+ return WebResourceResponse("text/plain", "utf-8", 403, "Blocked", emptyMap(), ByteArrayInputStream(ByteArray(0)))
+ }
+ // The sign-in flow lives on accounts.spotify.com: logging its steps is what turns
+ // "the login is stuck" into the exact request that failed (with the status from
+ // onReceivedHttpError below). Reported as B37 and unprovable without this trail.
+ if (url.startsWith("https://accounts.spotify.com/")) {
+ loginSteps++
+ Logbook.log("login step #$loginSteps ${request.method} ${url.substringAfter("accounts.spotify.com").substringBefore('?').take(90)}")
+ }
+ // The music itself: fetched here, so the WebView's own package-name header never
+ // travels with it (see MediaProxy).
+ if (media.handles(url)) {
+ val proxied = media.fetch(request)
+ if (proxied != null) {
+ if (debuggable) Logbook.log("audio proxied ${url.substringAfterLast('/').take(12)}…")
+ return proxied
+ }
+ Logbook.log("audio proxy failed, the WebView fetches it: ${url.take(110)}")
+ }
+ return null
}
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
- android.util.Log.d(LOG, "page start ${url.take(120)}")
+ Logbook.log("page start ${url.take(120)}")
pageStarts++
_url.value = url
_loginRequired.value = isLoginPage(url)
@@ -136,16 +187,16 @@ class WebPlayerHost(context: Context) : BridgeHost {
override fun onReceivedError(view: WebView, request: WebResourceRequest, error: android.webkit.WebResourceError) {
if (request.url.host?.contains("spotify") == true)
- android.util.Log.d(LOG, "load error ${error.errorCode} ${error.description} ${request.url.toString().take(120)}")
+ Logbook.log("load error ${error.errorCode} ${error.description} ${request.url.toString().take(120)}")
}
override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, response: WebResourceResponse) {
if (request.url.host?.contains("spotify") == true)
- android.util.Log.d(LOG, "http ${response.statusCode} ${request.method} ${request.url.toString().substringBefore('?').take(120)}")
+ Logbook.log("http ${response.statusCode} ${request.method} ${request.url.toString().substringBefore('?').take(120)}")
}
override fun onPageFinished(view: WebView, url: String) {
- android.util.Log.d(LOG, "page finished ${url.take(120)}")
+ Logbook.log("page finished ${url.take(120)}")
_url.value = url
_loginRequired.value = isLoginPage(url)
if (url.startsWith(PLAYER_URL)) onPageLoaded?.invoke()
@@ -159,9 +210,48 @@ class WebPlayerHost(context: Context) : BridgeHost {
.any { host == it || host.endsWith(".$it") }
return !allowed
}
+
+ /**
+ * The renderer died (the reported "the app crashed", "playback stops until the player
+ * is restarted"). A WebView whose renderer is gone can never be reused, and Android
+ * kills the whole process if one is still used after this returns false: the page is
+ * rebuilt on a new WebView, and true says "handled, do not kill the app".
+ */
+ override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
+ Logbook.log("renderer gone (crashed=${detail.didCrash()}): rebuilding the page")
+ rebuild()
+ return true
+ }
}
}
+ /** The container the page is attached to, so a rebuilt page goes back to the same place. */
+ private var container: ViewGroup? = null
+
+ /** Whether the page was shown full screen at the last [attach] (login). */
+ private var lastVisible = false
+
+ /**
+ * Replaces the page after its renderer died: the dead WebView is destroyed rather than reused,
+ * the new one takes its place in the same container, and the page loads again. Without this
+ * the app kept a dead page — a blank screen with the sound gone — until it was restarted.
+ */
+ private fun rebuild() = main.post {
+ val wasLoaded = loadAsked
+ val box = container
+ box?.let { runCatching { it.removeView(view) } }
+ runCatching { view.stopLoading() }
+ runCatching { view.destroy() }
+ view = createView()
+ pageStarts = 0
+ _url.value = ""
+ // attach() loads the page itself when a load is pending; the pending load is asked again
+ // just after, once, so a rebuilt page is loaded exactly once.
+ loadAsked = false
+ box?.let { attach(it, lastVisible) }
+ if (wasLoaded) load() else view.loadUrl("about:blank")
+ }
+
private fun isLoginPage(url: String?) =
url != null && (url.contains("accounts.spotify.com") || url.contains("/login") || url.contains("challenge.spotify.com"))
@@ -174,6 +264,9 @@ class WebPlayerHost(context: Context) : BridgeHost {
/** Page starts since the last [load]; the load watchdog looks at it. */
private var pageStarts = 0
+
+ /** Sign-in requests seen (accounts.spotify.com): a trail for a login that goes nowhere. */
+ private var loginSteps = 0
/** [load] was called and no [unload] since (data saver keeps the page off). */
private var loadAsked = false
@@ -185,7 +278,7 @@ class WebPlayerHost(context: Context) : BridgeHost {
private fun watchLoad(url: String, attempt: Int) {
main.postDelayed({
if (pageStarts > 0 || !loadAsked || attempt > LOAD_RETRIES) return@postDelayed
- android.util.Log.d(LOG, "page never started: loading again (attempt $attempt)")
+ Logbook.log("page never started: loading again (attempt $attempt)")
if (attempt > 1) view.stopLoading()
view.loadUrl(url)
watchLoad(url, attempt + 1)
@@ -224,6 +317,8 @@ class WebPlayerHost(context: Context) : BridgeHost {
* non-interactive view in [container] while the player is hidden.
*/
fun attach(container: ViewGroup, visible: Boolean) = main.post {
+ this.container = container
+ lastVisible = visible
// Re-added each time: addView converts the params to the container's own type
// (assigning plain ViewGroup.LayoutParams to a FrameLayout child crashes on measure).
(view.parent as? ViewGroup)?.removeView(view)
@@ -253,7 +348,5 @@ class WebPlayerHost(context: Context) : BridgeHost {
private const val LOAD_WATCH_MS = 4_000L
private const val LOAD_RETRIES = 4
const val LOGIN_URL = "https://accounts.spotify.com/login?continue=https%3A%2F%2Fopen.spotify.com%2F"
- const val DESKTOP_UA =
- "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36"
}
}
diff --git a/base/host-android/src/test/kotlin/app/myspoti/host/android/FingerprintTest.kt b/base/host-android/src/test/kotlin/app/myspoti/host/android/FingerprintTest.kt
new file mode 100644
index 00000000..a7910b7c
--- /dev/null
+++ b/base/host-android/src/test/kotlin/app/myspoti/host/android/FingerprintTest.kt
@@ -0,0 +1,76 @@
+package app.myspoti.host.android
+
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import kotlin.random.Random
+
+class FingerprintTest {
+
+ // Real desktop Chrome headers: the grease brand, its version and the order follow the major.
+ @Test fun `brands match what Chrome itself sends`() {
+ val real = mapOf(
+ 116 to "\"Chromium\";v=\"116\", \"Not)A;Brand\";v=\"24\", \"Google Chrome\";v=\"116\"",
+ 120 to "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
+ 124 to "\"Chromium\";v=\"124\", \"Google Chrome\";v=\"124\", \"Not-A.Brand\";v=\"99\"",
+ 131 to "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
+ )
+ real.forEach { (major, header) ->
+ assertEquals(header, Fingerprint(major, 1, 1, "6.8.0").secChUa)
+ }
+ }
+
+ @Test fun `the user agent is reduced, the full version stays in the hints`() {
+ val f = Fingerprint(141, 7390, 122, "6.8.0")
+ assertEquals("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36", f.userAgent)
+ assertEquals("141.0.7390.122", f.fullVersion)
+ assertTrue(f.brands.filter { it.name != "Chromium" && it.name != "Google Chrome" }.all { it.fullVersion.endsWith(".0.0.0") })
+ }
+
+ @Test fun `no lag is the WebView's own version`() {
+ val f = Fingerprint.resolve("141.0.7390.122", Fingerprint.Draw(lag = 0, patch = 57, kernel = "6.6.9"))
+ assertEquals(Fingerprint(141, 7390, 122, "6.6.9"), f)
+ }
+
+ @Test fun `a lag follows the WebView when it updates`() {
+ val draw = Fingerprint.Draw(lag = 1, patch = 57, kernel = "6.6.9")
+ assertEquals(140, Fingerprint.resolve("141.0.7390.122", draw).major)
+ assertEquals(142, Fingerprint.resolve("143.0.7499.40", draw).major)
+ assertEquals(7499 - Fingerprint.BUILDS_PER_MAJOR, Fingerprint.resolve("143.0.7499.40", draw).build)
+ assertEquals(57, Fingerprint.resolve("143.0.7499.40", draw).patch)
+ }
+
+ @Test fun `an unreadable WebView version falls back to a plausible Chrome`() {
+ val f = Fingerprint.resolve("not a version", Fingerprint.Draw(0, 1, "6.8.0"))
+ assertTrue(f.major in 100..300 && f.build > 0)
+ assertNull(Fingerprint.parseEngine("141.0"))
+ assertNull(Fingerprint.parseEngine(null))
+ }
+
+ @Test fun `draws stay within the bounds`() {
+ val random = Random(7)
+ repeat(500) {
+ val d = Fingerprint.draw(random)
+ assertTrue(d.lag in 0..Fingerprint.BACK_RELEASES)
+ assertTrue(d.patch in 1..199)
+ assertTrue(d.kernel in Fingerprint.KERNELS)
+ }
+ }
+
+ @Test fun `a file of the old shape keeps its place behind the WebView`() {
+ val old = JSONObject().put("major", 139).put("build", 8123).put("patch", 45).put("kernel", "6.7.2")
+ assertEquals(Fingerprint.Draw(lag = 2, patch = 45, kernel = "6.7.2"), Fingerprint.drawFrom(old, "141.0.7390.122"))
+ val newer = JSONObject().put("lag", 1).put("patch", 12).put("kernel", "6.8.0")
+ assertEquals(Fingerprint.Draw(1, 12, "6.8.0"), Fingerprint.drawFrom(newer, "141.0.7390.122"))
+ assertNull(Fingerprint.drawFrom(JSONObject().put("lag", 1), "141.0.7390.122"))
+ }
+
+ @Test fun `accept-language is written the way Chromium writes it`() {
+ assertEquals("fr-CH,fr;q=0.9,en;q=0.8", Fingerprint.acceptLanguage(listOf("fr-CH", "fr", "en")))
+ assertEquals("en", Fingerprint.acceptLanguage(listOf("en")))
+ assertFalse(Fingerprint.acceptLanguage(List(12) { "l$it" }).contains(";q=0.0"))
+ }
+}
diff --git a/base/host-cdp/src/main/kotlin/app/myspoti/host/cdp/CdpHost.kt b/base/host-cdp/src/main/kotlin/app/myspoti/host/cdp/CdpHost.kt
index 6b627481..17becfd6 100644
--- a/base/host-cdp/src/main/kotlin/app/myspoti/host/cdp/CdpHost.kt
+++ b/base/host-cdp/src/main/kotlin/app/myspoti/host/cdp/CdpHost.kt
@@ -92,12 +92,9 @@ class CdpHost private constructor(private val socket: WebSocket, private val lis
val requestId = params["requestId"]!!.jsonPrimitive.content
val request = params["request"]!!.jsonObject
val url = request["url"]!!.jsonPrimitive.content
- val method = request["method"]?.jsonPrimitive?.content ?: "GET"
- val post = request["postData"]?.jsonPrimitive?.content
- val reply = if (post != null && AdBlock.isDeviceRegistration(method, url)) {
- val body = java.util.Base64.getEncoder().encodeToString(AdBlock.withoutAdFormats(post).toByteArray())
- buildJsonObject { put("id", ids.incrementAndGet()); put("method", "Fetch.continueRequest"); putJsonObject("params") { put("requestId", requestId); put("postData", body) } }
- } else if (AdBlock.isBlocked(url)) {
+ // The device registration goes through as the Web Player sends it (see
+ // AdBlock.withDeviceName): the desktop host keeps the browser's own name.
+ val reply = if (AdBlock.isBlocked(url)) {
buildJsonObject { put("id", ids.incrementAndGet()); put("method", "Fetch.failRequest"); putJsonObject("params") { put("requestId", requestId); put("errorReason", "BlockedByClient") } }
} else {
buildJsonObject { put("id", ids.incrementAndGet()); put("method", "Fetch.continueRequest"); putJsonObject("params") { put("requestId", requestId) } }
diff --git a/docs/CHANGELOG-full.md b/docs/CHANGELOG-full.md
index bf50e569..52cf9b03 100644
--- a/docs/CHANGELOG-full.md
+++ b/docs/CHANGELOG-full.md
@@ -2,6 +2,12 @@
Every change, release by release. The short version is in [CHANGELOG.md](../CHANGELOG.md), which the app and the GitHub releases show.
+## Unreleased
+
+- **Skip intent**: next / previous / "skip to" made while the page cannot take them (an ad is current: "The operation is not allowed"; a reload: "local player is disabled", "not ready") move an intent instead of reaching the page; the screen shows that song, waiting. Whatever recovers playback (the ad recovery, any reload, the end of the ad) plays the intent, not the song after the last state seen; skips made meanwhile move it and the newest wins. A plain next is remembered too: if the page goes into an ad break instead, that song is asked for again after it. "Previous" refused during an ad is held, never turned into a seek (which restarted the ad).
+- **Ad breaks**: the watcher wakes as soon as an ad starts (its recovery starts after 1 s, no longer up to a 2 s tick later).
+- **Tests**: `tools/playback_test.py` fakes an ad in the page (`ad_taps`, `ad_previous`) and reloads it under taps (`reload_taps`), and checks that the app's media session shows the song that plays.
+
## 2.0.0-beta.8
- **SpotiFLAC**: when it is not verified (or the verification lapsed), Downloads and any download open the verification first, then the songs download; its page is full screen (Retry and Skip were hidden under the mini player); sessions follow SpotiFLAC Mobile's rules (renewed once, in their last hour, and a download refused because another one just renewed it is sent again), so many downloads at once no longer end the verification; you are told when it must be done again.
diff --git a/docs/spotiflac-research.md b/docs/spotiflac-research.md
index c2bdda1d..351af6ee 100644
--- a/docs/spotiflac-research.md
+++ b/docs/spotiflac-research.md
@@ -4,7 +4,7 @@ Recherche du 16/10/2026, sources : spotbye/SpotiFLAC v7.2.2 (desktop, Go+Wails,
spotiflacapp/SpotiFLAC-Mobile (Flutter+Rust, MIT), Spotui v1.6 (clone GPL-3 vendored `/tmp/spotui-vendor`),
vérifications réseau live des endpoints le jour même.
-## Décisions Dani
+## Décisions
- SpotiFLAC pour tous les téléchargements, **pas de YouTube** (plus de source YT).
- Sans match FLAC → **indisponible** (comportement actuel conservé).
- Qualité (16/24) = préférence utilisateur : onboarding + paramètre (comme les réglages data saver).
@@ -43,7 +43,7 @@ vérifications réseau live des endpoints le jour même.
par ISRC (AudioAlign, score ≥ 0,5) rejette le même enregistrement qu'aujourd'hui.
- **DASH-BTS multi-segments** (les manifestes `{url:[...]}`) : soit single-file seulement
(choix Spotui v1.6), soit porter le remux `downloadDashFlacToFile` (fLaC + STREAMINFO + payloads
- mdat, sans ffmpeg) pour débloquer HI_RES 24-bit — recommandé puisque Dani veut la qualité.
+ mdat, sans ffmpeg) pour débloquer HI_RES 24-bit — recommandé puisque la qualité est voulue.
- **Erreurs** (protocole officiel) : 429/502/504 → retry ×3 Retry-After clamp(1,300 s) ; 401
SESSION_INVALID → effacer la session + re-bootstrap ; 428 VERIFY_REQUIRED → relancer la WebView ;
403 → 1 essai avec session rafraîchie. Status API `spotbye.qzz.io/api/status` (fail-open).
diff --git a/docs/wrapped-playback-analysis.md b/docs/wrapped-playback-analysis.md
index 6f4366a0..5e4a1df3 100644
--- a/docs/wrapped-playback-analysis.md
+++ b/docs/wrapped-playback-analysis.md
@@ -39,7 +39,7 @@ SemanticMetric / KmPageView — analytics produit, pas de comptage d'écoute.
honnêtement dans le README (« no altered listening events » → « real listens
only, no fabricated events »).
-## Décisions ouvertes (posées à Dani le 16/10, sans réponse)
+## Décisions ouvertes (posées le 16/10, sans réponse)
1. Niveau d'honnêteté : écoutes réelles seules / + queue offline / match parfait des shapes.
2. sub_state qualité : reproduire 128k/HIGH/format 10 (comme le Web Player) ou valeurs réelles FLAC.
diff --git a/tools/capture.sh b/tools/capture.sh
index 5fe61ed6..90aa2149 100755
--- a/tools/capture.sh
+++ b/tools/capture.sh
@@ -3,7 +3,7 @@
# usage: tools/capture.sh <name> (stop with: touch tools/captures/<name>.stop)
set -u
ADB=${ADB:-$HOME/android-sdk/platform-tools/adb}
-SERIAL=${SERIAL:-adb-R3CX80NDH7F-gtly5q._adb-tls-connect._tcp}
+SERIAL=${SERIAL:-$("$ADB" devices | awk 'NR==2 && $2=="device"{print $1}')} # first device unless SERIAL is set
NAME=${1:-session}
OUT="$(dirname "$0")/captures/$NAME"
mkdir -p "$OUT"; rm -f "$OUT.stop"
diff --git a/tools/cdp.py b/tools/cdp.py
index 7889ab01..35da76f9 100644
--- a/tools/cdp.py
+++ b/tools/cdp.py
@@ -73,6 +73,10 @@ def main():
ap.add_argument("--serial")
ap.add_argument("--trace", type=float, default=0, help="seconds of Network tracing after evaluating expr")
ap.add_argument("--bodies", default="", help="regex: print request/response bodies for matching URLs (trace mode)")
+ ap.add_argument("--headers", action="store_true",
+ help="trace mode: print the headers of every spotify.com request, as the browser really "
+ "sends them (Network.requestWillBeSentExtraInfo), with the tells that matter: "
+ "X-Requested-With (the app's own package name), Sec-Fetch-*, client hints, language")
ap.add_argument("--click", default="", help="CSS selector: dispatch a trusted mouse click on its center")
ap.add_argument("expr", nargs="?", default="0")
a = ap.parse_args()
@@ -130,6 +134,21 @@ def main():
body = r.get("postData")
if body and body_re and body_re.search(r["url"]):
print(" >>", reqs[p["requestId"]], body[:2000])
+ elif m == "Network.requestWillBeSentExtraInfo":
+ if not a.headers:
+ continue
+ h = {k.lower(): v for k, v in (p.get("headers") or {}).items()}
+ url = reqs.get(p.get("requestId"), "")
+ if "spotify.com" not in url and "scdn.co" not in url:
+ continue
+ shown = [f"xrw={'YES' if 'x-requested-with' in h else 'no'}"]
+ for k in ("x-requested-with", "sec-fetch-site", "sec-fetch-mode", "sec-fetch-dest",
+ "accept-language", "referer", "origin", "sec-ch-ua", "sec-ch-ua-mobile",
+ "sec-ch-ua-platform", "client-token", "spotify-app-version", "app-platform"):
+ if k in h:
+ shown.append(f"{k}={h[k][:60]}")
+ shown.append("auth=" + ("yes" if "authorization" in h else "no"))
+ print("HDR", url.split("?")[0][:95], "|", " ".join(shown))
elif m == "Network.responseReceived":
print("HTTP", p["response"]["status"], reqs.get(p["requestId"], p["response"]["url"][:110]))
elif m == "Network.loadingFinished" and body_re and body_re.search(reqs.get(p["requestId"], "")):
diff --git a/tools/playback_test.py b/tools/playback_test.py
index d23bd371..d670b8a9 100644
--- a/tools/playback_test.py
+++ b/tools/playback_test.py
@@ -113,8 +113,27 @@ PROBE = """(async () => {
})()"""
-def probe():
- return evaluate(PROBE, timeout=15)
+def probe(patience=12):
+ """The page's state; retried for [patience] s while the page reloads (no bridge yet).
+
+ A missing track is normal: during an ad (and right after a reload) the app publishes no item at
+ all. Callers read `p["track"]["uri"]`, so an empty track dict is put in its place instead of
+ None — a test that crashes on an ad tells us nothing about the app.
+ """
+ end = time.time() + patience
+ while True:
+ try:
+ p = evaluate(PROBE, timeout=15)
+ if not isinstance(p.get("track"), dict):
+ p["track"] = {}
+ for k in ("uri", "name", "kind"):
+ p["track"].setdefault(k, None)
+ p["track"].setdefault("durationMs", 0)
+ return p
+ except Exception:
+ if time.time() > end:
+ raise
+ time.sleep(1)
# ── log ───────────────────────────────────────────────────────────────────────
@@ -187,7 +206,7 @@ class Run:
print(f" ad: {name(p)!r}, waiting it out")
end = time.time() + budget
while time.time() < end:
- if isinstance(p.get("media"), dict) and not p["media"]["muted"] and not p["media"]["paused"] and p["media"]["volume"] > 0 and p.get("volume", 0) not in (0, 0.0):
+ if isinstance(p.get("media"), dict) and not p["media"]["muted"] and not p["media"]["paused"] and p["media"]["volume"] > 0.01 and p.get("volume", 0) not in (0, 0.0):
raise Fail(f"ad {name(p)!r} audible (media not muted)")
time.sleep(1)
p = probe()
@@ -454,8 +473,88 @@ def pull_back_from(r, remote):
devices = bridge("service.call", {"service": "ConnectDevicesAPI", "method": "getDevices", "args": []})
if not any(d.get("isActive") and d.get("isLocal") for d in devices):
raise Fail("pull back: this phone is not the active device")
+ # The 'taken by' line is NOT required: a resume sent while the other device still holds playback
+ # makes the page claim playback here, and then no pull back is needed at all. What matters is the
+ # outcome — this phone active, the sound playing — which is what the checks above assert. Keep the
+ # line only as a note, so the fast path stays visible in the report instead of failing the run.
if not any("taken by" in l for l in r.log.lines[-400:]):
- raise Fail("pull back: the app did not see the other device")
+ r.notes.append(f"pull back from {remote['name']}: the resume claimed playback (no pull-back line)")
+
+
+def ui_title():
+ """The title the app shows (its media session: notification, lock screen)."""
+ out = adb("shell", "dumpsys", "media_session")
+ block = out.split("package=" + PKG, 1)[1] if ("package=" + PKG) in out else ""
+ m = re.search(r"description=(.*)", block)
+ return m.group(1).strip() if m else ""
+
+
+def same_on_screen(r, label):
+ """What is heard is what the app shows."""
+ p = probe()
+ shown = ui_title()
+ if not p.get("track") or not shown.startswith(p["track"]["name"]):
+ raise Fail(f"{label}: the app shows {shown!r} while {name(p)!r} plays")
+
+
+FAKE_AD = """(() => { try {
+ const host = document.getElementById('main') || document.body;
+ let plat = null;
+ for (const el of [host, ...host.querySelectorAll('*')]) { const key = Object.keys(el).find(k => k.startsWith('__reactContainer$')); if (!key) continue;
+ const stack = [el[key]]; while (stack.length && !plat) { const f = stack.pop(); const v = f.memoizedProps && f.memoizedProps.value;
+ if (v && typeof v === 'object' && typeof v.getRegistry === 'function') plat = v; if (f.sibling) stack.push(f.sibling); if (f.child) stack.push(f.child); } if (plat) break; }
+ const r = plat.getRegistry(); let pl = null; for (const k of r._map.keys()) if (k && k.description === 'PlayerAPI') pl = r.resolve(k);
+ // The page's state now says an ad plays (as Spotify's own ad items look); the page reload
+ // that the app's ad recovery does drops this patch.
+ const orig = pl.getState.bind(pl);
+ pl.getState = () => { const s = orig(); return s && Object.assign({}, s, { item: Object.assign({}, s.item, { type: 'ad', uri: 'spotify:ad:test', name: 'Test ad' }) }); };
+ window.Myspoti.announce();
+ return true;
+} catch (e) { return String(e && e.stack || e).slice(0, 600); } })()"""
+
+
+def s_ad_taps(r, ctx):
+ r.healthy(None, "before the ad", allow_track_change=True)
+ p = probe()
+ exp = p["upcoming"][2] if len(p["upcoming"]) > 2 else None
+ fake_ad()
+ time.sleep(0.2)
+ key([NEXT] * 3) # three fast taps while the ad is on
+ r.healthy(exp, "3 nexts during an ad", settle=40)
+ same_on_screen(r, "after the ad")
+
+
+def fake_ad():
+ for _ in range(5):
+ res = evaluate(FAKE_AD)
+ if res is True:
+ return
+ print(" fake ad not set:", res)
+ time.sleep(2)
+ raise Fail("could not fake an ad in the page")
+
+
+def s_ad_previous(r, ctx):
+ r.healthy(None, "before the ad", allow_track_change=True)
+ cur = probe()["track"]["uri"]
+ seek_to(r, 60_000)
+ fake_ad()
+ time.sleep(0.2)
+ key(PREV) # refused by the page during an ad: kept, never a seek on the ad
+ b = r.healthy(cur, "previous during an ad", settle=40)
+ if b["pos"] > 15_000:
+ raise Fail(f"previous during an ad: the song did not start over (at {b['pos']} ms)")
+ same_on_screen(r, "after the ad")
+
+
+def s_reload_taps(r, ctx):
+ p = probe()
+ exp = p["upcoming"][1] if len(p["upcoming"]) > 1 else None
+ fire("location.reload()")
+ time.sleep(0.3)
+ key([NEXT] * 2) # two fast taps while the page reloads
+ r.healthy(exp, "2 nexts during a reload", settle=45)
+ same_on_screen(r, "after the reload")
SCENARIOS = [
@@ -469,6 +568,9 @@ SCENARIOS = [
("song_end", s_song_end, ()),
("mute", s_mute, ()),
("reload", s_reload, ()),
+ ("reload_taps", s_reload_taps, ("transport failed",)),
+ ("ad_taps", s_ad_taps, ()),
+ ("ad_previous", s_ad_previous, ()),
("frozen", s_frozen, ("call timeout", "page not answering", "command failed", "transport failed")),
("background", s_background, ()),
("cold_start", s_cold_start, ()),
diff --git a/tools/ui_smoke.py b/tools/ui_smoke.py
new file mode 100644
index 00000000..d94deb75
--- /dev/null
+++ b/tools/ui_smoke.py
@@ -0,0 +1,136 @@
+#!/usr/bin/env python3
+"""Walks through the app's screens on a phone and fails on a crash, an ANR or the app leaving.
+
+usage: tools/ui_smoke.py [--serial S] [--depth 2] [--max 120]
+
+From each screen it opens every element that can be tapped (read from uiautomator), one by
+one, then comes back. Never taps what could change the account, the library or the settings
+(see DENY: like, follow, add, remove, delete, download, log out, switches...), nor anything
+that leaves the app on purpose (share, open in browser). Debug build app.myspoti.dev.
+"""
+import argparse, os, re, subprocess, sys, time
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import playback_test as t # noqa: E402
+
+PKG = t.PKG
+# Words (English and French, the phone's languages) of elements never tapped.
+DENY = re.compile(r"(log ?out|sign ?out|déconnex|se déconnecter|delete|supprim|remove|retir|effac|clear|reset|réinitialis|"
+ r"like|j'aime|aimé|follow|suivre|abonn|unfollow|ban|bloquer|ne pas jouer|add|ajout|download|télécharg|"
+ r"share|partag|report|signal|buy|achet|pay|donat|don\b|sponsor|ko-fi|github|discord|reddit|privacy|"
+ r"open in|ouvrir dans|navigateur|browser|spotify app|install|update|mettre à jour|quit|quitter|"
+ r"jam|appareil|device|connect|lecture aléatoire|shuffle|repeat|répét|minuteur|sleep|timer|"
+ r"vidéo|video|canvas|paroles|lyrics|enreg|record|notifications?$)", re.I)
+
+
+def adb(*a, check=False):
+ return t.adb(*a, check=check)
+
+
+def nodes():
+ adb("shell", "uiautomator", "dump", "/sdcard/msp-ui.xml")
+ xml = adb("shell", "cat", "/sdcard/msp-ui.xml")
+ out = []
+ for m in re.finditer(r"<node [^>]*>", xml):
+ n = m.group(0)
+ get = lambda k: (re.search(fr' {k}="([^"]*)"', n) or [None, ""])[1]
+ if get("package") != PKG or get("clickable") != "true" or get("checkable") == "true":
+ continue
+ label = (get("text") or get("content-desc")).strip()
+ b = re.findall(r"\d+", get("bounds"))
+ if len(b) != 4:
+ continue
+ x1, y1, x2, y2 = map(int, b)
+ if x2 - x1 < 8 or y2 - y1 < 8:
+ continue
+ out.append((label, (x1 + x2) // 2, (y1 + y2) // 2))
+ return out
+
+
+def foreground():
+ return PKG in adb("shell", "dumpsys", "window", "displays").split("mCurrentFocus", 1)[-1][:200]
+
+
+class Smoke:
+ def __init__(self, log, max_taps):
+ self.log = log
+ self.max = max_taps
+ self.taps = 0
+ self.seen = set()
+ self.problems = []
+
+ def check(self, what):
+ bad = [l for l in self.log.since(self.mark) if "FATAL EXCEPTION" in l or f"ANR in {PKG}" in l or "AndroidRuntime" in l]
+ if bad:
+ self.problems.append(f"{what}: " + " | ".join(bad[:3]))
+ if "Application Error" in adb("shell", "dumpsys", "window", "displays"):
+ self.problems.append(f"{what}: crash dialog")
+ adb("shell", "input", "keyevent", "4")
+
+ def back_to(self, screen_sig):
+ for _ in range(3):
+ if not foreground():
+ t.launch()
+ time.sleep(3)
+ if signature() == screen_sig:
+ return True
+ adb("shell", "input", "keyevent", "4")
+ time.sleep(1.2)
+ return signature() == screen_sig
+
+ def walk(self, depth, path):
+ here = signature()
+ for label, x, y in nodes():
+ if self.taps >= self.max:
+ return
+ key = (here, label)
+ if not label or key in self.seen or DENY.search(label):
+ continue
+ self.seen.add(key)
+ self.mark = self.log.mark()
+ self.taps += 1
+ print(f" [{self.taps}] {' > '.join(path + [label])[:110]}")
+ adb("shell", "input", "tap", str(x), str(y))
+ time.sleep(1.8)
+ self.check(" > ".join(path + [label]))
+ if not foreground():
+ self.problems.append(f"{' > '.join(path + [label])}: the app left the screen")
+ t.launch()
+ time.sleep(3)
+ elif depth > 1 and signature() != here:
+ self.walk(depth - 1, path + [label])
+ if not self.back_to(here):
+ return
+
+
+def signature():
+ """A screen, as the set of its tappable labels."""
+ return tuple(sorted({l for l, _, _ in nodes() if l}))[:40]
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--serial")
+ ap.add_argument("--depth", type=int, default=2)
+ ap.add_argument("--max", type=int, default=120)
+ a = ap.parse_args()
+ t.SERIAL = a.serial
+ adb("shell", "input", "keyevent", "224")
+ if "mDreamingLockscreen=true" in adb("shell", "dumpsys", "window") or "isKeyguardShowing=true" in adb("shell", "dumpsys", "window", "policy"):
+ sys.exit("unlock the phone first")
+ log = t.Log()
+ t.launch()
+ time.sleep(4)
+ s = Smoke(log, a.max)
+ s.mark = log.mark()
+ s.walk(a.depth, [])
+ s.check("end")
+ log.stop(os.path.join(os.path.dirname(os.path.abspath(__file__)), "captures", "ui_smoke.log"))
+ print(f"{s.taps} taps")
+ for p in s.problems:
+ print("PROBLEM", p)
+ sys.exit(1 if s.problems else 0)
+
+
+if __name__ == "__main__":
+ main()