Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Accounts Spotify refuses play through the official Web Playback SDK

Leloniod54007eabdf0
diff --git a/.kotlin/sessions/kotlin-compiler-8030064581042163335.salive b/.kotlin/sessions/kotlin-compiler-8030064581042163335.salive
new file mode 100644
index 0000000..e69de29
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 32f2b24..db0be9a 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -51,7 +51,7 @@ android {
minSdk = 26
targetSdk = 35
versionCode = 42
- versionName = "2.4.1"
+ versionName = "2.4.1-sdk1"
buildConfigField("boolean", "VERBOSE_LOG", "false")
ndk {
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 3e00ca4..903a544 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -52,6 +52,15 @@
android:supportsRtl="true"
android:theme="@style/Theme.Square">
+ <activity
+ android:name=".playback.websdk.WebSdkActivity"
+ android:exported="false"
+ android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation|keyboardHidden" />
+ <service
+ android:name=".playback.websdk.WebSdkService"
+ android:exported="false"
+ android:foregroundServiceType="mediaPlayback" />
+
<activity
android:name=".ui.MainActivity"
android:exported="true"
diff --git a/app/src/main/assets/websdk/player.html b/app/src/main/assets/websdk/player.html
new file mode 100644
index 0000000..1b300f6
--- /dev/null
+++ b/app/src/main/assets/websdk/player.html
@@ -0,0 +1,78 @@
+<!doctype html>
+<html><head><meta name="viewport" content="width=device-width, initial-scale=1"><title>Square Spotify SDK</title></head><body>
+<script>
+'use strict';
+let player;
+let lastState;
+const connectAfterProbe = __CONNECT__;
+const tokenRequests = new Map();
+let nextTokenRequest = 0;
+function event(type, data = {}) { SquareSdk.event(JSON.stringify({type, ...data})); }
+window.receiveToken = (id, token) => {
+ const callback = tokenRequests.get(id);
+ tokenRequests.delete(id);
+ if (callback && token) callback(token);
+};
+function emitState(state) {
+ if (!state) { event('inactive'); return; }
+ const track = state.track_window.current_track;
+ const ended = state.paused && state.position === 0 && lastState && !lastState.paused &&
+ lastState.track_window.current_track.uri === track.uri && lastState.duration > 0 &&
+ lastState.position >= lastState.duration - 2500;
+ lastState = state;
+ event('state', {uri: track.uri || '', ended: !!ended, paused: state.paused, position: state.position, duration: state.duration,
+ title: track.name, artist: track.artists.map(a => a.name).join(', ')});
+}
+window.command = async (name, position) => {
+ if (!player) return;
+ try {
+ switch (name) {
+ case 'pause': await player.pause(); break;
+ case 'resume': await player.activateElement(); await player.resume(); break;
+ case 'seek': await player.seek(position); break;
+ case 'activate': await player.activateElement(); break;
+ case 'disconnect': player.disconnect(); break;
+ case 'poll': emitState(await player.getCurrentState()); break;
+ }
+ } catch (_) { event('error', {code: 'command_error'}); }
+};
+window.onSpotifyWebPlaybackSDKReady = () => {
+ player = new Spotify.Player({
+ name: 'Square Web Player',
+ getOAuthToken: callback => {
+ const id = ++nextTokenRequest;
+ tokenRequests.set(id, callback);
+ SquareSdk.token(id);
+ },
+ volume: 1,
+ enableMediaSession: false // Native service owns the notification controls.
+ });
+ player.addListener('ready', ({device_id}) => event('ready', {deviceId: device_id}));
+ player.addListener('not_ready', () => event('not_ready'));
+ player.addListener('autoplay_failed', () => event('error', {code: 'autoplay_failed'}));
+ for (const name of ['initialization_error', 'authentication_error', 'account_error', 'playback_error']) {
+ player.addListener(name, () => event('error', {code: name}));
+ }
+ player.addListener('player_state_changed', emitState);
+ player.connect().then(ok => { if (!ok) event('error', {code: 'connect_error'}); })
+ .catch(() => event('error', {code: 'connect_error'}));
+};
+(async () => {
+ // Check the actual browser environment before requesting any Spotify token.
+ if (!window.isSecureContext || !navigator.requestMediaKeySystemAccess) {
+ event('error', {code: 'eme_unavailable'}); return;
+ }
+ try {
+ await navigator.requestMediaKeySystemAccess('com.widevine.alpha', [{
+ initDataTypes: ['cenc'],
+ audioCapabilities: [{contentType: 'audio/mp4; codecs="mp4a.40.2"'}]
+ }]);
+ } catch (_) { event('error', {code: 'eme_unavailable'}); return; }
+ event('capable');
+ if (!connectAfterProbe) return;
+ const script = document.createElement('script');
+ script.src = 'https://sdk.scdn.co/spotify-player.js';
+ script.onerror = () => event('error', {code: 'sdk_load_error'});
+ document.head.appendChild(script);
+})();
+</script></body></html>
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
index 56f8fde..8807a3d 100644
--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt
+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
@@ -93,6 +93,16 @@ class SquareApplication : Application(), ImageLoaderFactory {
)
}
+ // Whether Spotify goes through the official SDK depends on the source
+ // too: on YouTube Music the engine's features are all there.
+ kotlinx.coroutines.CoroutineScope(
+ kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.Default,
+ ).launch {
+ preferences.backend.collect {
+ dev.lelonio.square.playback.websdk.WebSdkRecovery.refresh(this@SquareApplication)
+ }
+ }
+
// Not a feature: a line in the log saying whether this install has been
// compiled ahead of time yet. See reportProfileStatus.
reportProfileStatus(
@@ -201,6 +211,7 @@ class SquareApplication : Application(), ImageLoaderFactory {
* are metered against a quota nobody else shares — see [WebApiAccount].
*/
val webApi: WebApiAccount by lazy { WebApiAccount(this) }
+ internal val spotifySdkAccount by lazy { dev.lelonio.square.playback.websdk.WebSdkAccount(this) }
/**
* Shared [OkHttpClient] providing a common connection pool, DNS cache, and dispatcher
diff --git a/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt b/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt
index 67c6929..b2e69d2 100644
--- a/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt
+++ b/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt
@@ -23,6 +23,19 @@ object RemoteConnect {
/** This device's own id, read once the engine has a session. */
private var ownId: String = ""
+ private var sdkId: String? = null
+
+ /** The official SDK is another Spotify device, but plays on this phone. */
+ fun registerSdkDevice(id: String) {
+ sdkId = id
+ runCatching { refresh() }
+ }
+
+ fun unregisterSdkDevice(id: String?) {
+ if (id == null || sdkId != id) return
+ sdkId = null
+ runCatching { refresh() }
+ }
private val _playback = MutableStateFlow<RemotePlayback?>(null)
@@ -70,7 +83,7 @@ object RemoteConnect {
/** Whether an id is this phone's own. */
fun isThisPhone(deviceId: String): Boolean {
if (ownId.isEmpty()) ownId = NativeBridge.deviceId()
- return deviceId.isNotEmpty() && deviceId == ownId
+ return deviceId.isNotEmpty() && (deviceId == ownId || deviceId == sdkId)
}
/** Called on every `cluster` event from the engine. */
@@ -93,10 +106,11 @@ object RemoteConnect {
// this phone it starts playing at once, while the account goes on naming
// the device it came from until that device lets go. Comparing ids meant
// the app believed the account and not its own ears.
- val elsewhere = NativeBridge.playbackElsewhere
+ val elsewhere = NativeBridge.playbackElsewhere && active != sdkId
_elsewhere.value = elsewhere
_playback.value = playback?.takeIf { elsewhere }
- _here.value = playback?.takeIf { !elsewhere && active.isNotEmpty() }
+ // The SDK adapter already owns its queue; it must not be adopted by librespot.
+ _here.value = playback?.takeIf { !elsewhere && active.isNotEmpty() && active != sdkId }
}
private fun read(state: JSONObject, active: String): RemotePlayback? {
@@ -159,6 +173,7 @@ object RemoteConnect {
/** Forgets everything. For a session ending, where none of it is true any more. */
fun clear() {
+ sdkId = null
_elsewhere.value = false
_playback.value = null
_here.value = null
@@ -176,7 +191,7 @@ object RemoteConnect {
type = device.optString("type"),
volume = device.optInt("volume"),
active = device.optBoolean("active"),
- isThisPhone = id == ownId,
+ isThisPhone = id == ownId || id == sdkId,
)
}
}
diff --git a/app/src/main/java/dev/lelonio/square/diagnostics/WidevineProbe.kt b/app/src/main/java/dev/lelonio/square/diagnostics/WidevineProbe.kt
index a0a095d..b1ebc6f 100644
--- a/app/src/main/java/dev/lelonio/square/diagnostics/WidevineProbe.kt
+++ b/app/src/main/java/dev/lelonio/square/diagnostics/WidevineProbe.kt
@@ -57,6 +57,7 @@ object WidevineProbe {
val on = mode == "on"
context.getSharedPreferences("square_keys", Context.MODE_PRIVATE)
.edit().putBoolean("account_refused", on).apply()
+ dev.lelonio.square.playback.websdk.WebSdkRecovery.refresh(context)
log("web playback forced ${if (on) "on" else "off"}")
if (on) {
forceWeb()
diff --git a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
index ee8ca65..8ba9447 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -1419,11 +1419,13 @@ class LibrespotPlayer(
if (what == 0L) {
refusalShown = false
keyNotes.edit().remove(ACCOUNT_REFUSED).apply()
+ dev.lelonio.square.playback.websdk.WebSdkRecovery.refresh(appContext)
return
}
val account = what == 2L || keyNotes.getBoolean(ACCOUNT_REFUSED, false)
if (what == 2L) {
keyNotes.edit().putBoolean(ACCOUNT_REFUSED, true).apply()
+ dev.lelonio.square.playback.websdk.WebSdkRecovery.refresh(appContext)
} else if (refusalShown) {
return
}
@@ -1515,6 +1517,7 @@ class LibrespotPlayer(
// A song playing is the account being given keys after all.
if (type == "playing" && keyNotes.contains(ACCOUNT_REFUSED)) {
keyNotes.edit().remove(ACCOUNT_REFUSED).apply()
+ dev.lelonio.square.playback.websdk.WebSdkRecovery.refresh(appContext)
}
// Nothing is coming out of the speaker any more, so the next load is a
diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
index 00a4fb9..b317dcd 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -329,12 +329,19 @@ class PlaybackService : MediaLibraryService() {
}
}
- // Spotify refusing this account every key (#35): what the engine was
- // about to play goes over to the web player's way of playing it.
+ // Only an explicit account-level refusal offers SDK recovery.
scope.launch {
dev.lelonio.square.backend.spotify.SpotifyWebPlayback.accountRefused.collect {
runCatching { moveToWebPlayback() }
- .onFailure { android.util.Log.w(TAG, "web playback: $it") }
+ .onFailure { android.util.Log.w(TAG, "SDK recovery failed", it) }
+ }
+ }
+ scope.launch {
+ dev.lelonio.square.playback.websdk.WebSdkRecovery.configured.collect {
+ if (webPlaybackNeeded()) {
+ if (playerKind == PlayerKind.SPOTIFY_WEB) { player.prepare(); player.play() }
+ else moveToWebPlayback()
+ }
}
}
@@ -667,19 +674,21 @@ class PlaybackService : MediaLibraryService() {
* last one, which is nothing at all.
*/
suspend fun ensurePlayerFor(firstUri: String?) {
+ pendingWebPlayback = null
val wanted = if (firstUri != null && dev.lelonio.square.data.LocalLibrary.isLocal(firstUri)) {
PlayerKind.LOCAL
} else {
kindFor(container.preferences.backend.value).let { kind ->
// An account Spotify refuses its keys goes on playing the web
// player's way, once the engine is up to lend it a token.
- if (kind == PlayerKind.SPOTIFY && webPlaybackNeeded() &&
- (librespot != null || parkedSpotify != null)
- ) {
- PlayerKind.SPOTIFY_WEB
- } else {
- kind
- }
+ if (kind == PlayerKind.SPOTIFY && webPlaybackNeeded()) {
+ if (dev.lelonio.square.playback.websdk.WebSdkRecovery.isConfigured(this)) {
+ PlayerKind.SPOTIFY_WEB
+ } else {
+ dev.lelonio.square.playback.websdk.WebSdkRecovery.requestSetup()
+ kind
+ }
+ } else kind
}
}
if (wanted == playerKind) return
@@ -708,33 +717,39 @@ class PlaybackService : MediaLibraryService() {
container.preferences.backend.value == dev.lelonio.square.backend.BackendId.SPOTIFY &&
dev.lelonio.square.backend.spotify.SpotifyWebPlayback.needed(this)
- /**
- * Carries the engine's queue, track and position over to the web player.
- *
- * The engine's items name their songs and nothing more; ExoPlayer plays an
- * address, so each is given its own name as one, which the web player's
- * resolver turns into its MP4 file.
- */
+ private data class PendingWebPlayback(
+ val items: List<androidx.media3.common.MediaItem>,
+ val index: Int,
+ val position: Long,
+ val shuffle: Boolean,
+ val repeat: Int,
+ )
+ private var pendingWebPlayback: PendingWebPlayback? = null
+
+ /** Keep the failed selection while OAuth is completed; resume through the official SDK. */
private suspend fun moveToWebPlayback() {
if (playerKind != PlayerKind.SPOTIFY) return
val engine = librespot ?: return
- val items = (0 until engine.mediaItemCount).map { index ->
- val item = engine.getMediaItemAt(index)
- item.buildUpon().setUri(item.mediaId).build()
+ if (pendingWebPlayback == null) {
+ val items = (0 until engine.mediaItemCount).map(engine::getMediaItemAt)
+ if (items.isEmpty()) return
+ pendingWebPlayback = PendingWebPlayback(items,
+ engine.currentMediaItemIndex.coerceIn(0, items.lastIndex),
+ engine.currentPosition.coerceAtLeast(0), engine.shuffleModeEnabled, engine.repeatMode)
}
- if (items.isEmpty()) return
- val index = engine.currentMediaItemIndex.coerceIn(0, items.lastIndex)
- val position = engine.currentPosition.coerceAtLeast(0)
- android.util.Log.i(TAG, "keys refused to the account: playing ${items.size} tracks the web player's way")
+ if (!dev.lelonio.square.playback.websdk.WebSdkRecovery.isConfigured(this)) {
+ engine.pause()
+ dev.lelonio.square.playback.websdk.WebSdkRecovery.requestSetup()
+ return
+ }
+ val pending = pendingWebPlayback ?: return
swapPlayer(PlayerKind.SPOTIFY_WEB, restore = false)
- player.setMediaItems(items, index, position)
+ player.setMediaItems(pending.items, pending.index, pending.position)
+ player.shuffleModeEnabled = pending.shuffle
+ player.repeatMode = pending.repeat
player.prepare()
player.play()
- android.widget.Toast.makeText(
- this,
- getString(dev.lelonio.square.R.string.web_playback_on),
- android.widget.Toast.LENGTH_LONG,
- ).show()
+ pendingWebPlayback = null
}
private fun buildPlayer(
@@ -807,22 +822,11 @@ class PlaybackService : MediaLibraryService() {
PlayerKind.SPOTIFY -> buildBackendPlayer(dev.lelonio.square.backend.BackendId.SPOTIFY)
PlayerKind.YOUTUBE -> buildBackendPlayer(dev.lelonio.square.backend.BackendId.YOUTUBE_MUSIC)
- // Spotify the way its web player plays it, for an account refused its
- // keys; see SpotifyWebPlayback. The engine stays parked behind it, for
- // the catalogue and for the token the licence is asked with.
+ // Keep the engine parked for catalogue access; only the SDK owns playback.
PlayerKind.SPOTIFY_WEB -> {
librespot = null
playerKind = kind
- dev.lelonio.square.backend.spotify.SpotifyWebPlayback.create(
- this,
- playbackHost.looper,
- LocalPlayerFactory.renderers(playbackHost),
- ).also { built ->
- built.playbackParameters = androidx.media3.common.PlaybackParameters(
- AudioEffects.speed.value,
- AudioEffects.pitch.value,
- )
- }
+ dev.lelonio.square.playback.websdk.WebSdkPlayer(this, playbackHost.looper)
}
}
diff --git a/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkAccount.kt b/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkAccount.kt
new file mode 100644
index 0000000..de30401
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkAccount.kt
@@ -0,0 +1,44 @@
+package dev.lelonio.square.playback.websdk
+
+import android.content.Context
+import dev.lelonio.square.auth.SpotifyOAuth
+import dev.lelonio.square.auth.TokenStore
+
+/** App-owned OAuth credentials, separate from both the native engine and search. */
+internal class WebSdkAccount(context: Context) {
+ private val app = context.applicationContext
+ private val prefs = context.getSharedPreferences("square_sdk_account", Context.MODE_PRIVATE)
+ var clientId: String = prefs.getString("client_id", "").orEmpty()
+ private set
+ val tokens = TokenStore(context, "square_sdk_tokens") {
+ clientId.takeIf { it.isNotBlank() } ?: error("SDK client id missing")
+ }
+
+ val enabled: Boolean get() = prefs.getBoolean("enabled", false)
+ val configured: Boolean get() = enabled && clientId.isNotBlank() && tokens.isLoggedIn
+ fun enable() { prefs.edit().putBoolean("enabled", true).commit() }
+ fun disconnect() {
+ tokens.clear()
+ prefs.edit().putBoolean("enabled", false).commit()
+ WebSdkRecovery.refresh(app)
+ WebSdkRecovery.stopPlayback()
+ }
+
+ fun configure(value: String) {
+ val next = value.trim()
+ require(next.matches(Regex("[a-fA-F0-9]{32}"))) { "Invalid client id" }
+ require(next != SpotifyOAuth.CLIENT_ID) { "Use your own Spotify developer application" }
+ if (next == clientId) return
+ disconnect()
+ prefs.edit().putString("client_id", next).commit()
+ clientId = next
+ }
+
+ suspend fun authorize(context: Context) {
+ val result = SpotifyOAuth.authorize(context, clientId, listOf(
+ "streaming", "user-read-private", "user-read-email",
+ "user-read-playback-state", "user-modify-playback-state",
+ ))
+ tokens.save(result)
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkActivity.kt b/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkActivity.kt
new file mode 100644
index 0000000..d0b6154
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkActivity.kt
@@ -0,0 +1,348 @@
+package dev.lelonio.square.playback.websdk
+
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.ServiceConnection
+import android.os.Bundle
+import android.os.IBinder
+import android.webkit.WebView
+import androidx.activity.ComponentActivity
+import androidx.activity.SystemBarStyle
+import androidx.activity.enableEdgeToEdge
+import androidx.activity.compose.setContent
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.*
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.*
+import androidx.compose.runtime.*
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.platform.LocalClipboardManager
+import androidx.compose.ui.platform.LocalUriHandler
+import androidx.compose.ui.text.AnnotatedString
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.viewinterop.AndroidView
+import androidx.core.content.ContextCompat
+import androidx.lifecycle.lifecycleScope
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import dev.lelonio.square.R
+import dev.lelonio.square.SquareApplication
+import dev.lelonio.square.auth.SpotifyOAuth
+import com.adamglin.PhosphorIcons
+import com.adamglin.phosphoricons.Regular
+import com.adamglin.phosphoricons.regular.ArrowLeft
+import com.adamglin.phosphoricons.regular.ArrowUpRight
+import dev.lelonio.square.ui.onboarding.*
+import dev.lelonio.square.ui.theme.Ink
+import dev.lelonio.square.ui.theme.InkDim
+import dev.lelonio.square.ui.theme.SquareTheme
+import kotlinx.coroutines.*
+
+/** Native controls around a service-owned WebView, retained when the screen goes off. */
+class WebSdkActivity : ComponentActivity() {
+ private var service by mutableStateOf<WebSdkService?>(null)
+ private var signedIn by mutableStateOf(false)
+ private var authorizing by mutableStateOf(false)
+ private var authError by mutableStateOf<String?>(null)
+ private var loginJob: Job? = null
+ private val connection = object : ServiceConnection {
+ override fun onServiceConnected(name: ComponentName, binder: IBinder) {
+ service = (binder as WebSdkService.LocalBinder).service
+ signedIn = service?.account?.tokens?.isLoggedIn == true
+ }
+ override fun onServiceDisconnected(name: ComponentName) { service = null }
+ }
+ override fun attachBaseContext(base: Context) {
+ super.attachBaseContext((base.applicationContext as SquareApplication).language.wrap(base))
+ }
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ // Transparent bars, as MainActivity has them; SquareTheme sets the icons.
+ enableEdgeToEdge(
+ statusBarStyle = SystemBarStyle.auto(android.graphics.Color.TRANSPARENT, android.graphics.Color.TRANSPARENT),
+ navigationBarStyle = SystemBarStyle.auto(android.graphics.Color.TRANSPARENT, android.graphics.Color.TRANSPARENT),
+ )
+ bindService(Intent(this, WebSdkService::class.java), connection, BIND_AUTO_CREATE)
+ setContent { SquareTheme {
+ val recovery = intent.getBooleanExtra("recovery", false)
+ val backend = service
+ val fallback = remember { kotlinx.coroutines.flow.MutableStateFlow(WebSdkState()) }
+ val state by (backend?.state ?: fallback).collectAsStateWithLifecycle()
+ LaunchedEffect(recovery, state.stage) {
+ if (recovery && state.stage == "ready") {
+ backend?.stopPlayback()
+ WebSdkRecovery.complete(this@WebSdkActivity)
+ finish()
+ }
+ }
+ val hint = (application as SquareApplication).webApi.clientId.value.orEmpty()
+ var clientId by rememberSaveable(backend) {
+ mutableStateOf(backend?.account?.clientId?.takeIf { it.isNotBlank() } ?: hint)
+ }
+ val connected = state.deviceId != null
+ val loading = state.stage == "loading"
+ // Drawn with the welcome guide's pieces: this is the same kind of
+ // trip to the developer dashboard, and it should look like one.
+ SetupScaffold(
+ top = {
+ RoundButton(PhosphorIcons.Regular.ArrowLeft, stringResource(R.string.back)) { finish() }
+ },
+ bottom = {
+ // The compatibility probe is a developer's question; someone
+ // recovering playback only needs the one way on.
+ if (!recovery && !connected) QuietButton(stringResource(R.string.web_sdk_check), onClick = {
+ if (backend != null && !loading && !authorizing) start(probeOnly = true)
+ })
+ // One control: sign in first, then turn the player on.
+ if (!signedIn) PrimaryButton(
+ stringResource(R.string.web_sdk_login),
+ onClick = { login(clientId) },
+ enabled = backend != null && !authorizing && clientId.isNotBlank(),
+ modifier = Modifier.weight(1f),
+ ) else PrimaryButton(
+ stringResource(if (recovery) R.string.web_sdk_enable else R.string.web_sdk_connect),
+ onClick = { start(probeOnly = false) },
+ enabled = clientId.trim() == backend?.account?.clientId &&
+ !authorizing && !loading && !connected,
+ modifier = Modifier.weight(1f),
+ )
+ },
+ ) {
+ Column(
+ Modifier
+ .fillMaxSize()
+ .verticalScroll(rememberScrollState())
+ .padding(horizontal = PAGE_MARGIN),
+ ) {
+ StepHeader(stringResource(if (recovery) R.string.web_sdk_recovery_title else R.string.web_sdk_title))
+ ProseText(stringResource(if (recovery) R.string.web_sdk_recovery_explainer else R.string.web_sdk_explainer))
+ // Said before the switch is turned on, not discovered afterwards.
+ if (recovery) Note(stringResource(R.string.web_sdk_limits))
+ Account(clientId, { clientId = it }, connected)
+ Status(state)
+ // The WebView belongs to the service. Detach when this screen leaves,
+ // without pausing or destroying the player being tested in background.
+ val view = backend?.webView
+ if (view != null) key(view) {
+ AndroidView(factory = { view }, modifier = Modifier.fillMaxWidth().height(1.dp),
+ onRelease = { (it.parent as? android.view.ViewGroup)?.removeView(it) })
+ }
+ if (!recovery) {
+ Tester(state)
+ val version = remember { WebView.getCurrentWebViewPackage()?.versionName.orEmpty() }
+ Text("Android WebView $version", style = MaterialTheme.typography.bodySmall, color = InkDim,
+ modifier = Modifier.padding(top = 18.dp))
+ }
+ Spacer(Modifier.height(28.dp))
+ }
+ }
+ } }
+ }
+ /**
+ * Where the developer app comes from and its Client ID, until the account is
+ * authorized with it; after that, only who is signed in and the way out.
+ */
+ @Composable
+ private fun Account(clientId: String, onClientId: (String) -> Unit, connected: Boolean) {
+ val backend = service
+ if (signedIn && !authorizing) {
+ Row(Modifier.padding(top = 22.dp), verticalAlignment = Alignment.CenterVertically) {
+ DoneRow(stringResource(R.string.web_sdk_authorized))
+ Spacer(Modifier.weight(1f))
+ if (!connected) QuietButton(stringResource(R.string.disconnect), onClick = {
+ backend?.stopPlayback()
+ lifecycleScope.launch {
+ withContext(Dispatchers.IO) { backend?.account?.disconnect() }
+ signedIn = false
+ }
+ })
+ }
+ } else {
+ val uriHandler = LocalUriHandler.current
+ val clipboard = LocalClipboardManager.current
+ CardButton(
+ title = stringResource(R.string.onboarding_open_dashboard),
+ detail = DASHBOARD_URL.removePrefix("https://"),
+ icon = PhosphorIcons.Regular.ArrowUpRight,
+ onClick = { uriHandler.openUri(DASHBOARD_URL) },
+ modifier = Modifier.padding(top = 18.dp),
+ )
+ Text(stringResource(R.string.web_sdk_redirect), style = MaterialTheme.typography.bodyMedium,
+ color = Prose, modifier = Modifier.padding(top = 18.dp))
+ Row(
+ Modifier
+ .padding(top = 8.dp)
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(12.dp))
+ .background(Ink.copy(alpha = 0.06f))
+ .padding(start = 12.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(SpotifyOAuth.REDIRECT_URI, style = MaterialTheme.typography.bodyMedium, color = Ink,
+ maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
+ QuietButton(stringResource(R.string.copy),
+ onClick = { clipboard.setText(AnnotatedString(SpotifyOAuth.REDIRECT_URI)) })
+ }
+ InkField(clientId, onClientId, stringResource(R.string.client_id),
+ enabled = !authorizing, modifier = Modifier.padding(top = 18.dp))
+ if (authorizing) Row(Modifier.padding(top = 14.dp), verticalAlignment = Alignment.CenterVertically) {
+ CircularProgressIndicator(strokeWidth = 2.dp, color = Ink, modifier = Modifier.size(18.dp))
+ Spacer(Modifier.weight(1f))
+ QuietButton(stringResource(R.string.cancel), onClick = {
+ loginJob?.cancel(); SpotifyOAuth.cancelActiveAuthorization()
+ })
+ }
+ }
+ authError?.let { ErrorText(errorMessage(it)) }
+ }
+ @Composable
+ private fun Status(state: WebSdkState) {
+ val loading = state.stage == "loading"
+ val label = stringResource(when (state.stage) {
+ "loading" -> R.string.web_sdk_loading
+ "ready" -> R.string.web_sdk_ready
+ "capable" -> R.string.web_sdk_capable
+ "error" -> R.string.web_sdk_failed
+ else -> R.string.web_sdk_idle
+ })
+ Column(Modifier.padding(top = 22.dp)) {
+ when {
+ state.stage == "ready" -> DoneRow(label)
+ loading -> Row(verticalAlignment = Alignment.CenterVertically) {
+ CircularProgressIndicator(strokeWidth = 2.dp, color = Ink, modifier = Modifier.size(18.dp))
+ Text(label, style = MaterialTheme.typography.bodyMedium, color = Ink,
+ modifier = Modifier.padding(start = 12.dp))
+ }
+ // The probe's answer; a failure is said by the error under it.
+ state.stage == "capable" -> Note(label)
+ }
+ state.error?.let { ErrorText(errorMessage(it)) }
+ }
+ }
+ /** The developer test: one track by hand, with the transport around it. */
+ @Composable
+ private fun Tester(state: WebSdkState) {
+ val backend = service
+ var track by rememberSaveable { mutableStateOf("") }
+ var seekPosition by remember { mutableStateOf<Float?>(null) }
+ val connected = state.deviceId != null
+ Column(
+ Modifier
+ .padding(top = 22.dp)
+ .fillMaxWidth()
+ .setupCard()
+ .padding(16.dp),
+ ) {
+ InkField(track, { track = it }, stringResource(R.string.web_sdk_track))
+ SecondaryButton(stringResource(R.string.play), onClick = {
+ if (connected && !state.busy) backend?.play(track)
+ }, busy = state.busy, modifier = Modifier.padding(top = 12.dp))
+ if (state.title.isNotBlank()) {
+ Text(state.title, style = MaterialTheme.typography.titleLarge, color = Ink,
+ modifier = Modifier.padding(top = 18.dp))
+ Text(state.artist, style = MaterialTheme.typography.bodyMedium, color = InkDim)
+ }
+ if (state.duration > 0) {
+ Slider(value = seekPosition ?: state.position.toFloat().coerceIn(0f, state.duration.toFloat()),
+ onValueChange = { seekPosition = it },
+ onValueChangeFinished = { seekPosition?.let { backend?.seek(it.toLong()) }; seekPosition = null },
+ valueRange = 0f..state.duration.toFloat(), enabled = connected,
+ colors = SliderDefaults.colors(thumbColor = Ink, activeTrackColor = Ink,
+ inactiveTrackColor = Ink.copy(alpha = 0.15f)),
+ modifier = Modifier.padding(top = 8.dp))
+ Text("${time(state.position)} / ${time(state.duration)}",
+ style = MaterialTheme.typography.bodySmall, color = InkDim)
+ }
+ Row(Modifier.padding(top = 12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ SecondaryButton(stringResource(if (state.paused) R.string.play else R.string.pause), onClick = {
+ if (connected) { if (state.paused) backend?.resume() else backend?.command("pause") }
+ }, modifier = Modifier.weight(1f))
+ SecondaryButton(stringResource(R.string.web_sdk_stop), onClick = { backend?.stopPlayback() },
+ modifier = Modifier.weight(1f))
+ }
+ }
+ Note(stringResource(R.string.web_sdk_background))
+ }
+ /** The guide's field: in ink, since the accent here would be whatever record is playing. */
+ @Composable
+ private fun InkField(
+ value: String,
+ onValueChange: (String) -> Unit,
+ label: String,
+ modifier: Modifier = Modifier,
+ enabled: Boolean = true,
+ ) {
+ OutlinedTextField(
+ value = value,
+ onValueChange = onValueChange,
+ label = { Text(label) },
+ singleLine = true,
+ enabled = enabled,
+ shape = RoundedCornerShape(16.dp),
+ colors = OutlinedTextFieldDefaults.colors(
+ focusedTextColor = Ink,
+ unfocusedTextColor = Ink,
+ focusedBorderColor = Ink,
+ unfocusedBorderColor = Ink.copy(alpha = 0.22f),
+ focusedLabelColor = Ink,
+ unfocusedLabelColor = InkDim,
+ cursorColor = Ink,
+ ),
+ modifier = modifier.fillMaxWidth(),
+ )
+ }
+ @Composable
+ private fun ErrorText(text: String) {
+ Text(text, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error,
+ modifier = Modifier.padding(top = 8.dp))
+ }
+ private fun start(probeOnly: Boolean) {
+ ContextCompat.startForegroundService(this, Intent(this, WebSdkService::class.java))
+ service?.connect(probeOnly)
+ }
+ private fun login(clientId: String) {
+ if (loginJob?.isActive == true) return
+ val backend = service ?: return
+ backend.stopPlayback()
+ loginJob = lifecycleScope.launch {
+ authorizing = true
+ authError = null
+ try {
+ withContext(Dispatchers.IO) { backend.account.configure(clientId) }
+ signedIn = backend.account.tokens.isLoggedIn
+ backend.account.authorize(this@WebSdkActivity)
+ signedIn = true
+ } catch (e: CancellationException) { throw e }
+ catch (_: Exception) { authError = "login_error" }
+ finally { authorizing = false; signedIn = backend.account.tokens.isLoggedIn }
+ }
+ }
+ @Composable
+ private fun errorMessage(code: String): String = stringResource(when (code) {
+ "eme_unavailable", "initialization_error" -> R.string.web_sdk_unsupported
+ "account_error" -> R.string.web_sdk_premium
+ "authentication_error", "login_error", "http_401" -> R.string.web_sdk_auth_error
+ "http_403" -> R.string.web_sdk_forbidden
+ "http_429" -> R.string.web_sdk_rate_limit
+ "invalid_track" -> R.string.web_sdk_invalid_track
+ "audio_focus" -> R.string.web_sdk_focus
+ else -> R.string.web_sdk_play_error
+ })
+ private fun time(ms: Long): String = "%d:%02d".format(ms / 60_000, ms / 1_000 % 60)
+ private companion object {
+ const val DASHBOARD_URL = "https://developer.spotify.com/dashboard"
+ }
+ override fun onDestroy() {
+ if (intent.getBooleanExtra("recovery", false)) WebSdkRecovery.closeSetup()
+ unbindService(connection)
+ service = null
+ super.onDestroy()
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkEngine.kt b/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkEngine.kt
new file mode 100644
index 0000000..fc466e4
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkEngine.kt
@@ -0,0 +1,266 @@
+package dev.lelonio.square.playback.websdk
+
+import android.app.*
+import android.content.Intent
+import android.media.session.MediaSession
+import android.media.session.PlaybackState
+import android.media.MediaMetadata
+import android.os.Binder
+import android.os.IBinder
+import android.webkit.*
+import androidx.core.app.NotificationCompat
+import dev.lelonio.square.R
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import okhttp3.*
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.RequestBody.Companion.toRequestBody
+import org.json.JSONObject
+import java.util.concurrent.TimeUnit
+
+/** Official SDK runtime shared by recovery playback and its setup screen. */
+data class WebSdkState(
+ val stage: String = "idle",
+ val error: String? = null,
+ val deviceId: String? = null,
+ val paused: Boolean = true,
+ val position: Long = 0,
+ val duration: Long = 0,
+ val title: String = "",
+ val artist: String = "",
+ val busy: Boolean = false,
+ val uri: String = "",
+ val ended: Boolean = false,
+ )
+
+class WebSdkEngine(private val context: android.content.Context) {
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+ private val mutableState = MutableStateFlow(WebSdkState())
+ val state = mutableState.asStateFlow()
+ internal val account = (context.applicationContext as dev.lelonio.square.SquareApplication).spotifySdkAccount
+ var webView: WebView? = null
+ private set
+ private var timeout: Job? = null
+ private var pollJob: Job? = null
+ private var playJob: Job? = null
+ private var revision = 0
+ private var playVersion = 0
+ private var registeredDeviceId: String? = null
+ private val http = OkHttpClient.Builder().callTimeout(20, TimeUnit.SECONDS).build()
+ // Chromium owns audio focus for the actual output.
+ private fun update(next: WebSdkState) { mutableState.value = next }
+
+ /** Called from a visible user action, after the notification service has started. */
+ fun connect(probeOnly: Boolean = false) {
+ if (state.value.stage == "loading" || state.value.deviceId != null) return
+ stopWebView()
+ val generation = revision
+ update(WebSdkState(stage = "loading"))
+ val page = context.assets.open("websdk/player.html").bufferedReader().use { it.readText() }
+ .replace("__CONNECT__", (!probeOnly).toString())
+ webView = WebView(context).apply {
+ settings.javaScriptEnabled = true
+ settings.domStorageEnabled = true
+ settings.mediaPlaybackRequiresUserGesture = false
+ settings.allowFileAccess = false
+ settings.allowContentAccess = false
+ settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
+ webViewClient = object : WebViewClient() {
+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
+ // Never navigate the bridge-bearing page to external content.
+ // The official SDK may load its own embedded frame.
+ return request.isForMainFrame || request.url.scheme != "https" ||
+ request.url.host != "sdk.scdn.co"
+ }
+ override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
+ fail("renderer_error")
+ stopWebView()
+ return true
+ }
+ }
+ webChromeClient = object : WebChromeClient() {
+ override fun onPermissionRequest(request: PermissionRequest) {
+ val allowedOrigin = request.origin.toString().trimEnd('/') == ORIGIN.trimEnd('/') ||
+ (request.origin.scheme == "https" && request.origin.host == "sdk.scdn.co")
+ if (allowedOrigin && PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID in request.resources) {
+ request.grant(arrayOf(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID))
+ } else request.deny()
+ }
+ }
+ addJavascriptInterface(object {
+ @JavascriptInterface fun event(json: String) {
+ if (json.length > 16_384) return
+ scope.launch { if (generation == revision) receive(json, probeOnly) }
+ }
+ @JavascriptInterface fun token(id: Int) {
+ scope.launch {
+ if (generation != revision) return@launch
+ try {
+ val token = withContext(Dispatchers.IO) { account.tokens.validAccessToken() }
+ if (generation == revision) evaluateJavascript(
+ "window.receiveToken($id,${JSONObject.quote(token)})", null,
+ )
+ } catch (e: CancellationException) { throw e }
+ catch (_: Exception) { if (generation == revision) fail("authentication_error") }
+ }
+ }
+ }, "SquareSdk")
+ loadDataWithBaseURL(ORIGIN, page, "text/html", "UTF-8", null)
+ }
+ timeout = scope.launch {
+ delay(45_000)
+ if (state.value.stage == "loading") fail("sdk_timeout")
+ }
+ }
+ private fun receive(raw: String, probeOnly: Boolean) {
+ val event = runCatching { JSONObject(raw) }.getOrNull() ?: return
+ when (event.optString("type")) {
+ "capable" -> {
+ android.util.Log.i(TAG, "WebView supports EME")
+ if (probeOnly) {
+ timeout?.cancel()
+ update(state.value.copy(stage = "capable"))
+ }
+ }
+ "ready" -> {
+ timeout?.cancel()
+ event.optString("deviceId").takeIf { it.isNotBlank() }?.let {
+ registeredDeviceId = it
+ dev.lelonio.square.data.RemoteConnect.registerSdkDevice(it)
+ }
+ update(state.value.copy(stage = "ready", error = null,
+ deviceId = event.optString("deviceId").takeIf { it.isNotBlank() }))
+ pollJob?.cancel()
+ pollJob = scope.launch {
+ while (isActive) {
+ delay(1_000)
+ command("poll")
+ }
+ }
+ android.util.Log.i(TAG, "SDK ready")
+ }
+ "not_ready" -> fail("device_offline")
+ "error" -> fail(event.optString("code"))
+ "inactive" -> update(state.value.copy(paused = true))
+ "state" -> {
+ update(state.value.copy(paused = event.optBoolean("paused", true),
+ position = event.optLong("position"), duration = event.optLong("duration"),
+ title = event.optString("title"), artist = event.optString("artist"),
+ uri = event.optString("uri"), ended = event.optBoolean("ended")))
+ }
+ }
+ }
+ private fun fail(code: String) {
+ dev.lelonio.square.data.RemoteConnect.unregisterSdkDevice(registeredDeviceId)
+ registeredDeviceId = null
+ timeout?.cancel()
+ pollJob?.cancel()
+ playJob?.cancel()
+ update(state.value.copy(stage = "error", error = code, deviceId = null, paused = true, busy = false))
+ command("pause")
+ // No tokens, URLs or server response bodies enter the logs.
+ android.util.Log.w(TAG, "SDK error: $code")
+ }
+ fun command(name: String, position: Long = 0) {
+ webView?.evaluateJavascript("window.command(${JSONObject.quote(name)},$position)", null)
+ }
+ fun resume() {
+ if (state.value.deviceId == null) return
+ command("resume")
+ }
+ fun seek(position: Long) { command("seek", position.coerceIn(0, state.value.duration)) }
+
+ fun play(input: String, following: List<String> = emptyList(), positionMs: Long = 0) {
+ val uri = trackUri(input)
+ if (uri == null) { update(state.value.copy(error = "invalid_track")); return }
+ val device = state.value.deviceId ?: return
+ command("activate")
+ playJob?.cancel()
+ val generation = revision
+ val requestVersion = ++playVersion
+ update(state.value.copy(busy = true, error = null, ended = false))
+ playJob = scope.launch {
+ try {
+ withContext(Dispatchers.IO) {
+ val uris = listOf(uri) + following.mapNotNull(::trackUri).take(99)
+ val body = JSONObject().put("uris", org.json.JSONArray(uris))
+ .put("position_ms", positionMs.coerceAtLeast(0)).toString()
+ val url = "https://api.spotify.com/v1/me/player/play".toHttpUrl()
+ .newBuilder().addQueryParameter("device_id", device).build()
+ suspend fun request(token: String): Int {
+ val call = http.newCall(Request.Builder().url(url)
+ .header("Authorization", "Bearer $token")
+ .put(body.toRequestBody("application/json".toMediaType())).build())
+ return suspendCancellableCoroutine { continuation ->
+ continuation.invokeOnCancellation { call.cancel() }
+ call.enqueue(object : Callback {
+ override fun onFailure(call: Call, error: java.io.IOException) {
+ if (continuation.isActive) continuation.resumeWith(Result.failure(error))
+ }
+ override fun onResponse(call: Call, response: Response) {
+ response.use {
+ if (continuation.isActive) continuation.resumeWith(Result.success(it.code))
+ }
+ }
+ })
+ }
+ }
+ var code = request(account.tokens.validAccessToken())
+ if (code == 401) code = request(account.tokens.forceRefresh())
+ if (code !in 200..299) error("http_$code")
+ }
+ if (generation == revision && requestVersion == playVersion) update(state.value.copy(busy = false))
+ } catch (e: CancellationException) { throw e }
+ catch (e: Exception) {
+ if (generation == revision && requestVersion == playVersion) {
+ val code = e.message?.takeIf { it.matches(Regex("http_[0-9]{3}")) } ?: "playback_error"
+ update(state.value.copy(busy = false, error = code))
+ }
+ }
+ }
+ }
+ fun stopPlayback() {
+ stopWebView()
+ update(WebSdkState())
+ }
+ private fun stopWebView() {
+ dev.lelonio.square.data.RemoteConnect.unregisterSdkDevice(registeredDeviceId)
+ registeredDeviceId = null
+ revision++
+ playVersion++
+ timeout?.cancel()
+ pollJob?.cancel()
+ playJob?.cancel()
+ webView?.let { view ->
+ view.evaluateJavascript("window.command('disconnect')", null)
+ (view.parent as? android.view.ViewGroup)?.removeView(view)
+ view.removeJavascriptInterface("SquareSdk")
+ view.stopLoading()
+ view.destroy()
+ }
+ webView = null
+ }
+ fun release() {
+ stopWebView()
+ scope.cancel()
+ }
+ companion object {
+ private const val ORIGIN = "https://square-sdk.invalid/"
+ private const val TAG = "SquareWebSdk"
+ internal fun trackUri(input: String): String? {
+ val value = input.trim()
+ val id = when {
+ value.startsWith("spotify:track:") -> value.removePrefix("spotify:track:")
+ else -> android.net.Uri.parse(value).takeIf {
+ it.scheme == "https" && it.host == "open.spotify.com"
+ }?.pathSegments?.let { parts ->
+ val offset = if (parts.firstOrNull()?.startsWith("intl-") == true) 1 else 0
+ if (parts.getOrNull(offset) == "track" && parts.size == offset + 2) parts.last() else null
+ }
+ }
+ return id?.takeIf { it.matches(Regex("[a-zA-Z0-9]{22}")) }?.let { "spotify:track:$it" }
+ }
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkPlayer.kt b/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkPlayer.kt
new file mode 100644
index 0000000..6aad791
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkPlayer.kt
@@ -0,0 +1,248 @@
+package dev.lelonio.square.playback.websdk
+
+import android.content.Context
+import android.os.Looper
+import androidx.media3.common.*
+import androidx.media3.common.util.UnstableApi
+import com.google.common.util.concurrent.Futures
+import com.google.common.util.concurrent.ListenableFuture
+import kotlinx.coroutines.*
+
+/** Media3 adapter: Square owns the queue and UI, the official SDK owns audio. */
+@UnstableApi
+class WebSdkPlayer(private val context: Context, looper: Looper) : SimpleBasePlayer(looper) {
+ private data class Entry(val uid: Long, val item: MediaItem)
+ private val engine = WebSdkEngine(context)
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+ private val items = mutableListOf<Entry>()
+ private var original: List<Entry>? = null
+ private var uid = 0L
+ private var index = 0
+ private var position = 0L
+ private var wantPlay = false
+ private var prepared = false
+ private var pending = false
+ private var awaitingTrack = false
+ private var sdk = WebSdkState()
+ private var playback = Player.STATE_IDLE
+ private var error: PlaybackException? = null
+ private var repeat = Player.REPEAT_MODE_OFF
+ private var shuffle = false
+ private var lastReportedPosition = 0L
+ private var chunkEnd = 0
+
+ init {
+ check(looper == Looper.getMainLooper())
+ scope.launch { WebSdkRecovery.disconnected.collect { handleStop(); invalidateState() } }
+ scope.launch { engine.state.collect { next ->
+ sdk = next
+ if (items.isEmpty()) return@collect
+ if (next.error != null) {
+ playback = Player.STATE_IDLE
+ pending = false
+ awaitingTrack = false
+ wantPlay = false
+ if (error == null) {
+ engine.command("pause")
+ error = PlaybackException(context.getString(dev.lelonio.square.R.string.web_sdk_play_error),
+ null, PlaybackException.ERROR_CODE_REMOTE_ERROR)
+ if (next.error in setOf("authentication_error", "account_error")) WebSdkRecovery.requestSetup()
+ }
+ } else if (next.stage == "ready") {
+ if (pending && wantPlay) startCurrent()
+ else if (!awaitingTrack && playback != Player.STATE_ENDED) playback = Player.STATE_READY
+ if (next.uri.isNotBlank()) {
+ val currentUri = items.getOrNull(index)?.item?.mediaId
+ if (next.uri != currentUri && !awaitingTrack) {
+ val found = (index + 1 until chunkEnd.coerceAtMost(items.size))
+ .firstOrNull { items[it].item.mediaId == next.uri }
+ if (found != null) index = found
+ }
+ if (items.getOrNull(index)?.item?.mediaId == next.uri) {
+ if (!next.paused && !next.busy) awaitingTrack = false
+ if (!awaitingTrack && playback != Player.STATE_ENDED) {
+ if (next.ended && wantPlay && !next.busy) {
+ when {
+ repeat == Player.REPEAT_MODE_ONE -> { position = 0; startCurrent() }
+ index + 1 < items.size -> { index++; position = 0; startCurrent() }
+ repeat == Player.REPEAT_MODE_ALL -> { index = 0; position = 0; startCurrent() }
+ else -> { wantPlay = false; playback = Player.STATE_ENDED }
+ }
+ } else {
+ // Consecutive duplicates have the same URI: a position
+ // reset at the end is still a real item transition.
+ if (!next.paused && lastReportedPosition > next.position + 2_500 &&
+ lastReportedPosition >= next.duration - 2_500 &&
+ index + 1 < chunkEnd && items[index + 1].item.mediaId == next.uri) index++
+ position = next.position
+ wantPlay = !next.paused
+ playback = Player.STATE_READY
+ }
+ lastReportedPosition = next.position
+ }
+ }
+ }
+ }
+ invalidateState()
+ } }
+ }
+ override fun getState(): State {
+ val builder = State.Builder().setAvailableCommands(COMMANDS)
+ .setPlaybackState(if (items.isEmpty()) Player.STATE_IDLE else playback)
+ .setPlayWhenReady(wantPlay, Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST)
+ .setContentPositionMs(position).setRepeatMode(repeat).setShuffleModeEnabled(shuffle)
+ .setPlayerError(error)
+ if (items.isNotEmpty()) {
+ builder.setPlaylist(items.map { entry ->
+ val duration = entry.item.mediaMetadata.durationMs ?: C.TIME_UNSET
+ MediaItemData.Builder(entry.uid).setMediaItem(entry.item)
+ .setDurationUs(if (duration == C.TIME_UNSET) C.TIME_UNSET else duration * 1_000)
+ .setIsSeekable(true)
+ .build()
+ }).setCurrentMediaItemIndex(index.coerceIn(items.indices))
+ }
+ return builder.build()
+ }
+ private fun done(): ListenableFuture<*> = Futures.immediateVoidFuture()
+ private fun startCurrent() {
+ if (items.isEmpty()) return
+ pending = true
+ error = null
+ playback = Player.STATE_BUFFERING
+ if (!engine.account.configured) {
+ wantPlay = false
+ playback = Player.STATE_IDLE
+ WebSdkRecovery.requestSetup()
+ } else if (sdk.deviceId == null) engine.connect()
+ else {
+ pending = false
+ awaitingTrack = true
+ chunkEnd = if (repeat == Player.REPEAT_MODE_ONE) index + 1 else (index + 100).coerceAtMost(items.size)
+ engine.play(items[index].item.mediaId,
+ items.subList(index + 1, chunkEnd).map { it.item.mediaId }, position)
+ }
+ invalidateState()
+ }
+ override fun handlePrepare(): ListenableFuture<*> {
+ prepared = true
+ error = null
+ if (items.isNotEmpty()) {
+ playback = Player.STATE_READY
+ if (wantPlay) startCurrent()
+ }
+ return done()
+ }
+ override fun handleSetPlayWhenReady(playWhenReady: Boolean): ListenableFuture<*> {
+ if (playWhenReady && playback == Player.STATE_ENDED) position = 0
+ wantPlay = playWhenReady
+ if (playWhenReady) {
+ if (sdk.deviceId == null || sdk.uri != items.getOrNull(index)?.item?.mediaId || playback != Player.STATE_READY)
+ startCurrent()
+ else engine.resume()
+ } else { pending = false; engine.command("pause") }
+ return done()
+ }
+ override fun handleSeek(mediaItemIndex: Int, positionMs: Long, seekCommand: Int): ListenableFuture<*> {
+ if (mediaItemIndex !in items.indices) return done()
+ val changed = index != mediaItemIndex
+ index = mediaItemIndex
+ position = positionMs.takeIf { it != C.TIME_UNSET }?.coerceAtLeast(0) ?: 0
+ lastReportedPosition = position
+ if (changed) { if (wantPlay) startCurrent() else { awaitingTrack = false; pending = false } }
+ else engine.seek(position)
+ return done()
+ }
+ override fun handleSetMediaItems(mediaItems: List<MediaItem>, startIndex: Int, startPositionMs: Long): ListenableFuture<*> {
+ engine.command("pause")
+ items.clear()
+ items.addAll(mediaItems.map { Entry(++uid, it) })
+ original = null
+ index = startIndex.takeIf { it != C.INDEX_UNSET }?.coerceIn(0, maxOf(0, items.lastIndex)) ?: 0
+ position = startPositionMs.takeIf { it != C.TIME_UNSET }?.coerceAtLeast(0) ?: 0
+ pending = false
+ awaitingTrack = false
+ error = null
+ playback = if (items.isEmpty()) Player.STATE_IDLE else if (prepared) Player.STATE_READY else Player.STATE_IDLE
+ if (shuffle) reorder(true)
+ if (wantPlay) startCurrent()
+ return done()
+ }
+ override fun handleAddMediaItems(index: Int, mediaItems: List<MediaItem>): ListenableFuture<*> {
+ val current = items.getOrNull(this.index)?.uid
+ items.addAll(index, mediaItems.map { Entry(++uid, it) })
+ original = null
+ this.index = items.indexOfFirst { it.uid == current }.coerceAtLeast(0)
+ if (wantPlay) startCurrent()
+ return done()
+ }
+ override fun handleRemoveMediaItems(fromIndex: Int, toIndex: Int): ListenableFuture<*> {
+ val current = items.getOrNull(index)?.uid
+ items.subList(fromIndex, toIndex).clear()
+ original = null
+ index = items.indexOfFirst { it.uid == current }.takeIf { it >= 0 } ?: fromIndex.coerceAtMost(maxOf(0, items.lastIndex))
+ if (items.isEmpty()) handleStop() else if (wantPlay) startCurrent()
+ return done()
+ }
+ override fun handleMoveMediaItems(fromIndex: Int, toIndex: Int, newIndex: Int): ListenableFuture<*> {
+ val current = items.getOrNull(index)?.uid
+ val moved = items.subList(fromIndex, toIndex).toList()
+ items.subList(fromIndex, toIndex).clear()
+ items.addAll(newIndex, moved)
+ original = null
+ index = items.indexOfFirst { it.uid == current }.coerceAtLeast(0)
+ if (wantPlay) startCurrent()
+ return done()
+ }
+ private fun reorder(enabled: Boolean) {
+ val current = items.getOrNull(index)
+ if (enabled) {
+ original = items.toList()
+ val rest = items.filter { it.uid != current?.uid }.shuffled()
+ items.clear()
+ current?.let { items.add(it) }
+ items.addAll(rest)
+ index = 0
+ } else {
+ original?.let { items.clear(); items.addAll(it) }
+ index = items.indexOfFirst { it.uid == current?.uid }.coerceAtLeast(0)
+ original = null
+ }
+ }
+ override fun handleSetShuffleModeEnabled(shuffleModeEnabled: Boolean): ListenableFuture<*> {
+ if (shuffle != shuffleModeEnabled) {
+ shuffle = shuffleModeEnabled
+ reorder(shuffle)
+ if (wantPlay) startCurrent()
+ }
+ return done()
+ }
+ override fun handleSetRepeatMode(repeatMode: Int): ListenableFuture<*> {
+ repeat = repeatMode
+ if (wantPlay) startCurrent()
+ return done()
+ }
+ override fun handleStop(): ListenableFuture<*> {
+ wantPlay = false
+ pending = false
+ awaitingTrack = false
+ playback = Player.STATE_IDLE
+ engine.stopPlayback()
+ return done()
+ }
+ override fun handleRelease(): ListenableFuture<*> {
+ scope.cancel()
+ engine.release()
+ return done()
+ }
+ companion object {
+ private val COMMANDS = Player.Commands.Builder().addAll(
+ Player.COMMAND_PLAY_PAUSE, Player.COMMAND_PREPARE, Player.COMMAND_STOP,
+ Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM, Player.COMMAND_SEEK_TO_MEDIA_ITEM,
+ Player.COMMAND_SEEK_TO_NEXT, Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM,
+ Player.COMMAND_SEEK_TO_PREVIOUS, Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM,
+ Player.COMMAND_SET_MEDIA_ITEM, Player.COMMAND_CHANGE_MEDIA_ITEMS,
+ Player.COMMAND_GET_CURRENT_MEDIA_ITEM, Player.COMMAND_GET_TIMELINE,
+ Player.COMMAND_GET_METADATA, Player.COMMAND_RELEASE, Player.COMMAND_SET_REPEAT_MODE, Player.COMMAND_SET_SHUFFLE_MODE,
+ ).build()
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkRecovery.kt b/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkRecovery.kt
new file mode 100644
index 0000000..1cb513f
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkRecovery.kt
@@ -0,0 +1,49 @@
+package dev.lelonio.square.playback.websdk
+
+import android.content.Context
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asSharedFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/** Only the engine's explicit account-level rejection activates this recovery. */
+object WebSdkRecovery {
+ private var sequence = 0
+ private var setupOpen = false
+ private val requests = MutableStateFlow(0)
+ val setupRequests = requests.asStateFlow()
+ private val changes = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
+ val configured = changes.asSharedFlow()
+ fun requestSetup() { if (!setupOpen && requests.value == 0) requests.value = ++sequence }
+ fun consume(request: Int) {
+ if (requests.value == request) { setupOpen = true; requests.value = 0 }
+ }
+ fun closeSetup() { setupOpen = false }
+ private val stops = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
+ val disconnected = stops.asSharedFlow()
+ fun stopPlayback() { stops.tryEmit(Unit) }
+ fun isConfigured(context: Context) = (context.applicationContext as dev.lelonio.square.SquareApplication).spotifySdkAccount.configured
+
+ private val use = MutableStateFlow(false)
+
+ /**
+ * Whether Spotify plays through the official SDK: Spotify is the source, the
+ * account is refused and the SDK is set up. What the SDK cannot do — crossfade, effects, karaoke,
+ * bitrate, downloads — is taken off screen while this holds.
+ */
+ val inUse: StateFlow<Boolean> = use.asStateFlow()
+
+ /** Read again after anything that can change either half of [inUse]. */
+ fun refresh(context: Context) {
+ val app = context.applicationContext as dev.lelonio.square.SquareApplication
+ use.value = app.preferences.backend.value == dev.lelonio.square.backend.BackendId.SPOTIFY &&
+ dev.lelonio.square.backend.spotify.SpotifyWebPlayback.needed(app) && isConfigured(app)
+ }
+
+ fun complete(context: Context) {
+ (context.applicationContext as dev.lelonio.square.SquareApplication).spotifySdkAccount.enable()
+ refresh(context)
+ changes.tryEmit(Unit)
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkService.kt b/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkService.kt
new file mode 100644
index 0000000..ed108e7
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/playback/websdk/WebSdkService.kt
@@ -0,0 +1,125 @@
+package dev.lelonio.square.playback.websdk
+
+import android.app.*
+import android.content.Intent
+import android.media.session.MediaSession
+import android.media.session.PlaybackState
+import android.media.MediaMetadata
+import android.os.Binder
+import android.os.IBinder
+import android.webkit.*
+import androidx.core.app.NotificationCompat
+import dev.lelonio.square.R
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import okhttp3.*
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.RequestBody.Companion.toRequestBody
+import org.json.JSONObject
+import java.util.concurrent.TimeUnit
+
+/** Isolated SDK proof of concept. No access to DRM keys or native-engine credentials. */
+class WebSdkService : Service() {
+ inner class LocalBinder : Binder() { val service get() = this@WebSdkService }
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+ private lateinit var engine: WebSdkEngine
+ val state get() = engine.state
+ internal val account get() = engine.account
+ val webView get() = engine.webView
+ private var foreground = false
+ private lateinit var media: MediaSession
+
+ override fun onCreate() {
+ super.onCreate()
+ engine = WebSdkEngine(this)
+ getSystemService(NotificationManager::class.java).createNotificationChannel(
+ NotificationChannel(CHANNEL, getString(R.string.web_sdk_title), NotificationManager.IMPORTANCE_LOW),
+ )
+ media = MediaSession(this, "SquareWebSdk").apply {
+ setCallback(object : MediaSession.Callback() {
+ override fun onPlay() { resume() }
+ override fun onPause() { command("pause") }
+ override fun onSeekTo(pos: Long) { seek(pos) }
+ override fun onStop() { stopPlayback() }
+ })
+ }
+ scope.launch { engine.state.collect { next ->
+ update(next)
+ if (next.stage in setOf("error", "idle", "capable") && foreground) {
+ stopForeground(STOP_FOREGROUND_REMOVE)
+ foreground = false
+ stopSelf()
+ }
+ } }
+ }
+ override fun onBind(intent: Intent): IBinder = LocalBinder()
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ if (intent?.action == STOP) stopPlayback() else {
+ promote()
+ if (intent?.action == TOGGLE) {
+ if (state.value.paused) resume() else command("pause")
+ }
+ }
+ return START_NOT_STICKY
+ }
+
+ private fun promote() {
+ startForeground(NOTIFICATION, notification())
+ foreground = true
+ }
+ private fun notification(): android.app.Notification {
+ val open = PendingIntent.getActivity(this, 0, Intent(this, WebSdkActivity::class.java), FLAGS)
+ fun action(name: String, id: Int) = PendingIntent.getService(this, id,
+ Intent(this, WebSdkService::class.java).setAction(name), FLAGS)
+ return NotificationCompat.Builder(this, CHANNEL)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle(state.value.title.ifBlank { getString(R.string.web_sdk_title) })
+ .setContentText(state.value.artist.ifBlank { getString(R.string.web_sdk_running) })
+ .setContentIntent(open).setOngoing(!state.value.paused)
+ .addAction(0, getString(if (state.value.paused) R.string.play else R.string.pause), action(TOGGLE, 1))
+ .addAction(0, getString(R.string.web_sdk_stop), action(STOP, 2))
+ .build()
+ }
+ private fun update(next: WebSdkState) {
+ media.isActive = next.deviceId != null
+ media.setPlaybackState(PlaybackState.Builder()
+ .setActions(PlaybackState.ACTION_PLAY or PlaybackState.ACTION_PAUSE or
+ PlaybackState.ACTION_SEEK_TO or PlaybackState.ACTION_STOP)
+ .setState(if (next.paused) PlaybackState.STATE_PAUSED else PlaybackState.STATE_PLAYING,
+ next.position, if (next.paused) 0f else 1f).build())
+ media.setMetadata(MediaMetadata.Builder().putString(MediaMetadata.METADATA_KEY_TITLE, next.title)
+ .putString(MediaMetadata.METADATA_KEY_ARTIST, next.artist)
+ .putLong(MediaMetadata.METADATA_KEY_DURATION, next.duration).build())
+ if (foreground) getSystemService(NotificationManager::class.java).notify(NOTIFICATION, notification())
+ }
+
+ fun connect(probeOnly: Boolean = false) {
+ promote()
+ engine.connect(probeOnly)
+ }
+ fun command(name: String, position: Long = 0) = engine.command(name, position)
+ fun resume() = engine.resume()
+ fun seek(position: Long) = engine.seek(position)
+ fun play(input: String) = engine.play(input)
+ fun stopPlayback() {
+ engine.stopPlayback()
+ stopForeground(STOP_FOREGROUND_REMOVE)
+ foreground = false
+ stopSelf()
+ }
+ override fun onDestroy() {
+ engine.release()
+ media.release()
+ scope.cancel()
+ super.onDestroy()
+ }
+ companion object {
+ private const val CHANNEL = "square_web_sdk"
+ private const val NOTIFICATION = 740
+ private const val STOP = "square.sdk.STOP"
+ private const val TOGGLE = "square.sdk.TOGGLE"
+ private const val FLAGS = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
index 1eda4a7..80e4528 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
@@ -2,6 +2,10 @@ package dev.lelonio.square.ui
import android.content.ComponentName
import android.os.Bundle
+import androidx.lifecycle.lifecycleScope
+import androidx.lifecycle.repeatOnLifecycle
+import androidx.lifecycle.Lifecycle
+import kotlinx.coroutines.launch
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.SystemBarStyle
@@ -88,6 +92,19 @@ class MainActivity : ComponentActivity() {
}
intent?.let(::takeLink)
+ lifecycleScope.launch {
+ repeatOnLifecycle(Lifecycle.State.STARTED) {
+ dev.lelonio.square.playback.websdk.WebSdkRecovery.setupRequests.collect { request ->
+ if (request > 0) {
+ dev.lelonio.square.playback.websdk.WebSdkRecovery.consume(request)
+ startActivity(android.content.Intent(this@MainActivity,
+ dev.lelonio.square.playback.websdk.WebSdkActivity::class.java)
+ .putExtra("recovery", true))
+ }
+ }
+ }
+ }
+
setContent {
SquareApp(
player = controller,
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
index 5bb4bf1..c5bf12c 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -2012,6 +2012,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
SpotifyOAuth.cancelActiveAuthorization()
container.tokenStore.clear()
container.webApi.disconnect()
+ container.spotifySdkAccount.disconnect()
+ getApplication<android.app.Application>().getSharedPreferences("square_keys", android.content.Context.MODE_PRIVATE)
+ .edit().remove("account_refused").apply()
+ dev.lelonio.square.playback.websdk.WebSdkRecovery.refresh(getApplication())
// The engine's own credential too, or the next launch would log itself
// back in with it and signing out would mean nothing.
dev.lelonio.square.auth.EngineCredentials.clear(getApplication())
@@ -3056,8 +3060,11 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
if (syncResult.isSuccess && container.downloadSettings.downloadLikedSongs.value) {
if (nowLiked) {
- container.downloads.addLiked(resolvedTrack)
- dev.lelonio.square.download.DownloadService.start(container)
+ // Nothing to fetch it with while the official SDK plays.
+ if (!dev.lelonio.square.playback.websdk.WebSdkRecovery.inUse.value) {
+ container.downloads.addLiked(resolvedTrack)
+ dev.lelonio.square.download.DownloadService.start(container)
+ }
} else {
container.downloads.removeLiked(trackUri)
container.downloads.pruneOrphans().forEach {
@@ -4072,7 +4079,9 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val it = uri ?: return false
val backend = container.activeBackend
return backend.owns(it) && when (backend.id) {
- BackendId.SPOTIFY -> it.startsWith("spotify:")
+ // The official SDK streams and keeps nothing; see WebSdkRecovery.inUse.
+ BackendId.SPOTIFY -> it.startsWith("spotify:") &&
+ !dev.lelonio.square.playback.websdk.WebSdkRecovery.inUse.value
BackendId.YOUTUBE_MUSIC -> true
}
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/onboarding/SetupPieces.kt b/app/src/main/java/dev/lelonio/square/ui/onboarding/SetupPieces.kt
index 3f3b55a..70537df 100644
--- a/app/src/main/java/dev/lelonio/square/ui/onboarding/SetupPieces.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/onboarding/SetupPieces.kt
@@ -139,13 +139,14 @@ internal fun PrimaryButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
+ enabled: Boolean = true,
) {
Box(
modifier
- .pressable(onClick, pressedScale = 0.96f)
+ .pressable({ if (enabled) onClick() }, pressedScale = if (enabled) 0.96f else 1f)
.height(52.dp)
.clip(CircleShape)
- .background(Ink)
+ .background(if (enabled) Ink else Ink.copy(alpha = 0.3f))
.padding(horizontal = 26.dp),
contentAlignment = Alignment.Center,
) {
diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerPanel.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerPanel.kt
index ce3a08b..d978d9e 100644
--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerPanel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerPanel.kt
@@ -131,10 +131,18 @@ fun PlayerPanelSection(
val effectsOn = speed != 1f || pitch != 1f || reverb > 0f
val karaoke by dev.lelonio.square.playback.AudioEffects.karaoke
.collectAsStateWithLifecycle()
- val karaokeOn = karaoke > 0f
-
- val views = remember {
- listOf(PlayerPanel.NONE, PlayerPanel.LYRICS, PlayerPanel.EFFECTS, PlayerPanel.INFO)
+ // The official SDK mixes its own audio, so it has no effects to offer.
+ val sdkPlayback by dev.lelonio.square.playback.websdk.WebSdkRecovery.inUse
+ .collectAsStateWithLifecycle()
+ val karaokeOn = karaoke > 0f && !sdkPlayback
+
+ val views = remember(sdkPlayback) {
+ listOfNotNull(
+ PlayerPanel.NONE,
+ PlayerPanel.LYRICS,
+ PlayerPanel.EFFECTS.takeUnless { sdkPlayback },
+ PlayerPanel.INFO,
+ )
}
val selected = views.indexOf(panel).coerceAtLeast(0)
// Stable, or LiquidBottomTabs throws away the state it keys on this and
@@ -164,29 +172,29 @@ fun PlayerPanelSection(
icon = PhosphorIcons.Regular.VinylRecord,
activeIcon = PhosphorIcons.Fill.VinylRecord,
label = stringResource(R.string.cover),
- selected = selected == 0,
+ selected = selected == views.indexOf(PlayerPanel.NONE),
) { onSelect(PlayerPanel.NONE) }
PanelTab(
icon = PhosphorIcons.Regular.TextAlignLeft,
activeIcon = PhosphorIcons.Fill.TextAlignLeft,
label = stringResource(R.string.lyrics),
- selected = selected == 1,
+ selected = selected == views.indexOf(PlayerPanel.LYRICS),
// The karaoke lives in this view and keeps working with the
// panel shut; see the same halo on the effects tab.
marked = karaokeOn,
) { onSelect(PlayerPanel.LYRICS) }
- PanelTab(
+ if (!sdkPlayback) PanelTab(
icon = PhosphorIcons.Regular.SlidersHorizontal,
activeIcon = PhosphorIcons.Fill.SlidersHorizontal,
label = stringResource(R.string.effects),
- selected = selected == 2,
+ selected = selected == views.indexOf(PlayerPanel.EFFECTS),
marked = effectsOn,
) { onSelect(PlayerPanel.EFFECTS) }
PanelTab(
icon = PhosphorIcons.Regular.Info,
activeIcon = PhosphorIcons.Fill.Info,
label = stringResource(R.string.credits),
- selected = selected == 3,
+ selected = selected == views.indexOf(PlayerPanel.INFO),
) { onSelect(PlayerPanel.INFO) }
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt
index be22720..247ab2c 100644
--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt
@@ -374,6 +374,11 @@ fun PlayerScreen(
onAnotherDevice: Boolean = false,
) {
var panel by remember { mutableStateOf(PlayerPanel.NONE) }
+ // The official SDK mixes its own audio: no effects or karaoke reach it.
+ val sdkPlayback by dev.lelonio.square.playback.websdk.WebSdkRecovery.inUse.collectAsStateWithLifecycle()
+ LaunchedEffect(sdkPlayback) {
+ if (sdkPlayback && panel == PlayerPanel.EFFECTS) panel = PlayerPanel.NONE
+ }
/** Bumped to open the karaoke control; see KaraokeDial. */
var karaokeExpand by remember { androidx.compose.runtime.mutableIntStateOf(0) }
@@ -925,7 +930,7 @@ fun PlayerScreen(
val karaokeAmount by dev.lelonio.square.playback.AudioEffects.karaoke
.collectAsStateWithLifecycle()
androidx.compose.animation.AnimatedVisibility(
- visible = karaokeAmount > 0f,
+ visible = karaokeAmount > 0f && !sdkPlayback,
enter = fadeIn(tween(220)),
exit = fadeOut(tween(180)),
modifier = Modifier
@@ -2433,7 +2438,10 @@ private fun LyricsStage(
)
}
- KaraokeDial(
+ // Not over the official SDK, whose audio never passes through the effect.
+ val sdkPlayback by dev.lelonio.square.playback.websdk.WebSdkRecovery.inUse
+ .collectAsStateWithLifecycle()
+ if (!sdkPlayback) KaraokeDial(
amount = karaoke,
onChange = dev.lelonio.square.playback.AudioEffects::setKaraoke,
backdrop = backdrop,
diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
index 3c06b9f..202d34f 100644
--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
@@ -155,6 +155,9 @@ fun SettingsScreen(
*/
val spotifyActive by app.preferences.backend.collectAsStateWithLifecycle()
val showSpotify = spotifyActive == BackendId.SPOTIFY
+ // Spotify through the official SDK, which mixes its own audio: none of the
+ // engine's crossfade, bitrate, effects or downloads reach it.
+ val sdkPlayback by dev.lelonio.square.playback.websdk.WebSdkRecovery.inUse.collectAsStateWithLifecycle()
/**
* Which page is open, or null for the list of them.
@@ -370,6 +373,24 @@ fun SettingsScreen(
}
}
+ if (shown == SettingsPage.Playback && showSpotify &&
+ (dev.lelonio.square.backend.spotify.SpotifyWebPlayback.needed(context) ||
+ dev.lelonio.square.playback.websdk.WebSdkRecovery.isConfigured(context))) item("web-sdk-recovery") {
+ Section(stringResource(R.string.web_sdk_settings_title)) {
+ ActionRow(stringResource(R.string.web_sdk_settings_open), destructive = false) {
+ context.startActivity(android.content.Intent(
+ context, dev.lelonio.square.playback.websdk.WebSdkActivity::class.java,
+ ).putExtra("recovery", true))
+ }
+ if (sdkPlayback) Text(
+ stringResource(R.string.web_sdk_limits),
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ modifier = Modifier.padding(start = 18.dp, end = 18.dp, bottom = 14.dp),
+ )
+ }
+ }
+
if (shown == SettingsPage.Playback) item("backend") {
BackendSection()
}
@@ -390,12 +411,12 @@ fun SettingsScreen(
StorageChart()
}
- if (shown == SettingsPage.Downloads && showSpotify) item("downloads") {
+ if (shown == SettingsPage.Downloads && showSpotify && !sdkPlayback) item("downloads") {
DownloadsSection(backdrop)
}
// The bitrate is librespot's; ExoPlayer takes what YouTube serves.
- if (shown == SettingsPage.Playback && showSpotify) item("quality") {
+ if (shown == SettingsPage.Playback && showSpotify && !sdkPlayback) item("quality") {
QualitySection()
}
@@ -442,7 +463,7 @@ fun SettingsScreen(
}
}
- if (shown == SettingsPage.Playback) item("crossfade") {
+ if (shown == SettingsPage.Playback && !sdkPlayback) item("crossfade") {
CrossfadeSection(backdrop)
}
@@ -458,7 +479,7 @@ fun SettingsScreen(
}
// The effects run on our own output, so this one holds for both backends.
- if (shown == SettingsPage.Playback) item("effect-quality") {
+ if (shown == SettingsPage.Playback && !sdkPlayback) item("effect-quality") {
EffectQualitySection()
}
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index d4e4cac..08cb2c4 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -481,4 +481,38 @@
<string name="added_to_queue">Aggiunto in coda: %s</string>
<string name="videos">Video</string>
<string name="web_playback_on">Spotify rifiuta a questo account le chiavi per i brani: li riproduco come fa il web player. In questa modalità Spotify Connect e i download non sono disponibili.</string>
+
+ <!-- Official Spotify SDK proof of concept. -->
+ <string name="web_sdk_title">Spotify Web Playback · prototipo</string>
+ <string name="web_sdk_open">Apri prova di riproduzione</string>
+ <string name="web_sdk_explainer">Prova il player ufficiale Spotify con un account Premium. Registra una tua applicazione sviluppatore abilitando Web Playback SDK, poi inserisci il suo Client ID.</string>
+ <string name="web_sdk_redirect">Sul dashboard apri la tua app, spunta Web Playback SDK e aggiungi questo URI di reindirizzamento:</string>
+ <string name="web_sdk_login">Accedi a Spotify</string>
+ <string name="web_sdk_reauthorize">Autorizza di nuovo</string>
+ <string name="web_sdk_check">Verifica compatibilità</string>
+ <string name="web_sdk_connect">Collega player</string>
+ <string name="web_sdk_loading">Verifica e collegamento…</string>
+ <string name="web_sdk_ready">Player pronto</string>
+ <string name="web_sdk_capable">DRM supportato. Accedi per provare la riproduzione Spotify.</string>
+ <string name="web_sdk_idle">Player fermo</string>
+ <string name="web_sdk_track">Link o URI di un brano Spotify</string>
+ <string name="web_sdk_stop">Ferma prova</string>
+ <string name="web_sdk_background">Dopo aver avviato un brano, spegni lo schermo o apri un’altra app. I controlli restano nella notifica. Questo prototipo non offre dissolvenza incrociata o riproduzione offline.</string>
+ <string name="web_sdk_running">Prova riproduzione Spotify SDK</string>
+ <string name="web_sdk_unsupported">Questa WebView Android non può eseguire il DRM richiesto da Spotify Web Playback SDK. Un servizio in background non risolve questo limite del browser.</string>
+ <string name="web_sdk_premium">È richiesto Spotify Premium.</string>
+ <string name="web_sdk_auth_error">Controlla il tuo Client ID e l’URI di reindirizzamento registrato, poi autorizza di nuovo.</string>
+ <string name="web_sdk_forbidden">Spotify ha rifiutato la riproduzione. Controlla Premium, permessi SDK e accesso alla tua applicazione sviluppatore.</string>
+ <string name="web_sdk_rate_limit">Limite richieste Spotify raggiunto. Attendi prima di riprovare.</string>
+ <string name="web_sdk_invalid_track">Inserisci il link di un brano Spotify o un URI spotify:track:.</string>
+ <string name="web_sdk_focus">Un’altra app controlla attualmente l’audio. Riprova.</string>
+ <string name="web_sdk_play_error">Collegamento o riproduzione non riusciti. Ferma la prova e ricollega il player.</string>
+ <string name="web_sdk_failed">Player non disponibile</string>
+ <string name="web_sdk_recovery_title">Attiva la riproduzione Spotify</string>
+ <string name="web_sdk_recovery_explainer">Spotify non riproduce i brani di questo account nel player abituale di Square. Square può usare il player web ufficiale di Spotify, con l’accesso tramite la tua app sviluppatore.</string>
+ <string name="web_sdk_enable">Attiva riproduzione</string>
+ <string name="web_sdk_settings_title">Riproduzione Spotify alternativa</string>
+ <string name="web_sdk_limits">Con questo player non sono disponibili dissolvenza incrociata, effetti audio, karaoke, scelta della qualità e download.</string>
+ <string name="web_sdk_settings_open">Configura player web</string>
+ <string name="web_sdk_authorized">Account Spotify autorizzato</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 0cb6edf..ed478dc 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -508,4 +508,38 @@
<string name="videos">Videos</string>
<string name="device_this_app" translatable="false">%1$s (Square)</string>
<string name="web_playback_on">Spotify refuses this account the keys its songs need: playing them the way the web player does. Spotify Connect and downloads are not available this way.</string>
+
+ <!-- Official Spotify SDK proof of concept. -->
+ <string name="web_sdk_title">Spotify Web Playback · prototype</string>
+ <string name="web_sdk_open">Open playback test</string>
+ <string name="web_sdk_explainer">Test the official Spotify player with a Premium account. Register your own developer app with Web Playback SDK enabled, then enter its Client ID.</string>
+ <string name="web_sdk_redirect">On the dashboard, open your app, tick Web Playback SDK and add this redirect URI:</string>
+ <string name="web_sdk_login">Sign in to Spotify</string>
+ <string name="web_sdk_reauthorize">Authorize again</string>
+ <string name="web_sdk_check">Check compatibility</string>
+ <string name="web_sdk_connect">Connect player</string>
+ <string name="web_sdk_loading">Checking and connecting…</string>
+ <string name="web_sdk_ready">Player ready</string>
+ <string name="web_sdk_capable">DRM supported. Sign in to test Spotify playback.</string>
+ <string name="web_sdk_idle">Player stopped</string>
+ <string name="web_sdk_track">Spotify track link or URI</string>
+ <string name="web_sdk_stop">Stop test</string>
+ <string name="web_sdk_background">After playback starts, turn off the screen or open another app. Notification controls stay available. This prototype does not provide crossfade or offline playback.</string>
+ <string name="web_sdk_running">Spotify SDK playback test</string>
+ <string name="web_sdk_unsupported">This Android WebView cannot run the DRM required by Spotify Web Playback SDK. A foreground service cannot fix this browser limitation.</string>
+ <string name="web_sdk_premium">Spotify Premium is required.</string>
+ <string name="web_sdk_auth_error">Check your own Client ID and registered redirect URI, then authorize again.</string>
+ <string name="web_sdk_forbidden">Spotify refused playback. Check Premium, SDK permissions and access to your developer app.</string>
+ <string name="web_sdk_rate_limit">Spotify request limit reached. Wait before trying again.</string>
+ <string name="web_sdk_invalid_track">Enter a Spotify track link or spotify:track: URI.</string>
+ <string name="web_sdk_focus">Another app currently controls audio. Try again.</string>
+ <string name="web_sdk_play_error">Player connection or playback failed. Stop the test and reconnect.</string>
+ <string name="web_sdk_failed">Player unavailable</string>
+ <string name="web_sdk_recovery_title">Turn on Spotify playback</string>
+ <string name="web_sdk_recovery_explainer">Spotify won’t play this account’s songs in Square’s usual player. Square can use Spotify’s official web player instead, signed in through your developer app.</string>
+ <string name="web_sdk_enable">Enable playback</string>
+ <string name="web_sdk_settings_title">Alternative Spotify playback</string>
+ <string name="web_sdk_limits">With this player, crossfade, audio effects, karaoke, sound quality and downloads are not available.</string>
+ <string name="web_sdk_settings_open">Configure web player</string>
+ <string name="web_sdk_authorized">Spotify account authorized</string>
</resources>
diff --git a/docs/web-playback-sdk.md b/docs/web-playback-sdk.md
new file mode 100644
index 0000000..c44831f
--- /dev/null
+++ b/docs/web-playback-sdk.md
@@ -0,0 +1,44 @@
+# Official Spotify Web Playback SDK recovery
+
+Branch: `web-playback`.
+
+Square offers additional setup when the native Spotify engine explicitly reports an account-level audio-key refusal. Generic network failures and individual unavailable tracks do not activate this path. Accounts that work with native playback keep using it.
+
+The recovery player uses the official SDK at `https://sdk.scdn.co/spotify-player.js`, public Spotify Web API commands and app-owned OAuth credentials. It does not intercept open.spotify.com tokens, request DRM licences directly or expose audio samples or keys. The earlier direct-stream experiment remains in the repository but is not used by this fallback.
+
+## Setup and normal playback
+
+1. When Square detects the refusal, it pauses the failed player and opens **Complete Spotify playback setup** when the app is visible. Setup is also available under **Settings → Playback → Alternative Spotify playback** for affected/configured accounts.
+2. Register a Spotify developer application with Web Playback SDK enabled and redirect URI `http://127.0.0.1:5588/login`. Ensure the Premium account has access to that application, including developer-mode access rules.
+3. Enter its Client ID and authorize the same Premium account in the external browser. An existing search application Client ID is offered as a starting value; its tokens are not shared.
+4. **Check compatibility** optionally probes secure-context EME and Widevine availability without Spotify login. **Enable playback** checks DRM and connects the official SDK.
+5. When ready, Square enables recovery, closes setup and resumes the failed selection with its position and queue. Subsequent Spotify selections use the SDK while the account refusal is remembered. Local files and YouTube playback retain their own engines.
+
+The Media3 adapter exposes SDK playback to Square’s normal mini player, full player, notification and lock-screen controls. Square retains item metadata, queue, manual next/previous, seek, repeat and shuffle. It sends up to 100 upcoming tracks to Spotify at a time and handles remaining chunks locally. The SDK device is recognized as playback on this phone, rather than mirrored as an external Connect device.
+
+OAuth uses PKCE. Tokens are kept in a dedicated encrypted TokenStore with renewal; no client secret is embedded. Scopes: `streaming`, `user-read-private`, `user-read-email`, `user-read-playback-state`, `user-modify-playback-state`. Disconnecting the SDK or signing out of Square clears SDK tokens and stops its output. A new Client ID requires authorization again.
+
+## Compatibility and limits
+
+Android WebView compatibility depends on secure-context EME/Widevine support. Unsupported DRM, renderer failure, initialization timeout and sanitized SDK/API errors are reported. A foreground service does not add missing browser DRM features. Crossfade, native PCM effects and Spotify offline downloads are unavailable through this player.
+
+The runtime is owned by the normal playback service; its hidden WebView survives closing the activity. A separate non-exported service handles the setup check and the developer test screen, then releases its runtime before normal playback connects. Chromium owns audio focus: a duplicate native focus request caused immediate pauses on the test phone and is deliberately avoided.
+
+The bridge is limited to the locally supplied HTTPS-origin document and the official SDK embedded frame. Only protected-media permission is granted. Logs exclude access tokens and server response bodies. Initialization times out after 45 seconds. Playback requests are cancellable and stale responses are ignored when the selection changes.
+
+## Validation (2026-10-04)
+
+- Compiled and installed on A059 (Android 17), Android WebView 153.0.8010.39.
+- On-device DRM probe and app-owned OAuth succeeded. The user confirmed audible official SDK playback.
+- The account-refusal diagnostic hook exercised additional setup, activation and recovery into the normal player, preserving the queue. The user confirmed audio also after choosing another playlist track. This simulates the refusal; it is not a test with a genuinely refused Premium account.
+- The standalone SDK smoke test continued while the device was Dozing (30,992 → 74,063 ms), and native pause, seek, resume and stop worked.
+- `node scripts/check-web-playback-sdk.mjs` passes mocked bridge checks for DRM gating, login-free compatibility probes, SDK loading, renewed token callbacks, URI/state events, natural end versus paused seeks, playback commands and sanitized errors.
+- The final installed build preserved a 1,196-item queue. Native media controls advanced Hollywood → Caos; pause and a full-player seek reported PAUSED at 89,826 ms, followed by resumed PLAYING. The artificial refusal flag was removed after testing and playback left paused.
+- These checks do not prove every Premium account, long background sessions, all OEM power policies or server-side expired-token behavior.
+
+## References
+
+- https://developer.spotify.com/documentation/web-playback-sdk
+- https://developer.spotify.com/documentation/web-playback-sdk/reference
+- https://developer.spotify.com/documentation/web-api/tutorials/code-pkce-flow
+- https://developer.spotify.com/documentation/web-api/reference/start-a-users-playback
diff --git a/scripts/check-web-playback-sdk.mjs b/scripts/check-web-playback-sdk.mjs
new file mode 100644
index 0000000..bcc140e
--- /dev/null
+++ b/scripts/check-web-playback-sdk.mjs
@@ -0,0 +1,42 @@
+import fs from 'node:fs';
+import vm from 'node:vm';
+import assert from 'node:assert/strict';
+const html=fs.readFileSync('app/src/main/assets/websdk/player.html','utf8');
+const script=html.match(/<script>([\s\S]*)<\/script>/)[1];
+async function env({eme=true,secure=true,probe=false,reject=false}={}) {
+ const events=[],tokens=[],scripts=[],calls=[],listeners={}; let options;
+ const context={SquareSdk:{event:s=>events.push(JSON.parse(s)),token:id=>tokens.push(id)},
+ navigator:eme?{requestMediaKeySystemAccess:async()=>{if(reject)throw Error()}}:{},
+ isSecureContext:secure,
+ document:{createElement:()=>({}),head:{appendChild:s=>scripts.push(s)}},
+ Spotify:{Player:function(o){options=o;return {
+ addListener:(name,fn)=>listeners[name]=fn,
+ connect:async()=>true,pause:async()=>calls.push('pause'),
+ resume:async()=>calls.push('resume'),activateElement:async()=>calls.push('activate'),
+ seek:async pos=>calls.push(['seek',pos]),disconnect:()=>calls.push('disconnect'),
+ getCurrentState:async()=>null
+ }} }
+ };context.window=context;
+ vm.runInNewContext(script.replace('__CONNECT__',String(!probe)),context);
+ await new Promise(resolve=>setImmediate(resolve));
+ return {context,events,tokens,scripts,calls,listeners,get options(){return options}};
+}
+for(const config of [{eme:false},{secure:false},{reject:true}]) {
+ const e=await env(config);assert.equal(e.events[0].code,'eme_unavailable');assert.equal(e.scripts.length,0);assert.equal(e.tokens.length,0);
+}
+const probe=await env({probe:true});assert.equal(probe.events[0].type,'capable');assert.equal(probe.scripts.length,0);
+const e=await env();assert.equal(e.scripts[0].src,'https://sdk.scdn.co/spotify-player.js');
+e.context.onSpotifyWebPlaybackSDKReady();
+let received=[];e.options.getOAuthToken(t=>received.push(t));e.options.getOAuthToken(t=>received.push(t));
+assert.deepEqual(e.tokens,[1,2]);e.context.receiveToken(2,'fresh-two');e.context.receiveToken(1,'fresh-one');e.context.receiveToken(1,'duplicate');assert.deepEqual(received,['fresh-two','fresh-one']);
+e.listeners.ready({device_id:'test-device'});assert.equal(e.events.at(-1).deviceId,'test-device');
+e.listeners.player_state_changed({paused:false,position:12000,duration:180000,track_window:{current_track:{name:'Track',artists:[{name:'Artist'}]}}});assert.equal(e.events.at(-1).artist,'Artist');assert.equal(e.events.at(-1).position,12000);
+await e.context.command('resume');await e.context.command('seek',15000);await e.context.command('pause');assert.deepEqual(e.calls,['activate','resume',['seek',15000],'pause']);
+const endingTrack={name:'Track',uri:'spotify:track:4PTG3Z6ehGkBFwjybzWkR8',artists:[{name:'Artist'}]};
+function report(paused,position){e.listeners.player_state_changed({paused,position,duration:180000,track_window:{current_track:endingTrack}});return e.events.at(-1);}
+report(false,179000);assert.equal(report(true,0).ended,true);
+assert.equal(report(true,0).ended,false); // Repeated polls must not advance the queue twice.
+report(false,179000);report(true,179000);assert.equal(report(true,0).ended,false); // Seeking while paused is not track completion.
+e.listeners.authentication_error({message:'SENSITIVE DETAILS'});assert.equal(e.events.at(-1).code,'authentication_error');assert.equal(JSON.stringify(e.events).includes('SENSITIVE'),false);
+e.scripts[0].onerror();assert.equal(e.events.at(-1).code,'sdk_load_error');
+console.log('PASS: DRM gates, probe without login, SDK loading, renewed token callbacks, playback events, commands and sanitized errors.');