Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
Let the account be the channel you picked
Lelonio882bff0feb17
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeAccount.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeAccount.ktindex 114a5a6..dde2e1f 100644--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeAccount.kt+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeAccount.kt@@ -97,14 +97,50 @@ class YouTubeAccount(context: Context) {* channel the request is for, the second which library to sync it against,* and a mismatched pair reads the right name over the wrong music.*/- fun useChannel(channel: YouTubeChannel) {+ suspend fun useChannel(channel: YouTubeChannel): Boolean {+ val previousPageId = prefs.getString(KEY_PAGE_ID, null)+ val previousSyncId = prefs.getString(KEY_DATA_SYNC_ID, null)+ val previousName = prefs.getString(KEY_NAME, null)++ // Lengths, not values: these two are what let a request act as this+ // channel, and a log is not the place for them. Whether they are there+ // at all is the whole question when a switch is refused.+ android.util.Log.i(+ TAG,+ "switching channel: pageId=${channel.pageId?.length ?: 0} chars," ++ " dataSyncId=${channel.dataSyncId?.length ?: 0} chars",+ )++ applyChannel(channel.pageId, channel.dataSyncId.orEmpty(), channel.name)++ // Tried before it is believed. The two tokens have to be the pair+ // Google issued together, and a mismatched one is refused — which used+ // to leave the app claiming the session had expired, when the session+ // was fine and it was this switch that was not.+ val attempt = YouTube.accountInfo()+ val worked = attempt.isSuccess+ if (!worked) {+ // The message, not just the outcome: "refused" covers a wrong token+ // pair, a client that does not accept the header, and a session+ // that was already gone, and those want three different answers.+ android.util.Log.w(+ TAG,+ "channel refused: ${attempt.exceptionOrNull()?.message?.take(400)}",+ )+ android.util.Log.w(TAG, "channel refused, going back to the previous one")+ applyChannel(previousPageId, previousSyncId.orEmpty(), previousName.orEmpty())+ }+ return worked+ }++ private fun applyChannel(pageId: String?, dataSyncId: String, name: String) {prefs.edit()- .putString(KEY_PAGE_ID, channel.pageId)- .putString(KEY_DATA_SYNC_ID, channel.dataSyncId.orEmpty())- .putString(KEY_NAME, channel.name)+ .putString(KEY_PAGE_ID, pageId)+ .putString(KEY_DATA_SYNC_ID, dataSyncId)+ .putString(KEY_NAME, name).apply()- _pageId.value = channel.pageId- _accountName.value = channel.name+ _pageId.value = pageId+ _accountName.value = nameapplyToInnerTube()}@@ -141,12 +177,16 @@ class YouTubeAccount(context: Context) {suspend fun revalidate() {if (!isSignedIn) return- webViewCookie()?.let { fresh ->- if (fresh != prefs.getString(KEY_COOKIE, null)) {- prefs.edit().putString(KEY_COOKIE, fresh).apply()- applyToInnerTube()- }- }+ // The cookie is left exactly as the sign-in left it.+ //+ // This used to be copied from the web view's store on every check, on+ // the theory that Google renews a session there and the saved copy goes+ // stale. It cost this account its session twice: the web view collects+ // cookies from any page of music.youtube.com it loads, and those are+ // not the signed-in session — the first time they lacked SAPISID+ // entirely, the second they carried one that answered 401. A saved+ // session that Google still accepts must not be replaced by a guess+ // about a better one.if (YouTube.visitorData.isNullOrBlank()) {YouTube.visitorData()@@ -176,17 +216,6 @@ class YouTubeAccount(context: Context) {}}- /**- * What the web view holds for `music.youtube.com` right now.- *- * That store is the one Google writes to, and it survives restarts, so it- * is where a renewed cookie shows up first.- */- private fun webViewCookie(): String? =- runCatching { android.webkit.CookieManager.getInstance().getCookie(MUSIC_URL) }- .getOrNull()- ?.takeIf { it.isNotBlank() }-fun signOut() {prefs.edit().clear().apply()_accountName.value = nulldiff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.ktindex 3b70504..8334ec4 100644--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt@@ -605,8 +605,11 @@ private fun YouTubeAccountSection(onSignIn: () -> Unit, onChannelChange: () -> U?: channel.name,selected = channel.pageId == pageId,) {- account.useChannel(channel)- onChannelChange()+ scope.launch {+ // Only a switch that Google accepted is worth+ // reloading a library for.+ if (account.useChannel(channel)) onChannelChange()+ }}}}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt b/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.ktindex 2aa1ade..7586f85 100644--- a/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt+++ b/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt@@ -174,7 +174,17 @@ class InnerTube {// Vendored: the channel within that account, where one was// chosen. Absent for the personal channel, which is what// the account answers as by default.- pageId?.takeIf { it.isNotBlank() }?.let { append("X-Goog-PageId", it) }+ //+ // The two travel together. `X-Goog-PageId` says which+ // channel to act as, and `X-Goog-AuthUser` says which of+ // the signed-in accounts that channel belongs to — sent on+ // its own, the first was answered with 401 and the words+ // "missing required authentication credential", which reads+ // as a dead session and is really an incomplete request.+ pageId?.takeIf { it.isNotBlank() }?.let {+ append("X-Goog-PageId", it)+ append("X-Goog-AuthUser", "0")+ }}}}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt b/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.ktindex 8ea66c2..eb05509 100644--- a/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt+++ b/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt@@ -83,6 +83,7 @@ import kotlinx.serialization.encodeToStringimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.decodeFromJsonElementimport kotlinx.serialization.json.jsonArrayimport kotlinx.serialization.json.jsonPrimitiveimport timber.log.Timber@@ -3363,22 +3364,27 @@ object YouTube {*/suspend fun accounts(): Result<List<YouTubeChannel>> =runCatching {- val raw = innerTube.accountsList(WEB_REMIX).bodyAsText()- val parsed = Json { ignoreUnknownKeys = true }- .decodeFromString<AccountsListResponse>(raw)- val channels = parsed- .contents- ?.accountSectionListRenderer- ?.contents- .orEmpty()- .mapNotNull { it.accountItemSectionRenderer }- .flatMap { it.contents.orEmpty() }- .mapNotNull { it.accountItem }+ val raw = innerTube.accountsList(YouTubeClient.WEB_ACCOUNTS).bodyAsText()+ // Found wherever they are, rather than walked down a path.+ //+ // Two attempts at that path both missed: the response is a popup+ // menu whose nesting differs between accounts, and each wrong guess+ // cost a build, an install and someone opening a settings page. The+ // items themselves are unambiguous — an `accountItem` is an account+ // and nothing else is called that — so the whole document is+ // searched for them and the shape around them stops mattering.+ val channels = accountItems(Json.parseToJsonElement(raw))+ .mapNotNull { item ->+ runCatching {+ Json { ignoreUnknownKeys = true }+ .decodeFromJsonElement<AccountsListResponse.AccountItem>(item)+ }.getOrNull()+ }.mapNotNull { item ->val tokens = item.serviceEndpoint?.selectActiveIdentityEndpoint?.supportedTokensYouTubeChannel(- name = item.accountName?.runs?.firstOrNull()?.text ?: return@mapNotNull null,- handle = item.accountByline?.runs?.firstOrNull()?.text,+ name = item.accountName?.text ?: return@mapNotNull null,+ handle = item.accountByline?.text,thumbnailUrl = item.accountPhoto?.thumbnails?.lastOrNull()?.url,pageId = tokens?.firstNotNullOfOrNull { it.pageIdToken?.pageId },dataSyncId = tokens?.firstNotNullOfOrNull { it.datasyncIdToken?.datasyncIdToken },@@ -3386,20 +3392,37 @@ object YouTube {)}if (channels.isEmpty()) {- // Which renderers came back, so a response shaped differently- // from the one this was written against can be read from a log- // rather than guessed at. Names only: the values are the- // account's own.- val renderers = Regex("\"([A-Za-z]+Renderer)\"")- .findAll(raw)- .map { it.groupValues[1] }- .distinct()- .joinToString(", ")- Timber.d("accounts(): none parsed; ${raw.length} bytes, renderers: $renderers")+ Timber.d("accounts(): the response listed no channels")}channels}+ /**+ * Every account in a response, found by what it holds rather than by name.+ *+ * The document nests them differently from one client to the next, and the+ * key they sit under is not `accountItem` here at all — the response+ * carries three of them and a search by that name found none. What does not+ * vary is the shape of an account: a name, and an endpoint that selects the+ * identity. Nothing else in the document has both, so that pair is what+ * identifies one.+ */+ private fun accountItems(+ element: kotlinx.serialization.json.JsonElement,+ ): List<kotlinx.serialization.json.JsonElement> = buildList {+ when (element) {+ is kotlinx.serialization.json.JsonObject -> {+ val looksLikeAccount = element.containsKey("accountName") &&+ element.containsKey("serviceEndpoint")+ if (looksLikeAccount) add(element)+ element.values.forEach { addAll(accountItems(it)) }+ }++ is kotlinx.serialization.json.JsonArray -> element.forEach { addAll(accountItems(it)) }+ else -> Unit+ }+ }+/** Which channel of the account calls are made as; see [accounts]. */var pageId: String?get() = innerTube.pageIddiff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeClient.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeClient.ktindex 8f46922..75e8039 100644--- a/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeClient.kt+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeClient.kt@@ -59,6 +59,24 @@ data class YouTubeClient(userAgent = USER_AGENT_WEB,)+ /**+ * Vendored addition: youtube.com's own client, with the session sent.+ *+ * Only for `account/accounts_list`. Asked as WEB_REMIX — YouTube Music+ * — that endpoint answers with the account sections present but empty:+ * the identities belong to YouTube proper, and the music client is not+ * shown them. Plain [WEB] cannot be used instead because it does not+ * carry a login, so the request would be anonymous and answer for+ * nobody.+ */+ val WEB_ACCOUNTS = YouTubeClient(+ clientName = "WEB",+ clientVersion = "2.20260114.08.00",+ clientId = "1",+ userAgent = USER_AGENT_WEB,+ loginSupported = true,+ )+val WEB_REMIX = YouTubeClient(clientName = "WEB_REMIX",clientVersion = "1.20260114.03.00",diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AccountsListResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AccountsListResponse.ktindex 791f99e..c6d756b 100644--- a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AccountsListResponse.kt+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AccountsListResponse.kt@@ -1,6 +1,5 @@package com.metrolist.innertube.models.response-import com.metrolist.innertube.models.Runsimport com.metrolist.innertube.models.Thumbnailsimport kotlinx.serialization.Serializable@@ -13,55 +12,100 @@ import kotlinx.serialization.Serializable* the active one, so a session opened on the wrong identity showed the wrong* library with no way to change it.*- * Each entry carries the tokens that select it: a page id for a brand channel,- * and the datasync id that tells the rest of the API which library to read.+ * The shape is the account menu's, not a page's: `account/accounts_list`+ * answers with an action that opens a popup, and the accounts are sections+ * inside it. Read off a real response — the first attempt at this assumed a+ * `contents` at the root and failed before it could say so.+ *+ * Every field is optional. This is read for what it happens to carry, and a+ * branch that is missing on some accounts must not fail the whole parse.*/@Serializabledata class AccountsListResponse(- val contents: Contents?,+ val actions: List<Action>? = null,) {@Serializable- data class Contents(- val accountSectionListRenderer: AccountSectionListRenderer?,+ data class Action(+ val openPopupAction: OpenPopupAction? = null,+ )++ @Serializable+ data class OpenPopupAction(+ val popup: Popup? = null,+ )++ @Serializable+ data class Popup(+ val multiPageMenuRenderer: MultiPageMenuRenderer? = null,+ )++ @Serializable+ data class MultiPageMenuRenderer(+ val sections: List<Section>? = null,+ )++ @Serializable+ data class Section(+ val accountSectionListRenderer: AccountSectionListRenderer? = null,)@Serializabledata class AccountSectionListRenderer(- val contents: List<Content>?,- ) {- @Serializable- data class Content(- val accountItemSectionRenderer: AccountItemSectionRenderer?,- )- }+ val contents: List<SectionContent>? = null,+ )++ @Serializable+ data class SectionContent(+ val accountItemSectionRenderer: AccountItemSectionRenderer? = null,+ )@Serializabledata class AccountItemSectionRenderer(- val contents: List<Content>?,+ val contents: List<ItemContent>? = null,+ )++ @Serializable+ data class ItemContent(+ val accountItem: AccountItem? = null,+ )++ /**+ * A piece of text, written either way.+ *+ * YouTube says the same thing in two shapes — `simpleText` for a plain+ * string, `runs` for one built out of segments — and this endpoint uses the+ * first while most of the module uses the second. Declaring these as `Runs`+ * is what made every account fail to decode, quietly, leaving a list that+ * looked empty when the response held three.+ */+ @Serializable+ data class Label(+ val simpleText: String? = null,+ val runs: List<Run>? = null,) {- @Serializable- data class Content(- val accountItem: AccountItem?,- )+ val text: String? get() = simpleText ?: runs?.firstOrNull()?.text}+ @Serializable+ data class Run(val text: String? = null)+@Serializabledata class AccountItem(- val accountName: Runs?,- val accountByline: Runs?,- val accountPhoto: Thumbnails?,+ val accountName: Label? = null,+ val accountByline: Label? = null,+ val accountPhoto: Thumbnails? = null,val isSelected: Boolean = false,- val serviceEndpoint: ServiceEndpoint?,+ val serviceEndpoint: ServiceEndpoint? = null,)@Serializabledata class ServiceEndpoint(- val selectActiveIdentityEndpoint: SelectActiveIdentityEndpoint?,+ val selectActiveIdentityEndpoint: SelectActiveIdentityEndpoint? = null,)@Serializabledata class SelectActiveIdentityEndpoint(- val supportedTokens: List<SupportedToken>?,+ val supportedTokens: List<SupportedToken>? = null,)@Serializable