Skip to content

Native Android client for Spotify, built with Jetpack Compose

Devices: a Chromecast takes Spotify songs through Spotify's own receiver (launched, logged in with a device token, then the playback transferred), and Spotify Connect speakers on the local network (Sonos included) are found and logged in the same way when tapped; Cast discovery no longer stalls on a lost resolve and a silent device no longer holds the Cast thread; a failed transfer goes back to the phone with an error, a fixed-volume device no longer shows 0 %, and the picker asks Spotify to look for devices when it opens

kota-zo36389db6d5e3
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 1d13a666..6d64a30f 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
@@ -416,7 +416,8 @@ class SpotifyDevices(private val bridge: Bridge) : Devices {
override suspend fun transfer(deviceId: String, play: Boolean) {
bridge.service("ConnectTransferAPI", "transferPlayback", JsonPrimitive(deviceId), json(mapOf("playOnTransfer" to play)))
- refresh()
+ // The transfer is done: a list that cannot be read now is not a failed transfer.
+ runCatching { refresh() }
}
override suspend fun pullHere() {
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastChannel.kt b/base/app/src/main/java/com/music/spotui/cast/CastChannel.kt
index 23a8aa56..93ad8220 100644
--- a/base/app/src/main/java/com/music/spotui/cast/CastChannel.kt
+++ b/base/app/src/main/java/com/music/spotui/cast/CastChannel.kt
@@ -46,9 +46,11 @@ class CastChannel(
val s = ctx.socketFactory.createSocket() as SSLSocket
try {
s.connect(InetSocketAddress(host, port), timeoutMs)
- s.soTimeout = 0
+ // The handshake is bounded too: a device that accepts and stays silent must not hold the caller.
+ s.soTimeout = timeoutMs
s.tcpNoDelay = true
s.startHandshake()
+ s.soTimeout = 0
} catch (e: Exception) {
// Not connected: the socket is closed here, nothing else holds it.
runCatching { s.close() }
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastDeviceRows.kt b/base/app/src/main/java/com/music/spotui/cast/CastDeviceRows.kt
index 9fce94be..517d4cc2 100644
--- a/base/app/src/main/java/com/music/spotui/cast/CastDeviceRows.kt
+++ b/base/app/src/main/java/com/music/spotui/cast/CastDeviceRows.kt
@@ -19,6 +19,7 @@ import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
@@ -29,6 +30,7 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import app.myspoti.engine.R
+import app.myspoti.host.android.MyspotiRuntime
import com.music.spotui.di.LocalPlayer
import com.music.spotui.ui.theme.AppAccent
import com.music.spotui.ui.theme.AppMuted
@@ -37,8 +39,9 @@ import com.music.spotui.ui.theme.AppText
/**
* The Cast devices of the network in the device picker, under the Spotify Connect devices: Myspoti's
* own songs (extensions, downloads, the phone's files) are cast to them. While a Spotify song
- * plays they are shown greyed: Spotify Connect casts those. While casting: back to this phone,
- * and the device's volume.
+ * plays, a tap wakes the device's Spotify receiver ([CastSpotify]) and the song moves to it as a
+ * Spotify Connect device; one already listed above under the same name is not repeated. While
+ * casting: back to this phone, and the device's volume.
*/
@Composable
fun CastDeviceRows(onDismiss: () -> Unit) {
@@ -63,12 +66,18 @@ fun CastDeviceRows(onDismiss: () -> Unit) {
CastPlayback.stop(back = true); onDismiss()
}
}
- CastDiscovery.devices.filter { it.id != casting?.id }.forEach { d ->
+ val waking = CastSpotify.waking.value
+ val connectNames = MyspotiRuntime.spotify.devices.devices.collectAsState().value.filter { !it.local }.map { it.name }.toSet()
+ CastDiscovery.devices.filter { it.id != casting?.id && (ownSong || it.name !in connectNames) }.forEach { d ->
val detail = when {
- !ownSong -> stringResource(R.string.cast_spotify_via_connect)
+ waking?.id == d.id -> stringResource(R.string.cast_connecting)
+ !ownSong -> stringResource(R.string.cast_spotify_detail)
else -> d.model.ifBlank { stringResource(R.string.cast_device_detail) }
}
- CastRow(Icons.Default.Cast, d.name, detail, enabled = ownSong) { CastPlayback.start(d); onDismiss() }
+ CastRow(Icons.Default.Cast, d.name, detail, enabled = waking == null) {
+ if (ownSong) CastPlayback.start(d) else CastSpotify.start(d)
+ onDismiss()
+ }
}
if (casting != null && CastPlayback.connecting.value)
CastRow(Icons.Default.CastConnected, casting.name, stringResource(R.string.cast_connecting), current = true) {}
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastDiscovery.kt b/base/app/src/main/java/com/music/spotui/cast/CastDiscovery.kt
index 1b20b135..9a8f87db 100644
--- a/base/app/src/main/java/com/music/spotui/cast/CastDiscovery.kt
+++ b/base/app/src/main/java/com/music/spotui/cast/CastDiscovery.kt
@@ -20,6 +20,7 @@ data class CastDevice(val id: String, val name: String, val model: String, val h
*/
object CastDiscovery {
private const val TYPE = "_googlecast._tcp"
+ private const val RESOLVE_MS = 6000L
/** The devices found, newest last (main thread). */
val devices = mutableStateListOf<CastDevice>()
private val main = Handler(Looper.getMainLooper())
@@ -29,6 +30,10 @@ object CastDiscovery {
/** Before Android 14 NsdManager resolves one service at a time: the others wait here. */
private val waiting = ArrayDeque<NsdServiceInfo>()
private var resolving = false
+ /** Each resolve has a number: the answer of one given up on (or of a stopped search) is ignored. */
+ private var resolveGen = 0
+ /** Services whose resolve failed once: tried once more, then left. */
+ private val retried = HashSet<String>()
/** Starts looking (each [start] wants one [stop]). Main thread. */
fun start(context: Context) {
@@ -38,6 +43,8 @@ object CastDiscovery {
nsd = m
// Found anew each time: a device switched off since is not offered.
devices.clear()
+ // A resolve of the search before may never have answered: it must not hold this one.
+ waiting.clear(); retried.clear(); resolving = false; resolveGen++
val l = object : NsdManager.DiscoveryListener {
override fun onDiscoveryStarted(serviceType: String) = log("looking for Cast devices")
override fun onDiscoveryStopped(serviceType: String) = log("stopped looking for Cast devices")
@@ -62,6 +69,7 @@ object CastDiscovery {
listener?.let { l -> runCatching { nsd?.stopServiceDiscovery(l) } }
listener = null
waiting.clear()
+ resolving = false; resolveGen++
}
@Suppress("DEPRECATION")
@@ -70,11 +78,18 @@ object CastDiscovery {
val info = waiting.removeFirstOrNull() ?: return
val m = nsd ?: return
resolving = true
- val done = { main.post { resolving = false; next() }; Unit }
+ val gen = ++resolveGen
+ val done = { main.post { if (gen == resolveGen) { resolving = false; next() } }; Unit }
+ // NsdManager sometimes never answers a resolve (seen on several phones): the next one must not wait for ever.
+ main.postDelayed({
+ if (gen == resolveGen && resolving) { log("a Cast device took too long to resolve"); resolving = false; next() }
+ }, RESOLVE_MS)
runCatching {
m.resolveService(info, object : NsdManager.ResolveListener {
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {
log("a Cast device could not be resolved (error $errorCode)")
+ // Another resolve was still under way (error 3) or the device was busy: once more, after the others.
+ main.post { if (listener != null && retried.add(info.serviceName)) waiting.addLast(info) }
done()
}
override fun onServiceResolved(s: NsdServiceInfo) {
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastProtocol.kt b/base/app/src/main/java/com/music/spotui/cast/CastProtocol.kt
index d5e6bea2..34e7fea3 100644
--- a/base/app/src/main/java/com/music/spotui/cast/CastProtocol.kt
+++ b/base/app/src/main/java/com/music/spotui/cast/CastProtocol.kt
@@ -15,10 +15,15 @@ object CastProtocol {
const val RECEIVER = "receiver-0"
/** Google's Default Media Receiver. */
const val DEFAULT_MEDIA_RECEIVER = "CC1AD845"
+ /** The receiver app of Spotify, and its private channel (what the Spotify app speaks to a Cast device). */
+ const val SPOTIFY_RECEIVER = "CC32E753"
+ const val NS_SPOTIFY = "urn:x-cast:com.spotify.chromecast.secure.v1"
+ /** The model a group of Cast speakers announces. */
+ const val GROUP_MODEL = "Google Cast Group"
fun type(t: String) = JSONObject().put("type", t)
fun connect() = type("CONNECT").put("userAgent", "Myspoti").put("origin", JSONObject())
- fun launch(requestId: Int) = type("LAUNCH").put("appId", DEFAULT_MEDIA_RECEIVER).put("requestId", requestId)
+ fun launch(requestId: Int, appId: String = DEFAULT_MEDIA_RECEIVER) = type("LAUNCH").put("appId", appId).put("requestId", requestId)
fun stopApp(requestId: Int, sessionId: String) = type("STOP").put("sessionId", sessionId).put("requestId", requestId)
fun setVolume(requestId: Int, level: Double) =
type("SET_VOLUME").put("volume", JSONObject().put("level", level.coerceIn(0.0, 1.0))).put("requestId", requestId)
@@ -37,17 +42,17 @@ object CastProtocol {
.put("autoplay", autoplay).put("currentTime", startMs.coerceAtLeast(0) / 1000.0)
}
- /** The Default Media Receiver running on the device, from a RECEIVER_STATUS. */
+ /** The receiver app [appId] running on the device, from a RECEIVER_STATUS. */
data class App(val sessionId: String, val transportId: String)
data class Receiver(val app: App?, val volume: Double?, val muted: Boolean)
- fun receiver(status: JSONObject): Receiver {
+ fun receiver(status: JSONObject, appId: String = DEFAULT_MEDIA_RECEIVER): Receiver {
val s = status.optJSONObject("status") ?: JSONObject()
val apps = s.optJSONArray("applications")
var app: App? = null
if (apps != null) for (k in 0 until apps.length()) {
val a = apps.optJSONObject(k) ?: continue
- if (a.optString("appId") == DEFAULT_MEDIA_RECEIVER) app = App(a.optString("sessionId"), a.optString("transportId"))
+ if (a.optString("appId") == appId) app = App(a.optString("sessionId"), a.optString("transportId"))
}
val v = s.optJSONObject("volume")
return Receiver(app, v?.optDouble("level")?.takeIf { !it.isNaN() }, v?.optBoolean("muted") == true)
@@ -66,4 +71,38 @@ object CastProtocol {
s.optJSONObject("media")?.optString("contentId")?.ifBlank { null },
)
}
+
+ // ── Spotify's receiver: the device becomes a Spotify Connect device of the account ──
+
+ /** The id Spotify Connect gives a Cast device woken this way: the MD5 of its name, in hex. */
+ fun spotifyDeviceId(name: String): String =
+ java.security.MessageDigest.getInstance("MD5").digest(name.toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) }
+
+ fun spotifyGetInfo(requestId: Int, name: String, deviceId: String, group: Boolean) = type("getInfo").put("requestId", requestId)
+ .put("payload", JSONObject().put("remoteName", name).put("deviceID", deviceId).put("deviceAPI_isGroup", group))
+
+ fun spotifyAddUser(requestId: Int, blob: String) = type("addUser").put("requestId", requestId)
+ .put("payload", JSONObject().put("blob", blob).put("tokenType", "accesstoken"))
+
+ /** What the Spotify receiver answers on its channel. */
+ sealed class SpotifyReply {
+ /** The receiver's client id, to ask Spotify for the token it logs in with. */
+ data class Info(val clientId: String) : SpotifyReply()
+ object UserAdded : SpotifyReply()
+ data class Failed(val type: String) : SpotifyReply()
+ }
+
+ fun spotifyReply(message: JSONObject): SpotifyReply? = when (val t = message.optString("type")) {
+ "getInfoResponse" -> message.optJSONObject("payload")?.let { it.optString("clientID").ifBlank { it.optString("clientId") } }
+ ?.takeIf { it.isNotBlank() }?.let { SpotifyReply.Info(it) } ?: SpotifyReply.Failed(t)
+ "addUserResponse" -> SpotifyReply.UserAdded
+ "getInfoError", "addUserError", "launchError" -> SpotifyReply.Failed(t)
+ else -> null
+ }
+
+ /** The body asking Spotify (device-auth/v1/refresh) for the token the receiver logs in with. */
+ fun deviceAuthBody(clientId: String, deviceId: String): String = JSONObject().put("clientId", clientId).put("deviceId", deviceId).toString()
+
+ /** The token in Spotify's answer, or null. */
+ fun deviceAuthToken(body: String): String? = runCatching { JSONObject(body).optString("accessToken").ifBlank { null } }.getOrNull()
}
diff --git a/base/app/src/main/java/com/music/spotui/cast/CastSpotify.kt b/base/app/src/main/java/com/music/spotui/cast/CastSpotify.kt
new file mode 100644
index 00000000..b5ae591e
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/cast/CastSpotify.kt
@@ -0,0 +1,152 @@
+package com.music.spotui.cast
+
+import androidx.compose.runtime.mutableStateOf
+import app.myspoti.host.android.MyspotiRuntime
+import com.music.spotui.di.Graph
+import com.music.spotui.di.SongPlayer
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.withTimeoutOrNull
+import org.json.JSONObject
+import java.io.IOException
+
+/**
+ * Spotify's own songs on a Cast device, the way the Spotify app does it: the Spotify receiver
+ * (CC32E753) is launched on the device, told who plays (getInfo, then addUser with a token
+ * Spotify's device-auth issues for the account's web token), and the device then shows up in
+ * the account's Spotify Connect devices, where the song is transferred to it like to any other.
+ * Spotify plays it itself (DRM): nothing goes through the phone, and a free account is refused
+ * by Spotify at the transfer, as for any Connect device.
+ *
+ * The idea is that of the Home Assistant integration Spotcast (Apache-2.0); the code is Myspoti's.
+ */
+object CastSpotify {
+ /** The device being woken (the picker shows it connecting). Main thread. */
+ val waking = mutableStateOf<CastDevice?>(null)
+
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ /** The connection kept to the device Spotify plays on: its receiver goes when the last sender leaves. */
+ private class Held(val channel: CastChannel, val app: CastProtocol.App)
+ @Volatile private var held: Held? = null
+ private var requestId = 10
+
+ /** Wakes [d] and moves the Spotify song to it (main thread). */
+ fun start(d: CastDevice) {
+ if (waking.value != null) return
+ waking.value = d
+ scope.launch {
+ val device = runCatching { wake(d) }
+ withContext(Dispatchers.Main) {
+ waking.value = null
+ device.onSuccess { SongPlayer.transferTo(it) }.onFailure {
+ log("failed: ${it.javaClass.simpleName} ${it.message.orEmpty().take(80)}")
+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(app.myspoti.engine.R.string.cast_spotify_failed, d.name), android.widget.Toast.LENGTH_LONG).show()
+ }
+ }
+ }
+ }
+
+ private suspend fun wake(d: CastDevice): SongPlayer.ConnectDevice {
+ val id = CastProtocol.spotifyDeviceId(d.name)
+ // Already one of the account's devices (the Spotify app woke it, or an earlier wake of ours).
+ connectDevice(d, id)?.let { log("already a Spotify Connect device"); return it }
+ release()
+ val inbox = Channel<Pair<CastMessage, JSONObject>>(Channel.UNLIMITED)
+ val c = CastChannel(d.host, d.port, onMessage = { m, j -> inbox.trySend(m to j) }, onClosed = { inbox.close(it) })
+ withContext(Dispatchers.IO) { c.open(10_000) }
+ try {
+ log("connected, launching the Spotify receiver")
+ c.send(CastProtocol.RECEIVER, CastProtocol.NS_RECEIVER, CastProtocol.launch(++requestId, CastProtocol.SPOTIFY_RECEIVER))
+ val app = inbox.next(25_000) { m, j ->
+ if (m.namespace != CastProtocol.NS_RECEIVER) return@next null
+ when (j.optString("type")) {
+ "LAUNCH_ERROR" -> throw IOException("launch refused")
+ "RECEIVER_STATUS" -> CastProtocol.receiver(j, CastProtocol.SPOTIFY_RECEIVER).app?.takeIf { it.transportId.isNotBlank() }
+ else -> null
+ }
+ } ?: throw IOException("no Spotify receiver")
+ c.send(app.transportId, CastProtocol.NS_CONNECTION, CastProtocol.connect())
+ // The receiver may not listen yet: asked again until it answers.
+ var info: CastProtocol.SpotifyReply.Info? = null
+ for (k in 0 until 5) {
+ c.send(app.transportId, CastProtocol.NS_SPOTIFY, CastProtocol.spotifyGetInfo(++requestId, d.name, id, d.model == CastProtocol.GROUP_MODEL))
+ val r = inbox.next(3_000) { m, j -> if (m.namespace == CastProtocol.NS_SPOTIFY) CastProtocol.spotifyReply(j) else null }
+ if (r is CastProtocol.SpotifyReply.Failed) throw IOException(r.type)
+ info = r as? CastProtocol.SpotifyReply.Info
+ if (info != null) break
+ }
+ val clientId = info?.clientId ?: throw IOException("no answer to getInfo")
+ val answer = MyspotiRuntime.spotify.raw.request("POST", "https://spclient.wg.spotify.com/device-auth/v1/refresh",
+ CastProtocol.deviceAuthBody(clientId, id).toByteArray(), mapOf("content-type" to "text/plain;charset=UTF-8"))
+ // The token is never logged.
+ val blob = (if (answer.status == 200) CastProtocol.deviceAuthToken(answer.body) else null) ?: throw IOException("device-auth ${answer.status}")
+ c.send(app.transportId, CastProtocol.NS_SPOTIFY, CastProtocol.spotifyAddUser(++requestId, blob))
+ val added = inbox.next(20_000) { m, j -> if (m.namespace == CastProtocol.NS_SPOTIFY) CastProtocol.spotifyReply(j) else null }
+ if (added !is CastProtocol.SpotifyReply.UserAdded) throw IOException((added as? CastProtocol.SpotifyReply.Failed)?.type ?: "no answer to addUser")
+ log("logged in on the device, waiting for it among the Spotify devices")
+ held = Held(c, app)
+ for (k in 0 until 14) {
+ delay(1500)
+ connectDevice(d, id)?.let { found -> watch(found.id); return found }
+ }
+ release()
+ throw IOException("the device did not show up")
+ } catch (t: Throwable) {
+ if (held?.channel !== c) c.close()
+ throw t
+ }
+ }
+
+ /** The next message [pick] accepts within [ms] (null: none came in time). */
+ private suspend fun <T : Any> Channel<Pair<CastMessage, JSONObject>>.next(ms: Long, pick: (CastMessage, JSONObject) -> T?): T? =
+ withTimeoutOrNull(ms) {
+ var found: T? = null
+ while (found == null) { val (m, j) = receive(); found = pick(m, j) }
+ found
+ }
+
+ /** [d] among the account's Spotify Connect devices: by the id Spotify gives it, else by name among the Cast ones. */
+ private suspend fun connectDevice(d: CastDevice, id: String): SongPlayer.ConnectDevice? {
+ val api = MyspotiRuntime.spotify.devices
+ runCatching { api.refresh() }
+ val all = api.devices.value.filter { !it.local }
+ val x = all.firstOrNull { it.id == id } ?: all.firstOrNull { it.name == d.name && it.type.startsWith("CAST", ignoreCase = true) } ?: return null
+ return SongPlayer.ConnectDevice(x.id, x.name, x.type, false, x.active)
+ }
+
+ /**
+ * Keeps the connection while Spotify plays on the device; once it has not played there for 15 s
+ * (back on the phone, another device) or never started in 2 min, the receiver is stopped.
+ */
+ private fun watch(connectId: String) {
+ val mine = held ?: return
+ scope.launch {
+ val list = MyspotiRuntime.spotify.devices.devices
+ fun playing() = list.value.any { it.id == connectId && it.active }
+ withTimeoutOrNull(120_000) { list.first { _ -> playing() } }
+ while (held === mine) {
+ list.first { _ -> !playing() }
+ delay(15_000)
+ if (!playing()) break
+ }
+ if (held === mine) release()
+ }
+ }
+
+ private fun release() {
+ val h = held ?: return
+ held = null
+ runCatching { h.channel.send(CastProtocol.RECEIVER, CastProtocol.NS_RECEIVER, CastProtocol.stopApp(++requestId, h.app.sessionId)) }
+ h.channel.close()
+ log("released the Spotify receiver")
+ }
+
+ private fun log(line: String) = app.myspoti.host.android.Logbook.log("cast: spotify: $line")
+}
diff --git a/base/app/src/main/java/com/music/spotui/connect/LanDeviceRows.kt b/base/app/src/main/java/com/music/spotui/connect/LanDeviceRows.kt
new file mode 100644
index 00000000..4a8372a1
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/connect/LanDeviceRows.kt
@@ -0,0 +1,64 @@
+package com.music.spotui.connect
+
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Speaker
+import androidx.compose.material3.Icon
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import app.myspoti.engine.R
+import app.myspoti.host.android.MyspotiRuntime
+import com.music.spotui.ui.theme.AppMuted
+import com.music.spotui.ui.theme.AppText
+
+/**
+ * The Spotify Connect devices of the network that are not among the account's yet, in the device
+ * picker: a tap logs the device in ([LanLogin]) and moves the song to it. Devices that do not
+ * announce the ids the login needs are counted in one line, so the picker says why they are not listed.
+ */
+@Composable
+fun LanDeviceRows() {
+ val context = LocalContext.current
+ DisposableEffect(Unit) {
+ LanDiscovery.start(context)
+ onDispose { LanDiscovery.stop() }
+ }
+ val listed = MyspotiRuntime.spotify.devices.devices.collectAsState().value.filter { !it.local }
+ val ids = listed.map { it.id }.toSet()
+ val names = listed.map { it.name }.toSet()
+ val unlisted = LanDiscovery.devices.filter { !Zeroconf.inConnectList(it.info, ids, names) }
+ val busy = LanLogin.busy.value
+ unlisted.filter { it.info.loginable }.forEach { d ->
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.fillMaxWidth().clickable(enabled = busy == null) { LanLogin.start(d) }
+ .alpha(if (busy == null) 1f else 0.5f).padding(horizontal = 20.dp, vertical = 14.dp),
+ ) {
+ Icon(Icons.Default.Speaker, contentDescription = null, tint = AppText, modifier = Modifier.size(28.dp))
+ Spacer(Modifier.width(16.dp))
+ Column {
+ Text(d.info.name.ifBlank { d.service }, color = AppText, fontSize = 16.sp, fontWeight = FontWeight.Medium)
+ Text(stringResource(if (busy?.service == d.service) R.string.lan_logging_in else R.string.lan_device_detail), color = AppMuted, fontSize = 13.sp)
+ }
+ }
+ }
+ val others = unlisted.count { !it.info.loginable }
+ if (others > 0) Text(stringResource(R.string.lan_others, others), color = AppMuted, fontSize = 13.sp, modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
+}
diff --git a/base/app/src/main/java/com/music/spotui/connect/LanDiscovery.kt b/base/app/src/main/java/com/music/spotui/connect/LanDiscovery.kt
new file mode 100644
index 00000000..576be1d4
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/connect/LanDiscovery.kt
@@ -0,0 +1,134 @@
+package com.music.spotui.connect
+
+import android.content.Context
+import android.net.nsd.NsdManager
+import android.net.nsd.NsdServiceInfo
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import androidx.compose.runtime.mutableStateListOf
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import java.io.ByteArrayOutputStream
+import java.net.Inet4Address
+import java.net.InetAddress
+import java.net.InetSocketAddress
+import java.net.Socket
+
+/** A Spotify Connect device found on the network, with what it said on its ZeroConf port. */
+data class LanDevice(val service: String, val host: InetAddress, val port: Int, val cpath: String, val info: ZeroconfInfo)
+
+/**
+ * Finds the Spotify Connect devices of the local network (mDNS `_spotify-connect._tcp` through
+ * NsdManager, which needs no permission; from targetSdk 37 on, Android asks ACCESS_LOCAL_NETWORK
+ * for the connections to those addresses, implicitly granted below that), while the device picker is open. The Web Player only
+ * lists the devices already logged in to the account; the Spotify app also looks on the network
+ * and logs a speaker in when it is tapped. Each device found is asked `getInfo` once.
+ */
+object LanDiscovery {
+ /** The devices that answered, newest last (main thread). */
+ val devices = mutableStateListOf<LanDevice>()
+ private val main = Handler(Looper.getMainLooper())
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private var nsd: NsdManager? = null
+ private var listener: NsdManager.DiscoveryListener? = null
+ private var users = 0
+ /** Before Android 14 NsdManager resolves one service at a time: the others wait here. */
+ private val waiting = ArrayDeque<NsdServiceInfo>()
+ private var resolving = false
+
+ /** Starts looking (each [start] wants one [stop]). Main thread. */
+ fun start(context: Context) {
+ if (users++ > 0) return
+ val m = context.applicationContext.getSystemService(Context.NSD_SERVICE) as? NsdManager ?: run { users = 0; return }
+ nsd = m
+ // Found anew each time: a device switched off since is not offered.
+ devices.clear()
+ val l = object : NsdManager.DiscoveryListener {
+ override fun onDiscoveryStarted(serviceType: String) = log("looking for Spotify Connect devices")
+ override fun onDiscoveryStopped(serviceType: String) = Unit
+ override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) = main.post {
+ log("discovery failed to start (error $errorCode)")
+ if (listener === this) { listener = null; users = 0 }
+ }.let { }
+ override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit
+ override fun onServiceFound(info: NsdServiceInfo) = main.post { waiting.addLast(info); next() }.let { }
+ override fun onServiceLost(info: NsdServiceInfo) = main.post { devices.removeAll { it.service == info.serviceName } }.let { }
+ }
+ listener = l
+ runCatching { m.discoverServices(Zeroconf.SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, l) }
+ .onFailure { log("discovery not available: ${it.javaClass.simpleName}"); listener = null; users = 0 }
+ }
+
+ fun stop() {
+ if (users == 0 || --users > 0) return
+ listener?.let { l -> runCatching { nsd?.stopServiceDiscovery(l) } }
+ listener = null
+ waiting.clear()
+ }
+
+ @Suppress("DEPRECATION")
+ private fun next() {
+ if (resolving || listener == null) return
+ val info = waiting.removeFirstOrNull() ?: return
+ val m = nsd ?: return
+ resolving = true
+ val done = { main.post { resolving = false; next() }; Unit }
+ runCatching {
+ m.resolveService(info, object : NsdManager.ResolveListener {
+ override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = done()
+ override fun onServiceResolved(s: NsdServiceInfo) { found(s); done() }
+ })
+ }.onFailure { done() }
+ }
+
+ @Suppress("DEPRECATION")
+ private fun found(s: NsdServiceInfo) {
+ val all = if (Build.VERSION.SDK_INT >= 34) s.hostAddresses else listOfNotNull(s.host)
+ val host = all.filter { Zeroconf.isLan(it) }.let { a -> a.firstOrNull { it is Inet4Address } ?: a.firstOrNull() } ?: return
+ val cpath = s.attributes["CPath"]?.let { String(it, Charsets.UTF_8) }
+ scope.launch {
+ val info = runCatching { getInfo(host, s.port, cpath) }.getOrNull()
+ if (info == null) { log("a device on the network did not answer getInfo"); return@launch }
+ // Brand, model and the kind of login only: no name, id or account.
+ log("found ${info.brand.ifBlank { "?" }} ${info.model.ifBlank { "" }} (login ${info.tokenType.ifBlank { "?" }}, zeroconf ${info.version.ifBlank { "?" }}, " +
+ "${if (info.activeUser.isBlank()) "no user" else "a user"} logged in)")
+ val d = LanDevice(s.serviceName, host, s.port, Zeroconf.path(cpath), info)
+ main.post {
+ val at = devices.indexOfFirst { it.info.deviceId == info.deviceId }
+ if (at >= 0) devices[at] = d else devices += d
+ }
+ }
+ }
+
+ suspend fun getInfo(host: InetAddress, port: Int, cpath: String?): ZeroconfInfo? =
+ call(host, port, Zeroconf.infoRequest(host.hostAddress.orEmpty(), port, cpath))?.takeIf { it.first == 200 }?.let { Zeroconf.parseInfo(it.second) }
+
+ /**
+ * One plain HTTP exchange with a device. A socket, not OkHttp: the app does not allow cleartext
+ * HTTP (`usesCleartextTraffic=false`), which is right for everything but a speaker's own port.
+ */
+ fun call(host: InetAddress, port: Int, request: ByteArray, timeoutMs: Int = 5_000): Pair<Int, String>? =
+ runCatching {
+ Socket().use { s ->
+ s.connect(InetSocketAddress(host, port), timeoutMs)
+ s.soTimeout = timeoutMs
+ s.getOutputStream().apply { write(request); flush() }
+ val out = ByteArrayOutputStream()
+ val buf = ByteArray(4096)
+ // Read to the end of the answer: its length, or the device closing (a timeout with an answer in hand is not a failure).
+ while (out.size() < MAX_ANSWER && !Zeroconf.complete(out.toByteArray())) {
+ val n = try { s.getInputStream().read(buf) } catch (_: java.net.SocketTimeoutException) { -1 }
+ if (n < 0) break
+ out.write(buf, 0, n)
+ }
+ Zeroconf.parseResponse(out.toByteArray())
+ }
+ }.getOrNull()
+
+ private const val MAX_ANSWER = 64 * 1024
+
+ private fun log(line: String) = app.myspoti.host.android.Logbook.log("lan: $line")
+}
diff --git a/base/app/src/main/java/com/music/spotui/connect/LanLogin.kt b/base/app/src/main/java/com/music/spotui/connect/LanLogin.kt
new file mode 100644
index 00000000..e472e91d
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/connect/LanLogin.kt
@@ -0,0 +1,84 @@
+package com.music.spotui.connect
+
+import androidx.compose.runtime.mutableStateOf
+import app.myspoti.host.android.MyspotiRuntime
+import com.music.spotui.di.Graph
+import com.music.spotui.di.SongPlayer
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.jsonPrimitive
+import org.json.JSONObject
+import java.io.IOException
+
+/**
+ * Logs a Spotify Connect device of the network in to the account, as the Spotify app does when a
+ * speaker is tapped: Spotify's device-auth issues a token for the device's client id (from the web
+ * token), `addUser` hands it to the device, the device joins the account's Connect devices, and
+ * the song is transferred to it like to any other. Tried for every device that announces its ids
+ * ([ZeroconfInfo.loginable]), Sonos included; the answer of each is in the log.
+ */
+object LanLogin {
+ /** The device being logged in (the picker shows it connecting). Main thread. */
+ val busy = mutableStateOf<LanDevice?>(null)
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ /** Logs [d] in and moves the song to it (main thread). */
+ fun start(d: LanDevice) {
+ if (busy.value != null) return
+ busy.value = d
+ scope.launch {
+ val device = runCatching { login(d) }
+ withContext(Dispatchers.Main) {
+ busy.value = null
+ device.onSuccess { SongPlayer.transferTo(it) }.onFailure {
+ log("failed: ${it.javaClass.simpleName} ${it.message.orEmpty().take(80)}")
+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(app.myspoti.engine.R.string.lan_failed, d.info.name.ifBlank { d.service }), android.widget.Toast.LENGTH_LONG).show()
+ }
+ }
+ }
+ }
+
+ private suspend fun login(d: LanDevice): SongPlayer.ConnectDevice {
+ connectDevice(d)?.let { log("already a Spotify Connect device"); return it }
+ val spotify = MyspotiRuntime.spotify
+ val user = (spotify.raw.service("UserAPI", "getUser") as? JsonObject)?.get("username")?.jsonPrimitive?.contentOrNull.orEmpty()
+ val auth = spotify.raw.request("POST", "https://spclient.wg.spotify.com/device-auth/v1/refresh",
+ JSONObject().put("clientId", d.info.clientId).put("deviceId", d.info.deviceId).toString().toByteArray(),
+ mapOf("content-type" to "text/plain;charset=UTF-8"))
+ // The token is never logged.
+ val token = (if (auth.status == 200) runCatching { JSONObject(auth.body).optString("accessToken").ifBlank { null } }.getOrNull() else null)
+ ?: throw IOException("device-auth ${auth.status}")
+ val me = android.os.Build.MODEL.ifBlank { "Android" }
+ val request = Zeroconf.addUserRequest(d.host.hostAddress.orEmpty(), d.port, d.cpath, user, token, d.info, me, controllerId(me))
+ val answer = withContext(Dispatchers.IO) { LanDiscovery.call(d.host, d.port, request, 10_000) } ?: throw IOException("no answer to addUser")
+ log("addUser answered ${answer.first}, ${Zeroconf.answerSummary(answer.second)} (device says ${d.info.tokenType.ifBlank { "?" }})")
+ if (!Zeroconf.addUserAccepted(answer.first, answer.second)) throw IOException("addUser refused ${answer.first}")
+ // It joins the account's devices a moment after (it logs in to Spotify first).
+ for (k in 0 until 10) {
+ delay(1500)
+ connectDevice(d)?.let { log("joined the Spotify Connect devices"); return it }
+ }
+ throw IOException("the device did not show up")
+ }
+
+ /** [d] among the account's Connect devices: by the id it announced, else by its name. */
+ private suspend fun connectDevice(d: LanDevice): SongPlayer.ConnectDevice? {
+ val api = MyspotiRuntime.spotify.devices
+ runCatching { api.refresh() }
+ val all = api.devices.value.filter { !it.local }
+ val x = all.firstOrNull { it.id == d.info.deviceId } ?: all.firstOrNull { d.info.name.isNotBlank() && it.name == d.info.name } ?: return null
+ return SongPlayer.ConnectDevice(x.id, x.name, x.type, false, x.active)
+ }
+
+ /** A stable id for this phone as a controller: the MD5 of its name, as Spotify's own clients derive one. */
+ private fun controllerId(name: String): String =
+ java.security.MessageDigest.getInstance("MD5").digest(name.toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) }
+
+ private fun log(line: String) = app.myspoti.host.android.Logbook.log("lan: login: $line")
+}
diff --git a/base/app/src/main/java/com/music/spotui/connect/Zeroconf.kt b/base/app/src/main/java/com/music/spotui/connect/Zeroconf.kt
new file mode 100644
index 00000000..aa96ee71
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/connect/Zeroconf.kt
@@ -0,0 +1,151 @@
+package com.music.spotui.connect
+
+import org.json.JSONObject
+import java.net.InetAddress
+import java.net.URLEncoder
+
+/** What a Spotify Connect device says about itself on its ZeroConf port (`getInfo`). */
+data class ZeroconfInfo(
+ val deviceId: String,
+ val name: String,
+ val clientId: String,
+ /** How it wants to be logged in: "accesstoken" (a token Spotify issues), "default" (stored credentials), "authorization_code" (Sonos). */
+ val tokenType: String,
+ val version: String,
+ /** The account logged in on it now ("" when none). Never logged. */
+ val activeUser: String,
+ val brand: String,
+ val model: String,
+) {
+ /**
+ * Worth a login attempt: it announced the ids Spotify's device-auth needs. A device that says
+ * "accesstoken" takes the token as it is (Bose, Onkyo, Yamaha, Audio Pro reported); one that
+ * says "authorization_code" (Sonos, reported once, no source says how its blob is made) is tried
+ * the same way, and the answer is logged, since nothing here can tell beforehand.
+ */
+ val loginable: Boolean get() = deviceId.isNotBlank() && clientId.isNotBlank()
+}
+
+/**
+ * Spotify Connect's ZeroConf API, the part that logs a speaker in: a speaker advertises
+ * `_spotify-connect._tcp` (mDNS) with its port and a `CPath`, answers `getInfo` and takes
+ * `addUser`. Devices whose getInfo says `tokenType=accesstoken` (Bose, Onkyo, Yamaha, Audio Pro
+ * firmware reported) take a token in the blob as it is; the token is the one Spotify's
+ * device-auth issues for the device's client id (the same one the Cast receiver gets), so
+ * the account's web token never leaves the phone. Sonos announces `authorization_code`. Pure functions: the sockets are in [ZeroconfClient].
+ */
+object Zeroconf {
+ const val SERVICE_TYPE = "_spotify-connect._tcp"
+ const val ACCESS_TOKEN = "accesstoken"
+ /** The ZeroConf version announced to the device (the one reported working with accesstoken devices). */
+ const val VERSION = "2.7.1"
+
+ /** The `CPath` of the service's TXT record as a path ("" and "/" both mean the root). */
+ fun path(cpath: String?): String = "/" + (cpath ?: "").trim().trimStart('/')
+
+ fun infoRequest(host: String, port: Int, cpath: String?): ByteArray =
+ "GET ${path(cpath)}?action=getInfo&version=$VERSION HTTP/1.1\r\nHost: $host:$port\r\nAccept: */*\r\nConnection: close\r\n\r\n"
+ .toByteArray(Charsets.UTF_8)
+
+ /** The `addUser` POST: the action in the query, the fields in the body (form encoded), as Spotify's partners' firmware reads it. */
+ fun addUserRequest(host: String, port: Int, cpath: String?, userName: String, token: String, info: ZeroconfInfo, controllerName: String, controllerId: String): ByteArray {
+ val body = form(
+ "userName" to userName, "blob" to token, "clientKey" to info.clientId, "tokenType" to ACCESS_TOKEN,
+ "loginId" to userName, "deviceName" to controllerName, "deviceId" to controllerId, "version" to VERSION,
+ ).toByteArray(Charsets.UTF_8)
+ val head = "POST ${path(cpath)}?action=addUser HTTP/1.1\r\nHost: $host:$port\r\nContent-Type: application/x-www-form-urlencoded\r\n" +
+ "Content-Length: ${body.size}\r\nAccept: */*\r\nConnection: close\r\n\r\n"
+ return head.toByteArray(Charsets.UTF_8) + body
+ }
+
+ fun form(vararg fields: Pair<String, String>): String =
+ fields.joinToString("&") { (k, v) -> URLEncoder.encode(k, "UTF-8") + "=" + URLEncoder.encode(v, "UTF-8") }
+
+ /** The device's getInfo answer, or null when it is not one (an error status, not JSON, no device id). */
+ fun parseInfo(body: String): ZeroconfInfo? {
+ val j = runCatching { JSONObject(body) }.getOrNull() ?: return null
+ if (j.has("status") && j.optInt("status") != 101) return null
+ val id = j.optString("deviceID").ifBlank { return null }
+ return ZeroconfInfo(
+ deviceId = id,
+ name = j.optString("remoteName"),
+ clientId = j.optString("clientID"),
+ tokenType = j.optString("tokenType"),
+ version = j.optString("version"),
+ activeUser = j.optString("activeUser"),
+ brand = j.optString("brandDisplayName"),
+ model = j.optString("modelDisplayName"),
+ )
+ }
+
+ /** The status and its name from an addUser answer, for the log (no token is ever in one). */
+ fun answerSummary(body: String): String =
+ runCatching { JSONObject(body) }.getOrNull()?.let { "status ${it.optInt("status", -1)} ${it.optString("statusString").take(40)}" } ?: "not JSON"
+
+ /** The answer to addUser: accepted (101), already in that state (404 with no body, as Bose does), or refused. */
+ fun addUserAccepted(status: Int, body: String): Boolean {
+ if (status == 404 && body.isBlank()) return true
+ val j = runCatching { JSONObject(body) }.getOrNull() ?: return false
+ return j.optInt("status", -1) == 101
+ }
+
+ /** The status and the body of an HTTP/1.1 answer read to its end (chunked included), or null when it is not one. */
+ fun parseResponse(raw: ByteArray): Pair<Int, String>? {
+ val end = indexOf(raw, "\r\n\r\n".toByteArray(), 0)
+ if (end < 0) return null
+ val head = String(raw, 0, end, Charsets.ISO_8859_1).split("\r\n")
+ val status = head.firstOrNull()?.split(' ')?.getOrNull(1)?.toIntOrNull() ?: return null
+ val chunked = head.any { it.startsWith("Transfer-Encoding:", true) && it.contains("chunked", true) }
+ val bytes = if (chunked) dechunk(raw, end + 4) else raw.copyOfRange(end + 4, raw.size)
+ return status to String(bytes, Charsets.UTF_8)
+ }
+
+ /** [raw] holds a whole answer already (the device may keep the connection open after it, whatever `Connection: close` says). */
+ fun complete(raw: ByteArray): Boolean {
+ val end = indexOf(raw, "\r\n\r\n".toByteArray(), 0)
+ if (end < 0) return false
+ val head = String(raw, 0, end, Charsets.ISO_8859_1).split("\r\n")
+ if (head.any { it.startsWith("Transfer-Encoding:", true) && it.contains("chunked", true) })
+ return indexOf(raw, "\r\n0\r\n".toByteArray(), end) >= 0 || (raw.size >= end + 7 && raw[end + 4] == '0'.code.toByte())
+ val length = head.firstNotNullOfOrNull { l -> l.takeIf { it.startsWith("Content-Length:", true) }?.substringAfter(':')?.trim()?.toIntOrNull() } ?: return false
+ return raw.size - (end + 4) >= length
+ }
+
+ private fun dechunk(raw: ByteArray, from: Int): ByteArray {
+ val out = java.io.ByteArrayOutputStream()
+ var at = from
+ while (at < raw.size) {
+ val eol = indexOf(raw, "\r\n".toByteArray(), at)
+ if (eol < 0) break
+ val size = String(raw, at, eol - at, Charsets.ISO_8859_1).substringBefore(';').trim().toIntOrNull(16) ?: break
+ if (size == 0) break
+ val start = eol + 2
+ out.write(raw, start, minOf(size, raw.size - start))
+ at = start + size + 2
+ }
+ return out.toByteArray()
+ }
+
+ private fun indexOf(a: ByteArray, pattern: ByteArray, from: Int): Int {
+ outer@ for (i in from..a.size - pattern.size) {
+ for (k in pattern.indices) if (a[i + k] != pattern[k]) continue@outer
+ return i
+ }
+ return -1
+ }
+
+ /**
+ * An address on the local network (private IPv4, link-local, IPv6 unique local): the only ones
+ * a token is ever sent to, so a service advertising a public address is not offered.
+ */
+ fun isLan(address: InetAddress): Boolean {
+ if (address.isLoopbackAddress) return false
+ if (address.isSiteLocalAddress || address.isLinkLocalAddress) return true
+ val b = address.address
+ return b.size == 16 && (b[0].toInt() and 0xFE) == 0xFC
+ }
+
+ /** [info] is one of the account's Connect devices already: by the id Spotify gives it, else by its name. */
+ fun inConnectList(info: ZeroconfInfo, ids: Set<String>, names: Set<String>): Boolean =
+ info.deviceId in ids || (info.name.isNotBlank() && info.name in names)
+}
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 754371cc..c2457ddb 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
@@ -838,9 +838,9 @@ object SongPlayer {
// ── Commands ──
/** Runs an API call off the caller, logging failures instead of crashing the UI. */
- private fun command(block: suspend () -> Unit) {
+ private fun command(onFailure: (Throwable) -> Unit = {}, block: suspend () -> Unit) {
scope.launch {
- runCatching { block() }.onFailure { Log.w(TAG, "command failed: ${it.message}") }
+ runCatching { block() }.onFailure { Log.w(TAG, "command failed: ${it.message}"); onFailure(it) }
}
}
@@ -1617,6 +1617,7 @@ object SongPlayer {
private const val PULL_BACK_SETTLE_MS = 600L
private const val PULL_BACK_WAIT_MS = 6_000L
private const val DEVICES_WAIT_MS = 2_000L
+ private const val DISCOVERY_WAIT_MS = 800L
/**
* How long the device list read by [takeBackPlayback] is trusted. Long enough that a burst of
@@ -2098,17 +2099,23 @@ object SongPlayer {
runCatching { api.devices.refresh() }
val active = api.devices.devices.value.firstOrNull { it.active }
_activeDevice.value = active?.takeIf { !it.local }?.let { ConnectDevice(it.id, it.name, it.type, false, true) }
- active?.volume?.let { if (SystemClock.elapsedRealtime() > volumeHoldUntil) _remoteVolume.intValue = (it * 100).toInt().coerceIn(0, 100) }
+ // A negative volume is a device with a fixed one (Web Player: disable_volume): not 0 %.
+ active?.volume?.takeIf { it >= 0 }?.let { if (SystemClock.elapsedRealtime() > volumeHoldUntil) _remoteVolume.intValue = (it * 100).toInt().coerceIn(0, 100) }
PlaybackService.setPlaybackDevice(_activeDevice.value != null, remoteVolume)
}
}
/** Devices of the account, this phone first. */
suspend fun devices(): List<ConnectDevice> {
+ // What the Web Player's own picker does when it opens: it asks Spotify to look for devices
+ // again. The answer is not known (no device test yet); bounded, and a page without it is fine.
+ kotlinx.coroutines.withTimeoutOrNull(DISCOVERY_WAIT_MS) { runCatching { MyspotiRuntime.spotify.raw.service("ConnectDiscoveryAPI", "startActiveDiscovery") } }
runCatching { api.devices.refresh() }
val list = api.devices.devices.value.map { ConnectDevice(it.id, it.name, it.type, it.local, it.active) }
.sortedWith(compareByDescending<ConnectDevice> { it.isSelf }.thenBy { it.name })
_activeDevice.value = list.firstOrNull { it.isActive && !it.isSelf }
+ // Kinds only (no names or ids): a report that says "no speaker" shows whether Spotify listed one.
+ app.myspoti.host.android.Logbook.log("connect: picker lists ${list.size} devices (${list.joinToString { it.type.lowercase() }})")
return list
}
@@ -2193,14 +2200,28 @@ object SongPlayer {
Log.i(TAG, "local song to ${device.name}: $track in $context at $at ms")
ConnectMirror.leaving(device.name)
LocalPlayer.stop()
- command {
+ command(onFailure = { transferFailed(device) }) {
api.devices.transfer(device.id)
api.player.play(context, trackUri = track.takeIf { it != context }, positionMs = at)
if (!wasPlaying) api.player.pause()
}
return
}
- command { if (device.isSelf) api.devices.pullHere() else api.devices.transfer(device.id) }
+ command(onFailure = { transferFailed(device) }) { if (device.isSelf) api.devices.pullHere() else api.devices.transfer(device.id) }
+ }
+
+ /**
+ * A transfer Spotify did not take (no such device any more, a speaker that went to sleep, a
+ * refusal): the picker had already shown the device as playing, and the app went on driving a
+ * device that plays nothing. Back on this phone, and the person is told.
+ */
+ private fun transferFailed(device: ConnectDevice) {
+ if (device.isSelf || chosenRemote != device.id) return
+ chosenRemote = null
+ _activeDevice.value = null
+ main.post {
+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(app.myspoti.engine.R.string.cast_failed, device.name), android.widget.Toast.LENGTH_LONG).show()
+ }
}
/** Volume (0..100) of the device that plays, as last reported. State: the player's volume bar follows it. */
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
index 2f3b29f4..a3625a21 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt
@@ -267,9 +267,11 @@ fun DevicesSheet(onDismiss: () -> Unit) {
DeviceRow(deviceIcon(d.type), d.name, null) { SongPlayer.transferTo(d); onDismiss() }
}
if (list.none { !it.isSelf } && !headphones && remote == null && com.music.spotui.cast.CastDiscovery.devices.isEmpty() &&
- com.music.spotui.cast.CastPlayback.device.value == null)
+ com.music.spotui.connect.LanDiscovery.devices.isEmpty() && com.music.spotui.cast.CastPlayback.device.value == null)
Text(stringResource(R.string.no_devices), color = AppText.copy(alpha = 0.7f), modifier = Modifier.padding(20.dp))
}
+ // Spotify Connect devices of the network that are not logged in to the account yet.
+ com.music.spotui.connect.LanDeviceRows()
// Cast devices, for Myspoti's own songs (Spotify's go through Spotify Connect above).
com.music.spotui.cast.CastDeviceRows(onDismiss)
JamSection(onDismiss)
diff --git a/base/app/src/main/res/values-de/myspoti_strings.xml b/base/app/src/main/res/values-de/myspoti_strings.xml
index e9922fda..a30b2a8c 100644
--- a/base/app/src/main/res/values-de/myspoti_strings.xml
+++ b/base/app/src/main/res/values-de/myspoti_strings.xml
@@ -571,7 +571,8 @@
<string name="cast_device_detail">Google Cast</string>
<string name="cast_failed">Wiedergabe auf %1$s nicht möglich</string>
<string name="cast_lost">Verbindung zu %1$s verloren: zurück auf diesem Handy</string>
- <string name="cast_spotify_via_connect">Spotify-Songs laufen auf Cast-Geräten über Spotify Connect</string>
+ <string name="cast_spotify_detail">Google Cast · spielt Spotify darauf ab</string>
+ <string name="cast_spotify_failed">Spotify konnte auf %1$s nicht gestartet werden</string>
<string name="downloads_need_source_detail">Songs werden von Erweiterungen heruntergeladen. Noch ist keine installiert: Öffne den Erweiterungs-Store und installiere Mornye, um herunterzuladen.</string>
<string name="downloads_need_source_title">Downloads brauchen eine Erweiterung</string>
<string name="episode_new">Neu</string>
@@ -599,4 +600,8 @@
<string name="hidden_songs_empty">Noch keine ausgeblendeten Songs. Wähle „Kein Interesse“ im Menü eines Songs.</string>
<string name="login_failed_title">Anmeldung nicht abgeschlossen</string>
<string name="login_failed_detail">Die Seite von Spotify wurde nicht geladen oder nicht gestartet. Prüfe deine Verbindung und versuche es erneut. Wenn es weiter scheitert, probiere ein anderes Netzwerk.</string>
+ <string name="lan_device_detail">In diesem Netzwerk</string>
+ <string name="lan_logging_in">Anmeldung…</string>
+ <string name="lan_failed">%1$s hat die Anmeldung nicht akzeptiert. Öffne es einmal mit der Spotify-App und versuche es erneut.</string>
+ <string name="lan_others">%1$d weitere Geräte in diesem Netzwerk müssen zuerst über die Spotify-App angemeldet werden</string>
</resources>
diff --git a/base/app/src/main/res/values-el/myspoti_strings.xml b/base/app/src/main/res/values-el/myspoti_strings.xml
index cbee9060..b3b8656e 100644
--- a/base/app/src/main/res/values-el/myspoti_strings.xml
+++ b/base/app/src/main/res/values-el/myspoti_strings.xml
@@ -571,7 +571,8 @@
<string name="cast_device_detail">Google Cast</string>
<string name="cast_failed">Δεν ήταν δυνατή η αναπαραγωγή στο %1$s</string>
<string name="cast_lost">Χάθηκε η σύνδεση με %1$s: ξανά σε αυτό το τηλέφωνο</string>
- <string name="cast_spotify_via_connect">Τα τραγούδια του Spotify παίζουν σε συσκευές Cast μέσω Spotify Connect</string>
+ <string name="cast_spotify_detail">Google Cast · παίζει Spotify σε αυτή τη συσκευή</string>
+ <string name="cast_spotify_failed">Δεν ήταν δυνατή η εκκίνηση του Spotify σε %1$s</string>
<string name="downloads_need_source_detail">Τα τραγούδια κατεβαίνουν από επεκτάσεις. Δεν έχει εγκατασταθεί καμία ακόμα: ανοίξτε το κατάστημα επεκτάσεων και εγκαταστήστε το Mornye για λήψεις.</string>
<string name="downloads_need_source_title">Οι λήψεις χρειάζονται επέκταση</string>
<string name="episode_new">Νέο</string>
@@ -599,4 +600,8 @@
<string name="hidden_songs_empty">Δεν υπάρχουν κρυφά τραγούδια. Επιλέξτε «Δεν με ενδιαφέρει» στο μενού ενός τραγουδιού.</string>
<string name="login_failed_title">Η σύνδεση δεν ολοκληρώθηκε</string>
<string name="login_failed_detail">Η σελίδα του Spotify δεν φόρτωσε ή δεν ξεκίνησε. Ελέγξτε τη σύνδεσή σας και δοκιμάστε ξανά. Αν εξακολουθεί να αποτυγχάνει, δοκιμάστε άλλο δίκτυο.</string>
+ <string name="lan_device_detail">Σε αυτό το δίκτυο</string>
+ <string name="lan_logging_in">Σύνδεση…</string>
+ <string name="lan_failed">Η συσκευή %1$s δεν δέχτηκε τη σύνδεση. Ανοίξτε την μία φορά με την εφαρμογή Spotify και δοκιμάστε ξανά.</string>
+ <string name="lan_others">%1$d ακόμη συσκευές σε αυτό το δίκτυο πρέπει πρώτα να συνδεθούν μέσω της εφαρμογής Spotify</string>
</resources>
diff --git a/base/app/src/main/res/values-es/myspoti_strings.xml b/base/app/src/main/res/values-es/myspoti_strings.xml
index 02bc4a47..e372d9c6 100644
--- a/base/app/src/main/res/values-es/myspoti_strings.xml
+++ b/base/app/src/main/res/values-es/myspoti_strings.xml
@@ -571,7 +571,8 @@
<string name="cast_device_detail">Google Cast</string>
<string name="cast_failed">No se pudo reproducir en %1$s</string>
<string name="cast_lost">Se perdió %1$s: de vuelta en este teléfono</string>
- <string name="cast_spotify_via_connect">Las canciones de Spotify suenan en los dispositivos Cast a través de Spotify Connect</string>
+ <string name="cast_spotify_detail">Google Cast · reproduce Spotify en él</string>
+ <string name="cast_spotify_failed">No se pudo iniciar Spotify en %1$s</string>
<string name="downloads_need_source_detail">Las canciones se descargan con extensiones. Aún no hay ninguna instalada: abre la tienda de extensiones e instala Mornye para descargar.</string>
<string name="downloads_need_source_title">Las descargas necesitan una extensión</string>
<string name="episode_new">Nuevo</string>
@@ -599,4 +600,8 @@
<string name="hidden_songs_empty">Aún no hay canciones ocultas. Elige No me interesa en el menú de una canción.</string>
<string name="login_failed_title">No se pudo completar el inicio de sesión</string>
<string name="login_failed_detail">La página de Spotify no se cargó o no arrancó. Comprueba tu conexión e inténtalo de nuevo. Si sigue fallando, prueba con otra red.</string>
+ <string name="lan_device_detail">En esta red</string>
+ <string name="lan_logging_in">Iniciando sesión…</string>
+ <string name="lan_failed">%1$s no aceptó el inicio de sesión. Ábrelo una vez con la app de Spotify y vuelve a intentarlo.</string>
+ <string name="lan_others">%1$d dispositivos más de esta red necesitan que la app de Spotify los conecte primero</string>
</resources>
diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xml
index 9e7d30bd..b149e0ac 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -576,7 +576,8 @@
<string name="cast_device_detail">Google Cast</string>
<string name="cast_failed">Impossible de lire sur %1$s</string>
<string name="cast_lost">%1$s perdu : retour sur ce téléphone</string>
- <string name="cast_spotify_via_connect">Les titres Spotify passent sur les appareils Cast par Spotify Connect</string>
+ <string name="cast_spotify_detail">Google Cast · lit Spotify dessus</string>
+ <string name="cast_spotify_failed">Impossible de lancer Spotify sur %1$s</string>
<string name="downloads_need_source_detail">Les titres sont téléchargés par des extensions. Aucune n\'est installée : ouvrez le store des extensions et installez Mornye pour télécharger.</string>
<string name="downloads_need_source_title">Les téléchargements demandent une extension</string>
<string name="episode_new">Nouveau</string>
@@ -604,4 +605,8 @@
<string name="hidden_songs_empty">Aucun titre masqué. Choisissez « Pas intéressé » dans le menu d\'un titre.</string>
<string name="login_failed_title">La connexion n\'a pas abouti</string>
<string name="login_failed_detail">La page de Spotify ne s\'est pas chargée ou n\'a pas démarré. Vérifiez votre connexion et réessayez. Si cela échoue encore, essayez un autre réseau.</string>
+ <string name="lan_device_detail">Sur ce réseau</string>
+ <string name="lan_logging_in">Connexion…</string>
+ <string name="lan_failed">%1$s n’a pas accepté la connexion. Ouvrez-le une fois avec l’application Spotify, puis réessayez.</string>
+ <string name="lan_others">%1$d autres appareils de ce réseau doivent d’abord être connectés par l’application Spotify</string>
</resources>
diff --git a/base/app/src/main/res/values-it/myspoti_strings.xml b/base/app/src/main/res/values-it/myspoti_strings.xml
index 830d1ee2..d287c4d9 100644
--- a/base/app/src/main/res/values-it/myspoti_strings.xml
+++ b/base/app/src/main/res/values-it/myspoti_strings.xml
@@ -571,7 +571,8 @@
<string name="cast_device_detail">Google Cast</string>
<string name="cast_failed">Impossibile riprodurre su %1$s</string>
<string name="cast_lost">%1$s perso: di nuovo su questo telefono</string>
- <string name="cast_spotify_via_connect">I brani Spotify vengono riprodotti sui dispositivi Cast tramite Spotify Connect</string>
+ <string name="cast_spotify_detail">Google Cast · riproduce Spotify sul dispositivo</string>
+ <string name="cast_spotify_failed">Impossibile avviare Spotify su %1$s</string>
<string name="downloads_need_source_detail">I brani vengono scaricati dalle estensioni. Non ne è ancora installata nessuna: apri lo store delle estensioni e installa Mornye per scaricare.</string>
<string name="downloads_need_source_title">I download richiedono un\'estensione</string>
<string name="episode_new">Nuovo</string>
@@ -599,4 +600,8 @@
<string name="hidden_songs_empty">Nessun brano nascosto. Scegli Non mi interessa nel menu di un brano.</string>
<string name="login_failed_title">Accesso non completato</string>
<string name="login_failed_detail">La pagina di Spotify non si è caricata o non è partita. Controlla la connessione e riprova. Se continua a fallire, prova un\'altra rete.</string>
+ <string name="lan_device_detail">Su questa rete</string>
+ <string name="lan_logging_in">Accesso in corso…</string>
+ <string name="lan_failed">%1$s non ha accettato l\'accesso. Aprilo una volta con l\'app Spotify, poi riprova.</string>
+ <string name="lan_others">Altri %1$d dispositivi su questa rete richiedono prima l\'accesso tramite l\'app Spotify</string>
</resources>
diff --git a/base/app/src/main/res/values-pl/myspoti_strings.xml b/base/app/src/main/res/values-pl/myspoti_strings.xml
index a061e7de..7a88cfb9 100644
--- a/base/app/src/main/res/values-pl/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pl/myspoti_strings.xml
@@ -582,7 +582,8 @@
<string name="cast_device_detail">Google Cast</string>
<string name="cast_failed">Nie udało się odtworzyć na %1$s</string>
<string name="cast_lost">Utracono %1$s: z powrotem na tym telefonie</string>
- <string name="cast_spotify_via_connect">Utwory Spotify grają na urządzeniach Cast przez Spotify Connect</string>
+ <string name="cast_spotify_detail">Google Cast · odtwarza Spotify na urządzeniu</string>
+ <string name="cast_spotify_failed">Nie udało się uruchomić Spotify na %1$s</string>
<string name="downloads_need_source_detail">Utwory pobierają rozszerzenia. Żadne nie jest jeszcze zainstalowane: otwórz sklep z rozszerzeniami i zainstaluj Mornye, aby pobierać.</string>
<string name="downloads_need_source_title">Pobieranie wymaga rozszerzenia</string>
<string name="episode_new">Nowy</string>
@@ -614,4 +615,8 @@
<string name="hidden_songs_empty">Brak ukrytych utworów. Wybierz Nie interesuje mnie w menu utworu.</string>
<string name="login_failed_title">Logowanie nie zostało dokończone</string>
<string name="login_failed_detail">Strona Spotify nie załadowała się lub nie wystartowała. Sprawdź połączenie i spróbuj ponownie. Jeśli nadal się nie udaje, spróbuj innej sieci.</string>
+ <string name="lan_device_detail">W tej sieci</string>
+ <string name="lan_logging_in">Logowanie…</string>
+ <string name="lan_failed">%1$s nie przyjął logowania. Otwórz go raz w aplikacji Spotify i spróbuj ponownie.</string>
+ <string name="lan_others">Jeszcze %1$d urządzeń w tej sieci musi najpierw zostać zalogowanych przez aplikację Spotify</string>
</resources>
diff --git a/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml b/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
index 251aaa6e..afdcbd9d 100644
--- a/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
@@ -571,7 +571,8 @@
<string name="cast_device_detail">Google Cast</string>
<string name="cast_failed">Não foi possível tocar em %1$s</string>
<string name="cast_lost">%1$s perdido: de volta neste celular</string>
- <string name="cast_spotify_via_connect">As músicas do Spotify tocam em dispositivos Cast pelo Spotify Connect</string>
+ <string name="cast_spotify_detail">Google Cast · reproduz o Spotify no dispositivo</string>
+ <string name="cast_spotify_failed">Não foi possível iniciar o Spotify em %1$s</string>
<string name="downloads_need_source_detail">As músicas são baixadas por extensões. Nenhuma está instalada ainda: abra a loja de extensões e instale o Mornye para baixar.</string>
<string name="downloads_need_source_title">Os downloads precisam de uma extensão</string>
<string name="episode_new">Novo</string>
@@ -599,4 +600,8 @@
<string name="hidden_songs_empty">Nenhuma música oculta. Escolha Sem interesse no menu de uma música.</string>
<string name="login_failed_title">O início de sessão não foi concluído</string>
<string name="login_failed_detail">A página do Spotify não carregou ou não arrancou. Verifique a ligação e tente novamente. Se continuar a falhar, experimente outra rede.</string>
+ <string name="lan_device_detail">Nesta rede</string>
+ <string name="lan_logging_in">A iniciar sessão…</string>
+ <string name="lan_failed">%1$s não aceitou o início de sessão. Abra-o uma vez com a aplicação Spotify e tente novamente.</string>
+ <string name="lan_others">Mais %1$d dispositivos nesta rede precisam primeiro de iniciar sessão através da aplicação Spotify</string>
</resources>
diff --git a/base/app/src/main/res/values-pt/myspoti_strings.xml b/base/app/src/main/res/values-pt/myspoti_strings.xml
index 4f8a7107..2788f7b9 100644
--- a/base/app/src/main/res/values-pt/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml
@@ -571,7 +571,8 @@
<string name="cast_device_detail">Google Cast</string>
<string name="cast_failed">Não foi possível tocar em %1$s</string>
<string name="cast_lost">%1$s perdido: de volta neste celular</string>
- <string name="cast_spotify_via_connect">As músicas do Spotify tocam em dispositivos Cast pelo Spotify Connect</string>
+ <string name="cast_spotify_detail">Google Cast · toca o Spotify no dispositivo</string>
+ <string name="cast_spotify_failed">Não foi possível iniciar o Spotify em %1$s</string>
<string name="downloads_need_source_detail">As músicas são baixadas por extensões. Nenhuma está instalada ainda: abra a loja de extensões e instale o Mornye para baixar.</string>
<string name="downloads_need_source_title">Os downloads precisam de uma extensão</string>
<string name="episode_new">Novo</string>
@@ -599,4 +600,8 @@
<string name="hidden_songs_empty">Nenhuma música oculta. Escolha Sem interesse no menu de uma música.</string>
<string name="login_failed_title">O login não foi concluído</string>
<string name="login_failed_detail">A página do Spotify não carregou ou não iniciou. Verifique sua conexão e tente novamente. Se continuar falhando, tente outra rede.</string>
+ <string name="lan_device_detail">Nesta rede</string>
+ <string name="lan_logging_in">Conectando…</string>
+ <string name="lan_failed">%1$s não aceitou o login. Abra-o uma vez com o app do Spotify e tente de novo.</string>
+ <string name="lan_others">Mais %1$d dispositivos nesta rede precisam primeiro do login pelo app do Spotify</string>
</resources>
diff --git a/base/app/src/main/res/values-ru/myspoti_strings.xml b/base/app/src/main/res/values-ru/myspoti_strings.xml
index 63de28d9..cfcd20f6 100644
--- a/base/app/src/main/res/values-ru/myspoti_strings.xml
+++ b/base/app/src/main/res/values-ru/myspoti_strings.xml
@@ -582,7 +582,8 @@
<string name="cast_device_detail">Google Cast</string>
<string name="cast_failed">Не удалось воспроизвести на %1$s</string>
<string name="cast_lost">Связь с %1$s потеряна: снова на этом телефоне</string>
- <string name="cast_spotify_via_connect">Треки Spotify играют на устройствах Cast через Spotify Connect</string>
+ <string name="cast_spotify_detail">Google Cast · воспроизводит Spotify на устройстве</string>
+ <string name="cast_spotify_failed">Не удалось запустить Spotify на %1$s</string>
<string name="downloads_need_source_detail">Треки скачивают расширения. Пока ни одно не установлено: откройте магазин расширений и установите Mornye, чтобы скачивать.</string>
<string name="downloads_need_source_title">Для загрузок нужно расширение</string>
<string name="episode_new">Новый</string>
@@ -614,4 +615,8 @@
<string name="hidden_songs_empty">Скрытых треков пока нет. Выберите «Не интересует» в меню трека.</string>
<string name="login_failed_title">Не удалось войти</string>
<string name="login_failed_detail">Страница Spotify не загрузилась или не запустилась. Проверьте подключение и повторите попытку. Если не получается, попробуйте другую сеть.</string>
+ <string name="lan_device_detail">В этой сети</string>
+ <string name="lan_logging_in">Вход…</string>
+ <string name="lan_failed">%1$s не принял вход. Откройте его один раз в приложении Spotify и повторите попытку.</string>
+ <string name="lan_others">Ещё %1$d устройств в этой сети сначала нужно подключить через приложение Spotify</string>
</resources>
diff --git a/base/app/src/main/res/values-zh/myspoti_strings.xml b/base/app/src/main/res/values-zh/myspoti_strings.xml
index 12392c3f..681b3ef2 100644
--- a/base/app/src/main/res/values-zh/myspoti_strings.xml
+++ b/base/app/src/main/res/values-zh/myspoti_strings.xml
@@ -573,7 +573,8 @@
<string name="cast_device_detail">Google Cast</string>
<string name="cast_failed">无法在 %1$s 上播放</string>
<string name="cast_lost">与 %1$s 的连接已断开:回到本手机播放</string>
- <string name="cast_spotify_via_connect">Spotify 歌曲通过 Spotify Connect 在 Cast 设备上播放</string>
+ <string name="cast_spotify_detail">Google Cast · 在该设备上播放 Spotify</string>
+ <string name="cast_spotify_failed">无法在 %1$s 上启动 Spotify</string>
<string name="downloads_need_source_detail">歌曲由扩展下载。目前尚未安装任何扩展:打开扩展商店并安装 Mornye 即可下载。</string>
<string name="downloads_need_source_title">下载需要扩展</string>
<string name="episode_new">新</string>
@@ -599,4 +600,8 @@
<string name="hidden_songs_empty">还没有已隐藏的歌曲。请在歌曲菜单中选择“不感兴趣”。</string>
<string name="login_failed_title">登录未完成</string>
<string name="login_failed_detail">Spotify 页面未能加载或启动。请检查网络连接后重试;如果仍然失败,请换一个网络试试。</string>
+ <string name="lan_device_detail">在此网络</string>
+ <string name="lan_logging_in">正在登录…</string>
+ <string name="lan_failed">%1$s 未接受登录。请先用 Spotify 应用打开它一次,然后重试。</string>
+ <string name="lan_others">此网络中还有 %1$d 台设备需要先通过 Spotify 应用登录</string>
</resources>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index cb8c8d97..5cd073c6 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -593,7 +593,8 @@
<string name="aa_library">Library</string>
<string name="aa_downloads">Downloads</string>
<string name="cast_device_detail">Google Cast</string>
- <string name="cast_spotify_via_connect">Spotify songs play on Cast devices through Spotify Connect</string>
+ <string name="cast_spotify_detail">Google Cast · plays Spotify on it</string>
+ <string name="cast_spotify_failed">Could not start Spotify on %1$s</string>
<string name="cast_connecting">Connecting…</string>
<string name="cast_failed">Could not play on %1$s</string>
<string name="cast_lost">Lost %1$s: back on this phone</string>
@@ -605,4 +606,8 @@
<string name="hidden_songs_empty">No hidden songs yet. Choose Not interested in a song\'s menu.</string>
<string name="login_failed_title">Sign-in did not finish</string>
<string name="login_failed_detail">Spotify\'s page did not load or did not start. Check your connection and try again. If it keeps failing, try another network.</string>
+ <string name="lan_device_detail">On this network</string>
+ <string name="lan_logging_in">Logging in…</string>
+ <string name="lan_failed">%1$s did not accept the login. Open it once with the Spotify app, then try again.</string>
+ <string name="lan_others">%1$d more on this network need the Spotify app to log them in first</string>
</resources>
diff --git a/base/app/src/test/java/com/music/spotui/cast/CastSpotifyTest.kt b/base/app/src/test/java/com/music/spotui/cast/CastSpotifyTest.kt
new file mode 100644
index 00000000..88be2c1f
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/cast/CastSpotifyTest.kt
@@ -0,0 +1,59 @@
+package com.music.spotui.cast
+
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class CastSpotifyTest {
+ @Test fun deviceIdIsTheMd5OfTheName() {
+ assertEquals("d41d8cd98f00b204e9800998ecf8427e", CastProtocol.spotifyDeviceId(""))
+ assertEquals("5d41402abc4b2a76b9719d911017c592", CastProtocol.spotifyDeviceId("hello"))
+ }
+
+ @Test fun getInfoCarriesTheNameTheIdAndTheGroupFlag() {
+ val m = CastProtocol.spotifyGetInfo(7, "Living room", "abc", group = false)
+ assertEquals("getInfo", m.getString("type"))
+ assertEquals(7, m.getInt("requestId"))
+ val p = m.getJSONObject("payload")
+ assertEquals("Living room", p.getString("remoteName"))
+ assertEquals("abc", p.getString("deviceID"))
+ assertEquals(false, p.getBoolean("deviceAPI_isGroup"))
+ }
+
+ @Test fun addUserCarriesTheTokenAsAnAccessToken() {
+ val p = CastProtocol.spotifyAddUser(8, "tok").getJSONObject("payload")
+ assertEquals("tok", p.getString("blob"))
+ assertEquals("accesstoken", p.getString("tokenType"))
+ }
+
+ @Test fun repliesAreTold() {
+ assertEquals(CastProtocol.SpotifyReply.Info("cid"),
+ CastProtocol.spotifyReply(JSONObject("""{"type":"getInfoResponse","payload":{"clientID":"cid"}}""")))
+ assertEquals(CastProtocol.SpotifyReply.Info("cid2"),
+ CastProtocol.spotifyReply(JSONObject("""{"type":"getInfoResponse","payload":{"clientId":"cid2"}}""")))
+ assertEquals(CastProtocol.SpotifyReply.Failed("getInfoResponse"),
+ CastProtocol.spotifyReply(JSONObject("""{"type":"getInfoResponse","payload":{}}""")))
+ assertEquals(CastProtocol.SpotifyReply.UserAdded, CastProtocol.spotifyReply(JSONObject("""{"type":"addUserResponse"}""")))
+ assertEquals(CastProtocol.SpotifyReply.Failed("addUserError"), CastProtocol.spotifyReply(JSONObject("""{"type":"addUserError","payload":{}}""")))
+ assertNull(CastProtocol.spotifyReply(JSONObject("""{"type":"somethingElse"}""")))
+ }
+
+ @Test fun deviceAuthBodyAndToken() {
+ val b = JSONObject(CastProtocol.deviceAuthBody("cid", "dev"))
+ assertEquals("cid", b.getString("clientId"))
+ assertEquals("dev", b.getString("deviceId"))
+ assertEquals("secret", CastProtocol.deviceAuthToken("""{"accessToken":"secret","expiresIn":3600}"""))
+ assertNull(CastProtocol.deviceAuthToken("""{"error":"x"}"""))
+ assertNull(CastProtocol.deviceAuthToken("not json"))
+ }
+
+ @Test fun receiverStatusIsReadForTheAppAsked() {
+ val status = JSONObject("""{"type":"RECEIVER_STATUS","status":{"applications":[{"appId":"CC32E753","sessionId":"s1","transportId":"t1"}]}}""")
+ assertEquals(CastProtocol.App("s1", "t1"), CastProtocol.receiver(status, CastProtocol.SPOTIFY_RECEIVER).app)
+ assertNull(CastProtocol.receiver(status).app)
+ assertTrue(CastProtocol.launch(1, CastProtocol.SPOTIFY_RECEIVER).toString().contains("CC32E753"))
+ assertEquals("CC1AD845", CastProtocol.launch(1).getString("appId"))
+ }
+}
diff --git a/base/app/src/test/java/com/music/spotui/connect/ZeroconfTest.kt b/base/app/src/test/java/com/music/spotui/connect/ZeroconfTest.kt
new file mode 100644
index 00000000..bb5afd59
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/connect/ZeroconfTest.kt
@@ -0,0 +1,86 @@
+package com.music.spotui.connect
+
+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.net.InetAddress
+
+class ZeroconfTest {
+ private val sonosInfo = """{"status":101,"statusString":"OK","spotifyError":0,"version":"2.7.1","deviceID":"abc123","remoteName":"Kitchen",
+ "activeUser":"","brandDisplayName":"Sonos","modelDisplayName":"One","clientID":"client9","tokenType":"authorization_code"}"""
+
+ @Test fun pathAlwaysStartsWithOneSlash() {
+ assertEquals("/", Zeroconf.path(null))
+ assertEquals("/", Zeroconf.path(""))
+ assertEquals("/spotifyzc", Zeroconf.path("/spotifyzc"))
+ assertEquals("/zc", Zeroconf.path(" zc "))
+ }
+
+ @Test fun getInfoIsParsedAndLoginable() {
+ val i = Zeroconf.parseInfo(sonosInfo)!!
+ assertEquals("abc123", i.deviceId)
+ assertEquals("Kitchen", i.name)
+ assertEquals("client9", i.clientId)
+ assertEquals("authorization_code", i.tokenType)
+ assertTrue(i.loginable)
+ }
+
+ @Test fun anAnswerWithoutIdsOrWithAnErrorIsNotAnInfo() {
+ assertNull(Zeroconf.parseInfo("""{"status":102,"statusString":"ERROR","deviceID":"x"}"""))
+ assertNull(Zeroconf.parseInfo("""{"status":101}"""))
+ assertNull(Zeroconf.parseInfo("not json"))
+ assertFalse(Zeroconf.parseInfo("""{"status":101,"deviceID":"x"}""")!!.loginable)
+ }
+
+ @Test fun addUserIsAFormPostWithTheActionInTheQuery() {
+ val info = Zeroconf.parseInfo(sonosInfo)!!
+ val text = String(Zeroconf.addUserRequest("192.168.1.5", 1400, "/spotifyzc", "me", "tok+/=", info, "Pixel", "id1"), Charsets.UTF_8)
+ val (head, body) = text.split("\r\n\r\n")
+ assertTrue(head.startsWith("POST /spotifyzc?action=addUser HTTP/1.1"))
+ assertTrue(head.contains("Host: 192.168.1.5:1400"))
+ assertTrue(head.contains("Content-Length: ${body.toByteArray().size}"))
+ val fields = body.split('&').associate { it.substringBefore('=') to java.net.URLDecoder.decode(it.substringAfter('='), "UTF-8") }
+ assertEquals("tok+/=", fields["blob"])
+ assertEquals("accesstoken", fields["tokenType"])
+ assertEquals("client9", fields["clientKey"])
+ assertEquals("me", fields["userName"])
+ assertEquals("Pixel", fields["deviceName"])
+ }
+
+ @Test fun responsesAreReadWithAndWithoutChunks() {
+ val plain = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello".toByteArray()
+ assertEquals(200 to "hello", Zeroconf.parseResponse(plain))
+ val chunked = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nhel\r\n2\r\nlo\r\n0\r\n\r\n".toByteArray()
+ assertEquals(200 to "hello", Zeroconf.parseResponse(chunked))
+ assertNull(Zeroconf.parseResponse("garbage".toByteArray()))
+ }
+
+ @Test fun anAnswerIsCompleteOnceItsLengthArrived() {
+ assertFalse(Zeroconf.complete("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhel".toByteArray()))
+ assertTrue(Zeroconf.complete("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello".toByteArray()))
+ assertFalse(Zeroconf.complete("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nhel\r\n".toByteArray()))
+ assertTrue(Zeroconf.complete("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nhel\r\n0\r\n\r\n".toByteArray()))
+ }
+
+ @Test fun addUserAnswers() {
+ assertTrue(Zeroconf.addUserAccepted(200, """{"status":101,"statusString":"OK"}"""))
+ assertTrue(Zeroconf.addUserAccepted(404, ""))
+ assertFalse(Zeroconf.addUserAccepted(200, """{"status":103,"statusString":"ERROR-INVALID-ARGUMENTS"}"""))
+ assertFalse(Zeroconf.addUserAccepted(500, "oops"))
+ assertEquals("status 103 ERROR-INVALID-ARGUMENTS", Zeroconf.answerSummary("""{"status":103,"statusString":"ERROR-INVALID-ARGUMENTS"}"""))
+ }
+
+ @Test fun onlyLocalAddressesAreTrusted() {
+ for (a in listOf("192.168.1.20", "10.0.0.7", "172.16.4.2", "169.254.3.3", "fd12:3456::1")) assertTrue(a, Zeroconf.isLan(InetAddress.getByName(a)))
+ for (a in listOf("8.8.8.8", "127.0.0.1", "2001:4860:4860::8888")) assertFalse(a, Zeroconf.isLan(InetAddress.getByName(a)))
+ }
+
+ @Test fun aDeviceIsKnownByIdOrByName() {
+ val i = Zeroconf.parseInfo(sonosInfo)!!
+ assertTrue(Zeroconf.inConnectList(i, setOf("abc123"), emptySet()))
+ assertTrue(Zeroconf.inConnectList(i, emptySet(), setOf("Kitchen")))
+ assertFalse(Zeroconf.inConnectList(i, setOf("zzz"), setOf("Bedroom")))
+ }
+}