Skip to content

Native Android client for Spotify, built with Jetpack Compose

Sign-in: the login page is shown once it has content, a page that stays blank, errors or never answers in 25 s shows Try again (clean cookies and storage), the wait for the session counts real time (one minute, not up to 40) and ends the connecting screen when it succeeds, a player that never got ready shows the error instead of looping back to the login, a renderer crash during sign-in reloads the login, cookies are written to disk once signed in and when the app goes to the background, the login page comes back in front after the activity is recreated, login pages told apart by host and path, and the login decisions written to the diagnostic log

kota-zo80aaaeac79e7
diff --git a/base/app/src/main/java/app/myspoti/MainActivity.kt b/base/app/src/main/java/app/myspoti/MainActivity.kt
index 8ed65227..319194c7 100644
--- a/base/app/src/main/java/app/myspoti/MainActivity.kt
+++ b/base/app/src/main/java/app/myspoti/MainActivity.kt
@@ -15,14 +15,38 @@ import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.systemBarsPadding
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
+import app.myspoti.engine.R
+import app.myspoti.host.android.LoginLoad
+import app.myspoti.host.android.Logbook
import app.myspoti.host.android.MyspotiRuntime
+import app.myspoti.host.android.SessionWait
import com.music.spotui.App
import com.music.spotui.di.AutoBrowser
import com.music.spotui.ui.screens.WelcomeScreen
@@ -31,9 +55,6 @@ import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
-/** Logcat tag, the host's own: playback and session land in one stream (`adb logcat -s Myspoti`). */
-private const val LOG = "Myspoti"
-
/**
* How long the player page is given to prove the session (a non-anonymous token) once it comes back.
* The sign-in page stays in front while this runs — the address alone is never taken for a session —
@@ -56,6 +77,8 @@ class MainActivity : AppCompatActivity() {
private var connecting by mutableStateOf(false)
/** A pending wait for the session to prove itself after the login page came back. */
private var loginWait: kotlinx.coroutines.Job? = null
+ /** The wait ended with a player that never became ready: an error with Try again, not another spinner. */
+ private var loginProblem by mutableStateOf(false)
/** The one-time setup screen (permissions, battery) after signing in. */
private var setupNeeded by mutableStateOf(false)
/** In the picture-in-picture window: only the music video is drawn. */
@@ -102,6 +125,18 @@ class MainActivity : AppCompatActivity() {
connecting -> ConnectingScreen()
else -> WelcomeScreen(onLogin = { showLogin() })
}
+ // The sign-in page opening (the app's own screen, never a white page) or not coming (an
+ // error with Try again, never a page that stays blank): over whatever is under it.
+ if (showingLogin) {
+ val load by MyspotiRuntime.host.loginLoad.collectAsState()
+ when {
+ load == LoginLoad.FAILED || loginProblem -> LoginProblemScreen(onRetry = {
+ if (load == LoginLoad.FAILED) MyspotiRuntime.host.retryLogin()
+ else { loginProblem = false; MyspotiRuntime.host.openLogin() }
+ })
+ load == LoginLoad.LOADING -> ConnectingScreen()
+ }
+ }
// Existing users, once, right after the update: the new look, live.
if (signedIn && !setupNeeded && !showLook && !showingLogin && !inPip && !lookOffered) {
if (com.music.spotui.data.preferences.LookPref.look == com.music.spotui.data.preferences.Look.IMMERSIVE) {
@@ -150,6 +185,13 @@ class MainActivity : AppCompatActivity() {
// Debug builds: `am start ... --ez showPlayer true` shows the Web Player page full screen.
val debuggable = applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0
MyspotiRuntime.host.attach(root, visible = debuggable && intent.getBooleanExtra("showPlayer", false))
+ // A new activity while the sign-in page is open (the system let the old one go while the user
+ // read the e-mail code): the page is still there and is put back in front as it was left. It
+ // used to stay hidden behind the welcome screen, and "Log in" started the flow over.
+ if (!signedIn && MyspotiRuntime.loginRequired.value) {
+ showingLogin = true
+ MyspotiRuntime.host.attach(root, visible = true)
+ }
showLook = debuggable && intent.getBooleanExtra("showLook", false)
// Debug builds: `am start ... --ez resetLookOffer true` shows the new-look popup again.
if (debuggable && intent.getBooleanExtra("resetLookOffer", false)) {
@@ -262,6 +304,8 @@ class MainActivity : AppCompatActivity() {
override fun onStop() {
super.onStop()
+ // The sign-in is only in memory until the WebView saves it: leaving the app (and being swiped away) must not lose it.
+ MyspotiRuntime.host.flushCookies()
app.myspoti.host.android.MainThreadWatch.stop()
if (!isChangingConfigurations) com.music.spotui.video.MusicVideoController.onBackground()
}
@@ -283,9 +327,46 @@ class MainActivity : AppCompatActivity() {
private fun hideLogin() {
showingLogin = false
+ loginProblem = false
MyspotiRuntime.host.attach(root, visible = false)
}
+ /**
+ * The token says signed in: the screens take over from the sign-in page. One door for the three
+ * places that find the session (the wait after the page came back, the return from the e-mail
+ * app, the player becoming ready). The wait used to hand the screen over without telling the
+ * app it was signed in, which only the player's ready signal did: when that signal had already
+ * come and gone, the loading screen stayed for ever (nothing else sets [signedIn]).
+ */
+ private fun sessionConfirmed() {
+ // Another door already started the screens over: this activity is on its way out.
+ if (isFinishing) return
+ loginProblem = false
+ if (com.music.spotui.di.SessionActions.signedOut.value) {
+ // Signed in again after a logout, maybe as someone else: start the
+ // screens over (a new activity also drops their view models).
+ com.music.spotui.di.SessionActions.signedIn()
+ prefs.edit().putBoolean("LoggedIn", true).apply()
+ MyspotiRuntime.host.flushCookies()
+ MyspotiRuntime.host.attach(root, visible = false)
+ startActivity(Intent(this, MainActivity::class.java)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK))
+ finish()
+ return
+ }
+ // The player reports ready on every page load: only a change is a session being established.
+ if (!signedIn || showingLogin || connecting) {
+ Logbook.log("session established: player shown")
+ MyspotiRuntime.host.flushCookies()
+ }
+ if (!signedIn) {
+ prefs.edit().putBoolean("LoggedIn", true).apply()
+ signedIn = true
+ }
+ connecting = false
+ if (showingLogin) hideLogin()
+ }
+
/** Logout: leave the app's screens for Spotify's login page. */
private fun watchLogout() {
lifecycleScope.launch {
@@ -311,10 +392,21 @@ class MainActivity : AppCompatActivity() {
lifecycleScope.launch {
MyspotiRuntime.host.url.collect { url ->
val backOnPlayer = url.startsWith("https://open.spotify.com") && !url.contains("/login")
- if (!(showingLogin && backOnPlayer)) return@collect
+ if (!(showingLogin && backOnPlayer)) {
+ // Spotify sent the page to its sign-in again while the waiting screen covered it: the
+ // wait is over and the page is shown. It stayed hidden, with the loading screen on, until
+ // the old wait ran out and reloaded the sign-in page under the user.
+ if (showingLogin && connecting && MyspotiRuntime.host.loginRequired.value) {
+ loginWait?.cancel()
+ connecting = false
+ MyspotiRuntime.host.veil(false)
+ }
+ return@collect
+ }
// Spotify's desktop player is not shown while the session is confirmed: the app's
// waiting screen is, behind the page made transparent (reported: it flashed).
connecting = true
+ loginProblem = false
MyspotiRuntime.host.veil(true)
// The address is not a session — and it comes back to open.spotify.com as soon as the
// user leaves the app to read the sign-in e-mail. Hiding the page here showed an
@@ -322,31 +414,39 @@ class MainActivity : AppCompatActivity() {
// The login page therefore stays in FRONT until a real token exists.
loginWait?.cancel()
loginWait = launch {
- var waited = 0L
- var elapsed = 0L
- while (waited < SESSION_WAIT_MS && elapsed < SESSION_LOAD_MAX_MS) {
+ val wait = SessionWait(SESSION_WAIT_MS, SESSION_LOAD_MAX_MS)
+ var last = android.os.SystemClock.elapsedRealtime()
+ while (!wait.expired) {
if (runCatching { MyspotiRuntime.isSignedIn() }.getOrDefault(false)) {
- android.util.Log.d(LOG, "session established: player shown")
- hideLogin()
+ sessionConfirmed()
return@launch
}
- // The countdown only runs while the user is looking at the app: away to read
- // the e-mail, the sign-in page must not be reset under them.
- // Nor while the player is still loading: it answers nothing before its bridge is
- // ready, which takes 10 s and more on a slow device (a DAP, a low-end Xiaomi).
- // Counted from the address alone, the wait ran out under a page that was still
- // booting and put the sign-in page back: the reported loop to the login page.
- if (lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) {
- elapsed += 500
- if (MyspotiRuntime.spotify.ready.value) waited += 500
- }
kotlinx.coroutines.delay(500)
+ // Real time, counted only while the user is looking at the app: away to read the
+ // e-mail, the sign-in page must not be reset under them. Nor while the player is
+ // still loading: it answers nothing before its bridge is ready, which takes 10 s
+ // and more on a slow device (a DAP, a low-end Xiaomi). Counted from the address
+ // alone, the wait ran out under a page that was still booting and put the sign-in
+ // page back: the reported loop to the login page. And by turns of this loop, not
+ // by the clock, a page that left each token request waiting its 20 s made the
+ // minute last 40.
+ val now = android.os.SystemClock.elapsedRealtime()
+ wait.tick(now - last, lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED),
+ MyspotiRuntime.spotify.ready.value)
+ last = now
}
- android.util.Log.d(LOG, "no session ${SESSION_WAIT_MS / 1000}s after the player came back: sign-in page restored")
- // The page may now be the anonymous player: send it back to the e-mail step so the
- // user is not left where nothing plays.
connecting = false
- if (!showingLogin) showLogin() else MyspotiRuntime.host.openLogin()
+ if (wait.playerNeverReady) {
+ // Not signed out: the player never started. The sign-in page would send it straight
+ // back here (the cookies are good), minute after minute: the reported loop.
+ Logbook.log("no session after ${wait.elapsedMs / 1000} s: the player never became ready (waited ${wait.waitedMs / 1000} s with it ready)")
+ loginProblem = true
+ } else {
+ Logbook.log("no session ${SESSION_WAIT_MS / 1000} s after the player came back: sign-in page restored")
+ // The page may now be the anonymous player: send it back to the e-mail step so the
+ // user is not left where nothing plays.
+ if (!showingLogin) showLogin() else MyspotiRuntime.host.openLogin()
+ }
}
}
}
@@ -361,12 +461,12 @@ class MainActivity : AppCompatActivity() {
if (!showingLogin) return
lifecycleScope.launch {
if (MyspotiRuntime.awaitSignedIn(1_500)) {
- android.util.Log.d(LOG, "back with a session: player shown")
- hideLogin()
+ Logbook.log("back with a session")
+ sessionConfirmed()
} else if (MyspotiRuntime.spotify.ready.value &&
MyspotiRuntime.host.url.value.let { it.startsWith("https://open.spotify.com") && !it.contains("/login") }) {
// Ready: a player still booting has not answered yet, and is left to watchLoginReturn.
- android.util.Log.d(LOG, "back without a session: sign-in page restored")
+ Logbook.log("back without a session: sign-in page restored")
MyspotiRuntime.host.openLogin()
}
}
@@ -385,29 +485,13 @@ class MainActivity : AppCompatActivity() {
ready && !login -> {
val user = runCatching { MyspotiRuntime.isSignedIn() }.getOrDefault(false)
if (user) {
- if (com.music.spotui.di.SessionActions.signedOut.value) {
- // Signed in again after a logout, maybe as someone else: start the
- // screens over (a new activity also drops their view models).
- com.music.spotui.di.SessionActions.signedIn()
- prefs.edit().putBoolean("LoggedIn", true).apply()
- MyspotiRuntime.host.attach(root, visible = false)
- startActivity(Intent(this@MainActivity, MainActivity::class.java)
- .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK))
- finish()
- return@collect
- }
- if (!signedIn) {
- prefs.edit().putBoolean("LoggedIn", true).apply()
- signedIn = true
- }
- connecting = false
- if (showingLogin) hideLogin()
+ sessionConfirmed()
} else if (signedIn) {
// The pref said "signed in", the token says anonymous: only the token
// counts. This is what left the app on its full UI (or on Spotify's
// anonymous page) with nothing playable — reported after leaving the app
// to read the sign-in e-mail, where the session never completed.
- android.util.Log.d(LOG, "anonymous token while the app thought it was signed in: back to the sign-in page")
+ Logbook.log("anonymous token while the app thought it was signed in: back to the sign-in page")
prefs.edit().putBoolean("LoggedIn", false).apply()
signedIn = false
connecting = false
@@ -470,3 +554,26 @@ private fun ConnectingScreen() {
androidx.compose.material3.CircularProgressIndicator(color = com.music.spotui.ui.theme.AppAccent)
}
}
+
+/** The sign-in page did not come (or the player did not start after it): what happened, and a way to go again. */
+private fun LoginProblemScreen(onRetry: () -> Unit) {
+ Column(
+ Modifier.fillMaxSize().background(com.music.spotui.ui.theme.AppBackground).systemBarsPadding().padding(28.dp),
+ verticalArrangement = Arrangement.Center,
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ Text(stringResource(R.string.login_failed_title), color = com.music.spotui.ui.theme.AppText, fontFamily = com.music.spotui.ui.theme.AppSans,
+ fontWeight = FontWeight.Bold, fontSize = 20.sp, textAlign = TextAlign.Center)
+ Text(stringResource(R.string.login_failed_detail), color = com.music.spotui.ui.theme.AppText.copy(alpha = 0.6f), fontFamily = com.music.spotui.ui.theme.AppSans,
+ fontSize = 15.sp, lineHeight = 21.sp, textAlign = TextAlign.Center, modifier = Modifier.padding(top = 10.dp, bottom = 28.dp))
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier.fillMaxWidth().height(54.dp).clip(RoundedCornerShape(50))
+ .background(com.music.spotui.ui.theme.AppAccent).clickable(onClick = onRetry),
+ ) {
+ Text(stringResource(R.string.retry_button), color = Color.Black, fontFamily = com.music.spotui.ui.theme.AppSans,
+ fontWeight = FontWeight.Bold, fontSize = 17.sp)
+ }
+ }
+}
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 311bfd05..e9922fda 100644
--- a/base/app/src/main/res/values-de/myspoti_strings.xml
+++ b/base/app/src/main/res/values-de/myspoti_strings.xml
@@ -597,4 +597,6 @@
<string name="hidden_songs_title">Ausgeblendete Songs</string>
<string name="hidden_songs_detail">Songs mit „Kein Interesse“ werden in Listen und Radios übersprungen</string>
<string name="hidden_songs_empty">Noch keine ausgeblendeten Songs. Wähle „Kein Interesse“ im Menü eines Songs.</string>
+ <string name="login_failed_title">Anmeldung nicht abgeschlossen</string>
+ <string name="login_failed_detail">Die Seite von Spotify wurde nicht geladen oder nicht gestartet. Prüfe deine Verbindung und versuche es erneut. Wenn es weiter scheitert, probiere ein anderes Netzwerk.</string>
</resources>
diff --git a/base/app/src/main/res/values-el/myspoti_strings.xml b/base/app/src/main/res/values-el/myspoti_strings.xml
index 74e7d3bc..cbee9060 100644
--- a/base/app/src/main/res/values-el/myspoti_strings.xml
+++ b/base/app/src/main/res/values-el/myspoti_strings.xml
@@ -597,4 +597,6 @@
<string name="hidden_songs_title">Κρυφά τραγούδια</string>
<string name="hidden_songs_detail">Τα τραγούδια που σημειώνονται ως «Δεν με ενδιαφέρει» παραλείπονται σε λίστες και ραδιόφωνα</string>
<string name="hidden_songs_empty">Δεν υπάρχουν κρυφά τραγούδια. Επιλέξτε «Δεν με ενδιαφέρει» στο μενού ενός τραγουδιού.</string>
+ <string name="login_failed_title">Η σύνδεση δεν ολοκληρώθηκε</string>
+ <string name="login_failed_detail">Η σελίδα του Spotify δεν φόρτωσε ή δεν ξεκίνησε. Ελέγξτε τη σύνδεσή σας και δοκιμάστε ξανά. Αν εξακολουθεί να αποτυγχάνει, δοκιμάστε άλλο δίκτυο.</string>
</resources>
diff --git a/base/app/src/main/res/values-es/myspoti_strings.xml b/base/app/src/main/res/values-es/myspoti_strings.xml
index 38b1fc39..02bc4a47 100644
--- a/base/app/src/main/res/values-es/myspoti_strings.xml
+++ b/base/app/src/main/res/values-es/myspoti_strings.xml
@@ -597,4 +597,6 @@
<string name="hidden_songs_title">Canciones ocultas</string>
<string name="hidden_songs_detail">Las canciones marcadas como No me interesa se saltan en listas y radios</string>
<string name="hidden_songs_empty">Aún no hay canciones ocultas. Elige No me interesa en el menú de una canción.</string>
+ <string name="login_failed_title">No se pudo completar el inicio de sesión</string>
+ <string name="login_failed_detail">La página de Spotify no se cargó o no arrancó. Comprueba tu conexión e inténtalo de nuevo. Si sigue fallando, prueba con otra red.</string>
</resources>
diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xml
index 61489534..9e7d30bd 100644
--- a/base/app/src/main/res/values-fr/myspoti_strings.xml
+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml
@@ -602,4 +602,6 @@
<string name="hidden_songs_title">Titres masqués</string>
<string name="hidden_songs_detail">Les titres marqués « Pas intéressé » sont passés dans les listes et les radios</string>
<string name="hidden_songs_empty">Aucun titre masqué. Choisissez « Pas intéressé » dans le menu d\'un titre.</string>
+ <string name="login_failed_title">La connexion n\'a pas abouti</string>
+ <string name="login_failed_detail">La page de Spotify ne s\'est pas chargée ou n\'a pas démarré. Vérifiez votre connexion et réessayez. Si cela échoue encore, essayez un autre réseau.</string>
</resources>
diff --git a/base/app/src/main/res/values-it/myspoti_strings.xml b/base/app/src/main/res/values-it/myspoti_strings.xml
index 77c4fd07..830d1ee2 100644
--- a/base/app/src/main/res/values-it/myspoti_strings.xml
+++ b/base/app/src/main/res/values-it/myspoti_strings.xml
@@ -597,4 +597,6 @@
<string name="hidden_songs_title">Brani nascosti</string>
<string name="hidden_songs_detail">I brani segnati come Non mi interessa vengono saltati nelle liste e nelle radio</string>
<string name="hidden_songs_empty">Nessun brano nascosto. Scegli Non mi interessa nel menu di un brano.</string>
+ <string name="login_failed_title">Accesso non completato</string>
+ <string name="login_failed_detail">La pagina di Spotify non si è caricata o non è partita. Controlla la connessione e riprova. Se continua a fallire, prova un\'altra rete.</string>
</resources>
diff --git a/base/app/src/main/res/values-pl/myspoti_strings.xml b/base/app/src/main/res/values-pl/myspoti_strings.xml
index bd5eca70..a061e7de 100644
--- a/base/app/src/main/res/values-pl/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pl/myspoti_strings.xml
@@ -612,4 +612,6 @@
<string name="hidden_songs_title">Ukryte utwory</string>
<string name="hidden_songs_detail">Utwory oznaczone jako Nie interesuje mnie są pomijane na listach i w radiach</string>
<string name="hidden_songs_empty">Brak ukrytych utworów. Wybierz Nie interesuje mnie w menu utworu.</string>
+ <string name="login_failed_title">Logowanie nie zostało dokończone</string>
+ <string name="login_failed_detail">Strona Spotify nie załadowała się lub nie wystartowała. Sprawdź połączenie i spróbuj ponownie. Jeśli nadal się nie udaje, spróbuj innej sieci.</string>
</resources>
diff --git a/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml b/base/app/src/main/res/values-pt-rPT/myspoti_strings.xml
index e6d68c0a..251aaa6e 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
@@ -597,4 +597,6 @@
<string name="hidden_songs_title">Músicas ocultas</string>
<string name="hidden_songs_detail">As músicas marcadas como Sem interesse são ignoradas em listas e rádios</string>
<string name="hidden_songs_empty">Nenhuma música oculta. Escolha Sem interesse no menu de uma música.</string>
+ <string name="login_failed_title">O início de sessão não foi concluído</string>
+ <string name="login_failed_detail">A página do Spotify não carregou ou não arrancou. Verifique a ligação e tente novamente. Se continuar a falhar, experimente outra rede.</string>
</resources>
diff --git a/base/app/src/main/res/values-pt/myspoti_strings.xml b/base/app/src/main/res/values-pt/myspoti_strings.xml
index d1ab2944..4f8a7107 100644
--- a/base/app/src/main/res/values-pt/myspoti_strings.xml
+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml
@@ -597,4 +597,6 @@
<string name="hidden_songs_title">Músicas ocultas</string>
<string name="hidden_songs_detail">As músicas marcadas como Sem interesse são puladas em listas e rádios</string>
<string name="hidden_songs_empty">Nenhuma música oculta. Escolha Sem interesse no menu de uma música.</string>
+ <string name="login_failed_title">O login não foi concluído</string>
+ <string name="login_failed_detail">A página do Spotify não carregou ou não iniciou. Verifique sua conexão e tente novamente. Se continuar falhando, tente outra rede.</string>
</resources>
diff --git a/base/app/src/main/res/values-ru/myspoti_strings.xml b/base/app/src/main/res/values-ru/myspoti_strings.xml
index 8da2c3ac..63de28d9 100644
--- a/base/app/src/main/res/values-ru/myspoti_strings.xml
+++ b/base/app/src/main/res/values-ru/myspoti_strings.xml
@@ -612,4 +612,6 @@
<string name="hidden_songs_title">Скрытые треки</string>
<string name="hidden_songs_detail">Треки с отметкой «Не интересует» пропускаются в списках и радио</string>
<string name="hidden_songs_empty">Скрытых треков пока нет. Выберите «Не интересует» в меню трека.</string>
+ <string name="login_failed_title">Не удалось войти</string>
+ <string name="login_failed_detail">Страница Spotify не загрузилась или не запустилась. Проверьте подключение и повторите попытку. Если не получается, попробуйте другую сеть.</string>
</resources>
diff --git a/base/app/src/main/res/values-zh/myspoti_strings.xml b/base/app/src/main/res/values-zh/myspoti_strings.xml
index 36818b45..12392c3f 100644
--- a/base/app/src/main/res/values-zh/myspoti_strings.xml
+++ b/base/app/src/main/res/values-zh/myspoti_strings.xml
@@ -597,4 +597,6 @@
<string name="hidden_songs_title">已隐藏的歌曲</string>
<string name="hidden_songs_detail">标记为“不感兴趣”的歌曲会在列表和电台中被跳过</string>
<string name="hidden_songs_empty">还没有已隐藏的歌曲。请在歌曲菜单中选择“不感兴趣”。</string>
+ <string name="login_failed_title">登录未完成</string>
+ <string name="login_failed_detail">Spotify 页面未能加载或启动。请检查网络连接后重试;如果仍然失败,请换一个网络试试。</string>
</resources>
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index bf1db917..cb8c8d97 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -603,4 +603,6 @@
<string name="hidden_songs_title">Hidden songs</string>
<string name="hidden_songs_detail">Songs marked Not interested are skipped in lists and radios</string>
<string name="hidden_songs_empty">No hidden songs yet. Choose Not interested in a song\'s menu.</string>
+ <string name="login_failed_title">Sign-in did not finish</string>
+ <string name="login_failed_detail">Spotify\'s page did not load or did not start. Check your connection and try again. If it keeps failing, try another network.</string>
</resources>
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/LoginLoad.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/LoginLoad.kt
new file mode 100644
index 00000000..35a2ba38
--- /dev/null
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/LoginLoad.kt
@@ -0,0 +1,109 @@
+package app.myspoti.host.android
+
+/**
+ * The sign-in page as the user meets it while it opens. The page used to be shown from the first
+ * tap: white until Spotify's page painted, white for ever when it never did (no timeout watched a
+ * login page, only the player's), and a page that failed to load had no way back but killing the
+ * app. Now the app's own waiting screen covers the page until it has content ([LOADING]), and an
+ * error with "Try again" replaces a page that did not come ([FAILED]). [WebPlayerHost] feeds this
+ * what the WebView reports; the rules below are pure so they are tested.
+ */
+enum class LoginLoad {
+ /** No sign-in page is being opened (or it is past this stage: signed in, or the player is back). */
+ NONE,
+ /** Asked for, no content yet: the waiting screen shows, the page is kept out of sight. */
+ LOADING,
+ /** Spotify's page has content: it is shown. */
+ SHOWN,
+ /** It did not load, or stayed blank: the error shows. */
+ FAILED;
+
+ /** What to do after a probe found the page still without content. */
+ enum class Blank { WAIT, RELOAD, FAIL }
+
+ companion object {
+ /** From the request to a page with content; past it the load is given up. */
+ const val TIMEOUT_MS = 25_000L
+
+ /** The page is looked at this long after it finished loading, then every [PROBE_EVERY_MS]. */
+ const val FIRST_PROBE_MS = 500L
+ const val PROBE_EVERY_MS = 1_000L
+
+ /** Probes of a page that finished but stays empty: loaded again once, then given up. */
+ private const val RELOAD_AFTER = 6
+ private const val FAIL_AFTER = 10
+
+ /**
+ * Read in the page: how much it shows (its text and its fields, buttons and links). Spotify's
+ * login is a script-built page, so an empty body after "finished" is a page that did not run.
+ */
+ const val PAINT_JS = "(function(){var b=document.body;if(!b)return 0;" +
+ "return (b.innerText||'').trim().length+b.querySelectorAll('input,button,a').length})()"
+
+ /** [PAINT_JS]'s answer as evaluateJavascript hands it back ("42", "0", "null"). */
+ fun painted(answer: String?): Boolean = (answer?.trim()?.trim('"')?.toDoubleOrNull() ?: 0.0) > 0.0
+
+ /** [probes] empty looks so far at this page; [reloaded]: it was already loaded again once. */
+ fun blank(probes: Int, reloaded: Boolean): Blank = when {
+ probes < RELOAD_AFTER -> Blank.WAIT
+ !reloaded -> Blank.RELOAD
+ probes < FAIL_AFTER -> Blank.WAIT
+ else -> Blank.FAIL
+ }
+
+ /** Spotify's own account pages: the one whose failure is the sign-in's failure. */
+ fun isSpotifyAccounts(url: String?): Boolean = hostOf(url) == "accounts.spotify.com"
+
+ /**
+ * A page of the sign-in: Spotify's account and challenge pages, a `/login` path anywhere,
+ * and the "Continue with Google / Facebook / Apple" pages. Judged on the host and the path,
+ * not on the whole address: a player address that merely carries one of these names in its
+ * query (a `continue=` back to the login) is not a sign-in page, and was taken for one.
+ */
+ fun isLoginUrl(url: String?): Boolean {
+ val uri = runCatching { java.net.URI((url ?: return false).substringBefore('#').substringBefore('?')) }.getOrNull() ?: return false
+ val host = uri.host?.lowercase() ?: return false
+ if (host == "accounts.spotify.com" || host == "challenge.spotify.com") return true
+ if (uri.path?.contains("/login") == true) return true
+ return host == "accounts.google.com" || host == "facebook.com" || host.endsWith(".facebook.com") || host == "appleid.apple.com"
+ }
+
+ private fun hostOf(url: String?): String? =
+ runCatching { java.net.URI((url ?: return null).substringBefore('#').substringBefore('?')).host?.lowercase() }.getOrNull()
+ }
+}
+
+/**
+ * How long the app waits for a session once the sign-in page has handed back to the player.
+ * Two clocks, both real time: [waitedMs] runs only while the screen is in front and the player's
+ * bridge is ready (a player that has not answered yet proves nothing), [elapsedMs] runs while the
+ * screen is in front, ready or not, and is the hard limit. The wait used to add 500 for every turn
+ * of its loop, but a turn that asked the page for its token could itself take 20 s (the bridge's
+ * call timeout): the "60 s" limit was 120 turns, which is 40 minutes of spinner when the page did
+ * not answer.
+ */
+class SessionWait(private val readyBudgetMs: Long, private val maxMs: Long) {
+ var waitedMs = 0L
+ private set
+ var elapsedMs = 0L
+ private set
+
+ /**
+ * Accounts for [dtMs] of real time that just passed. A turn counts for at most [MAX_TURN_MS]: the
+ * slowest honest one is a token request given its 20 s, and a longer gap is the phone asleep (Doze
+ * holds a coroutine's delay while the user reads the e-mail), which is not time spent waiting.
+ */
+ fun tick(dtMs: Long, inFront: Boolean, ready: Boolean) {
+ if (dtMs <= 0 || !inFront) return
+ val dt = minOf(dtMs, MAX_TURN_MS)
+ elapsedMs += dt
+ if (ready) waitedMs += dt
+ }
+
+ companion object { const val MAX_TURN_MS = 22_000L }
+
+ val expired: Boolean get() = waitedMs >= readyBudgetMs || elapsedMs >= maxMs
+
+ /** Expired without the player ever being ready for its budget: it did not start, which is not "signed out". */
+ val playerNeverReady: Boolean get() = expired && waitedMs < readyBudgetMs
+}
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
index eae17e22..663b5a5e 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
@@ -81,6 +81,10 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
private val _loginRequired = MutableStateFlow(false)
val loginRequired: StateFlow<Boolean> = _loginRequired
+ private val _loginLoad = MutableStateFlow(LoginLoad.NONE)
+ /** How the sign-in page is opening: the UI covers it while it loads and shows an error if it fails. */
+ val loginLoad: StateFlow<LoginLoad> = _loginLoad
+
/** Fires after each Web Player page load; the API injects the bridge then. */
var onPageLoaded: (() -> Unit)? = null
@@ -260,6 +264,10 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
main.removeCallbacks(loadTimeout)
if (android.net.Uri.parse(url).host == PLAYER_HOST) main.postDelayed(loadTimeout, PAGE_LOAD_TIMEOUT_MS)
pageStarts++
+ // The sign-in page was asked for and Spotify sent us elsewhere (the sign-in is done, or the
+ // session was still good: the player): there is no sign-in page left to wait for. Before the
+ // address is published, so whoever hides the page for the player does it after this.
+ if (!isLoginPage(url) && _loginLoad.value != LoginLoad.NONE && _loginLoad.value != LoginLoad.FAILED) setLoginLoad(LoginLoad.NONE)
_url.value = url
_loginRequired.value = isLoginPage(url)
if (url.startsWith(PLAYER_URL)) { drmAsked = false; licenseAnswersLogged = 0; onPageStarting?.invoke(); relay.injectNow() }
@@ -272,6 +280,10 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
// ERR_ABORTED: a load this app stopped itself (a timeout, a newer load) — not a failure.
if (request.isForMainFrame && request.url.host == PLAYER_HOST && "ERR_ABORTED" !in error.description.toString())
playerPageFailed("load error ${error.errorCode}")
+ // The sign-in page itself: the WebView's own error page is not something to leave a user on.
+ if (request.isForMainFrame && _loginLoad.value != LoginLoad.NONE && LoginLoad.isSpotifyAccounts(request.url.toString()) &&
+ "ERR_ABORTED" !in error.description.toString())
+ loginFailed("load error ${error.errorCode}")
}
override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, response: WebResourceResponse) {
@@ -282,6 +294,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
"http ${response.statusCode} ${request.method} ${request.url.toString().substringBefore('?').take(120)}")
if (request.isForMainFrame && request.url.host == PLAYER_HOST && (response.statusCode >= 500 || response.statusCode == 429))
playerPageFailed("http ${response.statusCode}")
+ if (request.isForMainFrame && _loginLoad.value != LoginLoad.NONE && LoginLoad.isSpotifyAccounts(request.url.toString()) && response.statusCode >= 500)
+ loginFailed("http ${response.statusCode}")
if (request.url.path?.contains("widevine-license") == true) {
if (response.statusCode == 429) onLicenseLimited()
response.responseHeaders.entries.firstOrNull { it.key.equals("retry-after", true) }
@@ -303,6 +317,12 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
if (url.startsWith(PLAYER_URL) && !mainFrameFailed) { pageFailures = 0; main.removeCallbacks(retryPlayerPage) }
_url.value = url
_loginRequired.value = isLoginPage(url)
+ // Finished is not painted: Spotify's sign-in is a script-built page. Looked at until it has content.
+ if (_loginLoad.value == LoginLoad.LOADING && isLoginPage(url)) {
+ loginProbes = 0
+ main.removeCallbacks(loginProbe)
+ main.postDelayed(loginProbe, LoginLoad.FIRST_PROBE_MS)
+ }
if (url.startsWith(PLAYER_URL)) {
onPageLoaded?.invoke()
if (!drmAsked) { main.removeCallbacks(drmWatch); main.postDelayed(drmWatch, DRM_WATCH_MS) }
@@ -315,6 +335,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
// Exact or subdomain match: "evilspotify.com" must not count as Spotify.
val allowed = listOf("spotify.com", "spotify.net", "scdn.co", "google.com", "facebook.com", "apple.com")
.any { host == it || host.endsWith(".$it") }
+ // A sign-in step that goes nowhere looks like a page that does nothing: say which host was refused.
+ if (!allowed) Logbook.log("navigation refused: ${host.ifEmpty { request.url.scheme.orEmpty() }}")
return !allowed
}
@@ -349,6 +371,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
private fun rebuild(): Boolean = main.post {
main.removeCallbacks(drmWatch)
val wasLoaded = loadAsked
+ // Mid sign-in: the page comes back to the sign-in, not to an anonymous player in front of the user.
+ val wasLogin = _loginRequired.value || _loginLoad.value != LoginLoad.NONE
val box = container
box?.let { runCatching { it.removeView(view) } }
(view as? AwakeWebView)?.releaseFromWindow()
@@ -363,13 +387,12 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
box?.let { attach(it, lastVisible) }
// The new view's first navigation can be lost while the browser side still settles after
// the kill (seen: no page start for 4 s): the watchdog looks again after 1.5 s, not 4 s.
- if (wasLoaded) load(firstWatchMs = REBUILD_WATCH_MS) else view.loadUrl("about:blank")
+ if (wasLogin) { loadAsked = wasLoaded; beginLoginLoad(); view.loadUrl(LOGIN_URL) }
+ else if (wasLoaded) load(firstWatchMs = REBUILD_WATCH_MS) else view.loadUrl("about:blank")
}
- private fun isLoginPage(url: String?) =
- url != null && (url.contains("accounts.spotify.com") || url.contains("/login") || url.contains("challenge.spotify.com") ||
- // "Continue with Google / Facebook / Apple": still mid sign-in on their pages.
- url.contains("accounts.google.com") || url.contains("facebook.com") || url.contains("appleid.apple.com"))
+ /** Spotify's sign-in pages and the "Continue with Google / Facebook / Apple" ones (see [LoginLoad.isLoginUrl]). */
+ private fun isLoginPage(url: String?) = LoginLoad.isLoginUrl(url)
fun load() = load(firstWatchMs = LOAD_WATCH_MS)
@@ -484,17 +507,100 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
main.postDelayed(retryPlayerPage, wait)
}
- fun openLogin() = main.post { view.alpha = 1f; view.loadUrl(LOGIN_URL) }
+ fun openLogin() = main.post {
+ // A player retry or load timeout still pending would replace the sign-in page just asked for.
+ main.removeCallbacks(retryPlayerPage)
+ main.removeCallbacks(loadTimeout)
+ beginLoginLoad()
+ view.loadUrl(LOGIN_URL)
+ }
/** Signs out of Spotify in this WebView, then shows the login page. */
- fun logout() = main.post {
+ fun logout() = main.post { beginLoginLoad(); cleanSlate { view.loadUrl(LOGIN_URL) } }
+
+ /**
+ * "Try again" after the sign-in page failed: from nothing. A failed attempt may have left half
+ * a sign-in behind (the cookies and storage of a flow that never finished), and Spotify's page
+ * answers "Oops! Something went wrong" to a flow it cannot match with its own state.
+ */
+ fun retryLogin() = main.post { beginLoginLoad(); cleanSlate { view.loadUrl(LOGIN_URL) } }
+
+ private fun cleanSlate(then: () -> Unit) {
CookieManager.getInstance().removeAllCookies {
main.post {
// Web storage too: localStorage/IndexedDB hold the player's session
// state, and clearCache(true) also drops the disk cache (false kept it).
android.webkit.WebStorage.getInstance().deleteAllData()
view.clearCache(true)
- view.loadUrl(LOGIN_URL)
+ then()
+ }
+ }
+ }
+
+ /**
+ * Writes the session cookies to disk now. The WebView keeps them in memory and saves them a
+ * while later: an app swiped away right after signing in (the exit log shows "SwipeUpClean" and
+ * "OneKeyClean" on Xiaomi) lost the sign-in and asked for it again at the next start.
+ */
+ fun flushCookies() = CookieManager.getInstance().flush()
+
+ private var loginProbes = 0
+ private var loginReloaded = false
+
+ /** The sign-in page was asked for: kept out of sight, with its clocks running, until it has content. */
+ private fun beginLoginLoad() {
+ loginProbes = 0
+ loginReloaded = false
+ main.removeCallbacks(loginProbe)
+ main.removeCallbacks(loginTimeout)
+ _loginLoad.value = LoginLoad.LOADING
+ view.alpha = 0f
+ main.postDelayed(loginTimeout, LoginLoad.TIMEOUT_MS)
+ Logbook.log("sign-in page: opening")
+ }
+
+ private fun setLoginLoad(state: LoginLoad) {
+ if (_loginLoad.value == state) return
+ _loginLoad.value = state
+ if (state != LoginLoad.LOADING) { main.removeCallbacks(loginProbe); main.removeCallbacks(loginTimeout) }
+ if (state == LoginLoad.SHOWN || state == LoginLoad.NONE) view.alpha = 1f
+ if (state == LoginLoad.NONE) return
+ Logbook.log("sign-in page: ${state.name.lowercase()}")
+ }
+
+ private fun loginFailed(what: String) {
+ if (_loginLoad.value == LoginLoad.FAILED) return
+ Logbook.log("sign-in page failed ($what)")
+ runCatching { view.stopLoading() }
+ view.alpha = 0f
+ setLoginLoad(LoginLoad.FAILED)
+ }
+
+ private val loginTimeout = Runnable {
+ if (_loginLoad.value != LoginLoad.LOADING) return@Runnable
+ // A page can show everything and still be "loading" (a stuck script or tracker): content decides.
+ view.evaluateJavascript(LoginLoad.PAINT_JS) { answer ->
+ if (_loginLoad.value != LoginLoad.LOADING) return@evaluateJavascript
+ if (LoginLoad.painted(answer) && isLoginPage(view.url)) setLoginLoad(LoginLoad.SHOWN)
+ else loginFailed("no content after ${LoginLoad.TIMEOUT_MS / 1000} s")
+ }
+ }
+
+ /** Asks the page how much it shows; empty after its load finished means a page that did not run. */
+ private val loginProbe: Runnable = Runnable {
+ if (_loginLoad.value != LoginLoad.LOADING) return@Runnable
+ view.evaluateJavascript(LoginLoad.PAINT_JS) { answer ->
+ if (_loginLoad.value != LoginLoad.LOADING) return@evaluateJavascript
+ if (LoginLoad.painted(answer)) { setLoginLoad(LoginLoad.SHOWN); return@evaluateJavascript }
+ when (LoginLoad.blank(++loginProbes, loginReloaded)) {
+ LoginLoad.Blank.WAIT -> main.postDelayed(loginProbe, LoginLoad.PROBE_EVERY_MS)
+ LoginLoad.Blank.RELOAD -> {
+ Logbook.log("sign-in page: finished but blank, loading it again")
+ loginReloaded = true
+ loginProbes = 0
+ view.loadUrl(LOGIN_URL)
+ }
+ LoginLoad.Blank.FAIL -> loginFailed("blank after a second load")
}
}
}
@@ -528,7 +634,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
val size = if (visible) ViewGroup.LayoutParams.MATCH_PARENT else 1
container.addView(view, ViewGroup.LayoutParams(size, size))
keepClearOfSystemBars(visible)
- view.alpha = 1f
+ // Still opening or failed, the sign-in page stays out of sight (the app's own screen covers it).
+ view.alpha = if (_loginLoad.value == LoginLoad.LOADING || _loginLoad.value == LoginLoad.FAILED) 0f else 1f
view.visibility = if (visible) View.VISIBLE else View.INVISIBLE
view.importantForAccessibility = if (visible) View.IMPORTANT_FOR_ACCESSIBILITY_AUTO else View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
// Typing in the login form needs touch focus, or the keyboard never opens.
@@ -537,6 +644,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
view.descendantFocusability = if (visible) ViewGroup.FOCUS_AFTER_DESCENDANTS else ViewGroup.FOCUS_BLOCK_DESCENDANTS
if (visible) view.requestFocus()
view.requestLayout()
+ // Shown again after being hidden at 1 px: a page that was not told to redraw can stay white.
+ if (visible) view.postInvalidateOnAnimation()
// Now in a window: a first navigation that never started gets another go.
if (loadAsked && _url.value.isEmpty() && pageStarts == 0) view.loadUrl(playerRoot())
}
diff --git a/base/host-android/src/test/kotlin/app/myspoti/host/android/LoginLoadTest.kt b/base/host-android/src/test/kotlin/app/myspoti/host/android/LoginLoadTest.kt
new file mode 100644
index 00000000..15dc3d0b
--- /dev/null
+++ b/base/host-android/src/test/kotlin/app/myspoti/host/android/LoginLoadTest.kt
@@ -0,0 +1,105 @@
+package app.myspoti.host.android
+
+import app.myspoti.host.android.LoginLoad.Blank
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class LoginLoadTest {
+
+ @Test fun `spotify sign-in pages are login pages`() {
+ assertTrue(LoginLoad.isLoginUrl("https://accounts.spotify.com/en/login?continue=https%3A%2F%2Fopen.spotify.com%2F"))
+ assertTrue(LoginLoad.isLoginUrl("https://accounts.spotify.com/authorize?client_id=x"))
+ assertTrue(LoginLoad.isLoginUrl("https://challenge.spotify.com/c/abc"))
+ assertTrue(LoginLoad.isLoginUrl("https://open.spotify.com/login"))
+ assertTrue(LoginLoad.isLoginUrl("https://www.spotify.com/es/login/"))
+ }
+
+ @Test fun `continue with google facebook apple stays mid sign-in`() {
+ assertTrue(LoginLoad.isLoginUrl("https://accounts.google.com/o/oauth2/v2/auth?client_id=1"))
+ assertTrue(LoginLoad.isLoginUrl("https://www.facebook.com/login.php?x=1"))
+ assertTrue(LoginLoad.isLoginUrl("https://m.facebook.com/dialog/oauth"))
+ assertTrue(LoginLoad.isLoginUrl("https://appleid.apple.com/auth/authorize"))
+ }
+
+ @Test fun `the player is not a login page, whatever its query says`() {
+ assertFalse(LoginLoad.isLoginUrl("https://open.spotify.com/"))
+ assertFalse(LoginLoad.isLoginUrl("https://open.spotify.com/intl-es/?flow_ctx=36e1%3A1792946057&ubi=CAIQ"))
+ // The old check read the whole address and took these for sign-in pages.
+ assertFalse(LoginLoad.isLoginUrl("https://open.spotify.com/intl-fr/?continue=https://accounts.spotify.com/login"))
+ assertFalse(LoginLoad.isLoginUrl("https://open.spotify.com/?next=facebook.com"))
+ assertFalse(LoginLoad.isLoginUrl("https://evilfacebook.com/"))
+ }
+
+ @Test fun `nothing and nonsense are not login pages`() {
+ assertFalse(LoginLoad.isLoginUrl(null))
+ assertFalse(LoginLoad.isLoginUrl(""))
+ assertFalse(LoginLoad.isLoginUrl("about:blank"))
+ assertFalse(LoginLoad.isLoginUrl("not a url at all"))
+ }
+
+ @Test fun `only accounts spotify is the sign-in's own host`() {
+ assertTrue(LoginLoad.isSpotifyAccounts("https://accounts.spotify.com/en/login"))
+ assertFalse(LoginLoad.isSpotifyAccounts("https://accounts.google.com/"))
+ assertFalse(LoginLoad.isSpotifyAccounts("https://open.spotify.com/?u=accounts.spotify.com"))
+ assertFalse(LoginLoad.isSpotifyAccounts(null))
+ }
+
+ @Test fun `the page's answer says whether it painted`() {
+ assertTrue(LoginLoad.painted("42"))
+ assertTrue(LoginLoad.painted("\"7\""))
+ assertFalse(LoginLoad.painted("0"))
+ assertFalse(LoginLoad.painted("null"))
+ assertFalse(LoginLoad.painted(null))
+ assertFalse(LoginLoad.painted(""))
+ }
+
+ @Test fun `a blank page is waited on, loaded again once, then given up`() {
+ assertEquals(Blank.WAIT, LoginLoad.blank(1, reloaded = false))
+ assertEquals(Blank.WAIT, LoginLoad.blank(5, reloaded = false))
+ assertEquals(Blank.RELOAD, LoginLoad.blank(6, reloaded = false))
+ // After the reload the count starts over: the second page gets its own wait, then the error.
+ assertEquals(Blank.WAIT, LoginLoad.blank(1, reloaded = true))
+ assertEquals(Blank.WAIT, LoginLoad.blank(9, reloaded = true))
+ assertEquals(Blank.FAIL, LoginLoad.blank(10, reloaded = true))
+ }
+
+ @Test fun `the wait counts only the time the screen is in front`() {
+ val w = SessionWait(readyBudgetMs = 6_000, maxMs = 60_000)
+ w.tick(10_000, inFront = false, ready = true)
+ assertEquals(0L, w.elapsedMs)
+ assertFalse(w.expired)
+ }
+
+ @Test fun `ready time is the short budget, a player that is not ready gets the long one`() {
+ val ready = SessionWait(6_000, 60_000)
+ repeat(12) { ready.tick(500, inFront = true, ready = true) }
+ assertTrue(ready.expired)
+ assertFalse(ready.playerNeverReady)
+
+ val booting = SessionWait(6_000, 60_000)
+ repeat(119) { booting.tick(500, inFront = true, ready = false) }
+ assertFalse(booting.expired)
+ booting.tick(500, inFront = true, ready = false)
+ assertTrue(booting.expired)
+ // Out of time without the player ever being ready: not "signed out".
+ assertTrue(booting.playerNeverReady)
+ assertEquals(0L, booting.waitedMs)
+ }
+
+ @Test fun `a turn that waited on the page counts its real time`() {
+ // Each turn asks the page for its token and waits the bridge's 20 s: three turns are a minute,
+ // not three turns of half a second.
+ val w = SessionWait(6_000, 60_000)
+ repeat(3) { w.tick(20_500, inFront = true, ready = false) }
+ assertTrue(w.expired)
+ }
+
+ @Test fun `a gap while the phone slept is not time waited`() {
+ val w = SessionWait(6_000, 60_000)
+ w.tick(5 * 60_000, inFront = true, ready = false)
+ assertEquals(SessionWait.MAX_TURN_MS, w.elapsedMs)
+ assertFalse(w.expired)
+ }
+}