Skip to content

Native Android client for Spotify, built with Jetpack Compose

Jam member, checked against a real host: the join carries the page's own device (local_device_id) and waits until the page sees the Jam's device, a refused play is never taken back here in a Jam, the songs go to Spotify (to the host) rather than through an audio-source extension, and the Jam is read again whenever the player page is ready; no more crash when a mix ends, and the "Mix into …" line is gone

kota-zo1493646feb14
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt
index 53048be8..0133e9ff 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt
@@ -62,6 +62,8 @@ class SpotifyApi(
override val extras = SpotifyTrackExtras(gql, bridge, this.http)
override val devices = SpotifyDevices(bridge)
override val jam = SpotifyJam(bridge, this.http)
+
+ init { player.inJam = { jam.member } }
override val blends = SpotifyBlends(this.http)
override val recents = SpotifyRecents(gql)
@@ -91,6 +93,9 @@ class SpotifyApi(
} catch (e: Exception) {
// No state now: the page's next state event brings it anyway.
}
+ // A Jam this account is in (joined before a restart or a reload): known at once, so
+ // nothing takes the host's playback here before the Jam sheet is opened.
+ try { jam.refresh() } catch (e: kotlinx.coroutines.CancellationException) { throw e } catch (e: Exception) { }
}
}
}
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 c711a80f..74605323 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
@@ -539,18 +539,49 @@ class SpotifyJam(private val bridge: Bridge, private val http: SpotifyHttp) : Ja
// service gives up at once on an account it marks RESTRICTED, while Spotify lets a free account
// join as in the room. Listening here first (LISTEN_AND_CONTROL, Premium), else in the room
// (CONTROL: this phone controls the host's playback), each try with its own attempt id.
+ // The page's own Connect device joins (local_device_id): without it the session took this
+ // account but not always the page's device, which then knew of no Jam, made itself the
+ // active device at the first command (a transfer to itself) and so left the Jam.
+ val device = localDevice()
var last = 0 to ""
for (control in listOf("LISTEN_AND_CONTROL", "CONTROL")) {
val body = buildJsonObject {
put("join_token", joinToken); put("join_type", "deeplinking"); put("playback_control", control)
+ device?.let { put("local_device_id", it) }
put("join_attempt_id", java.util.UUID.randomUUID().toString()); put("permission_mode", "FULL")
}
last = http.send("POST", "$SOCIAL/v3/sessions/join", body.toString())
- if (last.first in 200..299) parse(runCatching { Json.parseToJsonElement(last.second) }.getOrNull())?.let { _session.value = it; return it }
+ if (last.first in 200..299) parse(runCatching { Json.parseToJsonElement(last.second) }.getOrNull())?.let {
+ _session.value = it
+ awaitJamDevice()
+ return it
+ }
}
throw GqlException("jam", "join failed: HTTP ${last.first} ${last.second.take(200)}")
}
+ /** The page's own Connect device id, or null when the page does not say. */
+ private suspend fun localDevice(): String? = runCatching {
+ (bridge.service("ConnectDevicesAPI", "getDevices") as? kotlinx.serialization.json.JsonArray)
+ ?.firstOrNull { it.bool("isLocal") == true }?.let { it.str("id") ?: it.str("connectStateId") }
+ }.getOrNull()
+
+ /**
+ * Until the page sees the Jam's device as the active one (its commands then go to the host),
+ * 6 s at most: a command sent before that went to the page itself and took it out of the Jam.
+ */
+ private suspend fun awaitJamDevice() {
+ val end = System.currentTimeMillis() + 6_000
+ while (System.currentTimeMillis() < end) {
+ val devices = runCatching { bridge.service("ConnectDevicesAPI", "getDevices") as? kotlinx.serialization.json.JsonArray }.getOrNull()
+ if (devices?.any { it.bool("isActive") == true && it.bool("isLocal") != true } == true) return
+ kotlinx.coroutines.delay(400)
+ }
+ }
+
+ /** In a Jam this account joined: the music plays on the host's device, never to be pulled here. */
+ val member: Boolean get() = _session.value?.isHost == false
+
override suspend fun leave() {
_session.value?.let { http.send("POST", "$SOCIAL/v3/sessions/${it.id}/leave") }
_session.value = null
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
index 637540af..2da7e695 100644
--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt
@@ -48,6 +48,9 @@ import kotlinx.serialization.json.putJsonArray
* if that does not help either, [reloadHost] reloads the page and playback resumes there.
*/
class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScope) : Player {
+ /** True while this account is a member of a Jam: playback stays on the host's device (no transfer here). */
+ var inJam: () -> Boolean = { false }
+
private val _state = MutableStateFlow<PlayerState?>(null)
override val state: StateFlow<PlayerState?> = _state
private val _queue = MutableStateFlow<Queue?>(null)
@@ -964,6 +967,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop
if (!lastPlayRefusable) { bridge.logger?.invoke("play refused by Spotify: not the user's, left alone"); return }
// The step's own transfer refused: the step is judged by the play that follows it.
if (refusalTransferring) return
+ // A Jam member: taking playback here (step 2) would take this account out of the Jam.
+ if (inJam()) { bridge.logger?.invoke("play refused by Spotify in a Jam: left to the host"); return }
val ctx = last.first
var step = ++refusalStep
if (step == 1 && last.second == null) step = ++refusalStep
diff --git a/base/app/src/main/java/com/music/spotui/cli/Cli.kt b/base/app/src/main/java/com/music/spotui/cli/Cli.kt
index 025984e4..81429d86 100644
--- a/base/app/src/main/java/com/music/spotui/cli/Cli.kt
+++ b/base/app/src/main/java/com/music/spotui/cli/Cli.kt
@@ -44,6 +44,10 @@ sealed interface CliCommand {
/** Phone songs (a piece of each one's MediaStore folder + title) played as the local queue. */
data class AutoMixFiles(val names: List<String>) : CliCommand
data class AutoMixSeek(val ms: Long) : CliCommand
+ /** Jam: join by its token or link, where it stands (read again from Spotify), leave it. */
+ data class JamJoin(val token: String) : CliCommand
+ data object JamStatus : CliCommand
+ data object JamLeave : CliCommand
}
class CliError(message: String) : Exception(message)
@@ -53,7 +57,7 @@ object CliParser {
"status", "ext.list", "ext.install <zip path>", "ext.uninstall <id>", "ext.enable <id>", "ext.disable <id>",
"ext.setting <id> <key> <value|null>", "ext.press <id> <key>", "ext.call <id> <hook> [json]",
"ext.log <id> [lines]", "ext.storage <id>", "ext.why [n]", "play <spotify uri> [context uri]", "pause", "resume", "next", "previous",
- "nav <route>", "automix [on|off]", "automix.status", "automix.files <folder+title piece> <folder+title piece>...", "automix.seek <ms>",
+ "nav <route>", "automix [on|off]", "automix.status", "automix.files <folder+title piece> <folder+title piece>...", "automix.seek <ms>", "jam.join <token|link>", "jam.status", "jam.leave",
)
private val ID = Regex("[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
@@ -104,6 +108,9 @@ object CliParser {
"automix" -> CliCommand.AutoMixSet(when (args.getOrNull(0)) { null -> null; "on" -> true; "off" -> false; else -> throw CliError("automix: on or off") }).also { most(1) }
"automix.status" -> CliCommand.AutoMixStatus.also { most(0) }
"automix.files" -> CliCommand.AutoMixFiles(args.filter { it.isNotBlank() }.also { if (it.size < 2) throw CliError("automix.files: at least two files") })
+ "jam.join" -> CliCommand.JamJoin(arg(0, "token").let { a -> Regex("socialsession[:/]([A-Za-z0-9]+)").find(a)?.groupValues?.get(1) ?: a }).also { most(1) }
+ "jam.status" -> CliCommand.JamStatus.also { most(0) }
+ "jam.leave" -> CliCommand.JamLeave.also { most(0) }
"automix.seek" -> CliCommand.AutoMixSeek(arg(0, "ms").toLongOrNull()?.takeIf { it >= 0 } ?: throw CliError("automix.seek: <ms> is a number")).also { most(1) }
"pause" -> CliCommand.Pause.also { most(0) }
"resume" -> CliCommand.Resume.also { most(0) }
diff --git a/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt b/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt
index e460be01..6db789d6 100644
--- a/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt
+++ b/base/app/src/main/java/com/music/spotui/cli/CliReceiver.kt
@@ -216,6 +216,9 @@ class CliReceiver : BroadcastReceiver() {
c.on?.let { com.music.spotui.automix.AutoMix.set(it); com.music.spotui.di.LocalPlayer.autoMixChanged(it) }
JsonPrimitive(com.music.spotui.di.LocalPlayer.autoMixState())
}
+ is CliCommand.JamJoin -> jamJson(MyspotiRuntime.api.jam.join(c.token))
+ CliCommand.JamStatus -> { MyspotiRuntime.api.jam.refresh(); jamJson(MyspotiRuntime.api.jam.session.value) }
+ CliCommand.JamLeave -> { MyspotiRuntime.api.jam.leave(); JsonNull }
CliCommand.AutoMixStatus -> onMain {
buildJsonObject {
put("state", com.music.spotui.di.LocalPlayer.autoMixState())
@@ -273,6 +276,11 @@ class CliReceiver : BroadcastReceiver() {
return read
}
+ private fun jamJson(s: app.myspoti.api.JamSession?): JsonElement = if (s == null) JsonNull else buildJsonObject {
+ put("id", s.id); put("token", s.joinToken ?: ""); put("host", s.isHost); put("queueOnly", s.queueOnly)
+ put("members", JsonArray(s.members.map { m -> JsonPrimitive(m.name + if (m.host) " (host)" else "") }))
+ }
+
private suspend fun <T> onMain(block: () -> T): T = withContext(Dispatchers.Main) { block() }
companion object {
diff --git a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
index e79af07d..5ba91246 100644
--- a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
+++ b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt
@@ -729,7 +729,12 @@ object Extensions {
* An audio-source extension is asked for songs: one runs and is not inactive, or one that is on
* is still being started at launch (the song then waits for it, see [audio]).
*/
- fun hasAudioSource(): Boolean { providedState.value; return isReady && (providing(Hook.AUDIO_SOURCE).isNotEmpty() || startingAudioSource()) }
+ fun hasAudioSource(): Boolean {
+ providedState.value
+ // A Jam member's songs play on the host's device, sent there by Spotify: none through an extension here.
+ if (app.myspoti.host.android.MyspotiRuntime.isStarted && app.myspoti.host.android.MyspotiRuntime.spotify.jam.member) return false
+ return isReady && (providing(Hook.AUDIO_SOURCE).isNotEmpty() || startingAudioSource())
+ }
/** The app is still starting the extensions on at launch, an audio source among them. */
private fun startingAudioSource(): Boolean =
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AutoMixVisuals.kt b/base/app/src/main/java/com/music/spotui/ui/components/AutoMixVisuals.kt
index 0459bf61..0ea2d221 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/AutoMixVisuals.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/AutoMixVisuals.kt
@@ -223,51 +223,6 @@ fun DrawScope.drawMixZone(zone: ClosedFloatingPointRange<Float>, played: Float,
if (px > x0) drawRoundRect(color, Offset(x0, y - h / 2), Size(px - x0, h), radius)
}
-/**
- * The line under the seek bar that says a mix comes: "Mix into …" from 30 s before it,
- * "Mixing into …" while it plays. [positionMs] is the song playing's position.
- */
-@Composable
-fun MixHint(cue: LocalPlayer.MixCue?, positionMs: () -> Long, tint: Color, accent: Color, pulse: MixPulse?, modifier: Modifier = Modifier) {
- // Checked twice a second rather than per frame: the line comes 30 s ahead, give or take.
- var near by remember { androidx.compose.runtime.mutableStateOf(false) }
- LaunchedEffect(cue) {
- while (true) {
- near = cue != null && (cue.mixing || cue.skip || cue.exitMs - positionMs() < 30_000)
- if (cue == null) break
- kotlinx.coroutines.delay(500)
- }
- }
- AnimatedVisibility(
- visible = near && cue!!.nextTitle.isNotBlank(),
- enter = fadeIn() + expandVertically(expandFrom = Alignment.Top),
- exit = fadeOut() + shrinkVertically(shrinkTowards = Alignment.Top),
- modifier = modifier,
- ) {
- val c = remember { mutableLastCue() }
- cue?.let { c.value = it }
- val shown = c.value ?: return@AnimatedVisibility
- Row(
- Modifier
- .background(accent.copy(alpha = 0.16f), RoundedCornerShape(50))
- .padding(horizontal = 10.dp, vertical = 4.dp),
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.Center,
- ) {
- Icon(Icons.Rounded.GraphicEq, contentDescription = null, tint = accent,
- modifier = Modifier.size(14.dp).mixBeat(pulse, amount = 0.25f))
- Spacer(Modifier.width(6.dp))
- Text(
- stringResource(if (shown.mixing) R.string.automix_hint_mixing else R.string.automix_hint_next, shown.nextTitle),
- color = tint, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,
- )
- }
- }
-}
-
-private class LastCue { var value: LocalPlayer.MixCue? = null }
-private fun mutableLastCue() = LastCue()
-
/**
* The local player's speed when it is not 1× ("1.5×"), under the seek bar: a speed left at 2× in
* the equalizer page made downloads sound broken with nothing on screen to say why (#137). A tap
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt
index 2f668c3f..1f4cb397 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/PlayerControls.kt
@@ -144,10 +144,6 @@ internal fun PlayerScrubber(
mixPulse = { state.mixPulse?.level() ?: 0f },
)
ScrubTimes(frame, scrub, state)
- com.music.spotui.ui.components.MixHint(
- state.mixCue, state.positionMs, LocalPlayerTint.current.copy(alpha = 0.8f), com.music.spotui.ui.immersive.Immersive.Accent, state.mixPulse,
- Modifier.align(Alignment.CenterHorizontally).offset(y = (-4).dp),
- )
com.music.spotui.ui.components.PlaybackSpeedNote(LocalPlayerTint.current.copy(alpha = 0.8f), com.music.spotui.ui.immersive.Immersive.Accent,
Modifier.align(Alignment.CenterHorizontally).offset(y = (-4).dp))
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
index 7ba105d1..2fbac9ca 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt
@@ -653,10 +653,6 @@ fun PlayerScreen(navController: NavController) {
)
}
- com.music.spotui.ui.components.MixHint(
- mixCue, { mv.position() }, Color.White.copy(alpha = 0.8f), com.music.spotui.ui.theme.AppAccent, mixPulse,
- Modifier.align(Alignment.CenterHorizontally).padding(top = 4.dp),
- )
com.music.spotui.ui.components.PlaybackSpeedNote(Color.White.copy(alpha = 0.8f), com.music.spotui.ui.theme.AppAccent,
Modifier.align(Alignment.CenterHorizontally).padding(top = 4.dp))
PlayerFull(songPlayingState, playerViewModel, context, shuffle, repeat, queueSongs)
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 f983df90..e7488743 100644
--- a/base/app/src/main/res/values-de/myspoti_strings.xml
+++ b/base/app/src/main/res/values-de/myspoti_strings.xml
@@ -688,8 +688,6 @@
<string name="settings_automix_album_order_detail">Kein Mix zwischen Songs, die auf ihrem Album aufeinander folgen: Sie gehen ineinander über wie auf der Platte.</string>
<string name="settings_automix_show">Mix im Player zeigen</string>
<string name="settings_automix_show_detail">Der Abschnitt des Mixes ist auf der Fortschrittsleiste farbig, und das Cover leuchtet und pulsiert im Takt, solange er läuft.</string>
- <string name="automix_hint_next">Mix zu %1$s</string>
- <string name="automix_hint_mixing">Mischt zu %1$s</string>
<string name="settings_automix_title">AutoMix</string>
<string name="settings_automix_detail">DJ-artige Übergänge zwischen Songs aus Erweiterungen, Downloads und lokalen Dateien: Jeder Song wird einmal analysiert (Beats, Takte, Phrasen, Tonart) und der nächste setzt im Takt und im gleichen Tempo ein, mit einem Bass-Tausch. Songs, die sich nicht angleichen lassen, bekommen einen Schnitt im Takt oder eine Blende. Streams werden nur in unbegrenzten Netzen analysiert.</string>
<string name="settings_automix_length">Mix-Länge</string>
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 ae7fca71..9514afc4 100644
--- a/base/app/src/main/res/values-el/myspoti_strings.xml
+++ b/base/app/src/main/res/values-el/myspoti_strings.xml
@@ -688,8 +688,6 @@
<string name="settings_automix_album_order_detail">Χωρίς μίξη ανάμεσα σε τραγούδια που διαδέχονται το ένα το άλλο στο άλμπουμ τους: δένουν όπως στον δίσκο.</string>
<string name="settings_automix_show">Η μίξη στο πρόγραμμα αναπαραγωγής</string>
<string name="settings_automix_show_detail">Το τμήμα της μίξης χρωματίζεται στη γραμμή αναπαραγωγής και το εξώφυλλο λάμπει και πάλλεται στον ρυθμό όσο διαρκεί.</string>
- <string name="automix_hint_next">Μίξη προς %1$s</string>
- <string name="automix_hint_mixing">Μίξη προς %1$s</string>
<string name="settings_automix_title">AutoMix</string>
<string name="settings_automix_detail">Μεταβάσεις σαν DJ ανάμεσα σε τραγούδια από επεκτάσεις, λήψεις και τοπικά αρχεία: κάθε τραγούδι αναλύεται μία φορά (χτύποι, μέτρα, φράσεις, τονικότητα) και το επόμενο μπαίνει στον ρυθμό, στο ίδιο τέμπο, με εναλλαγή των μπάσων. Όσα δεν συγχρονίζονται παίρνουν κόψιμο στον ρυθμό ή σβήσιμο. Οι ροές αναλύονται μόνο σε δίκτυα χωρίς χρέωση δεδομένων.</string>
<string name="settings_automix_length">Διάρκεια μίξης</string>
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 e56a6ad6..478c2440 100644
--- a/base/app/src/main/res/values-es/myspoti_strings.xml
+++ b/base/app/src/main/res/values-es/myspoti_strings.xml
@@ -688,8 +688,6 @@
<string name="settings_automix_album_order_detail">Sin mezcla entre canciones que se siguen en su álbum: se encadenan como en el disco.</string>
<string name="settings_automix_show">Mostrar la mezcla en el reproductor</string>
<string name="settings_automix_show_detail">El tramo de la mezcla se colorea en la barra de reproducción, y la portada brilla y late al ritmo mientras suena.</string>
- <string name="automix_hint_next">Mezcla hacia %1$s</string>
- <string name="automix_hint_mixing">Mezclando hacia %1$s</string>
<string name="settings_automix_title">AutoMix</string>
<string name="settings_automix_detail">Transiciones al estilo DJ entre canciones de extensiones, descargas y archivos locales: cada canción se analiza una vez (pulsos, compases, frases, tonalidad) y la siguiente entra a tiempo, con el tempo igualado y un intercambio de graves. Las que no se pueden sincronizar tienen un corte a tiempo o un fundido. Las transmisiones solo se analizan en redes sin límite de datos.</string>
<string name="settings_automix_length">Duración de la mezcla</string>
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 138f0460..6311db8e 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -695,8 +695,6 @@
<string name="settings_automix_album_order_detail">Pas de mix entre deux morceaux qui se suivent sur leur album : ils s\'enchaînent comme sur le disque.</string>
<string name="settings_automix_show">Afficher le mix dans le lecteur</string>
<string name="settings_automix_show_detail">La portion du mix est colorée sur la barre de lecture, et la pochette s\'illumine et pulse au rythme pendant le mix.</string>
- <string name="automix_hint_next">Mix vers %1$s</string>
- <string name="automix_hint_mixing">Mix en cours vers %1$s</string>
<string name="settings_automix_length">Durée des mix</string>
<string name="settings_automix_length_short">Courte</string>
<string name="settings_automix_length_auto">Équilibrée</string>
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 41d61842..ca0437de 100644
--- a/base/app/src/main/res/values-it/myspoti_strings.xml
+++ b/base/app/src/main/res/values-it/myspoti_strings.xml
@@ -688,8 +688,6 @@
<string name="settings_automix_album_order_detail">Nessun mix tra brani che si susseguono nel loro album: si legano come sul disco.</string>
<string name="settings_automix_show">Mostra il mix nel player</string>
<string name="settings_automix_show_detail">Il tratto del mix è colorato sulla barra di avanzamento e la copertina si illumina e pulsa a tempo mentre suona.</string>
- <string name="automix_hint_next">Mix verso %1$s</string>
- <string name="automix_hint_mixing">Mix in corso verso %1$s</string>
<string name="settings_automix_title">AutoMix</string>
<string name="settings_automix_detail">Transizioni in stile DJ tra brani da estensioni, download e file locali: ogni brano viene analizzato una volta (battiti, battute, frasi, tonalità) e il successivo entra a tempo, con il tempo allineato e uno scambio dei bassi. I brani non sincronizzabili hanno un taglio a tempo o una dissolvenza. Gli stream vengono analizzati solo su reti senza limiti.</string>
<string name="settings_automix_length">Durata del mix</string>
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 e0b8124b..fb7c87f5 100644
--- a/base/app/src/main/res/values-pl/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pl/myspoti_strings.xml
@@ -703,8 +703,6 @@
<string name="settings_automix_album_order_detail">Bez miksu między utworami, które następują po sobie na albumie: łączą się jak na płycie.</string>
<string name="settings_automix_show">Pokazuj miks w odtwarzaczu</string>
<string name="settings_automix_show_detail">Fragment miksu jest pokolorowany na pasku odtwarzania, a okładka świeci i pulsuje w rytm, gdy trwa.</string>
- <string name="automix_hint_next">Miks do %1$s</string>
- <string name="automix_hint_mixing">Miksowanie do %1$s</string>
<string name="settings_automix_title">AutoMix</string>
<string name="settings_automix_detail">Przejścia w stylu DJ między utworami z rozszerzeń, pobrań i plików lokalnych: każdy utwór jest analizowany raz (bity, takty, frazy, tonacja), a następny wchodzi w rytm, z dopasowanym tempem i zamianą basu. Utwory, których nie da się zgrać, dostają cięcie w rytm albo wyciszenie. Strumienie są analizowane tylko w sieciach bez limitu.</string>
<string name="settings_automix_length">Długość miksu</string>
diff --git a/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml b/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml
index 892ab7e9..3da33030 100644
--- a/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt-rBR/myspoti_strings.xml
@@ -666,8 +666,6 @@
<string name="settings_automix_album_order_detail">Sem mixagem entre músicas que se seguem no álbum: elas se encadeiam como no disco.</string>
<string name="settings_automix_show">Mostrar a mixagem no player</string>
<string name="settings_automix_show_detail">O trecho da mixagem fica colorido na barra de reprodução, e a capa brilha e pulsa no ritmo enquanto toca.</string>
- <string name="automix_hint_next">Mixagem para %1$s</string>
- <string name="automix_hint_mixing">Mixando para %1$s</string>
<string name="settings_automix_title">AutoMix</string>
<string name="settings_automix_detail">Transições no estilo DJ entre músicas de extensões, downloads e arquivos locais: cada música é analisada uma vez (batidas, compassos, frases, tom) e a próxima entra no tempo, com o andamento igualado e uma troca de graves. As que não dá para sincronizar ganham um corte no tempo ou um fade. As transmissões só são analisadas em redes sem limite de dados.</string>
<string name="settings_automix_length">Duração da mixagem</string>
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 e0b35262..e2d1375d 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
@@ -635,8 +635,6 @@
<string name="settings_automix_album_order_detail">Sem mistura entre músicas que se seguem no seu álbum: encadeiam-se como no disco.</string>
<string name="settings_automix_show">Mostrar a mistura no leitor</string>
<string name="settings_automix_show_detail">O trecho da mistura é colorido na barra de reprodução, e a capa brilha e pulsa ao ritmo enquanto toca.</string>
- <string name="automix_hint_next">Mistura para %1$s</string>
- <string name="automix_hint_mixing">A misturar para %1$s</string>
<string name="settings_automix_title">AutoMix</string>
<string name="settings_automix_detail">Transições ao estilo DJ entre músicas de extensões, transferências e ficheiros locais: cada música é analisada uma vez (batidas, compassos, frases, tonalidade) e a seguinte entra no tempo, com o andamento igualado e uma troca de graves. As que não podem ser sincronizadas têm um corte no tempo ou um fade. As transmissões só são analisadas em redes sem limite de dados.</string>
<string name="settings_automix_length">Duração da mistura</string>
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 ac90abd5..2d74bac5 100644
--- a/base/app/src/main/res/values-pt/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml
@@ -688,8 +688,6 @@
<string name="settings_automix_album_order_detail">Sem mistura entre músicas que se seguem no seu álbum: encadeiam-se como no disco.</string>
<string name="settings_automix_show">Mostrar a mistura no leitor</string>
<string name="settings_automix_show_detail">O trecho da mistura é colorido na barra de reprodução, e a capa brilha e pulsa ao ritmo enquanto toca.</string>
- <string name="automix_hint_next">Mistura para %1$s</string>
- <string name="automix_hint_mixing">A misturar para %1$s</string>
<string name="settings_automix_title">AutoMix</string>
<string name="settings_automix_detail">Transições ao estilo DJ entre músicas de extensões, transferências e ficheiros locais: cada música é analisada uma vez (batidas, compassos, frases, tonalidade) e a seguinte entra no tempo, com o andamento igualado e uma troca de graves. As que não podem ser sincronizadas têm um corte no tempo ou um fade. As transmissões só são analisadas em redes sem limite de dados.</string>
<string name="settings_automix_length">Duração da mistura</string>
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 e7f44994..e93a53b0 100644
--- a/base/app/src/main/res/values-ru/myspoti_strings.xml
+++ b/base/app/src/main/res/values-ru/myspoti_strings.xml
@@ -703,8 +703,6 @@
<string name="settings_automix_album_order_detail">Без сведения между треками, идущими подряд на своём альбоме: они переходят друг в друга, как на пластинке.</string>
<string name="settings_automix_show">Показывать сведение в плеере</string>
<string name="settings_automix_show_detail">Участок сведения выделен цветом на полосе воспроизведения, а обложка светится и пульсирует в такт, пока оно идёт.</string>
- <string name="automix_hint_next">Сведение в %1$s</string>
- <string name="automix_hint_mixing">Сведение в %1$s</string>
<string name="settings_automix_title">AutoMix</string>
<string name="settings_automix_detail">Переходы в стиле диджея между треками из расширений, загрузок и локальных файлов: каждый трек анализируется один раз (доли, такты, фразы, тональность), и следующий вступает в такт, с выровненным темпом и сменой баса. Треки, которые нельзя свести, получают склейку в такт или затухание. Потоки анализируются только в безлимитных сетях.</string>
<string name="settings_automix_length">Длина сведения</string>
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 11aa0366..5f2b077c 100644
--- a/base/app/src/main/res/values-zh/myspoti_strings.xml
+++ b/base/app/src/main/res/values-zh/myspoti_strings.xml
@@ -688,8 +688,6 @@
<string name="settings_automix_album_order_detail">专辑中相邻的歌曲之间不混音:像唱片上一样直接衔接。</string>
<string name="settings_automix_show">在播放器中显示混音</string>
<string name="settings_automix_show_detail">混音段在进度条上以颜色标出,混音时封面会随节拍发光和律动。</string>
- <string name="automix_hint_next">即将混入 %1$s</string>
- <string name="automix_hint_mixing">正在混入 %1$s</string>
<string name="settings_automix_title">AutoMix</string>
<string name="settings_automix_detail">在扩展、下载和本地文件的歌曲之间进行 DJ 式过渡:每首歌只分析一次(节拍、小节、乐句、调性),下一首在节拍上进入,速度对齐并交换低音。无法对拍的歌曲会在节拍上切换或淡变。串流仅在不计流量的网络上分析。</string>
<string name="settings_automix_length">混音时长</string>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index b3f6a80e..af314310 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -696,8 +696,6 @@
<string name="settings_automix_album_order_detail">No mix between songs that follow each other on their album: they run into each other as on the record.</string>
<string name="settings_automix_show">Show the mix in the player</string>
<string name="settings_automix_show_detail">The mix\'s stretch is coloured on the seek bar, and the cover glows and pulses with the beat while it plays.</string>
- <string name="automix_hint_next">Mix into %1$s</string>
- <string name="automix_hint_mixing">Mixing into %1$s</string>
<string name="settings_automix_length">Mix length</string>
<string name="settings_automix_length_short">Short</string>
<string name="settings_automix_length_auto">Balanced</string>
diff --git a/base/host-cdp/build.gradle.kts b/base/host-cdp/build.gradle.kts
index ce7b4e1e..b68368ce 100644
--- a/base/host-cdp/build.gradle.kts
+++ b/base/host-cdp/build.gradle.kts
@@ -22,6 +22,9 @@ tasks.test {
useJUnitPlatform()
// Live tests need Chrome with --remote-debugging-port and a signed-in Web Player.
systemProperty("myspoti.cdp", providers.gradleProperty("cdp").getOrElse(""))
+ // JamLiveTest: a Jam to join (its token) and a command that prints the host's playback (see the test).
+ systemProperty("myspoti.jam", providers.gradleProperty("jam").getOrElse(""))
+ systemProperty("myspoti.jamHost", providers.gradleProperty("jamHost").getOrElse(""))
testLogging { events("passed", "failed", "skipped"); showStandardStreams = true }
outputs.upToDateWhen { false }
}
diff --git a/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/JamLiveTest.kt b/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/JamLiveTest.kt
new file mode 100644
index 00000000..53061964
--- /dev/null
+++ b/base/host-cdp/src/test/kotlin/app/myspoti/host/cdp/JamLiveTest.kt
@@ -0,0 +1,128 @@
+package app.myspoti.host.cdp
+
+import app.myspoti.spotify.SpotifyApi
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import org.junit.jupiter.api.AfterAll
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertNotEquals
+import org.junit.jupiter.api.Assertions.assertNotNull
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.BeforeAll
+import org.junit.jupiter.api.MethodOrderer
+import org.junit.jupiter.api.Order
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.TestInstance
+import org.junit.jupiter.api.TestMethodOrder
+import org.junit.jupiter.api.condition.EnabledIfSystemProperty
+
+/**
+ * A Jam joined from the Web Player as a member, the host being another device (the Spotify desktop
+ * app on another account): the member's commands must change the host's playback.
+ *
+ * ./gradlew :host-cdp:test --tests '*JamLiveTest*' -Pcdp=http://localhost:9333 -Pjam=<join token> \
+ * -PjamHost='python3 hostctl.py cluster'
+ *
+ * jamHost prints the host's playback as "... | track <uri> | ctx <uri> | paused <bool> ...".
+ */
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
+@TestMethodOrder(MethodOrderer.OrderAnnotation::class)
+@EnabledIfSystemProperty(named = "myspoti.jam", matches = ".+")
+class JamLiveTest {
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ private lateinit var host: CdpHost
+ private lateinit var api: SpotifyApi
+
+ private fun live(block: suspend () -> Any?) { runBlocking { withTimeout(90_000) { block() } } }
+
+ /** The host's playback, read with the jamHost command. */
+ private fun hostState(): Map<String, String> {
+ val cmd = System.getProperty("myspoti.jamHost")
+ val out = ProcessBuilder("bash", "-c", cmd).redirectErrorStream(true).start().inputStream.bufferedReader().readText().trim()
+ println("host: $out")
+ return Regex("""(track|ctx|paused) (\S+)""").findAll(out).associate { it.groupValues[1] to it.groupValues[2] }
+ }
+
+ private suspend fun <T> eventually(timeoutMs: Long = 12_000, check: suspend () -> T?): T {
+ val end = System.currentTimeMillis() + timeoutMs
+ while (System.currentTimeMillis() < end) { check()?.let { return it }; delay(700) }
+ error("condition not reached in $timeoutMs ms")
+ }
+
+ @BeforeAll
+ fun connect() = live {
+ host = CdpHost.connect(System.getProperty("myspoti.cdp"))
+ api = SpotifyApi(host, scope, language = "fr")
+ host.reload()
+ host.awaitLoad()
+ api.onPageLoaded()
+ api.awaitReady()
+ }
+
+ @AfterAll
+ fun close() {
+ runBlocking { runCatching { api.jam.leave() } }
+ host.close()
+ scope.cancel()
+ }
+
+ @Test @Order(1)
+ fun `joins the host's Jam`() = live {
+ val s = api.jam.join(System.getProperty("myspoti.jam"))
+ println("joined ${s.id} members=${s.members.map { it.name }} host=${s.isHost}")
+ api.jam.refresh()
+ assertNotNull(api.jam.session.value)
+ delay(3_000)
+ println("member sees: ${api.player.state.value?.item?.uri} state=${api.player.state.value?.let { it::class.simpleName }}")
+ }
+
+ @Test @Order(2)
+ fun `next moves the host on`() = live {
+ val before = hostState()["track"]
+ api.player.next()
+ val after = eventually { hostState()["track"]?.takeIf { it != before } }
+ assertNotEquals(before, after)
+ }
+
+ @Test @Order(3)
+ fun `a list played by the member plays on the host`() = live {
+ // In a Jam the host plays it as the Jam's own list (spotify:list:jam-list:<session>): its first song is checked.
+ val album = "spotify:album:2noRn2Aes5aoNVsU6iWThc"
+ val first = api.catalog.albumTracks(album, 0, 1).items.first().uri
+ api.player.play(album)
+ eventually { hostState()["track"]?.takeIf { it == first } }
+ }
+
+ @Test @Order(4)
+ fun `pause and resume reach the host`() = live {
+ api.player.pause()
+ eventually { hostState()["paused"]?.takeIf { it == "True" } }
+ api.player.resume()
+ eventually { hostState()["paused"]?.takeIf { it == "False" } }
+ }
+
+ @Test @Order(5)
+ fun `the member is still in the Jam after its player page reloads`() = live {
+ host.reload(); host.awaitLoad(); api.onPageLoaded(); api.awaitReady()
+ delay(4_000)
+ api.jam.refresh()
+ println("after a reload: ${api.jam.session.value?.id} members=${api.jam.session.value?.members?.map { it.name }}")
+ val before = hostState()["track"]
+ api.player.next()
+ eventually { hostState()["track"]?.takeIf { it != before } }
+ }
+
+ @Test @Order(6)
+ fun `the member is still in the Jam`() = live {
+ api.jam.refresh()
+ val s = api.jam.session.value
+ println("still in: ${s?.id} members=${s?.members?.map { it.name }}")
+ assertTrue(s != null)
+ assertEquals(false, s!!.isHost)
+ }
+}
diff --git a/docs/api/JAM.md b/docs/api/JAM.md
index 9c8a0793..613cee9f 100644
--- a/docs/api/JAM.md
+++ b/docs/api/JAM.md
@@ -16,5 +16,13 @@ what Myspoti goes through (`SpotifyJam`, `api-spotify/.../SpotifyMore.kt`). Host
| Invite link | `POST url-dispenser/v1/generate-url` | `spotify_uri: spotify:socialsession:<token>`, `custom_data` (`ssp=1`, `app_destination=socialsession`), `link_preview` (title, `https://shareables.scdn.co/publish/socialsession/<token>`), `utm_*` (`utm_medium` `share-link` or `qr`). Answers `shareable_url` (`spotify.link/…`), `share_id`, `full_url` (`open.spotify.com/socialsession/<token>?si=…`). Service: `getShortInviteLink(token, joinSessionUri, qr?)`. |
| Queued by | GraphQL `decorateQueuedByUsers` (`userUris`) | The host names who queued a song (seen when a member added one). |
+Checked from Myspoti's own code on a free account (`host-cdp` JamLiveTest, the desktop app as the
+host): `current_or_new` answers 403 `FREE_USER_NOT_ALLOWED` (a free account cannot start a Jam), the
+join answers 200 with `CONTROL`. With `local_device_id` set to the page's own Connect device, the
+member's commands (next, a list, pause, resume) go to `connect-state/v1/player/command/from/<device>/to/social-connect-<session>`
+(202) and the host follows, also after the member's page reloads; without it the page sometimes never
+learned of the Jam, sent its first command to itself (a transfer to itself) and so left the Jam.
+A list played by a member plays on the host as `spotify:list:jam-list:<session>`.
+
Who is in the session and what they do reaches the host through the dealer (pushed to the native
core on the desktop: not seen over CDP).