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
Keep a Google sign-in that works, and say so when one does not
Lelonio49054e1b133f
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 00f3321..a3c2bfc 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@@ -150,6 +150,9 @@ class YouTubeAccount(context: Context) {applyToInnerTube()}+ /** Hands the stored session back to InnerTube, after a sign-in that was not kept. */+ fun reapply() = applyToInnerTube()+fun save(cookie: String, visitorData: String, dataSyncId: String, name: String) {prefs.edit().putString(KEY_COOKIE, cookie)diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeLoginScreen.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeLoginScreen.ktindex 5614b96..c0a9f74 100644--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeLoginScreen.kt+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeLoginScreen.kt@@ -2,7 +2,6 @@ package dev.lelonio.square.backend.youtubeimport android.annotation.SuppressLintimport android.webkit.CookieManager-import android.webkit.JavascriptInterfaceimport android.webkit.WebViewimport android.webkit.WebViewClientimport androidx.activity.compose.BackHandler@@ -43,14 +42,14 @@ fun YouTubeLoginScreen(account: YouTubeAccount, onDone: () -> Unit) {var completing by remember { mutableStateOf(false) }var webView: WebView? = null- // Read out of the page rather than out of the cookie: they are not cookie- // values at all, they live in the page's own config object, and without- // them a Google account with several YouTube channels resolves to the- // wrong one.- var visitorData by remember { mutableStateOf("") }- var dataSyncId by remember { mutableStateOf("") }+ val context = androidx.compose.ui.platform.LocalContext.current- fun complete() {+ // [visitorData] and [dataSyncId] are read out of the page rather than out+ // of the cookie: they are not cookie values at all, they live in the+ // page's own config object, and without them a Google account with several+ // YouTube channels resolves to the wrong one. Handed in once the page has+ // answered; see onPageFinished.+ fun complete(visitorData: String = "", dataSyncId: String = "") {if (completing) returnval cookie = CookieManager.getInstance().getCookie(MUSIC_URL).orEmpty()// Backing out before signing in is an ordinary outcome, not a failure.@@ -60,35 +59,61 @@ fun YouTubeLoginScreen(account: YouTubeAccount, onDone: () -> Unit) {}completing = true- val capturedVisitorData = visitorData- val capturedDataSyncId = dataSyncIdscope.launch {YouTube.cookie = cookie- YouTube.visitorData = capturedVisitorData- YouTube.dataSyncId = capturedDataSyncId+ YouTube.visitorData = visitorData+ YouTube.dataSyncId = dataSyncId++ fun keep(name: String) {+ webView?.apply {+ stopLoading()+ clearHistory()+ }+ account.save(+ cookie = cookie,+ visitorData = visitorData,+ dataSyncId = dataSyncId,+ name = name,+ )+ onDone()+ }// The session is only worth keeping if it can actually read the// account. Asking now turns a cookie that will never work into a// login that visibly did not happen, rather than a library that is// mysteriously empty later.YouTube.accountInfo()- .onSuccess { info ->- webView?.apply {- stopLoading()- clearHistory()- }- account.save(- cookie = cookie,- visitorData = capturedVisitorData,- dataSyncId = capturedDataSyncId,- name = info.name,- )- onDone()- }+ .onSuccess { info -> keep(info.name) }.onFailure { error ->- android.util.Log.e(TAG, "youtube login failed: $error", error)+ val message = error.message.orEmpty()+ val refused = "401" in message || "403" in message+ android.util.Log.e(+ TAG,+ "youtube login check failed (refused=$refused, sapisid=${"SAPISID=" in cookie}, " ++ "visitorData=${visitorData.isNotEmpty()}, dataSyncId=${dataSyncId.isNotEmpty()}): $error",+ error,+ )+ // Only a refusal says the session does not work. Anything+ // else is the menu this asks coming back in a shape it+ // does not read: an account with no YouTube channel has+ // no header in it at all. Turned away for that, people+ // signed in, were sent back signed out, and the next try+ // found Google already signed in and did the same.+ if (!refused && "SAPISID=" in cookie) {+ val name = YouTube.accounts().getOrNull()?.firstOrNull()?.name+ keep(name ?: context.getString(dev.lelonio.square.R.string.youtube_account_fallback_name))+ return@onFailure+ }+ // Put back what was there, or the refused cookie went on+ // being sent for the rest of the run.+ account.reapply()completing = false+ android.widget.Toast.makeText(+ context,+ context.getString(dev.lelonio.square.R.string.youtube_sign_in_failed),+ android.widget.Toast.LENGTH_LONG,+ ).show()onDone()}}@@ -101,13 +126,6 @@ fun YouTubeLoginScreen(account: YouTubeAccount, onDone: () -> Unit) {WebView(context).apply {webViewClient = object : WebViewClient() {override fun onPageFinished(view: WebView, url: String?) {- view.loadUrl(- "javascript:Square.visitorData(window.yt.config_.VISITOR_DATA)",- )- view.loadUrl(- "javascript:Square.dataSyncId(window.yt.config_.DATASYNC_ID)",- )-// Landing back on music.youtube.com with a cookie is// what "signed in" looks like: Google's flow can take// any number of pages — password, 2FA, account@@ -116,26 +134,26 @@ fun YouTubeLoginScreen(account: YouTubeAccount, onDone: () -> Unit) {val signedIn = url?.contains("music.youtube.com") == true &&CookieManager.getInstance().getCookie(MUSIC_URL).orEmpty().isNotBlank()- if (signedIn && !completing) complete()+ if (!signedIn || completing) return+ // The page's ids first, then the check. Read+ // through a bridge and checked straight after,+ // the check always went before the page had+ // answered, with both of them empty.+ view.evaluateJavascript(+ "(function(){try{var c=window.yt.config_;" ++ "return [c.VISITOR_DATA||'',c.DATASYNC_ID||''];}catch(e){return ['',''];}})()",+ ) { result ->+ val ids = runCatching { org.json.JSONArray(result) }.getOrNull()+ complete(+ visitorData = ids?.optString(0).orEmpty(),+ // Two ids separated by `||`; the first is+ // this account's.+ dataSyncId = ids?.optString(1).orEmpty().substringBefore("||"),+ )+ }}}settings.javaScriptEnabled = true- addJavascriptInterface(- object {- @JavascriptInterface- fun visitorData(value: String?) {- if (value != null) visitorData = value- }-- @JavascriptInterface- fun dataSyncId(value: String?) {- // Two ids separated by `||`; the first is this- // account's.- if (value != null) dataSyncId = value.substringBefore("||")- }- },- "Square",- )webView = thisloadUrl(SIGN_IN_URL)}diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xmlindex 0d632b4..407327c 100644--- a/app/src/main/res/values-de/strings.xml+++ b/app/src/main/res/values-de/strings.xml@@ -596,4 +596,6 @@<string name="lyrics_preferred_title">Songtext-Quelle</string><string name="lyrics_preferred_auto">Automatisch (die beste)</string><string name="lyrics_preferred_note">Es werden nur Songtexte der gewählten Quelle angezeigt: Hat sie keinen für den Song, wird keiner angezeigt. Automatisch wählt die beste verfügbare.</string>+ <string name="youtube_account_fallback_name">Google-Konto</string>+ <string name="youtube_sign_in_failed">Anmeldung bei YouTube Music fehlgeschlagen. Versuch es noch einmal; wenn es wieder passiert, speichere einen Bericht unter Einstellungen → Info.</string></resources>diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xmlindex e557f1a..e3bae35 100644--- a/app/src/main/res/values-es/strings.xml+++ b/app/src/main/res/values-es/strings.xml@@ -602,4 +602,6 @@<string name="lyrics_preferred_title">Fuente de letras</string><string name="lyrics_preferred_auto">Automática (la mejor)</string><string name="lyrics_preferred_note">Solo se muestran letras de la fuente elegida: si no tiene la de la canción, no se muestra ninguna. Automática elige la mejor disponible.</string>+ <string name="youtube_account_fallback_name">Cuenta de Google</string>+ <string name="youtube_sign_in_failed">No se pudo iniciar sesión en YouTube Music. Inténtalo de nuevo; si vuelve a pasar, guarda un informe en Ajustes → Información.</string></resources>diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xmlindex 4d2b66f..3af2ebc 100644--- a/app/src/main/res/values-fr/strings.xml+++ b/app/src/main/res/values-fr/strings.xml@@ -596,4 +596,6 @@<string name="lyrics_preferred_title">Source des paroles</string><string name="lyrics_preferred_auto">Automatique (la meilleure)</string><string name="lyrics_preferred_note">Seules les paroles de la source choisie sont affichées : si elle n’en a pas pour le morceau, rien n’est affiché. Automatique choisit la meilleure disponible.</string>+ <string name="youtube_account_fallback_name">Compte Google</string>+ <string name="youtube_sign_in_failed">Impossible de se connecter à YouTube Music. Réessayez ; si cela se reproduit, enregistrez un rapport dans Réglages → À propos.</string></resources>diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xmlindex a9fbeb6..4d84b3f 100644--- a/app/src/main/res/values-hi/strings.xml+++ b/app/src/main/res/values-hi/strings.xml@@ -611,4 +611,6 @@<string name="lyrics_preferred_title">बोल का स्रोत</string><string name="lyrics_preferred_auto">स्वचालित (सबसे अच्छा)</string><string name="lyrics_preferred_note">सिर्फ़ चुने गए स्रोत के बोल दिखाए जाते हैं: अगर उसके पास गाने के बोल नहीं हैं, तो कुछ नहीं दिखेगा। स्वचालित सबसे अच्छा उपलब्ध स्रोत चुनता है।</string>+ <string name="youtube_account_fallback_name">Google खाता</string>+ <string name="youtube_sign_in_failed">YouTube Music में साइन इन नहीं हो सका। फिर से कोशिश करें; अगर फिर भी हो, तो सेटिंग → परिचय में रिपोर्ट सेव करें।</string></resources>diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xmlindex 7acc2b3..acda56e 100644--- a/app/src/main/res/values-it/strings.xml+++ b/app/src/main/res/values-it/strings.xml@@ -633,4 +633,6 @@<string name="lyrics_preferred_title">Fonte dei testi</string><string name="lyrics_preferred_auto">Automatica (la migliore)</string><string name="lyrics_preferred_note">Vengono mostrati solo i testi della fonte scelta: se non ha il testo del brano, non viene mostrato nulla. Automatica sceglie la migliore disponibile.</string>+ <string name="youtube_account_fallback_name">Account Google</string>+ <string name="youtube_sign_in_failed">Accesso a YouTube Music non riuscito. Riprova; se succede ancora, salva un report in Impostazioni → Informazioni.</string></resources>diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xmlindex e85ee59..bd95404 100644--- a/app/src/main/res/values-ja/strings.xml+++ b/app/src/main/res/values-ja/strings.xml@@ -652,5 +652,7 @@<string name="lyrics_preferred_title">歌詞のソース</string><string name="lyrics_preferred_auto">自動(最適なもの)</string><string name="lyrics_preferred_note">選んだソースの歌詞だけが表示されます。その曲の歌詞がなければ何も表示されません。自動では最適なソースが選ばれます。</string>+ <string name="youtube_account_fallback_name">Google アカウント</string>+ <string name="youtube_sign_in_failed">YouTube Music にログインできませんでした。もう一度お試しください。繰り返す場合は 設定 → アプリについて からレポートを保存してください。</string></resources>diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xmlindex 4796543..0511642 100644--- a/app/src/main/res/values-ko/strings.xml+++ b/app/src/main/res/values-ko/strings.xml@@ -620,4 +620,6 @@<string name="lyrics_preferred_title">가사 출처</string><string name="lyrics_preferred_auto">자동 (가장 좋은 출처)</string><string name="lyrics_preferred_note">선택한 출처의 가사만 표시됩니다. 그 출처에 노래 가사가 없으면 아무것도 표시되지 않습니다. 자동은 가장 좋은 출처를 고릅니다.</string>+ <string name="youtube_account_fallback_name">Google 계정</string>+ <string name="youtube_sign_in_failed">YouTube Music에 로그인하지 못했습니다. 다시 시도해 보고, 계속되면 설정 → 정보에서 보고서를 저장하세요.</string></resources>diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xmlindex b8327bc..2356fdc 100644--- a/app/src/main/res/values-pt/strings.xml+++ b/app/src/main/res/values-pt/strings.xml@@ -596,4 +596,6 @@<string name="lyrics_preferred_title">Fonte das letras</string><string name="lyrics_preferred_auto">Automática (a melhor)</string><string name="lyrics_preferred_note">Só são mostradas letras da fonte escolhida: se ela não tiver a da música, nenhuma é mostrada. Automática escolhe a melhor disponível.</string>+ <string name="youtube_account_fallback_name">Conta Google</string>+ <string name="youtube_sign_in_failed">Não foi possível entrar no YouTube Music. Tente de novo; se continuar, salve um relatório em Configurações → Sobre.</string></resources>diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xmlindex 9e1db7c..b96e32f 100644--- a/app/src/main/res/values-ru/strings.xml+++ b/app/src/main/res/values-ru/strings.xml@@ -625,4 +625,6 @@<string name="lyrics_preferred_title">Источник текстов</string><string name="lyrics_preferred_auto">Автоматически (лучший)</string><string name="lyrics_preferred_note">Показываются только тексты из выбранного источника: если у него нет текста песни, ничего не показывается. Автоматически выбирается лучший из доступных.</string>+ <string name="youtube_account_fallback_name">Аккаунт Google</string>+ <string name="youtube_sign_in_failed">Не удалось войти в YouTube Music. Попробуйте ещё раз; если повторится, сохраните отчёт в Настройки → О приложении.</string></resources>diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xmlindex 383c6f0..2f7c5b3 100644--- a/app/src/main/res/values-tr/strings.xml+++ b/app/src/main/res/values-tr/strings.xml@@ -609,4 +609,6 @@<string name="lyrics_preferred_title">Şarkı sözü kaynağı</string><string name="lyrics_preferred_auto">Otomatik (en iyisi)</string><string name="lyrics_preferred_note">Yalnızca seçilen kaynağın sözleri gösterilir: şarkı için sözü yoksa hiçbir şey gösterilmez. Otomatik, mevcut en iyisini seçer.</string>+ <string name="youtube_account_fallback_name">Google hesabı</string>+ <string name="youtube_sign_in_failed">YouTube Music\'e giriş yapılamadı. Tekrar dene; yine olursa Ayarlar → Hakkında\'dan bir rapor kaydet.</string></resources>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex cc2940b..10663b7 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -660,4 +660,6 @@<string name="lyrics_preferred_title">Lyrics source</string><string name="lyrics_preferred_auto">Automatic (best available)</string><string name="lyrics_preferred_note">Only lyrics from the chosen source are shown: if it has none for the song, no lyrics are shown. Automatic picks the best available.</string>+ <string name="youtube_account_fallback_name">Google account</string>+ <string name="youtube_sign_in_failed">Couldn\'t sign in to YouTube Music. Try again, and if it keeps happening, save a report in Settings → About.</string></resources>diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeClient.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeClient.ktindex 75e8039..6e6385a 100644--- a/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeClient.kt+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeClient.kt@@ -41,7 +41,8 @@ data class YouTubeClient(visitorData = visitorData),user = Context.User(- onBehalfOfUser = if (loginSupported) dataSyncId else null+ // Vendored: left out when there is none, rather than sent empty.+ onBehalfOfUser = if (loginSupported) dataSyncId?.takeIf { it.isNotBlank() } else null),)