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.

Go offline when mobile data carries nothing, and play downloads then

Lelonio24aefdcb670a
diff --git a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
index 6d59667..c156b7d 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -476,9 +476,15 @@ class LibrespotPlayer(
* answer to a step it cannot make is to stop. Skipping simply stopped the
* music, while picking a song by hand worked, because that path rebuilds
* the queue instead of stepping through it.
+ *
+ * And so does the app being offline with the session still standing. On
+ * mobile data with no coverage the session's sockets stay open for minutes
+ * with nothing coming through, so the device was not "lost", and the engine
+ * sends everything to the player then anyway; see engine.rs player_only.
*/
private val deviceGone: Boolean
- get() = runCatching { NativeBridge.isOffline }.getOrDefault(false) ||
+ get() = OfflineMode.active.value ||
+ runCatching { NativeBridge.isOffline }.getOrDefault(false) ||
runCatching { NativeBridge.spircLost }.getOrDefault(false)
/**
@@ -605,7 +611,10 @@ class LibrespotPlayer(
private fun withDevice(then: () -> Unit) {
// Keep downloaded tracks moving while Spotify is unavailable. A
// reconnect on every skip destroys the working downloads-only player.
- if (OfflineMode.active.value && runCatching { NativeBridge.isOffline }.getOrDefault(false)) {
+ // Offline for any reason: bringing the session back is the keeper's
+ // job, and a handshake tried here, on a network carrying nothing, held
+ // the downloaded track for as long as the handshake took to give up.
+ if (OfflineMode.active.value) {
handler.post { if (!released) then() }
return
}
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 9af84e6..93f4349 100644
--- a/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
@@ -96,6 +96,7 @@ class NetworkWatch(context: Context, private val scope: CoroutineScope) {
private fun evaluate() {
val connected = connected()
+ probeIfDoubtful()
val returned = connected && lastConnected == false
lastConnected = connected
// Only when it changes. The system reports every step in signal
@@ -127,14 +128,6 @@ class NetworkWatch(context: Context, private val scope: CoroutineScope) {
}
}
- /**
- * Whether there is an active link that can carry traffic.
- *
- * Wi-Fi, Ethernet, Cellular and VPNs are treated as connected without strictly
- * requiring NET_CAPABILITY_VALIDATED, because Android's captive portal check
- * (Google 204 probe) frequently fails or is blocked on local/regional networks
- * despite having working internet.
- */
/** The default network's capabilities: from the callbacks, or asked before the first one. */
private fun capabilities(): NetworkCapabilities? =
current?.let { (network, known) -> known ?: connectivity?.getNetworkCapabilities(network) }
@@ -155,6 +148,21 @@ class NetworkWatch(context: Context, private val scope: CoroutineScope) {
return "$transports internet=$internet validated=$validated"
}
+ /**
+ * Whether there is an active link that can carry traffic.
+ *
+ * Wi-Fi, Ethernet and VPNs are treated as connected without strictly
+ * requiring NET_CAPABILITY_VALIDATED, because Android's captive portal check
+ * (Google 204 probe) frequently fails or is blocked on local/regional networks
+ * despite having working internet.
+ *
+ * Mobile data is not given that benefit of the doubt. With data on and no
+ * coverage the cellular network stays the default, with internet and
+ * nothing getting through, and the app stayed online: a library full of
+ * songs it could not fetch, and downloaded ones handed to a session that
+ * could not answer. There it counts only while the system has validated it
+ * or a probe of this app's own got through, and not once a probe has failed.
+ */
private fun connected(): Boolean {
val capabilities = capabilities() ?: return false
val hasInternet = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
@@ -163,7 +171,102 @@ class NetworkWatch(context: Context, private val scope: CoroutineScope) {
val isCellular = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
val isVpn = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
- return hasInternet && (isWifi || isEthernet || isCellular || isVpn)
+ if (!hasInternet || !(isWifi || isEthernet || isCellular || isVpn)) return false
+ if (!onMobileData(capabilities)) return true
+ val validated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
+ val reached = reachable.takeIf { probed == current?.first }
+ return when (reached) {
+ false -> false
+ true -> true
+ // Not probed yet: the system's word, and a probe on its way when
+ // that word is no.
+ null -> validated
+ }
+ }
+
+ /** Mobile data alone: nothing faster or steadier carrying the traffic. */
+ private fun onMobileData(capabilities: NetworkCapabilities) =
+ capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) &&
+ !capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
+ !capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
+
+ /** What the last probe of [probed] found; null before one has finished. */
+ @Volatile
+ private var reachable: Boolean? = null
+
+ @Volatile
+ private var probed: Network? = null
+
+ private var probing: Job? = null
+ private var lastProbeAt = 0L
+
+ /**
+ * Probes mobile data, when there is a reason to doubt it.
+ *
+ * The reasons are the system not having validated it, and its capabilities
+ * changing, which on mobile data is mostly the signal getting weaker or
+ * stronger: the moment coverage goes. Not more often than every
+ * [PROBE_GAP_MS] while it answers, since every probe wakes the radio; and
+ * again every [PROBE_RETRY_MS] once it has stopped answering, because
+ * nothing else would notice it coming back.
+ */
+ private fun probeIfDoubtful() {
+ val network = current?.first
+ val capabilities = capabilities()
+ if (network == null || capabilities == null || !onMobileData(capabilities)) {
+ forgetProbe()
+ return
+ }
+ if (probed != network) {
+ probing?.cancel()
+ probed = network
+ reachable = null
+ lastProbeAt = 0L
+ }
+ if (probing?.isActive == true) return
+ val validated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
+ val now = android.os.SystemClock.elapsedRealtime()
+ if (validated && reachable != false && now - lastProbeAt < PROBE_GAP_MS) return
+ lastProbeAt = now
+ probing = scope.launch {
+ while (current?.first == network) {
+ val answered = answers(network)
+ lastProbeAt = android.os.SystemClock.elapsedRealtime()
+ if (probed != network) return@launch
+ if (reachable != answered) {
+ android.util.Log.i(TAG, "mobile data ${if (answered) "answers" else "carries nothing"}")
+ reachable = answered
+ evaluate()
+ }
+ if (answered) return@launch
+ delay(PROBE_RETRY_MS)
+ }
+ }
+ }
+
+ private fun forgetProbe() {
+ probing?.cancel()
+ probing = null
+ probed = null
+ reachable = null
+ }
+
+ /**
+ * Whether a connection opens through [network] to a server the app needs.
+ * Either one will do: the point is the link, not a service being down.
+ */
+ private suspend fun answers(network: Network): Boolean = PROBE_HOSTS.any { host ->
+ kotlinx.coroutines.withTimeoutOrNull(PROBE_TIMEOUT_MS) {
+ kotlinx.coroutines.runInterruptible(kotlinx.coroutines.Dispatchers.IO) {
+ runCatching {
+ val address = network.getAllByName(host).first()
+ network.socketFactory.createSocket().use { socket ->
+ socket.connect(java.net.InetSocketAddress(address, 443), PROBE_TIMEOUT_MS.toInt())
+ }
+ true
+ }.getOrDefault(false)
+ }
+ } ?: false
}
private companion object {
@@ -174,5 +277,16 @@ class NetworkWatch(context: Context, private val scope: CoroutineScope) {
/** How long the system takes to stop naming a network that has gone. */
const val SETTLE_MS = 1_200L
+
+ /** How long a probe waits for a connection before calling it gone. */
+ const val PROBE_TIMEOUT_MS = 4_000L
+
+ /** The least time between probes of mobile data that answers. */
+ const val PROBE_GAP_MS = 30_000L
+
+ /** How often mobile data that stopped answering is tried again. */
+ const val PROBE_RETRY_MS = 10_000L
+
+ val PROBE_HOSTS = listOf("apresolve.spotify.com", "music.youtube.com")
}
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
index 8b802e1..e39c578 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -4294,6 +4294,15 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
} catch (t: Throwable) {
android.util.Log.e(TAG, "detail load failed: ${chain(t)}", t)
if (isActive && _playlist.value.uri == playlist.uri) {
+ // Downloaded, it is on the phone whatever the network says:
+ // a connection that is up and carrying nothing fails here
+ // without the app being offline, and the songs it could
+ // play were hidden behind an error.
+ val downloaded = container.downloads.owners.value[playlist.uri]
+ if (cached.isEmpty() && rememberedArtist == null && downloaded != null) {
+ openDownloadedContext(playlist, downloaded)
+ return@launch
+ }
val hasCachedContent = cached.isNotEmpty() || rememberedArtist != null
val fallbackTracks = cached.ifEmpty { rememberedArtist?.tracks.orEmpty() }
publishPlaylist(
diff --git a/native/src/engine.rs b/native/src/engine.rs
index d9a4d22..91d9f87 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -841,6 +841,18 @@ pub fn set_offline_only(only: bool) {
}
}
+/// Whether commands go to the player alone, leaving Connect out of them.
+///
+/// With no session, with a device that is gone, and also whenever the app is
+/// offline, by the listener's switch or because the network stopped carrying
+/// anything. That last one was missing: on mobile data with no coverage the
+/// session's sockets stay open for minutes with nothing coming through them,
+/// so the device did not look lost, the load went to Connect, and Connect
+/// waited on Spotify for a downloaded track that needed nothing but its file.
+fn player_only() -> bool {
+ OFFLINE.load(Ordering::SeqCst) || OFFLINE_ONLY.load(Ordering::SeqCst) || spirc_lost()
+}
+
/// Whether the engine came up with no connection; see [`OFFLINE`].
pub fn is_offline() -> bool {
OFFLINE.load(Ordering::SeqCst)
@@ -1784,7 +1796,7 @@ pub fn load_queue(
// so with the network gone it died there — and a downloaded track, which
// needs nothing but the file, never got the chance to play. The player's
// own loader reads the disk first; it only has to be reached.
- if with_bundle(|e| e.spirc.is_none())? || spirc_lost() {
+ if with_bundle(|e| e.spirc.is_none())? || player_only() {
log::info!("no usable connect device; loading through the player");
return local_load(&uris, index, start_playing, position_ms);
}
@@ -1936,7 +1948,7 @@ fn transport(
});
}
- if OFFLINE.load(Ordering::SeqCst) || spirc_lost() {
+ if player_only() {
return with_bundle(|engine| {
log::warn!("{what}: no connect device, going straight to the player");
via_player(engine);
@@ -2109,7 +2121,7 @@ pub fn seek(position_ms: u32) -> EngineResult<()> {
// dragging or tapping the progress bar offline reached a Connect device
// that is not there and did nothing at all. What plays is the player's, and
// moving within a track is something it can do on its own.
- if OFFLINE.load(Ordering::SeqCst) || spirc_lost() {
+ if player_only() {
return with_bundle(|e| e.player.seek(position_ms));
}
with_bundle(|e| e.spirc()?.set_position_ms(position_ms))?.map_err(|e| format!("seek failed: {e}"))