Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
Sign in once, and stay where you were
Lelonio239bee751f2f
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.ktindex b32c86c..9b4ad32 100644--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt@@ -31,6 +31,19 @@ class SquareApplication : Application() {}val tokenStore: TokenStore by lazy { TokenStore(this) }++ /**+ * Whether Spotify can be used, which is not the same as holding a token.+ *+ * The engine keeps the credential the access point gave it and logs in with+ * that, so an OAuth session that has lapsed is no longer a reason to show+ * the login screen: everything the app plays goes through the access point,+ * and the access point is still answering. Only the Web API, which is the+ * user's own registered application, needs the token itself.+ */+ val spotifySignedIn: Boolean+ get() = tokenStore.isLoggedIn ||+ dev.lelonio.square.auth.EngineCredentials.exist(this)val recentStore: RecentStore by lazy { RecentStore(this) }/** Which playlists were opened most recently, for ordering the home page. */diff --git a/app/src/main/java/dev/lelonio/square/auth/EngineCredentials.kt b/app/src/main/java/dev/lelonio/square/auth/EngineCredentials.ktnew file mode 100644index 0000000..84cbcd4--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/auth/EngineCredentials.kt@@ -0,0 +1,37 @@+package dev.lelonio.square.auth++import android.content.Context+import java.io.File++/**+ * The credential the access point issued for this device, as seen from Kotlin.+ *+ * Signing in is an OAuth flow, but staying signed in is not. The token that flow+ * hands back lives an hour, and the refresh token behind it is rotated on every+ * use and revoked on the first one that goes wrong, so an app that needs OAuth+ * at every launch is one bad refresh away from an empty login screen. The blob+ * the access point answers a successful handshake with has neither limit: the+ * native side keeps it and logs in with it from then on.+ *+ * This is the Kotlin half of that: whether the engine can authenticate on its+ * own. It is the difference between "the OAuth session has lapsed, ask the user+ * to sign in" and "the OAuth session has lapsed, and playback carries on".+ */+object EngineCredentials {++ /** Where librespot keeps its own copy; the native side is given this path. */+ fun dir(context: Context): File = context.filesDir.resolve("librespot")++ /** True when the engine has a credential of its own to log in with. */+ fun exist(context: Context): Boolean =+ dir(context).resolve(KEPT).resolve(FILE).isFile++ /** Dropped along with the OAuth session, so signing out really signs out. */+ fun clear(context: Context) {+ dir(context).deleteRecursively()+ }++ /** Matches the directory the native side keeps the reusable blob in. */+ private const val KEPT = "reusable"+ private const val FILE = "credentials.json"+}diff --git a/app/src/main/java/dev/lelonio/square/auth/TokenStore.kt b/app/src/main/java/dev/lelonio/square/auth/TokenStore.ktindex 3539d0c..7fc58ed 100644--- a/app/src/main/java/dev/lelonio/square/auth/TokenStore.kt+++ b/app/src/main/java/dev/lelonio/square/auth/TokenStore.kt@@ -4,6 +4,9 @@ import android.content.Contextimport android.content.SharedPreferencesimport androidx.security.crypto.EncryptedSharedPreferencesimport androidx.security.crypto.MasterKey+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.asSharedFlowimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLock@@ -39,7 +42,29 @@ class TokenStore(EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,)- private val refreshLock = Mutex()+ /**+ * Shared by every store over the same file, not owned by this instance.+ *+ * The container hands out one store and that is how it should stay, but a+ * second instance is a single line to write and its cost is invisible until+ * days later: two locks are no lock, both callers refresh the same token,+ * and whichever loses is told the session was revoked. Keying the lock on+ * the file makes the guarantee belong to the tokens rather than to whoever+ * remembered to reuse the object.+ */+ private val refreshLock = lockFor(fileName)++ private val _sessionLost = MutableSharedFlow<Unit>(extraBufferCapacity = 1)++ /**+ * Emitted when a stored session is dropped because Spotify refused it.+ *+ * Something has to say so out loud. A session that ends quietly leaves the+ * app answering nothing and looking like it is merely slow, and the way back+ * in is a screen the user has to go looking for. Told about it, the app can+ * offer the one tap that fixes it.+ */+ val sessionLost: SharedFlow<Unit> = _sessionLost.asSharedFlow()/*** True when a request can be authenticated right now.@@ -108,6 +133,7 @@ class TokenStore(// recognise it: otherwise every later attempt retries the same// revoked token forever and the app never offers a way back in.clear()+ _sessionLost.tryEmit(Unit)throw e}save(tokens)@@ -129,5 +155,11 @@ class TokenStore(/** Refresh early so a token cannot expire mid-request. */const val SKEW_MILLIS = 60_000L++ private val locks = mutableMapOf<String, Mutex>()++ fun lockFor(fileName: String): Mutex = synchronized(locks) {+ locks.getOrPut(fileName) { Mutex() }+ }}}diff --git a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.ktindex c25766b..8100ef1 100644--- a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt+++ b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt@@ -35,7 +35,7 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {override val id = BackendId.SPOTIFYprivate val _authState = MutableStateFlow<BackendAuthState>(- if (container.tokenStore.isLoggedIn) BackendAuthState.Connecting else BackendAuthState.LoggedOut,+ if (container.spotifySignedIn) BackendAuthState.Connecting else BackendAuthState.LoggedOut,)override val authState: StateFlow<BackendAuthState> = _authState.asStateFlow()@@ -46,10 +46,10 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {* session every catalogue call would fail against.*/override val isReady: Boolean- get() = container.tokenStore.isLoggedIn && NativeBridge.isConnected+ get() = container.spotifySignedIn && NativeBridge.isConnectedoverride suspend fun refreshAuth() {- if (!container.tokenStore.isLoggedIn) {+ if (!container.spotifySignedIn) {_authState.value = BackendAuthState.LoggedOutreturn}diff --git a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.ktindex aa9c9a2..1a7ae1c 100644--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt@@ -74,10 +74,6 @@ class LibrespotPlayer(// screen would be someone else's.val asContext = queue.contextIsOrdered && !queue.isShuffled- android.util.Log.i(- "SquarePlayer",- "load ${uris.size} tracks at $index (playing=$startPlaying, context=$asContext)",- )fadeOutThen {// Back on the player's looper before anything is read or called.// The fade runs on its own thread, and everything here — the queue,@@ -491,7 +487,6 @@ class LibrespotPlayer(skipPending = falseval target = queue.currentIndexval from = engineIndex- android.util.Log.i("SquarePlayer", "skip settles: engine at $from, wanted $target")when {from == target -> {@@ -576,6 +571,15 @@ class LibrespotPlayer(// anyway would talk over it.if (!focus.requestFocus()) return Futures.immediateVoidFuture()wantPlay = true+ // Pressed before there is an engine to press it on. Remembered+ // rather than sent: the queue goes over the moment the access point+ // answers, and it goes over playing.+ if (awaitingEngine) {+ playbackState = Player.STATE_BUFFERING+ onPlaybackActive(true)+ invalidateState()+ return Futures.immediateVoidFuture()+ }onPlaybackActive(true)// Play is where a reconnection is worth waiting for. The engine has// no queue of its own, so a rebuilt device knows nothing until the@@ -791,6 +795,14 @@ class LibrespotPlayer(invalidateState()}+ /**+ * True while the queue on screen is one the engine has not been given yet.+ *+ * See [restore]: the saved queue is put back before there is an access point+ * to hand it to, so this is the window between the two.+ */+ private var awaitingEngine = false+fun restore(tracks: List<PlayQueue.Track>,shuffleOrder: List<Int>?,@@ -801,6 +813,18 @@ class LibrespotPlayer(contextUri: String?,contextIsOrdered: Boolean,contextLabel: String,+ /**+ * Whether the engine can be handed the queue now.+ *+ * False when the app has only just started. Authenticating takes a+ * handshake and a catalogue call, and none of that is a reason to leave+ * the screen blank in the meantime: what was paused is known from disk,+ * so it is put back straight away and shown as loading, and+ * [handOverToEngine] gives it to the access point once there is one.+ * The alternative, which is what this used to do, was an app that came+ * back looking as though nothing had ever been playing.+ */+ handOverNow: Boolean = true,) {if (tracks.isEmpty()) return@@ -820,7 +844,11 @@ class LibrespotPlayer(this.positionMs = positionMsplayWhenReady = falsewantPlay = false- playbackState = Player.STATE_READY+ awaitingEngine = !handOverNow+ // Loading, not ready: there is a track and a position to show, and+ // nothing that could answer a tap on play yet. Buffering is what the+ // mini player already draws a spinner for.+ playbackState = if (handOverNow) Player.STATE_READY else Player.STATE_BUFFERINGonQueueChanged()// Paused: an app that starts playing by itself when opened is worse@@ -830,12 +858,32 @@ class LibrespotPlayer(// done here at all when there is nothing to restore — activating on// launch would pull playback away from whatever the account is actually// playing on.- if (queue.items.isNotEmpty()) {+ if (queue.items.isNotEmpty() && handOverNow) {pushQueue(startPlaying = false, positionMs = positionMs.toInt())}invalidateState()}+ /**+ * Gives the engine the queue that was put back before it existed.+ *+ * Carries [wantPlay] with it, so a listener who pressed play while the app+ * was still connecting gets the track they asked for rather than a button+ * that did nothing.+ */+ fun handOverToEngine() {+ if (!awaitingEngine) return+ awaitingEngine = false+ if (queue.items.isEmpty()) {+ playbackState = Player.STATE_IDLE+ invalidateState()+ return+ }+ playbackState = if (wantPlay) Player.STATE_BUFFERING else Player.STATE_READY+ pushQueue(startPlaying = wantPlay, positionMs = positionMs.toInt())+ invalidateState()+ }+/*** Takes on a queue the engine is already playing.*@@ -962,7 +1010,6 @@ class LibrespotPlayer(val next = queue.currentIndex + 1if (!engineQueueStale || next > queue.items.lastIndex) return falseif (!queue.items[next].queued) return false- android.util.Log.i("SquarePlayer", "taking over for a queued track at $next")requestSkipTo(next, 0L)return true}@@ -1004,10 +1051,6 @@ class LibrespotPlayer(// those is a load with no play. Following only plays left// the app three songs behind what was in the speaker,// which is exactly how the two came apart.- android.util.Log.i(- "SquarePlayer",- "following the engine to $index ($type), screen was at ${queue.currentIndex}",- )queue.currentIndex = indexskipInFlight = falsepositionMs = 0diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.ktindex 2015e65..2d099bf 100644--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt@@ -73,9 +73,14 @@ class PlaybackService : MediaLibraryService() {override fun onCreate() {super.onCreate()- tokens = TokenStore(this)playbackStore = PlaybackStore(this)container = application as dev.lelonio.square.SquareApplication+ // The container's own store, not one of this service's making. Two+ // instances mean two refresh locks, so the screen and the engine could+ // refresh the same token at once: Spotify retires it as it issues the+ // next, the slower of the two is told the session is revoked, and the+ // user is asked to sign in again for no reason at all.+ tokens = container.tokenStorequality = container.qualitycrossfade = container.crossfade@@ -145,6 +150,16 @@ class PlaybackService : MediaLibraryService() {// returns at once once the file is open.AudioEffects.load(this)+ // What was paused, back on screen before anything is authenticated.+ //+ // Connecting is a handshake and a catalogue call, and on a cold start+ // that is seconds. Waiting for it meant the app came back with an empty+ // player, as if nothing had ever been playing, and the track appeared+ // only once the access point answered. The queue is on disk, so it goes+ // up straight away and shows as loading; the engine is given it in+ // `connectEngine`.+ restoreQueue(handOverNow = false)+// The bitrate is fixed when the player is built, so a change means a new// engine. Watched here rather than acted on from the settings screen:// the service owns the engine's lifetime, and it is the only place that@@ -539,14 +554,25 @@ class PlaybackService : MediaLibraryService() {// Guards against the repeated ACTION_CONNECT the UI may send: the native// side rejects a second start, and that error would look like a login// failure and clear a perfectly good session.- if (engineStarted || !tokens.isLoggedIn) return@launch+ if (engineStarted || !container.spotifySignedIn) return@launch// Nothing to authenticate against while another backend is playing, and// starting the engine would take the audio device out from under it.val engine = librespot ?: return@launchengineStarted = truerunCatching {- val accessToken = tokens.validAccessToken()+ // Empty is a real answer here. The engine keeps the credential the+ // access point issued and prefers it, so a token is only needed by a+ // device logging in for the first time: refusing to start without+ // one would throw away a session that works because the OAuth half+ // of it, which playback does not use, has lapsed.+ val kept = dev.lelonio.square.auth.EngineCredentials.exist(this@PlaybackService)+ val accessToken = runCatching { tokens.validAccessToken() }+ .getOrElse { error ->+ if (!kept) throw error+ android.util.Log.w(TAG, "no token, logging in with the kept credential", error)+ ""+ }withContext(Dispatchers.IO) {NativeBridge.start(// Must match the id the OAuth token was minted for.@@ -579,21 +605,22 @@ class PlaybackService : MediaLibraryService() {}.onFailure { error ->engineStarted = falseandroid.util.Log.e(TAG, "engine start failed: $error", error)- // The access point rejecting the token means the session is no- // longer usable, so send the user back through OAuth rather than- // retrying with the same credentials. A revoked refresh token is- // already cleared by TokenStore before it gets here.+ // Only a refused account ends the session here. Everything else the+ // handshake can fail with — no network, an access point that is+ // busy, a dealer that dropped — is temporary, and signing the user+ // out over it costs them their session for a failure that would+ // have fixed itself on the next attempt. A refresh token Spotify+ // really has revoked is cleared by TokenStore before it gets here.if (error.message?.contains(PREMIUM_REQUIRED) == true) {// Back to the login screen, with a reason. Staying signed in// would leave an app that looks connected and plays nothing.tokens.clear()+ dev.lelonio.square.auth.EngineCredentials.clear(this@PlaybackService)android.widget.Toast.makeText(this@PlaybackService,getString(dev.lelonio.square.R.string.premium_required),android.widget.Toast.LENGTH_LONG,).show()- } else if (error.message?.contains("login failed") == true) {- tokens.clear()}}.onSuccess {android.util.Log.i(TAG, "engine connected")@@ -609,9 +636,14 @@ class PlaybackService : MediaLibraryService() {* something and only then did the engine finish connecting, and overwriting* that would be worse than not restoring at all.*/- private fun restoreQueue() {+ private fun restoreQueue(handOverNow: Boolean = true) {val engine = librespot ?: return- if (player.mediaItemCount > 0) return+ if (player.mediaItemCount > 0) {+ // Already on screen from the early restore; all that is left is to+ // give it to the engine that has just come up.+ if (handOverNow) engine.handOverToEngine()+ return+ }val saved = playbackStore.load() ?: return// Spotify's own queue only. The store holds whichever source was last// playing, and handing librespot a queue of `ytmusic:` URIs would fill@@ -629,6 +661,7 @@ class PlaybackService : MediaLibraryService() {contextUri = saved.contextUri,contextIsOrdered = saved.contextOrdered,contextLabel = saved.contextLabel,+ handOverNow = handOverNow,)android.util.Log.i(TAG, "restored ${saved.tracks.size} tracks at ${saved.index}")}@@ -847,6 +880,35 @@ class PlaybackService : MediaLibraryService() {override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaLibrarySession? =session+ /**+ * Stays in the foreground while paused, which Media3 does not do on its own.+ *+ * Pausing makes it call this with `false`, the service drops out of the+ * foreground, and the notification is left attached to a process the system+ * is now free to reclaim. It usually does, within minutes, and what the+ * listener sees is the shade quietly emptying: the track they paused is+ * gone, and with it the one control that would have resumed it.+ *+ * Media playback is exactly what this kind of service is for, and the way+ * out of it is still the obvious one: swiping the app away stops the service+ * in [onTaskRemoved], which is where a paused session really should end.+ */+ override fun onUpdateNotification(session: MediaSession, startInForegroundRequired: Boolean) {+ // Kept rather than started. A foreground service may only be started+ // from the foreground, and this is also called for a service brought up+ // in the background — a media button, the car binding — where forcing it+ // would be the system refusing and taking the process with it. Staying+ // in a state already entered legitimately is always allowed.+ if (startInForegroundRequired) heldForeground = true+ super.onUpdateNotification(+ session,+ startInForegroundRequired || (heldForeground && player.mediaItemCount > 0),+ )+ }++ /** Whether playback has put this service in the foreground at least once. */+ private var heldForeground = false+override fun onTaskRemoved(rootIntent: Intent?) {// Saved first: this is the last chance to record where the track was,// and stopping is what makes the position worth having.diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.ktindex 6048ab7..4102e37 100644--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt@@ -121,7 +121,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {private var playlistJob: Job? = nullprivate val _state = MutableStateFlow<UiState>(- if (container.tokenStore.isLoggedIn) UiState.Connecting else UiState.LoggedOut,+ if (container.spotifySignedIn) UiState.Connecting else UiState.LoggedOut,)val state: StateFlow<UiState> = _state.asStateFlow()@@ -747,6 +747,15 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {val error: String? = null,/** What the user must register as a redirect URI in their dashboard. */val redirectUri: String = SpotifyOAuth.REDIRECT_URI,+ /**+ * Set when Spotify has refused the stored session, so the app can say+ * so and offer the way back in.+ *+ * The client id is already known and does not expire, so signing in+ * again is one tap: nothing has to be pasted or registered a second+ * time.+ */+ val expired: Boolean = false,)private val _webApi = MutableStateFlow(@@ -757,6 +766,23 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {)val webApi: StateFlow<WebApiState> = _webApi.asStateFlow()+ init {+ // Only worth saying while there is a client id to sign in with again:+ // an account that was never connected has its own setup card, and a+ // notice about a session that expired would be about nothing.+ viewModelScope.launch {+ container.webApi.tokens.sessionLost.collect {+ if (container.webApi.clientId.value == null) return@collect+ _webApi.value = _webApi.value.copy(connected = false, expired = true)+ }+ }+ }++ /** The notice is dismissed by hand; search and the feed keep working without it. */+ fun dismissWebApiExpiry() {+ _webApi.value = _webApi.value.copy(expired = false)+ }+fun onWebApiClientIdChange(value: String) {_webApi.value = _webApi.value.copy(clientId = value, error = null)}@@ -775,7 +801,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {return@launch}- _webApi.value = _webApi.value.copy(connecting = true, error = null)+ _webApi.value = _webApi.value.copy(connecting = true, error = null, expired = false)container.webApi.setClientId(clientId)runCatching {// Search needs no scope — it reads public catalogue data — but the@@ -874,7 +900,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {if (container.activeBackend.id != BackendId.SPOTIFY) {// No engine to authenticate, so nothing to send the service.refresh()- } else if (container.tokenStore.isLoggedIn) {+ } else if (container.spotifySignedIn) {PlaybackService.connect(app)refresh()}@@ -898,6 +924,9 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {fun logOut() {container.tokenStore.clear()+ // The engine's own credential too, or the next launch would log itself+ // back in with it and signing out would mean nothing.+ dev.lelonio.square.auth.EngineCredentials.clear(getApplication())container.recentStore.clear()container.playlistOrder.clear()// Somebody else's library must not be sitting in the cache when the@@ -920,7 +949,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {_search.value = SearchState()_youtubeHome.value = YouTubeHomeState()_state.value = UiState.Loading- if (container.activeBackend.id == BackendId.SPOTIFY && container.tokenStore.isLoggedIn) {+ if (container.activeBackend.id == BackendId.SPOTIFY && container.spotifySignedIn) {PlaybackService.connect(getApplication())}refresh()@@ -963,14 +992,14 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {return@launch}- if (!container.tokenStore.isLoggedIn) {+ if (!container.spotifySignedIn) {_state.value = UiState.LoggedOutreturn@launch}_state.value = UiState.Connectingif (!awaitEngine()) {- _state.value = if (container.tokenStore.isLoggedIn) {+ _state.value = if (container.spotifySignedIn) {UiState.Failed(string(R.string.cannot_connect))} else {UiState.LoggedOut@@ -1587,7 +1616,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {// this check the UI would sit on "connecting" for the full timeout// and then report a connection problem, when the real answer is// that the user has to log in again.- if (!container.tokenStore.isLoggedIn) return@withTimeoutOrNull false+ if (!container.spotifySignedIn) return@withTimeoutOrNull falsedelay(POLL_INTERVAL_MS)}truediff --git a/app/src/main/java/dev/lelonio/square/ui/SessionNotice.kt b/app/src/main/java/dev/lelonio/square/ui/SessionNotice.ktnew file mode 100644index 0000000..b37ef59--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/SessionNotice.kt@@ -0,0 +1,95 @@+package dev.lelonio.square.ui++import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.slideInVertically+import androidx.compose.animation.slideOutVertically+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.kyant.backdrop.Backdrop+import dev.lelonio.square.R+import dev.lelonio.square.ui.glass.pressable+import dev.lelonio.square.ui.player.GlassSurface+import androidx.compose.foundation.shape.RoundedCornerShape++/**+ * The one thing an expired Web API session should cost the listener: a tap.+ *+ * Spotify's own application, the one search and the home feed are metered+ * against, holds a token that lapses on its own schedule, and until now the only+ * sign of it was a search that quietly answered nothing and a settings screen+ * the user had to think to open. The client id is already stored and does not+ * expire, so the way back is the same OAuth flow with nothing to type: this says+ * what happened and runs it.+ */+@Composable+fun SessionExpiredNotice(+ visible: Boolean,+ backdrop: Backdrop,+ onReconnect: () -> Unit,+ onDismiss: () -> Unit,+ modifier: Modifier = Modifier,+) {+ AnimatedVisibility(+ visible = visible,+ enter = slideInVertically { -it } + fadeIn(),+ exit = slideOutVertically { -it } + fadeOut(),+ modifier = modifier,+ ) {+ GlassSurface(+ backdrop = backdrop,+ shape = RoundedCornerShape(26.dp),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),+ surfaceColor = Color.White.copy(alpha = 0.10f),+ ) {+ Column(+ Modifier.padding(horizontal = 20.dp, vertical = 16.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ Text(+ stringResource(R.string.web_api_expired_title),+ style = MaterialTheme.typography.titleSmall,+ fontWeight = FontWeight.SemiBold,+ color = Color.White,+ )+ Text(+ stringResource(R.string.web_api_expired_body),+ style = MaterialTheme.typography.bodySmall,+ color = Color.White.copy(alpha = 0.75f),+ )+ Row(+ Modifier.fillMaxWidth().padding(top = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(20.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(+ stringResource(R.string.web_api_expired_action),+ style = MaterialTheme.typography.labelLarge,+ fontWeight = FontWeight.SemiBold,+ color = Color.White,+ modifier = Modifier.pressable(onClick = onReconnect),+ )+ Text(+ stringResource(R.string.later),+ style = MaterialTheme.typography.labelLarge,+ color = Color.White.copy(alpha = 0.6f),+ modifier = Modifier.pressable(onClick = onDismiss),+ )+ }+ }+ }+ }+}diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.ktindex e5c58a0..366001b 100644--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt@@ -826,6 +826,18 @@ fun SquareApp(}}+ // Out here for the same reason as the bars below: it refracts+ // `pageBackdrop`, so it cannot be drawn inside it.+ SessionExpiredNotice(+ visible = webApi.expired && !webApi.connecting,+ backdrop = pageBackdrop,+ onReconnect = viewModel::connectWebApi,+ onDismiss = viewModel::dismissWebApiExpiry,+ modifier = Modifier+ .align(Alignment.TopCenter)+ .padding(top = statusBar + 8.dp),+ )+// Outside the recorded layer, and that is structural rather than// stylistic: these refract `pageBackdrop`, and a pane drawn// inside the layer it samples recurses on the render threaddiff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xmlindex c3698dd..b7a3052 100644--- a/app/src/main/res/values-de/strings.xml+++ b/app/src/main/res/values-de/strings.xml@@ -130,6 +130,10 @@<string name="scope_private_playlists">Zu privaten Playlists hinzufügen</string><string name="scope_public_playlists">Zu öffentlichen Playlists hinzufügen</string><string name="enter_client_id">Gib die Client ID ein.</string>+ <string name="web_api_expired_title">Sitzung abgelaufen</string>+ <string name="web_api_expired_body">Melde dich wieder bei deiner Spotify-Anwendung an, damit Suche und Startseite zurückkommen.</string>+ <string name="web_api_expired_action">Erneut anmelden</string>+ <string name="later">Später</string><string name="needs_your_app">Dafür braucht es deine eigene Spotify-Anwendung: richte sie unter Suchen ein.</string><string name="turn_on_search">SUCHE AKTIVIEREN</string>diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xmlindex e41bb8c..92961f2 100644--- a/app/src/main/res/values-es/strings.xml+++ b/app/src/main/res/values-es/strings.xml@@ -130,6 +130,10 @@<string name="scope_private_playlists">Añadir a playlists privadas</string><string name="scope_public_playlists">Añadir a playlists públicas</string><string name="enter_client_id">Introduce el client ID.</string>+ <string name="web_api_expired_title">Sesión caducada</string>+ <string name="web_api_expired_body">Vuelve a iniciar sesión en tu aplicación de Spotify para recuperar la búsqueda y el inicio.</string>+ <string name="web_api_expired_action">Iniciar sesión</string>+ <string name="later">Más tarde</string><string name="needs_your_app">Hace falta tu propia aplicación de Spotify: configúrala en Buscar.</string><string name="turn_on_search">ACTIVA LA BÚSQUEDA</string>diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xmlindex 9829ced..e7ab32f 100644--- a/app/src/main/res/values-fr/strings.xml+++ b/app/src/main/res/values-fr/strings.xml@@ -130,6 +130,10 @@<string name="scope_private_playlists">Ajouter aux playlists privées</string><string name="scope_public_playlists">Ajouter aux playlists publiques</string><string name="enter_client_id">Saisissez le client ID.</string>+ <string name="web_api_expired_title">Session expirée</string>+ <string name="web_api_expired_body">Reconnectez-vous à votre application Spotify pour retrouver la recherche et l’accueil.</string>+ <string name="web_api_expired_action">Se reconnecter</string>+ <string name="later">Plus tard</string><string name="needs_your_app">Votre propre application Spotify est nécessaire : configurez-la dans Rechercher.</string><string name="turn_on_search">ACTIVER LA RECHERCHE</string>diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xmlindex de31016..76965ad 100644--- a/app/src/main/res/values-hi/strings.xml+++ b/app/src/main/res/values-hi/strings.xml@@ -142,6 +142,10 @@<string name="scope_private_playlists">निजी प्लेलिस्ट में जोड़ना</string><string name="scope_public_playlists">सार्वजनिक प्लेलिस्ट में जोड़ना</string><string name="enter_client_id">क्लाइंट आईडी डालें।</string>+ <string name="web_api_expired_title">सत्र समाप्त हो गया</string>+ <string name="web_api_expired_body">खोज और होम वापस पाने के लिए अपने Spotify ऐप्लिकेशन में फिर से साइन इन करें।</string>+ <string name="web_api_expired_action">फिर से साइन इन करें</string>+ <string name="later">बाद में</string><string name="needs_your_app">आपका अपना Spotify ऐप्लिकेशन चाहिए: इसे खोज में सेट करें।</string><!-- Web API setup -->diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xmlindex ee6fa17..92bea79 100644--- a/app/src/main/res/values-it/strings.xml+++ b/app/src/main/res/values-it/strings.xml@@ -131,6 +131,10 @@<string name="scope_private_playlists">Aggiungi a playlist private</string><string name="scope_public_playlists">Aggiungi a playlist pubbliche</string><string name="enter_client_id">Inserisci il client id.</string>+ <string name="web_api_expired_title">Sessione scaduta</string>+ <string name="web_api_expired_body">Accedi di nuovo alla tua applicazione Spotify per riavere ricerca e home.</string>+ <string name="web_api_expired_action">Accedi di nuovo</string>+ <string name="later">Più tardi</string><string name="needs_your_app">Serve la tua applicazione Spotify: configurala in Cerca.</string><string name="turn_on_search">ATTIVA LA RICERCA</string>diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xmlindex bba4f3f..d6604e9 100644--- a/app/src/main/res/values-pt/strings.xml+++ b/app/src/main/res/values-pt/strings.xml@@ -130,6 +130,10 @@<string name="scope_private_playlists">Adicionar a playlists privadas</string><string name="scope_public_playlists">Adicionar a playlists públicas</string><string name="enter_client_id">Informe o client ID.</string>+ <string name="web_api_expired_title">Sessão expirada</string>+ <string name="web_api_expired_body">Entre novamente na sua aplicação do Spotify para ter de volta a busca e o início.</string>+ <string name="web_api_expired_action">Entrar de novo</string>+ <string name="later">Mais tarde</string><string name="needs_your_app">É preciso a sua própria aplicação do Spotify: configure-a em Buscar.</string><string name="turn_on_search">ATIVE A BUSCA</string>diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xmlindex c397c4f..344ae4a 100644--- a/app/src/main/res/values-tr/strings.xml+++ b/app/src/main/res/values-tr/strings.xml@@ -142,6 +142,10 @@<string name="scope_private_playlists">Özel çalma listelerine ekleme</string><string name="scope_public_playlists">Herkese açık listelere ekleme</string><string name="enter_client_id">İstemci kimliğini gir.</string>+ <string name="web_api_expired_title">Oturum sona erdi</string>+ <string name="web_api_expired_body">Arama ve ana sayfanın geri gelmesi için Spotify uygulamana yeniden giriş yap.</string>+ <string name="web_api_expired_action">Yeniden giriş yap</string>+ <string name="later">Sonra</string><string name="needs_your_app">Kendi Spotify uygulaman gerekiyor: Ara bölümünden ayarla.</string><!-- Web API setup -->diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 8ba1bf5..6094ea3 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -148,6 +148,10 @@<string name="scope_private_playlists">Add to private playlists</string><string name="scope_public_playlists">Add to public playlists</string><string name="enter_client_id">Enter the client ID.</string>+ <string name="web_api_expired_title">Session expired</string>+ <string name="web_api_expired_body">Sign in to your Spotify application again to bring search and the home page back.</string>+ <string name="web_api_expired_action">Sign in again</string>+ <string name="later">Later</string><string name="needs_your_app">You need your own Spotify application: set it up in Search.</string><!-- Web API setup -->diff --git a/native/src/engine.rs b/native/src/engine.rsindex 799c730..4db6230 100644--- a/native/src/engine.rs+++ b/native/src/engine.rs@@ -179,10 +179,11 @@ struct Recipe {session_config: SessionConfig,player_config: PlayerConfig,connect_config: ConnectConfig,- /// The OAuth credentials from the original login, used only if the cache has- /// nothing better. After the first handshake the cache holds a reusable blob- /// which outlives the access token, and that is what a reconnection wants.- credentials: Credentials,+ /// The OAuth credentials from the original login, if the caller had a token+ /// to give. Only the first login really needs one: the access point answers+ /// a successful handshake with a reusable credential, which is kept and used+ /// from then on. Empty means "use what was kept".+ credentials: Option<Credentials>,credentials_dir: String,cache_dir: String,}@@ -323,7 +324,11 @@ pub fn start(session_config.device_id = device_id.to_string();}- let credentials = Credentials::with_access_token(access_token);+ let credentials = if access_token.is_empty() {+ None+ } else {+ Some(Credentials::with_access_token(access_token))+ };let mixer = Arc::new(SoftMixer::open(MixerConfig::default()).map_err(|e| format!("mixer failed: {e}"))?,@@ -468,13 +473,46 @@ fn build_bundle(// replaced it and mark a device that is perfectly alive as gone.let generation = GENERATION.fetch_add(1, Ordering::SeqCst) + 1;- let mixer_volume = mixer.get_soft_volume();// Cloned before the async block takes ownership of the Arc as a `dyn Mixer`.let mixer_for_spirc: Arc<dyn Mixer> = mixer.clone();let session_config = recipe.session_config.clone();let player_config = recipe.player_config.clone();let connect_config = recipe.connect_config.clone();- let credentials = recipe.credentials.clone();++ // The credential the access point issued the first time this device logged+ // in, kept in a directory of its own.+ //+ // It is the difference between a session that lasts and one that has to be+ // renewed. An OAuth access token is good for an hour, and the refresh token+ // behind it is rotated on every use and revoked on the first mistake, so an+ // engine that needs one at every launch is one bad refresh away from asking+ // the listener to sign in again. The blob the handshake answers with has+ // neither property: it is what go-librespot writes to `credentials.json` and+ // then reuses forever, and it is why signing in there is something you do+ // once.+ //+ // Kept apart from librespot's own credentials file because that file is+ // written by the connection itself, and what has to survive is the copy+ // nothing else touches.+ let kept = Cache::new(+ Some(&std::path::Path::new(&recipe.credentials_dir).join("reusable")),+ None,+ None,+ None,+ )+ .map_err(|e| format!("cache failed: {e}"))?;++ // The kept credential first, the token second. A token is only ever the way+ // in for a device that has never been in.+ let attempts: Vec<(&str, Credentials)> = kept+ .credentials()+ .into_iter()+ .map(|c| ("the kept credential", c))+ .chain(recipe.credentials.clone().map(|c| ("an access token", c)))+ .collect();+ if attempts.is_empty() {+ return Err("no credentials".into());+ }// The account's other devices, watched over the same dealer.//@@ -487,63 +525,99 @@ fn build_bundle(let watch_tx = events_tx.clone();let (session, player, spirc, spirc_task) = rt.block_on(async move {- // Seed the cache with the OAuth credentials, then hand the cached copy- // to `connect` with storing switched off. Letting `connect` store- // instead would overwrite the cache with the handshake's reusable- // credentials, and that blob is what gets sent as the stored credential- // when login5 issues the access point's HTTP token.- cache.save_credentials(&credentials);- let session = Session::new(session_config, Some(cache));- let credentials = session- .cache()- .and_then(|cache| cache.credentials())- .unwrap_or(credentials);-- crate::remote::watch(&session, move || {- let _ = watch_tx.send(Pump::Cluster);- });-- // No `session.connect` here: `Spirc::new` registers its dealer- // listeners and then connects the session itself. Connecting first- // authenticated twice and left the second attempt reporting "Session is- // not connected", which is what this looked like from the outside.-- let player = Player::new(player_config, session.clone(), mixer_volume, move || {- Box::new(crate::sink::AndroidSink::new(AudioFormat::S16, generation))- });-- let (spirc, spirc_task) = Spirc::new(- connect_config,- session.clone(),- credentials.clone(),- player.clone(),- mixer_for_spirc,- )- .await- .map_err(|e| format!("connect failed: {e}"))?;-- // Spirc connects with credential storing switched on, which replaces- // the cached OAuth blob with the handshake's reusable one. login5 signs- // its stored-credential request with the session's client id, so the- // two have to agree or every catalogue call comes back BAD_REQUEST —- // putting the original back is what keeps the access point usable.- if let Some(cache) = session.cache() {+ let last = attempts.len() - 1;+ let mut failure = String::new();++ for (n, (kind, credentials)) in attempts.into_iter().enumerate() {+ log::info!("logging in with {kind}");+ // Seed the cache, then hand the cached copy to `connect` with+ // storing switched off. Letting `connect` store instead would+ // overwrite the cache with the handshake's own blob, and what is in+ // the cache is what gets sent as the stored credential when login5+ // issues the access point's HTTP token.+ let cache = cache.clone();cache.save_credentials(&credentials);- }+ let session = Session::new(session_config.clone(), Some(cache));++ let watch_tx = watch_tx.clone();+ crate::remote::watch(&session, move || {+ let _ = watch_tx.send(Pump::Cluster);+ });++ // No `session.connect` here: `Spirc::new` registers its dealer+ // listeners and then connects the session itself. Connecting first+ // authenticated twice and left the second attempt reporting+ // "Session is not connected", which is what this looked like from+ // the outside.++ // Read per attempt: the getter is a box the player takes, so one+ // made in advance would be gone by the second time round.+ let player = Player::new(+ player_config.clone(),+ session.clone(),+ mixer.get_soft_volume(),+ move || Box::new(crate::sink::AndroidSink::new(AudioFormat::S16, generation)),+ );++ let connected = Spirc::new(+ connect_config.clone(),+ session.clone(),+ credentials.clone(),+ player.clone(),+ mixer_for_spirc.clone(),+ )+ .await;++ let (spirc, spirc_task) = match connected {+ Ok(pair) => pair,+ Err(e) => {+ session.shutdown();+ failure = format!("connect failed: {e}");+ // A kept credential the account no longer honours — the+ // password changed, the device was removed from the list —+ // is a dead end, not a reason to stop: it is thrown away so+ // the token behind it gets its turn, and so the next launch+ // does not try it again.+ if n < last {+ log::warn!("{failure}, trying the next credential");+ let _ = std::fs::remove_dir_all(+ std::path::Path::new(&recipe.credentials_dir).join("reusable"),+ );+ continue;+ }+ return Err(failure);+ }+ };- // Checked here rather than left to the library. The vendored- // librespot-core used to call exit(1) on a non-premium account, which- // took the app's process down and left Android restarting the service- // in a loop; it now only logs, so the refusal has to be made an error- // the caller can show.- if let Some(account_type) = session.get_user_attribute("type") {- if account_type != "premium" {- session.shutdown();- return Err(PREMIUM_REQUIRED.to_string());+ // Spirc connects with credential storing switched on, so the cache+ // now holds the blob the access point answered with. That is the+ // one worth keeping, and the seed goes back into the cache after it+ // is taken: login5 signs its stored-credential request with the+ // session's client id, and the pair that is known to agree is the+ // one this session actually logged in with.+ if let Some(cache) = session.cache() {+ if let Some(reusable) = cache.credentials() {+ kept.save_credentials(&reusable);+ }+ cache.save_credentials(&credentials);}++ // Checked here rather than left to the library. The vendored+ // librespot-core used to call exit(1) on a non-premium account,+ // which took the app's process down and left Android restarting the+ // service in a loop; it now only logs, so the refusal has to be+ // made an error the caller can show.+ if let Some(account_type) = session.get_user_attribute("type") {+ if account_type != "premium" {+ session.shutdown();+ return Err(PREMIUM_REQUIRED.to_string());+ }+ }++ return Ok::<_, String>((session, player, spirc, spirc_task));}- Ok::<_, String>((session, player, spirc, spirc_task))+ Err(failure)})?;// The event loop runs for the life of the bundle: it is what answers the