Skip to content

Native Android client for Spotify, built with Jetpack Compose

Several Spotify accounts kept at once: each in its own WebView profile (cookies, storage, its own client device id, its plan), switched, added and removed from Settings > Accounts in both looks and from the profile sheet; a switch stops playback, empties what belongs to the account and sets aside its downloads, Recap and history until it comes back; without WebView profiles one account at a time, as before. Next and Previous go to the device that plays instead of pulling playback back to the phone

kota-zof17d387aa9a8
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 0133e9ff..be36e8ab 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
@@ -102,6 +102,17 @@ class SpotifyApi(
suspend fun onPageLoaded() = bridge.inject()
+ /**
+ * The page moves to another account (an account switch): its token, username and Jam are
+ * forgotten now, not at the next ready page, so no direct call goes out meanwhile as the account
+ * that left.
+ */
+ suspend fun forgetAccount() {
+ http.forgetWebToken()
+ users.forgetUsername()
+ jam.forgetSession()
+ }
+
/** The host calls this when a Web Player page load starts (reload, renderer back). */
fun onPageStarting() = bridge.pageGone()
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 74605323..027df78a 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
@@ -579,6 +579,9 @@ class SpotifyJam(private val bridge: Bridge, private val http: SpotifyHttp) : Ja
}
}
+ /** Another account takes the page: the Jam known is that of the account that left. */
+ internal fun forgetSession() { _session.value = null }
+
/** In a Jam this account joined: the music plays on the host's device, never to be pulled here. */
val member: Boolean get() = _session.value?.isHost == false
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 0097ff49..2e35e5e0 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
@@ -85,7 +85,7 @@ class SpotifyHttp(
* 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 var 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,
val fetchedAtMs: Long = System.currentTimeMillis())
@@ -95,6 +95,16 @@ class SpotifyHttp(
private var web: WebToken? = null
private var client: ClientToken? = null
+ /**
+ * Another account's device id (each account kept here has its own, so Spotify is not shown
+ * several accounts on one client): the client token minted for the last one is dropped.
+ */
+ fun useDeviceId(id: String) {
+ if (id == deviceId) return
+ deviceId = id
+ client = null
+ }
+
/** Drops the cached web token (it belongs to one account); the client token is kept. */
suspend fun forgetWebToken() = lock.withLock { web = null }
diff --git a/base/app/src/main/java/app/myspoti/MainActivity.kt b/base/app/src/main/java/app/myspoti/MainActivity.kt
index f4ea0f45..4bd9eb6f 100644
--- a/base/app/src/main/java/app/myspoti/MainActivity.kt
+++ b/base/app/src/main/java/app/myspoti/MainActivity.kt
@@ -210,6 +210,24 @@ class MainActivity : AppCompatActivity() {
watchSession()
watchLoginReturn()
watchLogout()
+ watchSwitch()
+ // On the sign-in page of an added account (or of one whose session was gone), back goes to
+ // the account used before instead of leaving the app on a page with no account.
+ // Enabled only then, so back keeps its system behaviour (and its predictive animation) elsewhere.
+ val backToAccount = object : androidx.activity.OnBackPressedCallback(false) {
+ override fun handleOnBackPressed() {
+ if (!com.music.spotui.di.SessionActions.backToPreviousAccount(this@MainActivity)) return
+ MyspotiRuntime.host.accounts.list.value.current?.name?.let {
+ android.widget.Toast.makeText(this@MainActivity, getString(R.string.accounts_back_to, it), android.widget.Toast.LENGTH_SHORT).show()
+ }
+ }
+ }
+ onBackPressedDispatcher.addCallback(this, backToAccount)
+ lifecycleScope.launch {
+ combine(androidx.compose.runtime.snapshotFlow { showingLogin && !connecting }, MyspotiRuntime.host.accounts.list) { login, list ->
+ login && MyspotiRuntime.host.multiProfile && list.others.isNotEmpty()
+ }.collect { backToAccount.isEnabled = it }
+ }
// Only on a fresh start: on recreation (theme, locale, process restore)
// the same intent would play its link again. New links arrive in onNewIntent.
if (savedInstanceState == null) handle(intent)
@@ -352,8 +370,8 @@ class MainActivity : AppCompatActivity() {
// Another door already started the screens over: this activity is on its way out.
if (isFinishing) return
loginProblem = false
- if (com.music.spotui.di.SessionActions.signedOut.value) {
- // Signed in again after a logout, maybe as someone else: start the
+ if (com.music.spotui.di.SessionActions.signedOut.value || com.music.spotui.di.SessionActions.switching.value) {
+ // Signed in again after a logout or an account switch, maybe as someone else: start the
// screens over (a new activity also drops their view models).
com.music.spotui.di.SessionActions.signedIn()
prefs.edit().putBoolean("LoggedIn", true).apply()
@@ -393,6 +411,48 @@ class MainActivity : AppCompatActivity() {
}
}
+ /**
+ * An account switch: the page is rebuilt on the other account's profile, hidden, while the app's
+ * own loading screen shows. Its session confirmed, the screens start over ([sessionConfirmed]).
+ * Spotify's sign-in page instead (that account's session is gone), or no session in time: the
+ * sign-in page is shown, as for any sign-in.
+ */
+ private fun watchSwitch() {
+ lifecycleScope.launch {
+ com.music.spotui.di.SessionActions.switching.collect { on ->
+ if (!on) return@collect
+ signedIn = false
+ showingLogin = false
+ loginProblem = false
+ connecting = true
+ MyspotiRuntime.host.attach(root, visible = false)
+ loginWait?.cancel()
+ loginWait = launch {
+ // The old page's state may still be published for a moment: the new one is looked at.
+ kotlinx.coroutines.delay(1_000)
+ val wait = SessionWait(SESSION_WAIT_MS, SESSION_LOAD_MAX_MS)
+ var last = android.os.SystemClock.elapsedRealtime()
+ while (!wait.expired) {
+ if (MyspotiRuntime.host.loginRequired.value) break
+ val ready = MyspotiRuntime.spotify.ready.value
+ val answer = if (ready) runCatching { MyspotiRuntime.isSignedIn() } else null
+ if (answer?.getOrNull() == true) { sessionConfirmed(); return@launch }
+ // An anonymous token: that account's session is gone.
+ if (answer?.getOrNull() == false) break
+ kotlinx.coroutines.delay(500)
+ val now = android.os.SystemClock.elapsedRealtime()
+ wait.tick(now - last, lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED), MyspotiRuntime.spotify.ready.value)
+ last = now
+ }
+ Logbook.log("account switch: no session on that account, sign-in page shown")
+ connecting = false
+ // Its sign-in, on its own profile: a session still good there comes straight back.
+ showLogin()
+ }
+ }
+ }
+ }
+
/**
* Spotify sent the user back to the player: the page is hidden now, the session follows.
*
diff --git a/base/app/src/main/java/com/music/spotui/data/api/ProfileCache.kt b/base/app/src/main/java/com/music/spotui/data/api/ProfileCache.kt
index 2bb4bb44..23344ef5 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/ProfileCache.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/ProfileCache.kt
@@ -51,7 +51,18 @@ object ProfileCache {
name = me.name
imageUrl = me.images.best(160)?.url
id = me.username
- // The downloads shown are this account's own (see OfflineAccounts).
+ // The accounts kept on the phone: this profile's name and picture, under the opaque key
+ // of its downloads (no id, no e-mail). The same account in another profile is one account.
+ val key = com.music.spotui.data.offline.OfflineAccounts.keyOf(me.username)
+ val host = MyspotiRuntime.host
+ val profile = host.profile
+ var duplicates = emptyList<String>()
+ host.accounts.update { list ->
+ list.signedIn(profile, key, me.name, imageUrl, System.currentTimeMillis()).also { duplicates = it.second }.first
+ }
+ duplicates.forEach { host.removeProfile(it) }
+ // Its listen history and its downloads are the ones shown (see OfflineAccounts).
+ com.music.spotui.data.local.ListenHistory.claim(key)
com.music.spotui.data.offline.OfflineAccounts.claim(context.applicationContext, me.username)
return@launch
}
diff --git a/base/app/src/main/java/com/music/spotui/data/local/ListenHistory.kt b/base/app/src/main/java/com/music/spotui/data/local/ListenHistory.kt
index f931c237..f79a4226 100644
--- a/base/app/src/main/java/com/music/spotui/data/local/ListenHistory.kt
+++ b/base/app/src/main/java/com/music/spotui/data/local/ListenHistory.kt
@@ -77,7 +77,49 @@ object ListenHistory {
list
}
- fun clear() = synchronized(lock) { loaded = null; file?.delete() }
+ fun clear() = synchronized(lock) { loaded = null; file?.delete(); owner()?.delete() }
+
+ /*
+ * The history belongs to the account it was heard on, as the downloads do (OfflineAccounts): on an
+ * account switch it is put aside under that account's key (`listen-history/<key>.jsonl`) and the
+ * next account's comes back. A history from before has no owner and goes to the first account read.
+ */
+ private fun owner(): File? = file?.let { File(it.parentFile, "listen_history.owner") }
+ private fun parked(key: String): File? = file?.let { File(it.parentFile, "listen-history/$key.jsonl") }
+ private fun ownerKey(): String? = owner()?.takeIf { it.isFile }?.let { runCatching { it.readText().trim() }.getOrNull() }?.ifBlank { null }
+
+ /** [from] is put after what [to] already holds (a copy left by an earlier move that went wrong), then removed. */
+ private fun moveInto(from: File, to: File) {
+ to.parentFile?.mkdirs()
+ if (!to.exists() && from.renameTo(to)) return
+ to.appendText(from.readText())
+ from.delete()
+ }
+
+ /** Leaving the account [key] (its stamp wins): its history goes aside, the next account starts with none. */
+ fun park(key: String?) = synchronized(lock) {
+ val f = file ?: return@synchronized
+ val owner = ownerKey() ?: key ?: "unclaimed-${System.currentTimeMillis()}"
+ runCatching { if (f.exists()) moveInto(f, parked(owner)!!) }
+ owner()?.delete()
+ loaded = null
+ }
+
+ /** The account [key] is signed in: its own history is the one shown; one with no owner yet becomes its own. */
+ fun claim(key: String) = synchronized(lock) {
+ val f = file ?: return@synchronized
+ val owner = ownerKey()
+ if (owner == key) return@synchronized
+ runCatching {
+ if (owner != null && f.exists()) moveInto(f, parked(owner)!!)
+ parked(key)?.takeIf { it.exists() }?.let { moveInto(it, f) }
+ owner()?.writeText(key)
+ }
+ loaded = null
+ }
+
+ /** The account [key] is removed from the phone: its history put aside goes with it. */
+ fun forget(key: String) = synchronized(lock) { parked(key)?.delete(); Unit }
data class Ranked(val name: String, val subtitle: String, val cover: String, val count: Int, val minutes: Long)
diff --git a/base/app/src/main/java/com/music/spotui/di/SessionActions.kt b/base/app/src/main/java/com/music/spotui/di/SessionActions.kt
index 9f73c74c..53f42167 100644
--- a/base/app/src/main/java/com/music/spotui/di/SessionActions.kt
+++ b/base/app/src/main/java/com/music/spotui/di/SessionActions.kt
@@ -13,16 +13,42 @@ object SessionActions {
/** True from a logout until the next sign-in: the activity shows the login page, then starts over. */
val signedOut: StateFlow<Boolean> = _signedOut
+ private val _switching = MutableStateFlow(false)
+ /**
+ * True from an account switch until that account's session is confirmed: the activity waits for
+ * it on its own loading screen (the sign-in page only if that account's session is gone), then starts over.
+ */
+ val switching: StateFlow<Boolean> = _switching
+
/**
* Signs out and drops everything tied to the account, so the next account on
* this phone starts clean: prefs and in-memory caches, the saved screens,
* the listen history (the Recap), and the Web Player's cookies, Web storage
* and cache (in the host). Downloads are put aside under the account (OfflineAccounts), not deleted.
+ * With other accounts kept on the phone, this one is removed and the one used last takes over.
*/
fun logout(context: android.content.Context) {
- val app = context.applicationContext
+ val host = MyspotiRuntime.host
+ val list = host.accounts.list.value
+ if (host.multiProfile && list.others.isNotEmpty()) {
+ removeAccount(context, list.active)
+ return
+ }
+ leaveAccount(context.applicationContext, forget = true)
+ _signedOut.value = true
+ host.logout()
+ }
+
+ /**
+ * Everything that follows the account leaves with it: nothing of it keeps playing or showing,
+ * its caches are dropped, its downloads put aside under it (OfflineAccounts). [forget]: a sign-out
+ * or a removal, its listen history goes; otherwise (a switch) it is put aside under it too.
+ * Extensions are the app's, not the account's: they keep running.
+ */
+ private fun leaveAccount(app: android.content.Context, forget: Boolean) {
// This account's downloads go aside: the next account on the phone sees none of them.
val account = com.music.spotui.data.api.ProfileCache.id
+ val key = account?.let { com.music.spotui.data.offline.OfflineAccounts.keyOf(it) } ?: MyspotiRuntime.host.accounts.list.value.current?.key
MyspotiRuntime.scope.launch {
runCatching { com.music.spotui.data.offline.OfflineAccounts.park(app, account) }
.onFailure { Logbook.log("offline: sign-out park failed: ${it.message}") }
@@ -51,10 +77,81 @@ object SessionActions {
"LikedSongsFromSpotify", "LikedAlbums", "FollowedArtists").forEach { name ->
app.getSharedPreferences(name, android.content.Context.MODE_PRIVATE).edit().clear().apply()
}
- com.music.spotui.data.local.ListenHistory.clear()
+ if (forget) com.music.spotui.data.local.ListenHistory.clear()
+ else com.music.spotui.data.local.ListenHistory.park(key)
AutoBrowser.clearSession()
+ // The API's token, username and Jam, and the plan: the next account's are read.
+ MyspotiRuntime.accountChanged()
+ }
+
+ /**
+ * Another account kept on the phone takes over ([profile], a WebView profile of its own): playback
+ * stops, what follows this account leaves ([leaveAccount]), and the page is rebuilt on the other
+ * profile, signed in as it was left. Without WebView profiles, one account at a time: signs out.
+ */
+ fun switchAccount(context: android.content.Context, profile: String) {
+ val host = MyspotiRuntime.host
+ if (!host.multiProfile) { logout(context); return }
+ val list = host.accounts.list.value
+ if (profile == list.active || list.accounts.none { it.profile == profile }) return
+ Logbook.log("account: switching to another account kept on the phone")
+ leaveAccount(context.applicationContext, forget = false)
+ _switching.value = true
+ host.switchProfile(profile)
+ }
+
+ /** "Add account": this one stays kept, and Spotify's sign-in page opens in a new profile. Without profiles: signs out. */
+ fun addAccount(context: android.content.Context) {
+ val host = MyspotiRuntime.host
+ if (!host.multiProfile) { logout(context); return }
+ Logbook.log("account: adding an account")
+ leaveAccount(context.applicationContext, forget = false)
_signedOut.value = true
- MyspotiRuntime.host.logout()
+ host.addProfile()
+ }
+
+ /**
+ * Back on the sign-in page of an added account (or of one whose session was gone): the account
+ * used last takes over again. False when there is none to go back to.
+ */
+ fun backToPreviousAccount(context: android.content.Context): Boolean {
+ val host = MyspotiRuntime.host
+ if (!host.multiProfile) return false
+ val list = host.accounts.list.value
+ val previous = list.others.firstOrNull() ?: return false
+ val left = list.current
+ switchAccount(context, previous.profile)
+ // An added profile nobody signed in to is not kept.
+ if (left != null && !left.known) host.removeProfile(left.profile)
+ return true
+ }
+
+ /**
+ * [profile] is removed from the phone: its sign-in and Web data are deleted (its profile), its listen
+ * history too; its downloads stay put aside (OfflineAccounts), back if it is added again. The active
+ * account is first left for the one used last; the only account left is signed out instead.
+ */
+ fun removeAccount(context: android.content.Context, profile: String) {
+ val host = MyspotiRuntime.host
+ val list = host.accounts.list.value
+ val gone = list.accounts.firstOrNull { it.profile == profile } ?: return
+ if (profile == list.active) {
+ val next = list.others.firstOrNull()
+ if (!host.multiProfile || next == null) {
+ leaveAccount(context.applicationContext, forget = true)
+ _signedOut.value = true
+ host.logout()
+ return
+ }
+ Logbook.log("account: removing the active account, the one used last takes over")
+ leaveAccount(context.applicationContext, forget = true)
+ _switching.value = true
+ host.switchProfile(next.profile)
+ } else {
+ Logbook.log("account: removing an account kept on the phone")
+ gone.key?.let { com.music.spotui.data.local.ListenHistory.forget(it) }
+ }
+ host.removeProfile(profile)
}
/**
@@ -72,5 +169,5 @@ object SessionActions {
}
/** The new account is signed in. */
- fun signedIn() { _signedOut.value = false }
+ fun signedIn() { _signedOut.value = false; _switching.value = false }
}
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 1e09b6e5..1d95d031 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
@@ -509,6 +509,8 @@ object SongPlayer {
lastTrackPrefs().edit().clear().apply(); savedLast = ""; resumeWhenReady = false
savedSource = com.music.spotui.data.preferences.LastSession.SOURCE_SPOTIFY; savedAtMs = 0L; restoredLocal = false
_activeDevice.value = null; _sleepEndsAt.value = null; sleepFade?.cancel(); main.removeCallbacks(sleepFadeRunnable); sleepTrackId = null; spotifyFallbackId = null
+ // The Connect device picked was the account's that leaves: the next one starts on this phone.
+ chosenRemote = null
boundState?.let { state ->
state.updateQueue(emptyList())
state.updateSongState("", "", "", false, 0, 0, "")
@@ -1622,7 +1624,7 @@ object SongPlayer {
}
// Off a song Spotify played for want of an extension: the next one is asked there first.
if (pendingSkips == 0) _queue.value.let { it.queued + it.nextUp }.firstOrNull()?.song?.let { t ->
- if (backToExtensions(t, trackIdOf(_nowPlaying.value.uri), upcomingSongs(t)) { intendPlaying(); transport { api.player.next() } }) return
+ if (backToExtensions(t, trackIdOf(_nowPlaying.value.uri), upcomingSongs(t)) { intendPlaying(); transport(pullBack = false) { api.player.next() } }) return
}
intendPlaying()
tapSeq++
@@ -1650,7 +1652,7 @@ object SongPlayer {
val tappedOn = api.player.state.value?.item?.uri
// The device check after the skip, as for a resume: before it, a slow network held
// every skip for the device list's round trip (up to DEVICES_WAIT_MS).
- transport(waitReady = !stateSeen, checkAfter = true, done = { ok -> skipDone(shown, ok) }) {
+ transport(waitReady = !stateSeen, checkAfter = true, pullBack = false, done = { ok -> skipDone(shown, ok) }) {
val now = api.player.state.value?.item?.uri
if (tappedOn != null && now != null && now != tappedOn) {
app.myspoti.host.android.Logbook.log("next not sent: the song it was tapped on had already ended")
@@ -1742,7 +1744,7 @@ object SongPlayer {
val target = burstUpcoming.getOrNull(burstTaps - 1)
app.myspoti.host.android.Logbook.log("next taps merged: $burstTaps skips${if (target != null) " in one jump to ${target.name}" else ", sent as a plain next"}")
val shown = pendingSkip
- transport(waitReady = !stateSeen, checkAfter = true, done = { ok -> skipDone(shown, ok) }) {
+ transport(waitReady = !stateSeen, checkAfter = true, pullBack = false, done = { ok -> skipDone(shown, ok) }) {
if (target == null) api.player.next() else api.player.skipTo(target)
}
if (target != null) {
@@ -1832,7 +1834,7 @@ object SongPlayer {
// Off a song Spotify played for want of an extension (a previous that goes back a song).
if (getCurrentPosition() <= 3_000) _nowPlaying.value.prev?.let { t ->
val songs = listOf(t) + upcomingSongs(_queue.value.current ?: t).filter { it.spotifyTrackId != t.spotifyTrackId }
- if (backToExtensions(t, trackIdOf(_nowPlaying.value.uri), songs, forward = false) { intendPlaying(); transport { api.player.previous() } }) return
+ if (backToExtensions(t, trackIdOf(_nowPlaying.value.uri), songs, forward = false) { intendPlaying(); transport(pullBack = false) { api.player.previous() } }) return
}
cancelBurst()
skipSentAt = SystemClock.elapsedRealtime()
@@ -1840,7 +1842,7 @@ object SongPlayer {
// position stays until Spotify reports, and a quick second previous would restart again.
positionMs = 0L
positionAt = SystemClock.elapsedRealtime()
- transport(waitReady = !stateSeen, checkAfter = true) { api.player.previous() }
+ transport(waitReady = !stateSeen, checkAfter = true, pullBack = false) { api.player.previous() }
}
/** Tracks shufflePlay plays without a context: the first one, plus up to 49 queued. */
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AccountsList.kt b/base/app/src/main/java/com/music/spotui/ui/components/AccountsList.kt
new file mode 100644
index 00000000..9c6c19c6
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/components/AccountsList.kt
@@ -0,0 +1,198 @@
+package com.music.spotui.ui.components
+
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Add
+import androidx.compose.material.icons.filled.Check
+import androidx.compose.material.icons.filled.Close
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.rememberModalBottomSheetState
+import androidx.compose.runtime.Composable
+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.graphics.Color
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
+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.compose.collectAsStateWithLifecycle
+import app.myspoti.engine.R
+import app.myspoti.host.android.MyspotiRuntime
+import app.myspoti.host.android.SavedAccount
+import com.music.spotui.di.Graph
+import com.music.spotui.di.SessionActions
+import com.music.spotui.ui.immersive.Immersive
+import com.music.spotui.ui.navigation.isImmersive
+import com.music.spotui.ui.theme.AppAccent
+import com.music.spotui.ui.theme.AppMuted
+import com.music.spotui.ui.theme.AppText
+import com.music.spotui.ui.theme.tone
+
+/** The colours the account rows are drawn in: the Classic look's or the Immersive one's. */
+private class AccountsLook(val text: Color, val muted: Color, val accent: Color, val destructive: Color, val dialog: Color)
+
+@Composable
+private fun accountsLook(): AccountsLook =
+ if (isImmersive()) AccountsLook(Immersive.Text, Immersive.TextSecondary, Immersive.Accent, Immersive.Destructive, Color.Transparent)
+ else AccountsLook(AppText, AppMuted, AppAccent, Color(0xFFFF6B6B), tone(0xFF282828))
+
+/**
+ * The Spotify accounts kept on this phone, in both looks (Settings, and the sheet behind the
+ * avatar): each with its name, picture and plan, the active one ticked. Another one is switched to
+ * after a word that playback stops; "Add account" opens Spotify's sign-in in a new WebView profile;
+ * Remove deletes an account's sign-in from the phone. A WebView without profiles keeps one account
+ * at a time, and says so: adding signs this one out.
+ */
+@Composable
+fun AccountsList(onLeave: () -> Unit = {}) {
+ val look = accountsLook()
+ val ctx = LocalContext.current
+ val host = MyspotiRuntime.host
+ val list by host.accounts.list.collectAsStateWithLifecycle()
+ val livePlan by app.myspoti.spotify.AccountPlan.premium.collectAsStateWithLifecycle()
+ var switchTo by remember { mutableStateOf<SavedAccount?>(null) }
+ var remove by remember { mutableStateOf<SavedAccount?>(null) }
+ var addSingle by remember { mutableStateOf(false) }
+ // The account in use first, then the one used last; one not signed in yet (an "Add account" left) last.
+ val shown = remember(list) {
+ val active = list.current ?: SavedAccount(profile = list.active)
+ listOf(active) + list.accounts.filter { it.profile != list.active }.sortedWith(compareBy<SavedAccount> { !it.known }.thenByDescending { it.usedAt })
+ }
+ Column(Modifier.fillMaxWidth()) {
+ shown.forEach { account ->
+ val active = account.profile == list.active
+ // The account in use: its name and picture as read now, before they are saved.
+ val name = (if (active) com.music.spotui.data.api.ProfileCache.name else null) ?: account.name
+ val image = (if (active) com.music.spotui.data.api.ProfileCache.imageUrl else null) ?: account.imageUrl
+ val premium = if (active) livePlan ?: account.premium else account.premium
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth()
+ .clickable(enabled = !active, role = Role.Button) { switchTo = account }
+ .padding(start = 20.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
+ ) {
+ ProfileAvatar(url = image, name = name, size = 40.dp)
+ Column(Modifier.weight(1f).padding(start = 14.dp)) {
+ Text(
+ name?.takeIf { it.isNotBlank() } ?: stringResource(if (account.known || active) R.string.spotify_account else R.string.accounts_not_signed_in),
+ color = look.text, fontSize = 16.sp, fontWeight = if (active) FontWeight.Bold else FontWeight.Normal,
+ maxLines = 1, overflow = TextOverflow.Ellipsis,
+ )
+ val plan = when (premium) {
+ true -> stringResource(R.string.accounts_plan_premium)
+ false -> stringResource(R.string.accounts_plan_free)
+ null -> null
+ }
+ val detail = listOfNotNull(plan, if (active) stringResource(R.string.accounts_in_use) else null).joinToString(" · ")
+ if (detail.isNotEmpty()) Text(detail, color = if (active) look.accent else look.muted, fontSize = 12.sp)
+ }
+ if (active) Icon(Icons.Filled.Check, contentDescription = stringResource(R.string.accounts_in_use), tint = look.accent,
+ modifier = Modifier.padding(horizontal = 12.dp).size(22.dp))
+ // The account in use is removed by "Log out"; the others from here.
+ else IconButton(onClick = { remove = account }) {
+ Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.accounts_remove), tint = look.muted, modifier = Modifier.size(20.dp))
+ }
+ }
+ }
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth()
+ .clickable(role = Role.Button) {
+ if (host.multiProfile) { onLeave(); SessionActions.addAccount(Graph.app) } else addSingle = true
+ }
+ .padding(horizontal = 20.dp, vertical = 10.dp),
+ ) {
+ Icon(Icons.Filled.Add, contentDescription = null, tint = look.text, modifier = Modifier.size(40.dp).padding(8.dp))
+ Column(Modifier.padding(start = 14.dp)) {
+ Text(stringResource(R.string.accounts_add), color = look.text, fontSize = 16.sp)
+ Text(stringResource(if (host.multiProfile) R.string.accounts_add_detail else R.string.accounts_add_single_detail), color = look.muted, fontSize = 12.sp)
+ }
+ }
+ Text(
+ stringResource(if (host.multiProfile) R.string.accounts_footer else R.string.accounts_single_footer),
+ color = look.muted, fontSize = 12.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 6.dp),
+ )
+ }
+ switchTo?.let { account ->
+ val name = account.name?.takeIf { it.isNotBlank() } ?: stringResource(R.string.spotify_account)
+ LookAlertDialog(
+ onDismissRequest = { switchTo = null },
+ containerColor = look.dialog,
+ title = { Text(stringResource(R.string.accounts_switch_title, name), color = look.text) },
+ text = { Text(stringResource(R.string.accounts_switch_text), color = look.muted) },
+ confirmButton = {
+ TextButton(onClick = { switchTo = null; onLeave(); SessionActions.switchAccount(Graph.app, account.profile) }) {
+ Text(stringResource(R.string.accounts_switch_confirm), color = look.accent)
+ }
+ },
+ dismissButton = { TextButton(onClick = { switchTo = null }) { Text(stringResource(R.string.add_to_playlist_button_cancel), color = look.text) } },
+ )
+ }
+ remove?.let { account ->
+ val name = account.name?.takeIf { it.isNotBlank() } ?: stringResource(if (account.known) R.string.spotify_account else R.string.accounts_not_signed_in)
+ LookAlertDialog(
+ onDismissRequest = { remove = null },
+ containerColor = look.dialog,
+ title = { Text(stringResource(R.string.accounts_remove_title, name), color = look.text) },
+ text = { Text(stringResource(R.string.accounts_remove_text), color = look.muted) },
+ confirmButton = {
+ TextButton(onClick = { remove = null; SessionActions.removeAccount(ctx, account.profile) }) {
+ Text(stringResource(R.string.accounts_remove), color = look.destructive)
+ }
+ },
+ dismissButton = { TextButton(onClick = { remove = null }) { Text(stringResource(R.string.add_to_playlist_button_cancel), color = look.text) } },
+ )
+ }
+ if (addSingle) LookAlertDialog(
+ onDismissRequest = { addSingle = false },
+ containerColor = look.dialog,
+ title = { Text(stringResource(R.string.accounts_add), color = look.text) },
+ text = { Text(stringResource(R.string.accounts_single_footer), color = look.muted) },
+ confirmButton = {
+ TextButton(onClick = { addSingle = false; onLeave(); SessionActions.addAccount(Graph.app) }) {
+ Text(stringResource(R.string.connect_device_menu_logout), color = look.accent)
+ }
+ },
+ dismissButton = { TextButton(onClick = { addSingle = false }) { Text(stringResource(R.string.add_to_playlist_button_cancel), color = look.text) } },
+ )
+}
+
+/** The detail of the "Switch account" row behind the avatar: the other accounts kept, by name. */
+@Composable
+fun switchAccountDetail(): String {
+ val list by MyspotiRuntime.host.accounts.list.collectAsStateWithLifecycle()
+ return list.others.mapNotNull { it.name?.takeIf { n -> n.isNotBlank() } }.joinToString(", ")
+ .ifEmpty { stringResource(R.string.accounts_switch_row_detail) }
+}
+
+/** [AccountsList] in a sheet of the current look, from the sheet behind the avatar. */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun AccountsSheet(onDismiss: () -> Unit, onLeave: () -> Unit = onDismiss) {
+ val look = accountsLook()
+ LookSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), containerColor = tone(0xFF282828)) {
+ Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(bottom = 16.dp)) {
+ Text(stringResource(R.string.accounts_title), color = look.text, fontSize = 18.sp, fontWeight = FontWeight.Bold,
+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
+ // Switching or adding leaves the screens: the sheet goes, and whatever opened it.
+ AccountsList(onLeave = onLeave)
+ }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
index 54f42e01..4eeabaf9 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt
@@ -25,6 +25,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Download
import androidx.compose.material.icons.rounded.Extension
import androidx.compose.material.icons.rounded.Palette
+import androidx.compose.material.icons.rounded.Person
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.SignalCellularAlt
import androidx.compose.material.icons.rounded.Info
@@ -70,7 +71,7 @@ import com.music.spotui.ui.screens.shareDiagnosticReport
import kotlinx.coroutines.launch
/** Where the Immersive Settings are: the list of categories, one category, or a choice inside it. */
-private enum class SettingsPage { Root, Playback, StreamingWifi, StreamingCell, Crossfade, Downloads, DownloadQuality, Storage, Data, Display, Look, Rotation, Language, LyricsLanguage, App }
+private enum class SettingsPage { Root, Playback, StreamingWifi, StreamingCell, Crossfade, Downloads, DownloadQuality, Storage, Data, Display, Look, Rotation, Language, LyricsLanguage, App, Accounts }
private val StreamingChoices = listOf(
Triple(StreamingQuality.AUTO, R.string.quality_streaming_auto, R.string.quality_streaming_auto_detail),
@@ -141,6 +142,7 @@ fun ImmersiveSettingsScreen(navController: NavController) {
SettingsPage.Language -> LanguagePage(back)
SettingsPage.LyricsLanguage -> LyricsLanguagePage(back)
SettingsPage.App -> AppPage(navController, back)
+ SettingsPage.Accounts -> AccountsPage(back)
}
}
}
@@ -160,6 +162,14 @@ private fun SettingsRoot(navController: NavController, open: (SettingsPage) -> U
row { ImmersiveGroupRow(stringResource(R.string.settings_section_display), icon = Icons.Rounded.Palette, chevron = true, onClick = { open(SettingsPage.Display) }) }
row { ImmersiveGroupRow(stringResource(R.string.settings_section_app), icon = Icons.Rounded.Info, chevron = true, onClick = { open(SettingsPage.App) }) }
}
+ immersiveGroup("accounts") {
+ row {
+ ImmersiveGroupRow(
+ stringResource(R.string.accounts_title), detail = com.music.spotui.ui.components.switchAccountDetail(),
+ icon = Icons.Rounded.Person, chevron = true, onClick = { open(SettingsPage.Accounts) },
+ )
+ }
+ }
immersiveGroup("extensions") {
row {
ImmersiveGroupRow(
@@ -985,3 +995,23 @@ private fun AppPage(navController: NavController, back: () -> Unit) {
}
}
}
+
+// ---------------------------------------------------------------- Accounts
+
+/** The Spotify accounts kept on the phone ([com.music.spotui.ui.components.AccountsList]), and signing this one out. */
+@Composable
+private fun AccountsPage(back: () -> Unit) {
+ ImmersivePage(title = stringResource(R.string.accounts_title), onBack = back) {
+ immersiveGroup("accounts") {
+ row { com.music.spotui.ui.components.AccountsList() }
+ }
+ immersiveGroup("sign-out") {
+ row {
+ ImmersiveGroupRow(
+ stringResource(R.string.connect_device_menu_logout), destructive = true,
+ onClick = { com.music.spotui.di.SessionActions.logout(com.music.spotui.di.Graph.app) },
+ )
+ }
+ }
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeProfile.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeProfile.kt
index 2ce45333..164a2bd6 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeProfile.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveHomeProfile.kt
@@ -202,6 +202,12 @@ internal fun ImmersiveProfileSheet(onOpen: (route: String) -> Unit, onDismiss: (
perks = true
}
}
+ // The other Spotify accounts kept on the phone: switch, add, remove.
+ var accounts by remember { mutableStateOf(false) }
+ if (accounts) com.music.spotui.ui.components.AccountsSheet(onDismiss = { accounts = false }, onLeave = { accounts = false; onDismiss() })
+ SheetRow(stringResource(R.string.accounts_switch_row), com.music.spotui.ui.components.switchAccountDetail()) {
+ accounts = true
+ }
SheetRow(stringResource(R.string.connect_device_menu_logout), null) {
onDismiss()
SessionActions.logout(Graph.app)
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/AccountBrowser.kt b/base/app/src/main/java/com/music/spotui/ui/screens/AccountBrowser.kt
index 375f07da..14f28d9b 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/AccountBrowser.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/AccountBrowser.kt
@@ -5,7 +5,6 @@ import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
-import android.webkit.CookieManager
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.OnBackPressedCallback
@@ -21,7 +20,7 @@ import java.util.concurrent.TimeUnit
/**
* Spotify's account pages (plan, privacy, apps, devices) in a browser that shares the
- * app's sign-in: WebViews of one app share cookies, so no second login.
+ * app's sign-in: WebViews on the same profile (the active account's) share cookies, so no second login.
*/
class AccountBrowser : ComponentActivity() {
private lateinit var web: WebView
@@ -30,9 +29,12 @@ class AccountBrowser : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
web = WebView(this).apply {
+ // The active account's WebView profile, before anything else: its sign-in is the one shared.
+ val host = app.myspoti.host.android.MyspotiRuntime.host
+ host.useProfile(this)
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
- CookieManager.getInstance().setAcceptThirdPartyCookies(this, true)
+ host.cookies().setAcceptThirdPartyCookies(this, true)
webViewClient = WebViewClient()
}
val url = intent.getStringExtra(EXTRA_URL) ?: ACCOUNT_URL
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 1d9532fe..a954eef4 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
@@ -577,6 +577,15 @@ private fun ProfileSheet(onOpen: (route: String) -> Unit = {}, onDismiss: () ->
Text(stringResource(R.string.supporter_perks_title), color = AppText, fontSize = 16.sp)
Text(stringResource(R.string.supporter_perks_detail), color = AppMuted, fontSize = 12.sp)
}
+ // The other Spotify accounts kept on the phone: switch, add, remove.
+ var accounts by remember { androidx.compose.runtime.mutableStateOf(false) }
+ if (accounts) com.music.spotui.ui.components.AccountsSheet(onDismiss = { accounts = false }, onLeave = { accounts = false; onDismiss() })
+ androidx.compose.foundation.layout.Column(
+ Modifier.fillMaxWidth().clickable { accounts = true }.padding(horizontal = 20.dp, vertical = 10.dp),
+ ) {
+ Text(stringResource(R.string.accounts_switch_row), color = AppText, fontSize = 16.sp)
+ Text(com.music.spotui.ui.components.switchAccountDetail(), color = AppMuted, fontSize = 12.sp)
+ }
Text(
stringResource(R.string.connect_device_menu_logout),
color = AppText, fontSize = 16.sp,
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 da44cb85..f1d48c30 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
@@ -76,7 +76,7 @@ fun SettingsScreen(navController: NavController) {
// One tab per group, so the page is no longer one long list.
var tab by androidx.compose.runtime.saveable.rememberSaveable { mutableStateOf(0) }
val tabs = listOf(R.string.settings_section_playback, R.string.settings_section_downloads, R.string.settings_tab_appearance,
- R.string.extensions_title, R.string.settings_tab_about)
+ R.string.extensions_title, R.string.settings_tab_about, R.string.accounts_title)
androidx.compose.material3.ScrollableTabRow(
selectedTabIndex = tab, containerColor = Color.Transparent, contentColor = AppText, edgePadding = 12.dp,
indicator = { positions ->
@@ -406,6 +406,17 @@ fun SettingsScreen(navController: NavController) {
Text(stringResource(R.string.diagnostic_export_detail), color = AppMuted, fontSize = 12.sp)
}
}
+ if (tab == 5) {
+ // The Spotify accounts kept on the phone: switch, add, remove; and signing this one out.
+ Section(R.string.accounts_title)
+ com.music.spotui.ui.components.AccountsList()
+ Divider()
+ Text(
+ stringResource(R.string.connect_device_menu_logout), color = AppText, fontSize = 16.sp,
+ modifier = Modifier.fillMaxWidth().clickable { com.music.spotui.di.SessionActions.logout(com.music.spotui.di.Graph.app) }
+ .padding(horizontal = 20.dp, vertical = 14.dp),
+ )
+ }
// Clear of the mini player and the navigation bar, as every other page (96 dp left the
// last rows, "Restart the player" among them, under the mini player).
Spacer(Modifier.height(com.music.spotui.ui.components.bottomBarsSpace()))
diff --git a/base/app/src/main/res/values-de/accounts_strings.xml b/base/app/src/main/res/values-de/accounts_strings.xml
new file mode 100644
index 00000000..2a5faa80
--- /dev/null
+++ b/base/app/src/main/res/values-de/accounts_strings.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Several Spotify accounts kept on the phone: Settings > Accounts and the sheet behind the avatar. -->
+<resources>
+ <string name="accounts_title">Konten</string>
+ <string name="accounts_switch_row">Konto wechseln</string>
+ <string name="accounts_switch_row_detail">Deine Spotify-Konten auf diesem Telefon</string>
+ <string name="accounts_add">Konto hinzufügen</string>
+ <string name="accounts_add_detail">Öffnet die Spotify-Anmeldung; die Konten hier bleiben angemeldet</string>
+ <string name="accounts_add_single_detail">Meldet dieses Konto ab und öffnet die Spotify-Anmeldung</string>
+ <string name="accounts_not_signed_in">Nicht angemeldet</string>
+ <string name="accounts_in_use">Aktiv</string>
+ <string name="accounts_plan_premium">Premium</string>
+ <string name="accounts_plan_free">Free</string>
+ <string name="accounts_switch_title">Zu %1$s wechseln?</string>
+ <string name="accounts_switch_text">Die Wiedergabe stoppt. Downloads und der Hörverlauf gehören zu ihrem eigenen Konto; Erweiterungen laufen weiter.</string>
+ <string name="accounts_switch_confirm">Wechseln</string>
+ <string name="accounts_remove">Entfernen</string>
+ <string name="accounts_remove_title">%1$s entfernen?</string>
+ <string name="accounts_remove_text">Anmeldung und Webdaten werden von diesem Telefon gelöscht, ebenso der Hörverlauf. Die Downloads werden beiseitegelegt und kommen zurück, wenn du das Konto wieder hinzufügst.</string>
+ <string name="accounts_footer">Jedes Konto bleibt auf diesem Telefon angemeldet. Ein Wechsel stoppt die Wiedergabe; Downloads und Hörverlauf gehören zu ihrem Konto; Erweiterungen laufen weiter.</string>
+ <string name="accounts_single_footer">Das WebView dieses Telefons hält nur ein Konto gleichzeitig: Wechseln oder Hinzufügen meldet dieses Konto ab und öffnet die Spotify-Anmeldung. Mit einem aktuellen Android System WebView bleiben mehrere Konten angemeldet.</string>
+ <string name="accounts_back_to">Zurück zu %1$s</string>
+</resources>
diff --git a/base/app/src/main/res/values-el/accounts_strings.xml b/base/app/src/main/res/values-el/accounts_strings.xml
new file mode 100644
index 00000000..dd2b669e
--- /dev/null
+++ b/base/app/src/main/res/values-el/accounts_strings.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Several Spotify accounts kept on the phone: Settings > Accounts and the sheet behind the avatar. -->
+<resources>
+ <string name="accounts_title">Λογαριασμοί</string>
+ <string name="accounts_switch_row">Αλλαγή λογαριασμού</string>
+ <string name="accounts_switch_row_detail">Οι λογαριασμοί σας Spotify σε αυτό το τηλέφωνο</string>
+ <string name="accounts_add">Προσθήκη λογαριασμού</string>
+ <string name="accounts_add_detail">Ανοίγει τη σύνδεση του Spotify· οι λογαριασμοί εδώ παραμένουν συνδεδεμένοι</string>
+ <string name="accounts_add_single_detail">Αποσυνδέει αυτόν τον λογαριασμό και ανοίγει τη σύνδεση του Spotify</string>
+ <string name="accounts_not_signed_in">Μη συνδεδεμένος</string>
+ <string name="accounts_in_use">Σε χρήση</string>
+ <string name="accounts_plan_premium">Premium</string>
+ <string name="accounts_plan_free">Δωρεάν</string>
+ <string name="accounts_switch_title">Αλλαγή σε %1$s;</string>
+ <string name="accounts_switch_text">Η αναπαραγωγή σταματά. Οι λήψεις και το ιστορικό ακρόασης ακολουθούν τον δικό τους λογαριασμό· οι επεκτάσεις συνεχίζουν να λειτουργούν.</string>
+ <string name="accounts_switch_confirm">Αλλαγή</string>
+ <string name="accounts_remove">Αφαίρεση</string>
+ <string name="accounts_remove_title">Αφαίρεση %1$s;</string>
+ <string name="accounts_remove_text">Η σύνδεση και τα δεδομένα web του διαγράφονται από αυτό το τηλέφωνο, μαζί με το ιστορικό ακρόασης. Οι λήψεις του φυλάσσονται και επιστρέφουν αν τον προσθέσετε ξανά.</string>
+ <string name="accounts_footer">Κάθε λογαριασμός παραμένει συνδεδεμένος σε αυτό το τηλέφωνο. Η αλλαγή σταματά την αναπαραγωγή· οι λήψεις και το ιστορικό ακρόασης ακολουθούν τον λογαριασμό τους· οι επεκτάσεις συνεχίζουν να λειτουργούν.</string>
+ <string name="accounts_single_footer">Το WebView αυτού του τηλεφώνου κρατά έναν λογαριασμό τη φορά: η αλλαγή ή η προσθήκη λογαριασμού αποσυνδέει αυτόν και ανοίγει τη σύνδεση του Spotify. Με ενημέρωση του Android System WebView μένουν συνδεδεμένοι πολλοί λογαριασμοί.</string>
+ <string name="accounts_back_to">Επιστροφή σε %1$s</string>
+</resources>
diff --git a/base/app/src/main/res/values-es/accounts_strings.xml b/base/app/src/main/res/values-es/accounts_strings.xml
new file mode 100644
index 00000000..5a4d557e
--- /dev/null
+++ b/base/app/src/main/res/values-es/accounts_strings.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Several Spotify accounts kept on the phone: Settings > Accounts and the sheet behind the avatar. -->
+<resources>
+ <string name="accounts_title">Cuentas</string>
+ <string name="accounts_switch_row">Cambiar de cuenta</string>
+ <string name="accounts_switch_row_detail">Tus cuentas de Spotify en este teléfono</string>
+ <string name="accounts_add">Añadir cuenta</string>
+ <string name="accounts_add_detail">Abre el inicio de sesión de Spotify; las cuentas de aquí siguen conectadas</string>
+ <string name="accounts_add_single_detail">Cierra la sesión de esta cuenta y abre el inicio de sesión de Spotify</string>
+ <string name="accounts_not_signed_in">Sin sesión iniciada</string>
+ <string name="accounts_in_use">En uso</string>
+ <string name="accounts_plan_premium">Premium</string>
+ <string name="accounts_plan_free">Free</string>
+ <string name="accounts_switch_title">¿Cambiar a %1$s?</string>
+ <string name="accounts_switch_text">La reproducción se detiene. Las descargas y el historial de escucha siguen a su propia cuenta; las extensiones siguen funcionando.</string>
+ <string name="accounts_switch_confirm">Cambiar</string>
+ <string name="accounts_remove">Quitar</string>
+ <string name="accounts_remove_title">¿Quitar %1$s?</string>
+ <string name="accounts_remove_text">Su sesión y sus datos web se borran de este teléfono, junto con su historial de escucha. Sus descargas se guardan aparte y vuelven si la añades de nuevo.</string>
+ <string name="accounts_footer">Cada cuenta sigue con la sesión iniciada en este teléfono. Cambiar detiene la reproducción; las descargas y el historial de escucha siguen a su cuenta; las extensiones siguen funcionando.</string>
+ <string name="accounts_single_footer">El WebView de este teléfono guarda una sola cuenta a la vez: cambiar o añadir una cuenta cierra la sesión de esta y abre el inicio de sesión de Spotify. Actualizar Android System WebView permite mantener varias cuentas conectadas.</string>
+ <string name="accounts_back_to">De vuelta a %1$s</string>
+</resources>
diff --git a/base/app/src/main/res/values-fr/accounts_strings.xml b/base/app/src/main/res/values-fr/accounts_strings.xml
new file mode 100644
index 00000000..38284465
--- /dev/null
+++ b/base/app/src/main/res/values-fr/accounts_strings.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Several Spotify accounts kept on the phone: Settings > Accounts and the sheet behind the avatar. -->
+<resources>
+ <string name="accounts_title">Comptes</string>
+ <string name="accounts_switch_row">Changer de compte</string>
+ <string name="accounts_switch_row_detail">Vos comptes Spotify sur ce téléphone</string>
+ <string name="accounts_add">Ajouter un compte</string>
+ <string name="accounts_add_detail">Ouvre la connexion Spotify ; les comptes déjà ici restent connectés</string>
+ <string name="accounts_add_single_detail">Déconnecte ce compte et ouvre la connexion Spotify</string>
+ <string name="accounts_not_signed_in">Non connecté</string>
+ <string name="accounts_in_use">Utilisé</string>
+ <string name="accounts_plan_premium">Premium</string>
+ <string name="accounts_plan_free">Gratuit</string>
+ <string name="accounts_switch_title">Passer à %1$s ?</string>
+ <string name="accounts_switch_text">La lecture s\'arrête. Les téléchargements et l\'historique d\'écoute suivent leur propre compte ; les extensions continuent de fonctionner.</string>
+ <string name="accounts_switch_confirm">Changer</string>
+ <string name="accounts_remove">Retirer</string>
+ <string name="accounts_remove_title">Retirer %1$s ?</string>
+ <string name="accounts_remove_text">Sa connexion et ses données web sont supprimées de ce téléphone, avec son historique d\'écoute. Ses téléchargements sont mis de côté et reviennent si vous l\'ajoutez à nouveau.</string>
+ <string name="accounts_footer">Chaque compte reste connecté sur ce téléphone. Changer de compte arrête la lecture ; les téléchargements et l\'historique d\'écoute suivent leur compte ; les extensions continuent de fonctionner.</string>
+ <string name="accounts_single_footer">La WebView de ce téléphone ne garde qu\'un compte à la fois : changer ou ajouter un compte déconnecte celui-ci et ouvre la connexion Spotify. Mettre à jour Android System WebView permet de garder plusieurs comptes connectés.</string>
+ <string name="accounts_back_to">Retour à %1$s</string>
+</resources>
diff --git a/base/app/src/main/res/values-it/accounts_strings.xml b/base/app/src/main/res/values-it/accounts_strings.xml
new file mode 100644
index 00000000..42a47136
--- /dev/null
+++ b/base/app/src/main/res/values-it/accounts_strings.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Several Spotify accounts kept on the phone: Settings > Accounts and the sheet behind the avatar. -->
+<resources>
+ <string name="accounts_title">Account</string>
+ <string name="accounts_switch_row">Cambia account</string>
+ <string name="accounts_switch_row_detail">I tuoi account Spotify su questo telefono</string>
+ <string name="accounts_add">Aggiungi account</string>
+ <string name="accounts_add_detail">Apre l\'accesso a Spotify; gli account qui restano connessi</string>
+ <string name="accounts_add_single_detail">Disconnette questo account e apre l\'accesso a Spotify</string>
+ <string name="accounts_not_signed_in">Non connesso</string>
+ <string name="accounts_in_use">In uso</string>
+ <string name="accounts_plan_premium">Premium</string>
+ <string name="accounts_plan_free">Free</string>
+ <string name="accounts_switch_title">Passare a %1$s?</string>
+ <string name="accounts_switch_text">La riproduzione si ferma. I download e la cronologia di ascolto seguono il proprio account; le estensioni continuano a funzionare.</string>
+ <string name="accounts_switch_confirm">Cambia</string>
+ <string name="accounts_remove">Rimuovi</string>
+ <string name="accounts_remove_title">Rimuovere %1$s?</string>
+ <string name="accounts_remove_text">L\'accesso e i dati web vengono eliminati da questo telefono, insieme alla cronologia di ascolto. I download vengono messi da parte e tornano se lo aggiungi di nuovo.</string>
+ <string name="accounts_footer">Ogni account resta connesso su questo telefono. Cambiare account ferma la riproduzione; i download e la cronologia di ascolto seguono il loro account; le estensioni continuano a funzionare.</string>
+ <string name="accounts_single_footer">La WebView di questo telefono tiene un solo account alla volta: cambiare o aggiungere un account disconnette questo e apre l\'accesso a Spotify. Aggiornando Android System WebView più account restano connessi.</string>
+ <string name="accounts_back_to">Di nuovo su %1$s</string>
+</resources>
diff --git a/base/app/src/main/res/values-pl/accounts_strings.xml b/base/app/src/main/res/values-pl/accounts_strings.xml
new file mode 100644
index 00000000..28aafe13
--- /dev/null
+++ b/base/app/src/main/res/values-pl/accounts_strings.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Several Spotify accounts kept on the phone: Settings > Accounts and the sheet behind the avatar. -->
+<resources>
+ <string name="accounts_title">Konta</string>
+ <string name="accounts_switch_row">Zmień konto</string>
+ <string name="accounts_switch_row_detail">Twoje konta Spotify na tym telefonie</string>
+ <string name="accounts_add">Dodaj konto</string>
+ <string name="accounts_add_detail">Otwiera logowanie Spotify; konta tutaj pozostają zalogowane</string>
+ <string name="accounts_add_single_detail">Wylogowuje to konto i otwiera logowanie Spotify</string>
+ <string name="accounts_not_signed_in">Niezalogowane</string>
+ <string name="accounts_in_use">W użyciu</string>
+ <string name="accounts_plan_premium">Premium</string>
+ <string name="accounts_plan_free">Free</string>
+ <string name="accounts_switch_title">Przełączyć na %1$s?</string>
+ <string name="accounts_switch_text">Odtwarzanie się zatrzyma. Pobrane utwory i historia słuchania należą do swojego konta; rozszerzenia działają dalej.</string>
+ <string name="accounts_switch_confirm">Przełącz</string>
+ <string name="accounts_remove">Usuń</string>
+ <string name="accounts_remove_title">Usunąć %1$s?</string>
+ <string name="accounts_remove_text">Logowanie i dane internetowe zostaną usunięte z tego telefonu, razem z historią słuchania. Pobrane utwory zostaną odłożone i wrócą, jeśli dodasz konto ponownie.</string>
+ <string name="accounts_footer">Każde konto pozostaje zalogowane na tym telefonie. Przełączenie zatrzymuje odtwarzanie; pobrane utwory i historia słuchania należą do swojego konta; rozszerzenia działają dalej.</string>
+ <string name="accounts_single_footer">WebView tego telefonu przechowuje jedno konto naraz: zmiana lub dodanie konta wylogowuje to konto i otwiera logowanie Spotify. Aktualizacja Android System WebView pozwala zachować kilka zalogowanych kont.</string>
+ <string name="accounts_back_to">Powrót do %1$s</string>
+</resources>
diff --git a/base/app/src/main/res/values-pt-rBR/accounts_strings.xml b/base/app/src/main/res/values-pt-rBR/accounts_strings.xml
new file mode 100644
index 00000000..9eb138f4
--- /dev/null
+++ b/base/app/src/main/res/values-pt-rBR/accounts_strings.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Several Spotify accounts kept on the phone: Settings > Accounts and the sheet behind the avatar. -->
+<resources>
+ <string name="accounts_title">Contas</string>
+ <string name="accounts_switch_row">Trocar de conta</string>
+ <string name="accounts_switch_row_detail">Suas contas do Spotify neste celular</string>
+ <string name="accounts_add">Adicionar conta</string>
+ <string name="accounts_add_detail">Abre o login do Spotify; as contas daqui continuam conectadas</string>
+ <string name="accounts_add_single_detail">Desconecta esta conta e abre o login do Spotify</string>
+ <string name="accounts_not_signed_in">Não conectada</string>
+ <string name="accounts_in_use">Em uso</string>
+ <string name="accounts_plan_premium">Premium</string>
+ <string name="accounts_plan_free">Free</string>
+ <string name="accounts_switch_title">Trocar para %1$s?</string>
+ <string name="accounts_switch_text">A reprodução para. Os downloads e o histórico de reprodução seguem a própria conta; as extensões continuam funcionando.</string>
+ <string name="accounts_switch_confirm">Trocar</string>
+ <string name="accounts_remove">Remover</string>
+ <string name="accounts_remove_title">Remover %1$s?</string>
+ <string name="accounts_remove_text">O login e os dados da web são apagados deste celular, junto com o histórico de reprodução. Os downloads ficam guardados à parte e voltam se você adicionar a conta de novo.</string>
+ <string name="accounts_footer">Cada conta continua conectada neste celular. Trocar de conta interrompe a reprodução; os downloads e o histórico de reprodução seguem a sua conta; as extensões continuam funcionando.</string>
+ <string name="accounts_single_footer">O WebView deste celular guarda uma conta por vez: trocar ou adicionar uma conta desconecta esta e abre o login do Spotify. Atualizar o Android System WebView permite manter várias contas conectadas.</string>
+ <string name="accounts_back_to">De volta para %1$s</string>
+</resources>
diff --git a/base/app/src/main/res/values-pt-rPT/accounts_strings.xml b/base/app/src/main/res/values-pt-rPT/accounts_strings.xml
new file mode 100644
index 00000000..6d574e78
--- /dev/null
+++ b/base/app/src/main/res/values-pt-rPT/accounts_strings.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Several Spotify accounts kept on the phone: Settings > Accounts and the sheet behind the avatar. -->
+<resources>
+ <string name="accounts_title">Contas</string>
+ <string name="accounts_switch_row">Mudar de conta</string>
+ <string name="accounts_switch_row_detail">As suas contas Spotify neste telemóvel</string>
+ <string name="accounts_add">Adicionar conta</string>
+ <string name="accounts_add_detail">Abre o início de sessão do Spotify; as contas aqui continuam ligadas</string>
+ <string name="accounts_add_single_detail">Termina a sessão desta conta e abre o início de sessão do Spotify</string>
+ <string name="accounts_not_signed_in">Sem sessão iniciada</string>
+ <string name="accounts_in_use">Em uso</string>
+ <string name="accounts_plan_premium">Premium</string>
+ <string name="accounts_plan_free">Free</string>
+ <string name="accounts_switch_title">Mudar para %1$s?</string>
+ <string name="accounts_switch_text">A reprodução para. As transferências e o histórico de audição seguem a sua própria conta; as extensões continuam a funcionar.</string>
+ <string name="accounts_switch_confirm">Mudar</string>
+ <string name="accounts_remove">Remover</string>
+ <string name="accounts_remove_title">Remover %1$s?</string>
+ <string name="accounts_remove_text">A sessão e os dados web são apagados deste telemóvel, com o histórico de audição. As transferências ficam guardadas à parte e voltam se a adicionar de novo.</string>
+ <string name="accounts_footer">Cada conta continua com sessão iniciada neste telemóvel. Mudar de conta interrompe a reprodução; as transferências e o histórico de audição seguem a sua conta; as extensões continuam a funcionar.</string>
+ <string name="accounts_single_footer">O WebView deste telemóvel guarda uma conta de cada vez: mudar ou adicionar uma conta termina a sessão desta e abre o início de sessão do Spotify. Atualizar o Android System WebView permite manter várias contas ligadas.</string>
+ <string name="accounts_back_to">De volta a %1$s</string>
+</resources>
diff --git a/base/app/src/main/res/values-pt/accounts_strings.xml b/base/app/src/main/res/values-pt/accounts_strings.xml
new file mode 100644
index 00000000..9eb138f4
--- /dev/null
+++ b/base/app/src/main/res/values-pt/accounts_strings.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Several Spotify accounts kept on the phone: Settings > Accounts and the sheet behind the avatar. -->
+<resources>
+ <string name="accounts_title">Contas</string>
+ <string name="accounts_switch_row">Trocar de conta</string>
+ <string name="accounts_switch_row_detail">Suas contas do Spotify neste celular</string>
+ <string name="accounts_add">Adicionar conta</string>
+ <string name="accounts_add_detail">Abre o login do Spotify; as contas daqui continuam conectadas</string>
+ <string name="accounts_add_single_detail">Desconecta esta conta e abre o login do Spotify</string>
+ <string name="accounts_not_signed_in">Não conectada</string>
+ <string name="accounts_in_use">Em uso</string>
+ <string name="accounts_plan_premium">Premium</string>
+ <string name="accounts_plan_free">Free</string>
+ <string name="accounts_switch_title">Trocar para %1$s?</string>
+ <string name="accounts_switch_text">A reprodução para. Os downloads e o histórico de reprodução seguem a própria conta; as extensões continuam funcionando.</string>
+ <string name="accounts_switch_confirm">Trocar</string>
+ <string name="accounts_remove">Remover</string>
+ <string name="accounts_remove_title">Remover %1$s?</string>
+ <string name="accounts_remove_text">O login e os dados da web são apagados deste celular, junto com o histórico de reprodução. Os downloads ficam guardados à parte e voltam se você adicionar a conta de novo.</string>
+ <string name="accounts_footer">Cada conta continua conectada neste celular. Trocar de conta interrompe a reprodução; os downloads e o histórico de reprodução seguem a sua conta; as extensões continuam funcionando.</string>
+ <string name="accounts_single_footer">O WebView deste celular guarda uma conta por vez: trocar ou adicionar uma conta desconecta esta e abre o login do Spotify. Atualizar o Android System WebView permite manter várias contas conectadas.</string>
+ <string name="accounts_back_to">De volta para %1$s</string>
+</resources>
diff --git a/base/app/src/main/res/values-ru/accounts_strings.xml b/base/app/src/main/res/values-ru/accounts_strings.xml
new file mode 100644
index 00000000..f6b52f44
--- /dev/null
+++ b/base/app/src/main/res/values-ru/accounts_strings.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Several Spotify accounts kept on the phone: Settings > Accounts and the sheet behind the avatar. -->
+<resources>
+ <string name="accounts_title">Аккаунты</string>
+ <string name="accounts_switch_row">Сменить аккаунт</string>
+ <string name="accounts_switch_row_detail">Ваши аккаунты Spotify на этом телефоне</string>
+ <string name="accounts_add">Добавить аккаунт</string>
+ <string name="accounts_add_detail">Открывает вход в Spotify; аккаунты здесь остаются в системе</string>
+ <string name="accounts_add_single_detail">Выходит из этого аккаунта и открывает вход в Spotify</string>
+ <string name="accounts_not_signed_in">Вход не выполнен</string>
+ <string name="accounts_in_use">Используется</string>
+ <string name="accounts_plan_premium">Premium</string>
+ <string name="accounts_plan_free">Free</string>
+ <string name="accounts_switch_title">Переключиться на %1$s?</string>
+ <string name="accounts_switch_text">Воспроизведение остановится. Загрузки и история прослушивания остаются со своим аккаунтом; расширения продолжают работать.</string>
+ <string name="accounts_switch_confirm">Переключить</string>
+ <string name="accounts_remove">Удалить</string>
+ <string name="accounts_remove_title">Удалить %1$s?</string>
+ <string name="accounts_remove_text">Вход и веб-данные будут удалены с этого телефона вместе с историей прослушивания. Загрузки откладываются и вернутся, если вы снова добавите аккаунт.</string>
+ <string name="accounts_footer">Каждый аккаунт остаётся в системе на этом телефоне. Переключение останавливает воспроизведение; загрузки и история прослушивания остаются со своим аккаунтом; расширения продолжают работать.</string>
+ <string name="accounts_single_footer">WebView этого телефона хранит только один аккаунт: смена или добавление аккаунта выходит из этого и открывает вход в Spotify. После обновления Android System WebView несколько аккаунтов смогут оставаться в системе.</string>
+ <string name="accounts_back_to">Снова %1$s</string>
+</resources>
diff --git a/base/app/src/main/res/values-zh/accounts_strings.xml b/base/app/src/main/res/values-zh/accounts_strings.xml
new file mode 100644
index 00000000..ae16bb13
--- /dev/null
+++ b/base/app/src/main/res/values-zh/accounts_strings.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Several Spotify accounts kept on the phone: Settings > Accounts and the sheet behind the avatar. -->
+<resources>
+ <string name="accounts_title">账号</string>
+ <string name="accounts_switch_row">切换账号</string>
+ <string name="accounts_switch_row_detail">此手机上的 Spotify 账号</string>
+ <string name="accounts_add">添加账号</string>
+ <string name="accounts_add_detail">打开 Spotify 登录;这里的账号保持登录</string>
+ <string name="accounts_add_single_detail">退出此账号并打开 Spotify 登录</string>
+ <string name="accounts_not_signed_in">未登录</string>
+ <string name="accounts_in_use">使用中</string>
+ <string name="accounts_plan_premium">Premium</string>
+ <string name="accounts_plan_free">免费</string>
+ <string name="accounts_switch_title">切换到 %1$s?</string>
+ <string name="accounts_switch_text">播放会停止。下载和收听历史跟随各自的账号;扩展继续运行。</string>
+ <string name="accounts_switch_confirm">切换</string>
+ <string name="accounts_remove">移除</string>
+ <string name="accounts_remove_title">移除 %1$s?</string>
+ <string name="accounts_remove_text">其登录和网页数据将从此手机删除,收听历史也一并删除。其下载内容会被保留在一旁,再次添加该账号时会恢复。</string>
+ <string name="accounts_footer">每个账号在此手机上保持登录。切换会停止播放;下载和收听历史跟随各自的账号;扩展继续运行。</string>
+ <string name="accounts_single_footer">此手机的 WebView 一次只能保留一个账号:切换或添加账号会退出当前账号并打开 Spotify 登录。更新 Android System WebView 后可同时保持多个账号登录。</string>
+ <string name="accounts_back_to">已返回 %1$s</string>
+</resources>
diff --git a/base/app/src/main/res/values/accounts_strings.xml b/base/app/src/main/res/values/accounts_strings.xml
new file mode 100644
index 00000000..ad600bc4
--- /dev/null
+++ b/base/app/src/main/res/values/accounts_strings.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Several Spotify accounts kept on the phone: Settings > Accounts and the sheet behind the avatar. -->
+<resources>
+ <string name="accounts_title">Accounts</string>
+ <string name="accounts_switch_row">Switch account</string>
+ <string name="accounts_switch_row_detail">Your Spotify accounts on this phone</string>
+ <string name="accounts_add">Add account</string>
+ <string name="accounts_add_detail">Opens Spotify\'s sign-in; the accounts here stay signed in</string>
+ <string name="accounts_add_single_detail">Signs this account out and opens Spotify\'s sign-in</string>
+ <string name="accounts_not_signed_in">Not signed in</string>
+ <string name="accounts_in_use">In use</string>
+ <string name="accounts_plan_premium">Premium</string>
+ <string name="accounts_plan_free">Free</string>
+ <string name="accounts_switch_title">Switch to %1$s?</string>
+ <string name="accounts_switch_text">Playback stops. Downloads and the listening history follow their own account; extensions keep running.</string>
+ <string name="accounts_switch_confirm">Switch</string>
+ <string name="accounts_remove">Remove</string>
+ <string name="accounts_remove_title">Remove %1$s?</string>
+ <string name="accounts_remove_text">Its sign-in and web data are deleted from this phone, with its listening history. Its downloads are kept aside and come back if you add it again.</string>
+ <string name="accounts_footer">Each account stays signed in on this phone. Switching stops playback; downloads and the listening history follow their account; extensions keep running.</string>
+ <string name="accounts_single_footer">This phone\'s WebView keeps one account at a time: switching or adding an account signs this one out and opens Spotify\'s sign-in. Updating Android System WebView lets several accounts stay signed in.</string>
+ <string name="accounts_back_to">Back to %1$s</string>
+</resources>
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/Accounts.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/Accounts.kt
new file mode 100644
index 00000000..2629c7a1
--- /dev/null
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/Accounts.kt
@@ -0,0 +1,196 @@
+package app.myspoti.host.android
+
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.buildJsonArray
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.intOrNull
+import kotlinx.serialization.json.longOrNull
+import kotlinx.serialization.json.put
+import java.io.File
+
+/**
+ * One Spotify account kept on this phone: the WebView profile that holds its sign-in (cookies,
+ * Web storage), and what the app shows of it. No e-mail and no user id: [key] is the opaque folder
+ * key of the downloads (OfflineAccounts), the name and picture are the public profile's.
+ */
+data class SavedAccount(
+ val profile: String,
+ /** Opaque key of the Spotify user (a hash of its id); null until the account was read signed in. */
+ val key: String? = null,
+ val name: String? = null,
+ val imageUrl: String? = null,
+ /** The plan (AccountPlan): true Premium, false Free, null not read yet. */
+ val premium: Boolean? = null,
+ /** When it was last the active account (ms): the account to go back to is the one used last. */
+ val usedAt: Long = 0L,
+) {
+ /** Signed in on its profile at least once: something to switch to. */
+ val known: Boolean get() = key != null
+}
+
+/**
+ * The accounts kept on this phone, each in a WebView profile of its own, and the active one (the
+ * profile the page is built with). Pure: every change returns a new list, [AccountStore] keeps it.
+ *
+ * The account a WebView without profiles holds is in [DEFAULT_PROFILE], so an install from before
+ * keeps its sign-in as its first account.
+ */
+data class AccountList(
+ val active: String = DEFAULT_PROFILE,
+ val accounts: List<SavedAccount> = emptyList(),
+ /** Number of the next profile [adding] makes. Never reused: a profile still being deleted keeps its name. */
+ val next: Int = 1,
+ /** Profiles removed whose data could not be deleted yet (still in use by a WebView): deleted later. */
+ val doomed: List<String> = emptyList(),
+) {
+ val current: SavedAccount? get() = accounts.firstOrNull { it.profile == active }
+
+ /** The accounts signed in at least once other than the active one, the one used last first. */
+ val others: List<SavedAccount> get() = accounts.filter { it.profile != active && it.known }.sortedByDescending { it.usedAt }
+
+ /** A new, empty profile for another account, made the active one; its name is returned with the list. */
+ fun adding(now: Long): Pair<AccountList, String> {
+ var n = next
+ var name = "$PROFILE_PREFIX$n"
+ while (accounts.any { it.profile == name } || name in doomed) { n++; name = "$PROFILE_PREFIX$n" }
+ val list = copy(
+ active = name,
+ accounts = touched(now) + SavedAccount(profile = name, usedAt = now),
+ next = n + 1,
+ )
+ return list to name
+ }
+
+ /** [profile] becomes the active one (unchanged when it is not kept here). */
+ fun switchTo(profile: String, now: Long): AccountList {
+ if (accounts.none { it.profile == profile }) return this
+ return copy(active = profile, accounts = touched(now).map { if (it.profile == profile) it.copy(usedAt = now) else it })
+ }
+
+ /**
+ * [profile] is signed in as the account [key], named [name] with the picture [imageUrl]. The same
+ * account kept in another profile too (signed in twice through "Add account") is one account: the
+ * profile just signed in stays, the others are dropped and returned, for their data to be deleted.
+ */
+ fun signedIn(profile: String, key: String, name: String?, imageUrl: String?, now: Long): Pair<AccountList, List<String>> {
+ val duplicates = accounts.filter { it.profile != profile && it.key == key }.map { it.profile }
+ val mine = accounts.firstOrNull { it.profile == profile }
+ val updated = (mine ?: SavedAccount(profile = profile)).copy(
+ key = key,
+ name = name?.takeIf { it.isNotBlank() } ?: mine?.name?.takeIf { mine.key == key },
+ imageUrl = imageUrl?.takeIf { it.isNotBlank() } ?: mine?.imageUrl?.takeIf { mine.key == key },
+ // Another account signed in on that profile (after a sign-out) has its own plan, read later.
+ premium = mine?.premium?.takeIf { mine.key == key },
+ usedAt = if (profile == active) now else mine?.usedAt ?: 0L,
+ )
+ val kept = (if (mine == null) accounts + updated else accounts.map { if (it.profile == profile) updated else it })
+ .filter { it.profile !in duplicates }
+ val list = copy(accounts = kept, doomed = doomed + duplicates.filter { it !in doomed })
+ return list to duplicates
+ }
+
+ /** The plan of [profile]'s account read (or forgotten: null keeps the one known). */
+ fun plan(profile: String, premium: Boolean?): AccountList {
+ if (premium == null) return this
+ return copy(accounts = accounts.map { if (it.profile == profile && it.known) it.copy(premium = premium) else it })
+ }
+
+ /** [profile] signed out: it stays the profile it is, with no account in it any more. */
+ fun signedOut(profile: String): AccountList =
+ copy(accounts = accounts.map { if (it.profile == profile) SavedAccount(profile = profile, usedAt = it.usedAt) else it })
+
+ /**
+ * [profile] is no longer kept: its entry goes, and its data is to be deleted ([doomed]); the
+ * default profile cannot be deleted and is cleared instead (by the host). The active profile is
+ * never removed here: the page is first moved to another one ([switchTo]).
+ */
+ fun removed(profile: String): AccountList {
+ if (profile == active || accounts.none { it.profile == profile }) return this
+ return copy(
+ accounts = accounts.filter { it.profile != profile },
+ doomed = if (profile in doomed) doomed else doomed + profile,
+ )
+ }
+
+ /** [profile]'s data was deleted (or never existed): nothing left to do for it. */
+ fun deleted(profile: String): AccountList = copy(doomed = doomed - profile)
+
+ private fun touched(now: Long) = accounts.map { if (it.profile == active) it.copy(usedAt = now) else it }
+
+ fun toJson(): String = buildJsonObject {
+ put("active", active)
+ put("next", next)
+ put("accounts", buildJsonArray {
+ accounts.forEach { a ->
+ add(buildJsonObject {
+ put("profile", a.profile)
+ a.key?.let { put("key", it) }
+ a.name?.let { put("name", it) }
+ a.imageUrl?.let { put("image", it) }
+ a.premium?.let { put("premium", it) }
+ put("used", a.usedAt)
+ })
+ }
+ })
+ put("doomed", buildJsonArray { doomed.forEach { add(JsonPrimitive(it)) } })
+ }.toString()
+
+ companion object {
+ /** androidx.webkit.Profile.DEFAULT_PROFILE_NAME: the profile every WebView used before. */
+ const val DEFAULT_PROFILE = "Default"
+ const val PROFILE_PREFIX = "account-"
+
+ /** The list saved by [toJson]; an empty one (the default profile active) when there is none or it cannot be read. */
+ fun fromJson(text: String?): AccountList {
+ val o = text?.let { runCatching { Json.parseToJsonElement(it) as? JsonObject }.getOrNull() } ?: return AccountList()
+ fun JsonObject.str(k: String) = (this[k] as? JsonPrimitive)?.contentOrNull
+ val accounts = (o["accounts"] as? JsonArray).orEmpty().mapNotNull { e ->
+ val a = e as? JsonObject ?: return@mapNotNull null
+ val profile = a.str("profile")?.takeIf { it.isNotBlank() } ?: return@mapNotNull null
+ SavedAccount(
+ profile = profile,
+ key = a.str("key"),
+ name = a.str("name"),
+ imageUrl = a.str("image"),
+ premium = (a["premium"] as? JsonPrimitive)?.booleanOrNull,
+ usedAt = (a["used"] as? JsonPrimitive)?.longOrNull ?: 0L,
+ )
+ }.distinctBy { it.profile }
+ val doomed = (o["doomed"] as? JsonArray).orEmpty().mapNotNull { (it as? JsonPrimitive)?.contentOrNull }
+ val active = o.str("active")?.takeIf { a -> accounts.any { it.profile == a } }
+ ?: accounts.maxByOrNull { it.usedAt }?.profile ?: DEFAULT_PROFILE
+ return AccountList(active, accounts, ((o["next"] as? JsonPrimitive)?.intOrNull ?: 1).coerceAtLeast(1), doomed)
+ }
+ }
+}
+
+/**
+ * The [AccountList] of this install, saved in `filesDir/spotify/accounts.json`. A WebView without
+ * profiles (MULTI_PROFILE unsupported) keeps one account at a time, in [AccountList.DEFAULT_PROFILE].
+ */
+class AccountStore(private val file: File) {
+ private val _list = MutableStateFlow(AccountList.fromJson(runCatching { file.readText() }.getOrNull()))
+ val list: StateFlow<AccountList> = _list
+
+ /** Applies [change] and saves the result; returns it. */
+ fun update(change: (AccountList) -> AccountList): AccountList = synchronized(this) {
+ val next = change(_list.value)
+ if (next != _list.value) {
+ _list.value = next
+ runCatching {
+ file.parentFile?.mkdirs()
+ val tmp = File(file.parentFile, "${file.name}.tmp")
+ tmp.writeText(next.toJson())
+ if (!tmp.renameTo(file)) { file.writeText(next.toJson()); tmp.delete() }
+ }.onFailure { Logbook.log("accounts: could not be saved (${it.javaClass.simpleName})") }
+ }
+ next
+ }
+}
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 bea20ade..4f6f06a5 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
@@ -17,6 +17,7 @@ import java.util.Locale
*/
object MyspotiRuntime {
lateinit var host: WebPlayerHost
+ private var appContext: Context? = null
private set
lateinit var spotify: SpotifyApi
private set
@@ -32,10 +33,11 @@ object MyspotiRuntime {
/** [loadPage] false (data saver on a metered network): nothing goes out until [resume]. */
fun start(context: Context, loadPage: Boolean = true) {
if (isStarted) return
+ appContext = context.applicationContext
val updater = app.myspoti.spotify.gql.GqlOpsUpdater(okhttp3.OkHttpClient(), java.io.File(context.filesDir, "spotify/gql-ops.json"))
host = WebPlayerHost(context)
AudioModeWatch.install(context.applicationContext)
- spotify = SpotifyApi(host, scope, language = Locale.getDefault().language, ops = updater.load(), deviceId = clientDeviceId(context), userAgent = host.userAgent)
+ spotify = SpotifyApi(host, scope, language = Locale.getDefault().language, ops = updater.load(), deviceId = clientDeviceId(context, host.accounts.list.value.active), userAgent = host.userAgent)
spotify.bridge.logger = { line -> Logbook.log(line) }
host.onPageLoaded = { scope.launch { spotify.onPageLoaded() } }
host.onPageStarting = { spotify.onPageStarting() }
@@ -58,8 +60,6 @@ object MyspotiRuntime {
// changes is logged when it changes, not once every 10 s whether or not anything happened.
scope.launch {
var last = ""
- // When the account's plan was last asked for (AccountPlan), so a failed or unknown answer is asked again later.
- var planAskedAt = 0L
// A login page or an anonymous session seen in this run: the sign-in that follows is new.
var sawSignedOut = false
// A page that loaded but whose player never became ready (no bridge, a script that
@@ -85,15 +85,19 @@ object MyspotiRuntime {
if (spotify.ready.value && runCatching { isSignedIn() }.getOrDefault(false)) {
host.noteSignedIn(fresh = sawSignedOut)
val now = android.os.SystemClock.elapsedRealtime()
- if (AccountPlan.premium.value == null && now - planAskedAt >= PLAN_ASK_GAP_MS) {
+ if (AccountPlan.premium.value == null && (planAskedAt == 0L || now - planAskedAt >= PLAN_ASK_GAP_MS)) {
planAskedAt = now
+ // The account asked about: a switch while the answer comes leaves the next one's plan unknown.
+ val profile = host.profile
runCatching {
val answer = spotify.raw.gql("accountAttributes", kotlinx.serialization.json.buildJsonObject { })
val a = ((answer as kotlinx.serialization.json.JsonObject)["data"] as kotlinx.serialization.json.JsonObject)
.let { (it["me"] as kotlinx.serialization.json.JsonObject)["account"] as kotlinx.serialization.json.JsonObject }
val attrs = a["attributes"] as? kotlinx.serialization.json.JsonObject
fun v(o: kotlinx.serialization.json.JsonObject?, k: String) = (o?.get(k) as? kotlinx.serialization.json.JsonPrimitive)?.content
- AccountPlan.set(AccountPlan.fromAnswer(answer))
+ val plan = AccountPlan.fromAnswer(answer)
+ host.accounts.update { it.plan(profile, plan) }
+ if (host.profile == profile) AccountPlan.set(plan)
Logbook.log("account: product=${v(a, "product")} country=${v(a, "country")} catalogue=${v(attrs, "catalogue")} onDemand=${v(attrs, "onDemand")} ads=${v(attrs, "ads")}")
Logbook.fact("account", "product=${v(a, "product")} country=${v(a, "country")} catalogue=${v(attrs, "catalogue")} onDemand=${v(attrs, "onDemand")} ads=${v(attrs, "ads")}")
}
@@ -148,6 +152,21 @@ object MyspotiRuntime {
return runCatching { isSignedIn() }.getOrDefault(false)
}
+ /** When the account's plan was last asked for (AccountPlan), so a failed or unknown answer is asked again later; 0: at once. */
+ @Volatile private var planAskedAt = 0L
+
+ /**
+ * The page is moving to another account (a switch, an added account): what the API knows of the
+ * one that leaves (its token, username, Jam) and its plan are forgotten, and the next one's plan
+ * is asked for as soon as it is signed in.
+ */
+ fun accountChanged() {
+ appContext?.let { spotify.http.useDeviceId(clientDeviceId(it, host.accounts.list.value.active)) }
+ AccountPlan.set(null)
+ planAskedAt = 0L
+ scope.launch { spotify.forgetAccount() }
+ }
+
/** Data saver: frees the page; [resume] loads it again. */
fun suspendPlayer() = host.unload()
fun resume() = host.load()
@@ -156,8 +175,10 @@ object MyspotiRuntime {
* 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")
+ /** The client's device id for the account kept in [profile]: the first account keeps the one it always had. */
+ private fun clientDeviceId(context: Context, profile: String): String {
+ val name = if (profile == AccountList.DEFAULT_PROFILE) "device-id" else "device-id-" + profile.filter { it.isLetterOrDigit() || it == '-' || it == '_' }
+ val file = java.io.File(context.filesDir, "spotify/$name")
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) }
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 ada39c4d..87d017a4 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
@@ -194,6 +194,30 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
/** Fetches the audio files itself: the last request the WebView would stamp with its package. */
private val media = MediaProxy(MediaProxy.client()) { relay.identityPair() }
+ /**
+ * WebView profiles (androidx.webkit MULTI_PROFILE): each account keeps its own cookies and Web
+ * storage, so several stay signed in at once. Without them (an older WebView) the page holds one
+ * account at a time, in the default profile, as before.
+ */
+ val multiProfile: Boolean = runCatching {
+ androidx.webkit.WebViewFeature.isFeatureSupported(androidx.webkit.WebViewFeature.MULTI_PROFILE)
+ }.getOrDefault(false)
+
+ /** The accounts kept on this phone and the active one ([AccountList]). */
+ val accounts = AccountStore(java.io.File(context.filesDir, "spotify/accounts.json"))
+
+ /** The profile the page is built with: the active account's, chosen before the WebView loads anything. */
+ @Volatile var profile: String = if (multiProfile) accounts.list.value.active else AccountList.DEFAULT_PROFILE
+ private set
+
+ init {
+ if (!multiProfile && accounts.list.value.active != AccountList.DEFAULT_PROFILE) {
+ // The WebView lost its profiles (downgraded): the default one is all there is.
+ accounts.update { it.copy(active = AccountList.DEFAULT_PROFILE) }
+ }
+ purgeRemovedProfiles()
+ }
+
@SuppressLint("SetJavaScriptEnabled")
var view: WebView = createView()
@@ -204,6 +228,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
*/
@SuppressLint("SetJavaScriptEnabled")
private fun createView(): WebView = AwakeWebView(android.content.MutableContextWrapper(context.applicationContext)).apply {
+ // The account's profile, before anything else is done with the view (androidx.webkit's rule).
+ useProfile(this)
settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
@@ -250,7 +276,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
it.install()
}
val webView = this
- CookieManager.getInstance().apply {
+ cookies().apply {
setAcceptCookie(true)
setAcceptThirdPartyCookies(webView, true)
}
@@ -445,7 +471,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
* 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(): Boolean = main.post {
+ private fun rebuild(then: (() -> Unit)? = null): Boolean = main.post {
main.removeCallbacks(drmWatch)
val wasLoaded = loadAsked
// Mid sign-in: the page comes back to the sign-in, not to an anonymous player in front of the user.
@@ -462,6 +488,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
// just after, once, so a rebuilt page is loaded exactly once.
loadAsked = false
box?.let { attach(it, lastVisible) }
+ // Another account's page ([switchProfile], [addProfile]): what it opens on is the caller's.
+ if (then != null) { then(); return@post }
// The new view's first navigation can be lost while the browser side still settles after
// the kill (seen: no page start for 4 s): the watchdog looks again after 1.5 s, not 4 s.
if (wasLogin) { loadAsked = wasLoaded; beginLoginLoad(); view.loadUrl(LOGIN_URL) }
@@ -608,7 +636,13 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
}
/** Signs out of Spotify in this WebView, then shows the login page. */
- fun logout() = main.post { roots.edit().remove(SIGNED_IN_KEY).apply(); beginLoginLoad(); cleanSlate { view.loadUrl(LOGIN_URL) } }
+ fun logout() = main.post {
+ roots.edit().remove(SIGNED_IN_KEY).apply()
+ // The profile stays, with no account in it: the next sign-in on it is read as whoever it is.
+ accounts.update { it.signedOut(profile) }
+ beginLoginLoad()
+ cleanSlate { view.loadUrl(LOGIN_URL) }
+ }
/**
* "Try again" after the sign-in page failed: from nothing. A failed attempt may have left half
@@ -618,11 +652,11 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
fun retryLogin() = main.post { beginLoginLoad(); cleanSlate { view.loadUrl(LOGIN_URL) } }
private fun cleanSlate(then: () -> Unit) {
- CookieManager.getInstance().removeAllCookies {
+ cookies().removeAllCookies {
main.post {
// Web storage too: localStorage/IndexedDB hold the player's session
// state, and clearCache(true) also drops the disk cache (false kept it).
- android.webkit.WebStorage.getInstance().deleteAllData()
+ webStorage().deleteAllData()
view.clearCache(true)
then()
}
@@ -634,7 +668,95 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
* while later: an app swiped away right after signing in (the exit log shows "SwipeUpClean" and
* "OneKeyClean" on Xiaomi) lost the sign-in and asked for it again at the next start.
*/
- fun flushCookies() = CookieManager.getInstance().flush()
+ fun flushCookies() = cookies().flush()
+
+ /** The active profile's cookies (the default ones without profiles). Main thread. */
+ fun cookies(): CookieManager =
+ if (multiProfile) androidx.webkit.ProfileStore.getInstance().getOrCreateProfile(profile).cookieManager
+ else CookieManager.getInstance()
+
+ private fun webStorage(): android.webkit.WebStorage =
+ if (multiProfile) androidx.webkit.ProfileStore.getInstance().getOrCreateProfile(profile).webStorage
+ else android.webkit.WebStorage.getInstance()
+
+ /**
+ * Puts [webView] on the active account's profile, so it shares the page's sign-in (the account
+ * pages' browser). Call it on a new view, before anything else is done with it. Main thread.
+ */
+ fun useProfile(webView: WebView) {
+ if (!multiProfile) return
+ androidx.webkit.ProfileStore.getInstance().getOrCreateProfile(profile)
+ androidx.webkit.WebViewCompat.setProfile(webView, profile)
+ }
+
+ /**
+ * The page moves to the account kept in [profileName]: a new WebView on that profile (its own
+ * cookies and storage), built as after a dead renderer ([rebuild]), opening the player. Whoever
+ * follows the account (the API's token and username, the plan, the app's caches) forgets it on
+ * the caller's side. Nothing without profiles (the caller signs out instead).
+ */
+ fun switchProfile(profileName: String) {
+ if (!multiProfile) return
+ val list = accounts.update { it.switchTo(profileName, System.currentTimeMillis()) }
+ if (list.active != profileName) return
+ moveTo(profileName) { load(firstWatchMs = REBUILD_WATCH_MS) }
+ }
+
+ /** "Add account": a new, empty profile becomes the active one and opens Spotify's sign-in page. */
+ fun addProfile() {
+ if (!multiProfile) return
+ var name = ""
+ accounts.update { list -> list.adding(System.currentTimeMillis()).also { name = it.second }.first }
+ moveTo(name) { loadAsked = true; beginLoginLoad(); view.loadUrl(LOGIN_URL) }
+ }
+
+ /**
+ * [profileName] is no longer kept: its entry goes and its data (cookies, storage, cache) is
+ * deleted. The active profile is first left ([switchProfile]); the default profile cannot be
+ * deleted and is cleared instead. A profile still held by a WebView is deleted at the next start.
+ */
+ fun removeProfile(profileName: String) {
+ if (profileName == accounts.list.value.active) return
+ accounts.update { it.removed(profileName) }
+ main.post { purgeRemovedProfiles() }
+ // The replaced WebView may take a moment to let its profile go.
+ main.postDelayed({ purgeRemovedProfiles() }, PURGE_RETRY_MS)
+ }
+
+ private fun moveTo(profileName: String, open: () -> Unit) = main.post {
+ Logbook.log("account: page moved to another profile")
+ profile = profileName
+ // Both said something of the account that leaves: when it signed in, and its language's root.
+ roots.edit().remove(SIGNED_IN_KEY).remove(ROOT_KEY).apply()
+ main.removeCallbacks(retryPlayerPage)
+ main.removeCallbacks(loadTimeout)
+ mainFrameFailed = false
+ pageFailures = 0
+ // A sign-in left open on the old page (back from an added account's) is not this page's:
+ // its clocks stop, and nothing reads "sign-in page" until the new page says so itself.
+ setLoginLoad(LoginLoad.NONE)
+ _loginRequired.value = false
+ // The page is gone: the calls it had fail now, not each after its timeout.
+ onPageStarting?.invoke()
+ rebuild(then = open)
+ main.post { purgeRemovedProfiles() }
+ }
+
+ /** Deletes the data of the profiles removed ([AccountList.doomed]); one still in use waits for later. Main thread. */
+ private fun purgeRemovedProfiles() {
+ if (!multiProfile) return
+ for (name in accounts.list.value.doomed) {
+ if (name == profile) continue
+ val done = runCatching {
+ val store = androidx.webkit.ProfileStore.getInstance()
+ if (name == AccountList.DEFAULT_PROFILE) {
+ store.getProfile(name)?.let { p -> p.cookieManager.removeAllCookies(null); p.webStorage.deleteAllData() }
+ } else store.deleteProfile(name)
+ }
+ if (done.isSuccess) accounts.update { it.deleted(name) }
+ else Logbook.log("account: a removed profile is still in use, deleted later (${done.exceptionOrNull()?.javaClass?.simpleName})")
+ }
+ }
private var loginProbes = 0
private var loginReloaded = false
@@ -754,8 +876,9 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
view.requestLayout()
// Shown again after being hidden at 1 px: a page that was not told to redraw can stay white.
if (visible) view.postInvalidateOnAnimation()
- // Now in a window: a first navigation that never started gets another go.
- if (loadAsked && _url.value.isEmpty() && pageStarts == 0) view.loadUrl(playerRoot())
+ // Now in a window: a first navigation that never started gets another go. Not over a
+ // sign-in page being opened on a new view (another account's, or after a dead renderer).
+ if (loadAsked && _url.value.isEmpty() && pageStarts == 0 && _loginLoad.value == LoginLoad.NONE) view.loadUrl(playerRoot())
}
/**
@@ -816,6 +939,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
private val RETRY_PAGE_MS = longArrayOf(2_000, 5_000, 15_000, 30_000, 60_000)
private const val LOAD_WATCH_MS = 4_000L
private const val REBUILD_WATCH_MS = 1_500L
+ /** A removed profile still held by the WebView just replaced: deleted again after this. */
+ private const val PURGE_RETRY_MS = 10_000L
private const val LOAD_RETRIES = 4
const val LOGIN_URL = "https://accounts.spotify.com/login?continue=https%3A%2F%2Fopen.spotify.com%2F"
}
diff --git a/base/host-android/src/test/kotlin/app/myspoti/host/android/AccountsTest.kt b/base/host-android/src/test/kotlin/app/myspoti/host/android/AccountsTest.kt
new file mode 100644
index 00000000..35eedea2
--- /dev/null
+++ b/base/host-android/src/test/kotlin/app/myspoti/host/android/AccountsTest.kt
@@ -0,0 +1,122 @@
+package app.myspoti.host.android
+
+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 java.nio.file.Files
+
+class AccountsTest {
+ private val default = AccountList.DEFAULT_PROFILE
+
+ /** An install from before: one account, signed in on the default profile. */
+ private fun oneAccount() = AccountList().signedIn(default, "k1", "Ana", "https://i/ana", now = 10).first
+
+ @Test fun `an install from before keeps its account on the default profile`() {
+ val list = AccountList()
+ assertEquals(default, list.active)
+ assertNull(list.current)
+ val signed = oneAccount()
+ assertEquals("Ana", signed.current?.name)
+ assertTrue(signed.current!!.known)
+ assertTrue(signed.others.isEmpty())
+ }
+
+ @Test fun `adding makes a new empty profile the active one, the previous one first among the others`() {
+ val (list, name) = oneAccount().adding(now = 20)
+ assertEquals("account-1", name)
+ assertEquals(name, list.active)
+ assertFalse(list.current!!.known)
+ assertEquals(listOf(default), list.others.map { it.profile })
+ assertEquals(20, list.accounts.first { it.profile == default }.usedAt)
+ assertEquals(2, list.next)
+ }
+
+ @Test fun `a profile name is never reused, even one still being deleted`() {
+ val (a, first) = oneAccount().adding(now = 20)
+ val signed = a.signedIn(first, "k2", "Bo", null, now = 21).first.switchTo(default, now = 22).removed(first)
+ assertEquals(listOf(first), signed.doomed)
+ val (_, second) = signed.adding(now = 23)
+ assertEquals("account-2", second)
+ }
+
+ @Test fun `switching changes the active account and remembers when each was used`() {
+ val (a, p) = oneAccount().adding(now = 20)
+ val b = a.signedIn(p, "k2", "Bo", null, now = 30).first
+ val back = b.switchTo(default, now = 40)
+ assertEquals(default, back.active)
+ assertEquals(40, back.current!!.usedAt)
+ assertEquals(40, back.accounts.first { it.profile == p }.usedAt)
+ assertEquals(listOf(p), back.others.map { it.profile })
+ }
+
+ @Test fun `switching to a profile not kept changes nothing`() {
+ val list = oneAccount()
+ assertEquals(list, list.switchTo("account-9", now = 50))
+ }
+
+ @Test fun `the same account signed in twice is one account, in the profile just signed in`() {
+ val (a, p) = oneAccount().adding(now = 20)
+ val (list, dropped) = a.signedIn(p, "k1", "Ana", null, now = 30)
+ assertEquals(listOf(default), dropped)
+ assertEquals(listOf(p), list.accounts.map { it.profile })
+ // The default profile cannot be deleted: it is cleared (purge) and listed to be.
+ assertEquals(listOf(default), list.doomed)
+ assertEquals("Ana", list.current!!.name)
+ assertEquals("k1", list.current!!.key)
+ }
+
+ @Test fun `another account signed in on a profile does not inherit the previous one's name, picture or plan`() {
+ val list = oneAccount().plan(default, true).signedOut(default)
+ assertNull(list.current!!.key)
+ val again = list.signedIn(default, "k3", "Cy", null, now = 40).first
+ assertEquals("Cy", again.current!!.name)
+ assertNull(again.current!!.imageUrl)
+ assertNull(again.current!!.premium)
+ }
+
+ @Test fun `the plan is kept per account and an unknown answer keeps the known one`() {
+ val list = oneAccount().plan(default, false)
+ assertEquals(false, list.current!!.premium)
+ assertEquals(false, list.plan(default, null).current!!.premium)
+ assertEquals(true, list.plan(default, true).current!!.premium)
+ }
+
+ @Test fun `the active account is never removed, another one is`() {
+ val (a, p) = oneAccount().adding(now = 20)
+ assertEquals(a, a.removed(p))
+ val removed = a.removed(default)
+ assertEquals(listOf(p), removed.accounts.map { it.profile })
+ assertEquals(listOf(default), removed.doomed)
+ assertTrue(removed.deleted(default).doomed.isEmpty())
+ }
+
+ @Test fun `the list survives a save and a read`() {
+ val (a, p) = oneAccount().plan(default, true).adding(now = 20)
+ val list = a.signedIn(p, "k2", "Bo \"B\"", "https://i/bo", now = 30).first.removed(default).let { it.copy(doomed = it.doomed + "account-7") }
+ assertEquals(list, AccountList.fromJson(list.toJson()))
+ }
+
+ @Test fun `an unreadable or missing list is an empty one on the default profile`() {
+ assertEquals(AccountList(), AccountList.fromJson(null))
+ assertEquals(AccountList(), AccountList.fromJson("{not json"))
+ // An active profile that is not in the list: the one used last instead.
+ val read = AccountList.fromJson("""{"active":"gone","accounts":[{"profile":"account-1","used":5},{"profile":"account-2","used":9}]}""")
+ assertEquals("account-2", read.active)
+ }
+
+ @Test fun `the store saves every change and reads it back`() {
+ val dir = Files.createTempDirectory("accounts").toFile()
+ try {
+ val file = java.io.File(dir, "spotify/accounts.json")
+ val store = AccountStore(file)
+ store.update { it.signedIn(default, "k1", "Ana", null, now = 1).first }
+ store.update { it.adding(now = 2).first }
+ assertEquals(store.list.value, AccountStore(file).list.value)
+ assertEquals("account-1", AccountStore(file).list.value.active)
+ } finally {
+ dir.deleteRecursively()
+ }
+ }
+}