Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Premium accounts: the plan read once per session (product, ads) is the one source of truth; on a paid plan with no ads the ad hosts are let through (trackers stay blocked), the page's ad managers are left alone, the ad watcher, its mute and reloads and the remote ad mute do nothing, and the diagnostic says no ads (Premium); unknown or free: as before
kota-zoe66570b3188e
diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/AccountPlan.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/AccountPlan.ktnew file mode 100644index 00000000..8dd30796--- /dev/null+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/AccountPlan.kt@@ -0,0 +1,49 @@+package app.myspoti.spotify++import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.contentOrNull++/**+ * The account's plan, from the Web Player's accountAttributes answer (`data.me.account`: `product`+ * and `attributes.ads`). Read once the page is signed in, and forgotten when the account signs out,+ * so it always says which account plays now.+ *+ * [premium] is null until it is read: the ad machinery then works as it always did. True for a paid+ * plan with its ads off, where nothing refuses, mutes or reloads for an ad (Spotify sends none there).+ * False for a free account, or one that still gets ads.+ */+object AccountPlan {+ private val _premium = MutableStateFlow<Boolean?>(null)+ val premium: StateFlow<Boolean?> = _premium++ /** True when the account is a paid one with its ads off: the ad machinery is off. */+ val isPremium: Boolean get() = _premium.value == true++ /** The plan read, or forgotten (null): a sign-out, or a new sign-in. */+ fun set(premium: Boolean?) { _premium.value = premium }++ /** The plan in an accountAttributes answer, `{"data":{"me":{"account":...}}}`; null when it does not say. */+ fun fromAnswer(answer: JsonElement?): Boolean? {+ val me = ((answer as? JsonObject)?.get("data") as? JsonObject)?.get("me") as? JsonObject ?: return null+ val account = me["account"] as? JsonObject ?: return null+ return fromAccount(account)+ }++ /**+ * The plan of an account object: a product other than FREE or OPEN (PREMIUM, DUO, FAMILY,+ * STUDENT...) with `attributes.ads` false is Premium; FREE or OPEN is free, whatever the ads say.+ * Null when the product or the ads flag is missing (a paid product with unknown ads is not guessed).+ */+ fun fromAccount(account: JsonObject): Boolean? {+ val product = (account["product"] as? JsonPrimitive)?.contentOrNull?.trim()?.lowercase()+ ?.takeIf { it.isNotEmpty() } ?: return null+ if (product == "free" || product == "open") return false+ val ads = ((account["attributes"] as? JsonObject)?.get("ads") as? JsonPrimitive)?.booleanOrNull ?: return null+ return !ads+ }+}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.ktindex 5ed9e9a8..1d55a3c6 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@@ -723,6 +723,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop)}+ /** The ad machinery acts on an ad: off on a Premium account, which has none (see [AccountPlan]). */+ private val adsHandled: Boolean get() = !AccountPlan.isPremium+/*** Every [WATCH_TICK_MS]: the page answers (else it is frozen and reloaded), the song it* says it plays is heard (its media element moves), the sound is on, ads are got past,@@ -812,7 +815,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopif (localMuted && s?.item?.uri != hushedUri) { hushedUri = s?.item?.uri; applyHush() }if (tick % VOLUME_CHECK_TICKS == 0) guardVolume(s, media)if (!_adPlaying.value) { remoteAdLogged = false; adHeldLogged = false }- if (_adPlaying.value && remoteActive) {+ // On a Premium account (AccountPlan) an ad is not watched: no mute, skip, reload or recovery.+ if (_adPlaying.value && adsHandled && remoteActive) {// The ad plays on another device of the account (Connect, Cast): muted there by the// app (RemoteAdMute), never got past from here. A reload or a play of the next song// was refused by it, or pulled playback back to the phone.@@ -823,7 +827,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopkey = null; silentSince = 0Lcontinue}- if (_adPlaying.value) {+ if (_adPlaying.value && adsHandled) {// The screens show the break (or the song before it, waiting), not a stall.notStalled()val ad = adState@@ -1749,6 +1753,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScoprunCatching { bridge.call("media.hush", buildJsonObject { put("on", clipHushed || localMuted) }).toString().trim('"').toIntOrNull() ?: 0 }.getOrDefault(0)private suspend fun muteForAd() = runCatching {+ if (!adsHandled) return@runCatchingadMuted = trueadMutedAt = System.currentTimeMillis()var muted = bridge.call("media.mute", buildJsonObject { put("on", true) })diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.ktindex 84473ad8..e30c9f86 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/Bridge.kt@@ -1,5 +1,6 @@package app.myspoti.spotify.bridge+import app.myspoti.spotify.AccountPlanimport kotlinx.coroutines.channels.BufferOverflowimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.CancellationException@@ -140,7 +141,8 @@ class Bridge(private val host: BridgeHost, scope: CoroutineScope) {// re-announces only when the host is not ready (a page it thought it had lost).// The page's generation goes in with it: a call made for a page that went away is refused// by the next one (see [call]) instead of running there.- host.evaluate("window.__mspPage = $pagesGone; window.__mspReannounce = ${!_ready.value}; ${BridgeScript.source}")+ // The account's plan as known now (see AccountPlan): on Premium the page's ad managers are left on.+ host.evaluate("window.__mspPage = $pagesGone; window.__mspReannounce = ${!_ready.value}; window.__mspKeepAds = ${AccountPlan.isPremium}; ${BridgeScript.source}")}/**diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.ktindex 82bcf662..2abc959c 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt@@ -1,5 +1,6 @@package app.myspoti.spotify.bridge+import app.myspoti.spotify.AccountPlanimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.serialization.json.Json@@ -52,7 +53,7 @@ object AdBlock {* never calls them stands out. Ads that come anyway are muted and skipped by the player,* and sponsored content is dropped from the screens.*/- val blockedHosts = listOf(+ private val adHosts = listOf(// The ad audio files."adstudio-assets.scdn.co",// Google's ad servers (audio and video ads served in other markets).@@ -63,17 +64,28 @@ object AdBlock {"imasdk.googleapis.com",// DoubleClick's ad media CDN (host list credit: coldMEW/Hush, GPL-3.0)."s0.2mdn.net",- // Third-party audience trackers the page loads (nothing it needs to play).+ )++ /** Third-party audience trackers the page loads (nothing it needs to play): refused on every account. */+ private val trackerHosts = listOf("googletagmanager.com","google-analytics.com","scorecardresearch.com","fastly-insights.com",)+ /** Every host refused on a free account. */+ val blockedHosts = adHosts + trackerHosts++ /**+ * Whether [url] is refused. On a Premium account ([AccountPlan.isPremium]) the ad hosts are let+ * through (Spotify sends no ads there, and nothing is to be interfered with); the trackers stay refused.+ */fun isBlocked(url: String): Boolean {val rest = url.substringAfter("://")val host = rest.substringBefore('/').substringBefore('?').substringBefore(':').lowercase()- return blockedHosts.any { host == it || host.endsWith(".$it") }+ val refused = if (AccountPlan.isPremium) trackerHosts else blockedHosts+ return refused.any { host == it || host.endsWith(".$it") }}/**@@ -88,7 +100,7 @@ object AdBlock {* is left as it is; an ad that is already the current state cannot be left out either.*/fun withoutAds(body: String): Pair<String, List<String>>? {- if (!AD_HINT.containsMatchIn(body)) return null+ if (AccountPlan.isPremium || !AD_HINT.containsMatchIn(body)) return nullval root = runCatching { Json.parseToJsonElement(body).jsonObject }.getOrNull() ?: return nullval notes = mutableListOf<String>()val out = root.toMutableMap()@@ -115,7 +127,7 @@ object AdBlock {/** The [AdAhead] in a track-playback reply (after [withoutAds]), or null. */fun adAhead(body: String): AdAhead? = runCatching {- if (!AD_HINT.containsMatchIn(body)) return null+ if (AccountPlan.isPremium || !AD_HINT.containsMatchIn(body)) return nullval root = Json.parseToJsonElement(body).jsonObjectval machine = root["state_machine"] as? JsonObject ?: return nullval tracks = machine["tracks"] as? JsonArray ?: return null@@ -163,6 +175,7 @@ object AdBlock {* at all). Null when it does not look like one.*/fun whyKept(body: String): String? = runCatching {+ if (AccountPlan.isPremium) return nullval marker = AD_HINT.find(body)?.value?.trim('"') ?: return nullval root = Json.parseToJsonElement(body).jsonObjectval machine = root["state_machine"] as? JsonObject ?: return "$marker: no state machine in the reply"diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/report/Refusal402.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/report/Refusal402.ktindex 36adf6d4..477974ec 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/report/Refusal402.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/report/Refusal402.kt@@ -1,5 +1,7 @@package app.myspoti.spotify.report+import app.myspoti.spotify.AccountPlan+/*** The "402 summary" at the top of a diagnostic report: what one report from an account whose* Connect commands Spotify refuses (402 COMMAND_FAILED, some free accounts) must settle, in one@@ -186,7 +188,8 @@ object Refusal402 {}out += "verdict" to verdictout += "account" to listOfNotNull(account ?: "unknown", installAge?.let { "app installed $it" }).joinToString(", ")- out += "ads" to "blocked by the app; ad breaks this session=$adBreaks, ad states left out=$adStatesLeftOut"+ out += "ads" to if (AccountPlan.isPremium) "none (Premium)"+ else "blocked by the app; ad breaks this session=$adBreaks, ad states left out=$adStatesLeftOut"out += "devices" to (firstCluster?.let { first -> if (first == lastCluster) first else "$first | last: $lastCluster" } ?: "no cluster seen")out += "timing" to listOfNotNull("first command ${firstCommand ?: "none"}",diff --git a/base/api-spotify/src/main/resources/bridge/player-bridge.js b/base/api-spotify/src/main/resources/bridge/player-bridge.jsindex e3c256ce..4b6599e4 100644--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js@@ -354,6 +354,9 @@// ad that came through was tools/playback_test.py's own fake.let adsLatched = false;const adsOff = () => {+ // A Premium account (the host sets window.__mspKeepAds from its AccountPlan): no ads to turn off,+ // and the page's own ad managers are left as they are.+ if (window.__mspKeepAds) return 'kept (Premium)';if (!services) return 'not ready';if (adsLatched) return 'already off';let audio = null;diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/AccountPlanTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/AccountPlanTest.ktnew file mode 100644index 00000000..bfbfc267--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/AccountPlanTest.kt@@ -0,0 +1,64 @@+package app.myspoti.spotify++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonElement+import org.junit.jupiter.api.AfterEach+import org.junit.jupiter.api.Assertions.assertEquals+import org.junit.jupiter.api.Assertions.assertFalse+import org.junit.jupiter.api.Assertions.assertNull+import org.junit.jupiter.api.Assertions.assertTrue+import org.junit.jupiter.api.Test++/** The plan of an accountAttributes answer; the fixtures are real answers with personal fields replaced. */+class AccountPlanTest {+ private fun fixture(name: String): JsonElement =+ Json.parseToJsonElement(javaClass.getResourceAsStream("/fixtures/$name")!!.bufferedReader().use { it.readText() })++ private fun answer(product: String?, ads: String?): JsonElement {+ val fields = listOfNotNull(+ product?.let { "\"product\":\"$it\"" },+ "\"attributes\":" + (ads?.let { "{\"ads\":$it}" } ?: "{}"),+ )+ return Json.parseToJsonElement("""{"data":{"me":{"account":{${fields.joinToString(",")}}}}}""")+ }++ @AfterEach fun forget() = AccountPlan.set(null)++ @Test fun `the Premium answer is Premium`() = assertEquals(true, AccountPlan.fromAnswer(fixture("account-premium.json")))++ @Test fun `the free answer is free, with its ads on`() = assertEquals(false, AccountPlan.fromAnswer(fixture("account-free.json")))++ @Test fun `a paid product with its ads off is Premium, whatever the paid plan is called`() {+ for (product in listOf("PREMIUM", "premium", "DUO", "FAMILY", "STUDENT"))+ assertEquals(true, AccountPlan.fromAnswer(answer(product, "false")), product)+ }++ @Test fun `free and open products are free, whatever their ads say`() {+ for (product in listOf("FREE", "free", "OPEN")) {+ assertEquals(false, AccountPlan.fromAnswer(answer(product, "false")), product)+ assertEquals(false, AccountPlan.fromAnswer(answer(product, "true")), product)+ }+ }++ @Test fun `a paid product that still gets ads is not Premium here`() =+ assertEquals(false, AccountPlan.fromAnswer(answer("PREMIUM", "true")))++ @Test fun `an answer that does not say is unknown`() {+ assertNull(AccountPlan.fromAnswer(answer(null, "false")))+ assertNull(AccountPlan.fromAnswer(answer("PREMIUM", null)))+ assertNull(AccountPlan.fromAnswer(answer(" ", "false")))+ assertNull(AccountPlan.fromAnswer(Json.parseToJsonElement("""{"data":{"me":{}}}""")))+ assertNull(AccountPlan.fromAnswer(Json.parseToJsonElement("""{"errors":[{"message":"x"}]}""")))+ assertNull(AccountPlan.fromAnswer(null))+ }++ @Test fun `the plan is unknown until set, and forgotten when set back`() {+ assertNull(AccountPlan.premium.value)+ assertFalse(AccountPlan.isPremium)+ AccountPlan.set(true)+ assertTrue(AccountPlan.isPremium)+ AccountPlan.set(null)+ assertNull(AccountPlan.premium.value)+ assertFalse(AccountPlan.isPremium)+ }+}diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdBlockPremiumTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdBlockPremiumTest.ktnew file mode 100644index 00000000..e66025ad--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdBlockPremiumTest.kt@@ -0,0 +1,65 @@+package app.myspoti.spotify.bridge++import app.myspoti.spotify.AccountPlan+import org.junit.jupiter.api.AfterEach+import org.junit.jupiter.api.Assertions.assertFalse+import org.junit.jupiter.api.Assertions.assertNotNull+import org.junit.jupiter.api.Assertions.assertNull+import org.junit.jupiter.api.Assertions.assertTrue+import org.junit.jupiter.api.Test++/** The ad machinery with the account's plan: unknown and free refuse and rewrite as before, Premium does not. */+class AdBlockPremiumTest {+ @AfterEach fun forget() = AccountPlan.set(null)++ private val adAudio = "https://adstudio-assets.scdn.co/mp3/d0448345e619692e0b13626ad4994d4b824f7107.mp3"+ private val adServer = "https://pubads.g.doubleclick.net/gampad/ads?x=1"+ private val adMedia = "https://s0.2mdn.net/ads/richmedia/studio/abc.mp4"+ private val tracker = "https://www.googletagmanager.com/gtm.js?id=x"++ private fun track(type: String, name: String) =+ """{"content_type":"$type","metadata":{"uri":"spotify:${type.lowercase()}:${name.replace(' ', '-')}","name":"$name"},"manifest":{}}"""++ private fun go(to: Int?) = if (to == null) "null" else """{"state_index":$to,"paused":false,"active_alias":null}"""++ private fun state(track: Int, advance: Int? = null, next: Int? = null, show: Int? = null) =+ """{"state_id":"s$track","track":$track,"transitions":{"skip_next":${go(next)},"skip_prev":null,"show_next":${go(show)},"show_prev":null,"advance":${go(advance)}}}"""++ // The song before an ad: its end goes to the ad, its skip to the song after it (as in AdQueueTest).+ private val withAd = """{"state_machine":{"state_machine_id":"m","tracks":[${track("AD", "An ad")},${track("TRACK", "Before")},${track("TRACK", "Playing")},${track("TRACK", "After")}],"states":[${state(0)},${state(1)},${state(2, advance = 0, next = 4, show = 4)},${state(2)},${state(3)}],"attributes":{}},"updated_state_ref":{"state_index":2,"paused":false}}"""++ @Test fun `unknown and free accounts have the ad hosts refused`() {+ for (plan in listOf(null, false)) {+ AccountPlan.set(plan)+ assertTrue(AdBlock.isBlocked(adAudio), "$plan")+ assertTrue(AdBlock.isBlocked(adServer), "$plan")+ assertTrue(AdBlock.isBlocked(adMedia), "$plan")+ assertTrue(AdBlock.isBlocked(tracker), "$plan")+ assertNotNull(AdBlock.withoutAds(withAd), "$plan")+ }+ }++ @Test fun `on Premium the ad hosts are let through and the trackers stay refused`() {+ AccountPlan.set(true)+ assertFalse(AdBlock.isBlocked(adAudio))+ assertFalse(AdBlock.isBlocked(adServer))+ assertFalse(AdBlock.isBlocked(adMedia))+ assertTrue(AdBlock.isBlocked(tracker))+ assertTrue(AdBlock.isBlocked("https://www.google-analytics.com/collect"))+ assertTrue(AdBlock.isBlocked("https://scorecardresearch.com/beacon.js"))+ assertTrue(AdBlock.isBlocked("https://fastly-insights.com/x.js"))+ assertFalse(AdBlock.isBlocked("https://audio-fa.scdn.co/audio/abc"))+ }++ @Test fun `on Premium an ad in the queue is not left out and is not reported as kept`() {+ AccountPlan.set(true)+ assertNull(AdBlock.withoutAds(withAd))+ assertNull(AdBlock.adAhead(withAd))+ assertNull(AdBlock.whyKept(withAd))+ }++ @Test fun `the page keeps its ad managers on Premium`() {+ // The bridge reads the flag the host sets at each injection (Bridge.inject).+ assertTrue("window.__mspKeepAds) return 'kept (Premium)';" in BridgeScript.source)+ }+}diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.ktindex 701b05e7..3de4787c 100644--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.kt+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/BridgeMessagesTest.kt@@ -86,6 +86,17 @@ class BridgeMessagesTest {}}+ @Test fun `the Premium flag reaches the page at each injection`() = runBlocking {+ val host = TellingHost { "true" }+ val bridge = Bridge(host, scope)+ host.messages.subscriptionCount.first { it > 0 }+ app.myspoti.spotify.AccountPlan.set(true)+ try { bridge.inject() } finally { app.myspoti.spotify.AccountPlan.set(null) }+ assertEquals(true, "window.__mspKeepAds = true;" in host.scripts.last())+ bridge.inject()+ assertEquals(true, "window.__mspKeepAds = false;" in host.scripts.last())+ }+@Test fun `a call is made for the page of its generation`() = runBlocking {val host = TellingHost { "true" }val bridge = Bridge(host, scope)diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/report/Refusal402Test.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/report/Refusal402Test.ktindex a1400e0f..9f0e1544 100644--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/report/Refusal402Test.kt+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/report/Refusal402Test.kt@@ -1,5 +1,6 @@package app.myspoti.spotify.report+import app.myspoti.spotify.AccountPlanimport org.junit.jupiter.api.AfterEachimport org.junit.jupiter.api.Assertions.assertEqualsimport org.junit.jupiter.api.Assertions.assertFalse@@ -15,6 +16,12 @@ class Refusal402Test {private fun summary() = Refusal402.summary("product=FREE country=ID", "7-30 d ago").toMap()+ @Test fun `on a Premium account the ads line says there is none`() {+ fresh()+ AccountPlan.set(true)+ try { assertEquals("none (Premium)", summary()["ads"]) } finally { AccountPlan.set(null) }+ }+@Test fun `a refused session reads in one screen`() {fresh()Refusal402.pageReady()diff --git a/base/api-spotify/src/test/resources/fixtures/account-free.json b/base/api-spotify/src/test/resources/fixtures/account-free.jsonnew file mode 100644index 00000000..b4114f16--- /dev/null+++ b/base/api-spotify/src/test/resources/fixtures/account-free.json@@ -0,0 +1,44 @@+{+ "data": {+ "me": {+ "account": {+ "attributes": {+ "accessTokenSignal": "<session-signal>",+ "ads": true,+ "ageAssuranceAccountWarningTimestamp": null,+ "ageAssuranceEnabledAccountSettings": false,+ "ageAssuranceState": "UNSET",+ "canInviteParentToManage": true,+ "canvasDisabled": false,+ "catalogue": "free",+ "dsaModeAvailable": false,+ "dsaModeEnabled": false,+ "estimatedAge": 0,+ "filterExplicitContent": null,+ "hasAudiobooksAvailable": true,+ "hasPodcastsAvailable": true,+ "lockCanvasDisabled": null,+ "lockMusicVideoDisabled": null,+ "lockOtherVideoDisabled": null,+ "mixingTools": "VIEW",+ "multiUserPlanCurrentSize": null,+ "multiUserPlanMemberType": null,+ "musicVideoDisabled": false,+ "onDemand": true,+ "optInTrialPremiumOnlyMarket": false,+ "otherVideoDisabled": false,+ "ratingAccess": true,+ "shouldAssureAgeContentPlayback": false,+ "shouldAssureAgeSocial": false,+ "showCreateManagedAccountInParentalControls": true,+ "showManagedAccountListInParentalControls": false+ },+ "country": "XX",+ "features": {+ "personalizedRecommendations": "PERMITTED"+ },+ "product": "FREE"+ }+ }+ }+}diff --git a/base/api-spotify/src/test/resources/fixtures/account-premium.json b/base/api-spotify/src/test/resources/fixtures/account-premium.jsonnew file mode 100644index 00000000..f13c5b8a--- /dev/null+++ b/base/api-spotify/src/test/resources/fixtures/account-premium.json@@ -0,0 +1,44 @@+{+ "data": {+ "me": {+ "account": {+ "attributes": {+ "accessTokenSignal": "<session-signal>",+ "ads": false,+ "ageAssuranceAccountWarningTimestamp": null,+ "ageAssuranceEnabledAccountSettings": false,+ "ageAssuranceState": "UNSET",+ "canInviteParentToManage": true,+ "canvasDisabled": null,+ "catalogue": "premium",+ "dsaModeAvailable": false,+ "dsaModeEnabled": false,+ "estimatedAge": 0,+ "filterExplicitContent": null,+ "hasAudiobooksAvailable": true,+ "hasPodcastsAvailable": true,+ "lockCanvasDisabled": null,+ "lockMusicVideoDisabled": null,+ "lockOtherVideoDisabled": null,+ "mixingTools": "EDIT",+ "multiUserPlanCurrentSize": null,+ "multiUserPlanMemberType": null,+ "musicVideoDisabled": null,+ "onDemand": true,+ "optInTrialPremiumOnlyMarket": false,+ "otherVideoDisabled": null,+ "ratingAccess": true,+ "shouldAssureAgeContentPlayback": false,+ "shouldAssureAgeSocial": false,+ "showCreateManagedAccountInParentalControls": true,+ "showManagedAccountListInParentalControls": false+ },+ "country": "XX",+ "features": {+ "personalizedRecommendations": "PERMITTED"+ },+ "product": "PREMIUM"+ }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/connect/RemoteAdMute.kt b/base/app/src/main/java/com/music/spotui/connect/RemoteAdMute.ktindex 0d07e612..0c564c6f 100644--- a/base/app/src/main/java/com/music/spotui/connect/RemoteAdMute.kt+++ b/base/app/src/main/java/com/music/spotui/connect/RemoteAdMute.kt@@ -2,6 +2,7 @@ package com.music.spotui.connectimport app.myspoti.host.android.Logbookimport app.myspoti.host.android.MyspotiRuntime+import app.myspoti.spotify.AccountPlanimport com.music.spotui.di.Graphimport com.music.spotui.di.SongPlayerimport kotlinx.coroutines.CoroutineScope@@ -113,6 +114,8 @@ object RemoteAdMute {}private suspend fun onChange(ad: Boolean, elsewhere: Boolean) {+ // Premium: Spotify sends no ads to this account, so nothing is muted here (AccountPlan).+ if (AccountPlan.isPremium) returnval api = MyspotiRuntime.apimuted?.let { m ->if (ad) { holdUntilTooLong(m); return }diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.ktindex dd88089f..bea20ade 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt@@ -2,6 +2,7 @@ package app.myspoti.host.androidimport android.content.Contextimport app.myspoti.api.MyspotiApi+import app.myspoti.spotify.AccountPlanimport app.myspoti.spotify.SpotifyApiimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers@@ -22,6 +23,9 @@ object MyspotiRuntime {val api: MyspotiApi get() = spotifyval scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)+ /** A plan not known yet is asked again after this (a failed or unclear answer). */+ private const val PLAN_ASK_GAP_MS = 60_000L+val isStarted: Boolean get() = ::host.isInitializedval loginRequired: StateFlow<Boolean> get() = host.loginRequired@@ -54,7 +58,8 @@ object MyspotiRuntime {// changes is logged when it changes, not once every 10 s whether or not anything happened.scope.launch {var last = ""- var planLogged = false+ // When the account's plan was last asked for (AccountPlan), so a failed or unknown answer is asked again later.+ var planAskedAt = 0L// A login page or an anonymous session seen in this run: the sign-in that follows is new.var sawSignedOut = false// A page that loaded but whose player never became ready (no bridge, a script that@@ -74,20 +79,25 @@ object MyspotiRuntime {notReadyWait = (notReadyWait * 2).coerceAtMost(600_000L)host.reload()}- // Once per signed-in session: the account's plan, the first thing a refused play- // (402) needs. No name, no id — only what decides what the account may play.- if (!planLogged && spotify.ready.value && runCatching { isSignedIn() }.getOrDefault(false)) {- planLogged = true+ // The account's plan (AccountPlan: Premium turns the ad machinery off), asked while it is not+ // known, once the page is signed in; forgotten at a sign-out (below). Its log line is the first+ // thing a refused play (402) needs. No name, no id, only what decides what the account may play.+ if (spotify.ready.value && runCatching { isSignedIn() }.getOrDefault(false)) {host.noteSignedIn(fresh = sawSignedOut)- runCatching {- val a = spotify.raw.gql("accountAttributes", kotlinx.serialization.json.buildJsonObject { })- .let { (it as kotlinx.serialization.json.JsonObject)["data"] as kotlinx.serialization.json.JsonObject }- .let { (it["me"] as kotlinx.serialization.json.JsonObject)["account"] as kotlinx.serialization.json.JsonObject }- val attrs = a["attributes"] as? kotlinx.serialization.json.JsonObject- fun v(o: kotlinx.serialization.json.JsonObject?, k: String) = (o?.get(k) as? kotlinx.serialization.json.JsonPrimitive)?.content- Logbook.log("account: product=${v(a, "product")} country=${v(a, "country")} catalogue=${v(attrs, "catalogue")} onDemand=${v(attrs, "onDemand")} ads=${v(attrs, "ads")}")- Logbook.fact("account", "product=${v(a, "product")} country=${v(a, "country")} catalogue=${v(attrs, "catalogue")} onDemand=${v(attrs, "onDemand")} ads=${v(attrs, "ads")}")- }.onFailure { planLogged = false }+ val now = android.os.SystemClock.elapsedRealtime()+ if (AccountPlan.premium.value == null && now - planAskedAt >= PLAN_ASK_GAP_MS) {+ planAskedAt = now+ runCatching {+ val answer = spotify.raw.gql("accountAttributes", kotlinx.serialization.json.buildJsonObject { })+ val a = ((answer as kotlinx.serialization.json.JsonObject)["data"] as kotlinx.serialization.json.JsonObject)+ .let { (it["me"] as kotlinx.serialization.json.JsonObject)["account"] as kotlinx.serialization.json.JsonObject }+ val attrs = a["attributes"] as? kotlinx.serialization.json.JsonObject+ fun v(o: kotlinx.serialization.json.JsonObject?, k: String) = (o?.get(k) as? kotlinx.serialization.json.JsonPrimitive)?.content+ AccountPlan.set(AccountPlan.fromAnswer(answer))+ Logbook.log("account: product=${v(a, "product")} country=${v(a, "country")} catalogue=${v(attrs, "catalogue")} onDemand=${v(attrs, "onDemand")} ads=${v(attrs, "ads")}")+ Logbook.fact("account", "product=${v(a, "product")} country=${v(a, "country")} catalogue=${v(attrs, "catalogue")} onDemand=${v(attrs, "onDemand")} ads=${v(attrs, "ads")}")+ }+ }}val s = spotify.player.state.value// "login" alone said nothing (it only meant "the page is on a login URL"): a bug@@ -97,7 +107,11 @@ object MyspotiRuntime {// The token in hand: a fresh one every 10 s held every request behind the page's answer.else -> when (spotify.signedInHint()) { true -> "signed-in"; false -> "anonymous"; null -> "unknown" }}- if (session == "login-page" || session == "anonymous") sawSignedOut = true+ if (session == "login-page" || session == "anonymous") {+ sawSignedOut = true+ // Signed out: the plan of the account that left is forgotten (a new sign-in reads its own).+ AccountPlan.set(null)+ }val line = "status ready=${spotify.ready.value} session=$session " +"track=${s?.item?.name} paused=${s?.isPaused} buffering=${s?.isBuffering} url=${host.url.value.take(60)}"if (line != last) {