Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Reconnect Spotify's session when the network returns, and only call it back once it is

Lelonio4a7c7d9a9abc
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
index 734a0de..a6459ac 100644
--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt
+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
@@ -75,6 +75,9 @@ class SquareApplication : Application(), ImageLoaderFactory {
val offlineScope = kotlinx.coroutines.CoroutineScope(
kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.Default,
)
+ dev.lelonio.square.playback.SessionKeeper.attach(offlineScope) {
+ preferences.backend.value == dev.lelonio.square.backend.BackendId.SPOTIFY && spotifySignedIn
+ }
dev.lelonio.square.playback.NetworkWatch(this, offlineScope).start()
offlineScope.launch {
dev.lelonio.square.playback.OfflineMode.active.collect { offline ->
diff --git a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
index c4597c6..f556d3f 100644
--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
@@ -259,8 +259,11 @@ object NativeBridge {
*/
fun reconnect() {
nativeReconnect()
- // A successful call may have rebuilt the downloads-only player.
- dev.lelonio.square.playback.OfflineMode.setNoSession(isOffline)
+ // Only a live session counts as one. The call returns as soon as it is
+ // done trying, and a try that got nowhere is not offline by the
+ // engine's own flag; read that way, a failed reconnection declared the
+ // session back.
+ dev.lelonio.square.playback.OfflineMode.setNoSession(isOffline || !isConnected)
}
// --- The account's other devices ---
diff --git a/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt b/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
index a0c10ed..b1cfb0f 100644
--- a/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
@@ -89,10 +89,15 @@ class NetworkWatch(context: Context, private val scope: CoroutineScope) {
if (connected) {
// Signal-strength updates do not prove that Spotify's session is
// back. Only an actual network return starts a reconnection.
- if (returned) OfflineMode.setNoSession(false)
+ // A network is not a session: the keeper reconnects the engine and
+ // ends offline once the engine itself has one. Declaring it back
+ // here was how the library stayed on the downloads after the
+ // signal returned.
+ if (returned) SessionKeeper.networkReturned()
OfflineMode.setSlow(false)
return
}
+ SessionKeeper.networkGone()
pending = scope.launch {
delay(GRACE_MS)
android.util.Log.i(TAG, "still gone: going offline")
diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
index 3cf5ba6..6a0049b 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -273,6 +273,9 @@ class PlaybackService : MediaLibraryService() {
override fun onCreate() {
super.onCreate()
+ // The keeper starts this engine again when its start failed; see
+ // SessionKeeper.engine.
+ SessionKeeper.engine = SessionKeeper.Engine(running = { engineStarted }, start = { connectEngine() })
playbackStore = PlaybackStore(this)
container = application as dev.lelonio.square.SquareApplication
// The container's own store, not one of this service's making. Two
@@ -1429,6 +1432,11 @@ class PlaybackService : MediaLibraryService() {
}.onFailure { error ->
engineStarted = false
android.util.Log.e(TAG, "engine start failed: $error", error)
+ // Not up at all, which on no data is ordinary: the keeper starts it
+ // again when there is a chance it works. A refused account below
+ // signs out, and the keeper then finds nothing wanted.
+ dev.lelonio.square.playback.OfflineMode.setNoSession(true)
+ SessionKeeper.sessionMissing()
// Only a refused account ends the session here. Everything else the
// handshake can fail with — no network, an access point that is
// busy, a dealer that dropped — is temporary, and signing the user
@@ -1455,6 +1463,8 @@ class PlaybackService : MediaLibraryService() {
val offline = runCatching { NativeBridge.isOffline }.getOrDefault(false)
dev.lelonio.square.playback.OfflineMode.setNoSession(offline)
android.util.Log.i(TAG, if (offline) "engine started offline" else "engine connected")
+ // Up with no session: try again for as long as there is a network.
+ if (offline) SessionKeeper.sessionMissing()
if (restoreQueue) restoreQueue()
observeForSaving()
}
@@ -1906,6 +1916,7 @@ class PlaybackService : MediaLibraryService() {
}
override fun onDestroy() {
+ SessionKeeper.engine = null
// Before cancelling the scope: the last position is the one worth having.
runCatching { savePlayback() }
// Nothing plays once the service is gone, whatever the widget last heard.
diff --git a/app/src/main/java/dev/lelonio/square/playback/SessionKeeper.kt b/app/src/main/java/dev/lelonio/square/playback/SessionKeeper.kt
new file mode 100644
index 0000000..370bf91
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/playback/SessionKeeper.kt
@@ -0,0 +1,113 @@
+package dev.lelonio.square.playback
+
+import dev.lelonio.square.nativecore.NativeBridge
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+/**
+ * Brings Spotify's session back, and is the one that says when it is back.
+ *
+ * Before this, nothing reconnected the engine when the network returned: the
+ * network watch declared the session back on the strength of a network being
+ * there, the app rebuilt its library, asked the engine, and the engine, which
+ * had come up offline and been told nothing, answered offline. The library
+ * stayed on the downloads with no banner to say why, until a song was played
+ * or the banner's button pressed, the only two things that rebuilt the
+ * session. And a phone with signal and no data never got a session at all:
+ * the network was "up", so nothing ever tried again.
+ *
+ * Here a network that comes back, or an engine that came up with no session
+ * while a network is there, starts tries: at once, then further and further
+ * apart, then once a minute for as long as the network stays. Offline ends only
+ * when the engine itself reports a live session.
+ */
+object SessionKeeper {
+
+ private var scope: CoroutineScope? = null
+ private var tries: Job? = null
+
+ /** Whether the engine is wanted at all: Spotify the source, and signed in. */
+ private var wanted: () -> Boolean = { false }
+
+ /**
+ * The service's own: whether its engine is up, and how to start it.
+ *
+ * An engine whose start failed (no data, nothing downloaded to fall back
+ * on) is not there to reconnect; it has to be started again, which only the
+ * service can do. Null while no service is running.
+ */
+ @Volatile
+ var engine: Engine? = null
+
+ class Engine(val running: () -> Boolean, val start: () -> Unit)
+
+ fun attach(scope: CoroutineScope, wanted: () -> Boolean) {
+ this.scope = scope
+ this.wanted = wanted
+ }
+
+ /** The network came back after being gone. */
+ fun networkReturned() = start("network returned")
+
+ /** The network went; no point trying until it is back. */
+ fun networkGone() {
+ tries?.cancel()
+ tries = null
+ }
+
+ /**
+ * The engine came up, or came back, with no session while a network is up:
+ * signal and no data, a server that did not answer, a login that timed out.
+ */
+ fun sessionMissing() = start("no session")
+
+ private fun start(why: String) {
+ val scope = scope ?: return
+ if (tries?.isActive == true) return
+ tries = scope.launch {
+ for ((attempt, wait) in schedule().withIndex()) {
+ delay(wait)
+ if (!wanted() || OfflineMode.reason.value == OfflineMode.Reason.MANUAL) return@launch
+ if (live()) {
+ OfflineMode.setNoSession(false)
+ return@launch
+ }
+ val engine = engine
+ if (engine != null && !engine.running()) {
+ android.util.Log.i(TAG, "starting the engine again ($why, try ${attempt + 1})")
+ engine.start()
+ // The start runs on its own and reports through the
+ // service; give the handshake its time before looking.
+ delay(START_WAIT_MS)
+ } else {
+ android.util.Log.i(TAG, "reconnecting ($why, try ${attempt + 1})")
+ withContext(Dispatchers.IO) { runCatching { NativeBridge.reconnect() } }
+ }
+ if (live()) {
+ android.util.Log.i(TAG, "session back")
+ OfflineMode.setNoSession(false)
+ return@launch
+ }
+ // Still nothing: offline for what it is worth, and try again.
+ OfflineMode.setNoSession(true)
+ }
+ }
+ }
+
+ /** A session the engine itself vouches for, not a network that happens to be there. */
+ private fun live(): Boolean =
+ runCatching { NativeBridge.isConnected && !NativeBridge.isOffline }.getOrDefault(false)
+
+ /** At once, then further apart, then once a minute for good. */
+ private fun schedule(): Sequence<Long> =
+ sequenceOf(0L, 2_000L, 5_000L, 15_000L, 30_000L) + generateSequence { 60_000L }
+
+ private const val TAG = "SquareSession"
+
+ /** How long a fresh start is given before it is looked at. */
+ private const val START_WAIT_MS = 8_000L
+}