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.

Offline as a place the app can actually be

Lelonio5543f7bc2690
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
index dc95542..903ddfc 100644
--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt
+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
@@ -45,6 +45,20 @@ class SquareApplication : Application() {
downloads.isDownloaded(it)
}
+ // Two things feed the offline state, and one thing reads it out to the
+ // engine. The switch below is the listener's; the watch is the network
+ // going; and the engine has to be told either way, because it cannot
+ // see either of them and would otherwise go on fetching.
+ val offlineScope = kotlinx.coroutines.CoroutineScope(
+ kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.Default,
+ )
+ dev.lelonio.square.playback.NetworkWatch(this, offlineScope).start()
+ offlineScope.launch {
+ dev.lelonio.square.playback.OfflineMode.active.collect { offline ->
+ runCatching { dev.lelonio.square.nativecore.NativeBridge.setOfflineOnly(offline) }
+ }
+ }
+
// The listener's own offline switch is persisted, so it has to be put
// back before anything reads it. Collected rather than read once: it is
// the one input to OfflineMode that can change without the service
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 df91ade..9f837ba 100644
--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
@@ -498,6 +498,15 @@ object NativeBridge {
*/
val isOffline: Boolean get() = nativeIsOffline()
+ /**
+ * Whether the player may play anything that is not on the phone.
+ *
+ * Told rather than asked: the engine cannot see the listener's own offline
+ * switch, and a mode that still reaches for the network when a track is
+ * missing is a label rather than a mode.
+ */
+ fun setOfflineOnly(only: Boolean) = nativeSetOfflineOnly(only)
+
/**
* Where downloaded tracks are kept.
*
@@ -551,6 +560,7 @@ object NativeBridge {
private external fun nativeTrackRelatives(trackUri: String): String
private external fun nativeCanvas(trackUri: String): String
private external fun nativeIsOffline(): Boolean
+ private external fun nativeSetOfflineOnly(only: Boolean)
private external fun nativeSetDownloadRoot(path: String)
private external fun nativeDownloadTrack(trackUri: String, bitrateKbps: Int): String
private external fun nativeDownloadState(trackUri: String): String
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 57f4689..9201e8c 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -419,8 +419,19 @@ class LibrespotPlayer(
}
/** Whether the engine says its Connect device is gone; false if it cannot answer. */
+ /**
+ * Whether a step command has anything to reach.
+ *
+ * Offline counts, and has to: the engine reports no lost device then —
+ * there is none to lose — so a skip took the ordinary road, was handed to a
+ * Connect device that does not exist, and fell through to the player, whose
+ * 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.
+ */
private val deviceGone: Boolean
- get() = runCatching { NativeBridge.spircLost }.getOrDefault(false)
+ get() = OfflineMode.active.value ||
+ runCatching { NativeBridge.spircLost }.getOrDefault(false)
/** Set while a reconnection is in flight, so a burst of taps starts one. */
private var reconnecting = false
diff --git a/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt b/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
new file mode 100644
index 0000000..9e33891
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/playback/NetworkWatch.kt
@@ -0,0 +1,135 @@
+package dev.lelonio.square.playback
+
+import android.content.Context
+import android.net.ConnectivityManager
+import android.net.Network
+import android.net.NetworkCapabilities
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+/**
+ * Turns the app offline when the connection goes, and back when it returns.
+ *
+ * Offline used to be decided once, when the engine started, which left the
+ * common case unhandled: a phone that loses signal while playing kept behaving
+ * as though it were online — queues full of tracks it could not fetch, no line
+ * on the page saying why, and a listener wondering what had broken.
+ *
+ * Losing the network waits a few seconds before it counts. Signal drops for a
+ * moment in a lift or between cells, and an app that rearranged itself every
+ * time would be worse than one that noticed late. Coming back counts at once:
+ * there is nothing to protect against there, and the sooner the library is
+ * whole again the better.
+ */
+class NetworkWatch(context: Context, private val scope: CoroutineScope) {
+
+ private val connectivity = context.applicationContext
+ .getSystemService(ConnectivityManager::class.java)
+
+ /** Held so a connection that returns within the grace period cancels it. */
+ private var pending: Job? = null
+
+ /** A second look, because the first one races the system's own bookkeeping. */
+ private var settle: Job? = null
+
+ private val callback = object : ConnectivityManager.NetworkCallback() {
+ override fun onAvailable(network: Network) = recheck()
+ override fun onLost(network: Network) = recheck()
+ override fun onCapabilitiesChanged(
+ network: Network,
+ capabilities: NetworkCapabilities,
+ ) = recheck()
+ }
+
+ fun start() {
+ val registered = runCatching {
+ connectivity?.registerDefaultNetworkCallback(callback)
+ }.isSuccess
+ android.util.Log.i(TAG, "network watch started (registered=$registered)")
+ recheck()
+ }
+
+ private fun recheck() {
+ // Asked again a moment later, always.
+ //
+ // The callback for the last network going away arrives before the
+ // system stops reporting that network as the active one, so reading it
+ // here answered "still connected" — and since nothing changes after the
+ // last network is gone, no further callback ever came to correct it.
+ // The app stayed online, on a phone with the radios off, for as long as
+ // it was left running.
+ settle?.cancel()
+ settle = scope.launch {
+ delay(SETTLE_MS)
+ evaluate()
+ }
+ evaluate()
+ }
+
+ private fun evaluate() {
+ val connected = connected()
+ android.util.Log.i(TAG, "network is ${if (connected) "up" else "gone"}: ${describe()}")
+ pending?.cancel()
+ if (connected) {
+ OfflineMode.setNoSession(false)
+ return
+ }
+ pending = scope.launch {
+ delay(GRACE_MS)
+ android.util.Log.i(TAG, "still gone: going offline")
+ OfflineMode.setNoSession(true)
+ }
+ }
+
+ /**
+ * Whether there is a link that actually reaches the internet.
+ *
+ * `NET_CAPABILITY_VALIDATED` rather than merely connected: a Wi-Fi that has
+ * not passed its own check — a captive portal, a router with no line behind
+ * it — is a network to the system and nothing at all to this app.
+ */
+ /**
+ * What the system says is carrying the traffic, for the log.
+ *
+ * Which transport it is matters: reporting "up" with everything switched
+ * off means this is reading something that is not the listener's
+ * connection — a tunnel, a tether, a link the system has not torn down yet
+ * — and the name of it is the difference between a wrong answer and a
+ * wrong question.
+ */
+ private fun describe(): String {
+ val network = connectivity?.activeNetwork ?: return "no active network"
+ val capabilities = connectivity.getNetworkCapabilities(network)
+ ?: return "active network with no capabilities"
+ val transports = listOfNotNull(
+ "wifi".takeIf { capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) },
+ "cellular".takeIf { capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) },
+ "ethernet".takeIf { capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) },
+ "vpn".takeIf { capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) },
+ "usb".takeIf { capabilities.hasTransport(NetworkCapabilities.TRANSPORT_USB) },
+ "bluetooth".takeIf { capabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) },
+ ).joinToString("+").ifEmpty { "unknown transport" }
+ val internet = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
+ val validated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
+ return "$transports internet=$internet validated=$validated"
+ }
+
+ private fun connected(): Boolean {
+ val network = connectivity?.activeNetwork ?: return false
+ val capabilities = connectivity.getNetworkCapabilities(network) ?: return false
+ return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
+ capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
+ }
+
+ private companion object {
+ const val TAG = "SquareNetwork"
+
+ /** How long the network has to stay gone before the app believes it. */
+ const val GRACE_MS = 6_000L
+
+ /** How long the system takes to stop naming a network that has gone. */
+ const val SETTLE_MS = 1_200L
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/playback/OfflineMode.kt b/app/src/main/java/dev/lelonio/square/playback/OfflineMode.kt
index 3fa76a8..f0b2383 100644
--- a/app/src/main/java/dev/lelonio/square/playback/OfflineMode.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/OfflineMode.kt
@@ -50,15 +50,19 @@ object OfflineMode {
val active: StateFlow<Boolean> = _active.asStateFlow()
fun setManual(on: Boolean) {
- if (_manual.value == on) return
- _manual.value = on
+ synchronized(this) {
+ if (_manual.value == on) return
+ _manual.value = on
+ }
recompute()
}
/** Told by the service once the engine has answered for itself. */
fun setNoSession(on: Boolean) {
- if (_noSession.value == on) return
- _noSession.value = on
+ synchronized(this) {
+ if (_noSession.value == on) return
+ _noSession.value = on
+ }
recompute()
}
@@ -67,11 +71,25 @@ object OfflineMode {
* already holds. See `PlaybackService.watchConnection`.
*/
fun setSlow(on: Boolean) {
- if (_slow.value == on) return
- _slow.value = on
+ synchronized(this) {
+ if (_slow.value == on) return
+ _slow.value = on
+ }
recompute()
}
+ /**
+ * Worked out under a lock, because three things write to it.
+ *
+ * The switch, the network watch and the engine all report in, and two of
+ * them arriving together is not rare: a connection returning cancels the
+ * watch's timer at the same moment the timer fires. Read without one, each
+ * caller decided from a state the other had already moved on from, and the
+ * app settled into "offline, because there is no session" a few
+ * milliseconds after the session came back — off by exactly one update,
+ * with a reason that was no longer true.
+ */
+ @Synchronized
private fun recompute() {
val next = when {
_manual.value -> Reason.MANUAL
@@ -80,6 +98,11 @@ object OfflineMode {
else -> null
}
if (_reason.value == next) return
+ android.util.Log.i(
+ "SquareOffline",
+ "offline reason: ${_reason.value} -> $next" +
+ " (manual=${_manual.value}, noSession=${_noSession.value}, slow=${_slow.value})",
+ )
_reason.value = next
_active.value = next != null
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
index 913d540..b8583e8 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
@@ -288,9 +288,34 @@ class MainActivity : ComponentActivity() {
positionMs: Long = 0L,
) {
val player = controller ?: return
+
+ // Offline, the queue is only what can actually be played.
+ //
+ // The rows for the rest are already inert, so nothing here is being
+ // taken away that the listener could have chosen — but a queue is not
+ // only what was tapped. Left whole it would advance into a track that
+ // cannot be fetched, and the silence after a downloaded song would look
+ // like the download had failed rather than like the song after it was
+ // never here. Files on the phone play in every mode; they were never
+ // coming over the network.
+ val playable = if (!dev.lelonio.square.playback.OfflineMode.active.value) {
+ tracks
+ } else {
+ val here = (application as dev.lelonio.square.SquareApplication)
+ .downloads.files.value
+ tracks.filter { it.uri.startsWith("local:") || it.uri in here }
+ }
+ if (playable.isEmpty()) return
+
+ // The song that was tapped keeps its place, wherever the filtering left
+ // it; falling back to the top rather than to whatever now sits at the
+ // old index, which would be a different song entirely.
+ val wanted = tracks.getOrNull(index)?.uri
+ val start = playable.indexOfFirst { it.uri == wanted }.coerceAtLeast(0)
+
player.setMediaItems(
- tracks.map { toMediaItem(it, contextUri, asContext, contextLabel) },
- index,
+ playable.map { toMediaItem(it, contextUri, asContext, contextLabel) },
+ start,
positionMs,
)
player.prepare()
@@ -340,7 +365,21 @@ class MainActivity : ComponentActivity() {
// YouTube's shelves carry no length, and a zero here would
// win over the one the player works out from the stream.
.setDurationMs(track.durationMs.takeIf { it > 0 })
- .setArtworkUri(track.artworkUrl?.let(android.net.Uri::parse))
+ // The copy saved beside the download, when there is one.
+ //
+ // Not a fallback but a preference, the same way the app's
+ // own artwork reads it: the URL names the picture, so the
+ // bytes cannot have changed, and a file plays offline while
+ // a URL is a fetch that fails. The notification was the one
+ // place still handed the URL, so a downloaded song played
+ // with a blank tile on the lock screen.
+ .setArtworkUri(
+ track.artworkUrl?.let { url ->
+ dev.lelonio.square.download.DownloadExtras.fileOf(url, "art")
+ ?.let(android.net.Uri::fromFile)
+ ?: android.net.Uri.parse(url)
+ },
+ )
// Where the queue came from, carried with the item because
// the engine lives in the service and this is the only
// channel between them that survives the session boundary.
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 815130b..e521dd5 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -47,6 +47,7 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
@@ -471,6 +472,47 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
private var devicesJob: Job? = null
init {
+ // Offline and back, without a restart in between.
+ //
+ // The library and the home page are each built once, from whichever
+ // source was available at the time, and nothing rebuilt them when that
+ // changed: a phone that found signal again went on showing the handful
+ // of downloaded playlists, and one that lost it went on offering rows
+ // it could no longer fetch. Both directions are the same event, so both
+ // are handled here.
+ //
+ // The current value is skipped — the first load is already on its way
+ // when this starts, and running it twice would be two libraries built
+ // at once.
+ viewModelScope.launch {
+ dev.lelonio.square.playback.OfflineMode.active
+ .drop(1)
+ .distinctUntilChanged()
+ .collect { offline ->
+ android.util.Log.i(TAG, "offline changed to $offline: rebuilding")
+ if (offline) {
+ // What needed a connection goes now rather than staying
+ // as rows that answer nothing when tapped.
+ _feed.value = FeedState()
+ _homeShelves.value = emptyList()
+ _friends.value = emptyList()
+ }
+ // Waited for, not merely started. The library load is
+ // what waits for the session to come back up, and
+ // everything below reads that session: fired alongside it
+ // they all asked while the handshake was still in flight,
+ // failed quietly, and were never tried again — which is why
+ // coming back online left the app's own shelves on the home
+ // page and none of Spotify's.
+ refresh().join()
+ if (!offline) {
+ loadFeed()
+ loadHomeShelves()
+ loadFriends()
+ }
+ }
+ }
+
// The list, kept true by the engine rather than by asking.
//
// The Web API answers this too, but only when asked, so a sheet left
@@ -1412,6 +1454,21 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
return@launch
}
+ // Offline, there is nothing to wait for.
+ //
+ // The wait below is for a session to come up, and it ends either when
+ // one does or after thirty seconds. Neither happens with the network
+ // gone: the engine is up, it simply has no session, so the spinner sat
+ // there for several seconds before the downloads appeared — the one
+ // moment the app should be quickest, since everything it is about to
+ // show is already on the phone.
+ if (dev.lelonio.square.playback.OfflineMode.active.value) {
+ offlineLibrary()?.let {
+ _state.value = it
+ return@launch
+ }
+ }
+
_state.value = UiState.Connecting
if (!awaitEngine()) {
// A library with no session is not an empty library. Everything
@@ -1476,8 +1533,14 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
CatalogPlaylist(uri = uri, name = it.name, artworkUrl = it.artworkUrl)
}
}
- val singles = owners[DownloadStore.SINGLES].orEmpty()
- val shelf = singles.takeIf { it.isNotEmpty() }?.let {
+ // Everything on the phone, not only the songs downloaded on their own.
+ //
+ // It was the loose ones at first, which is what the store calls them —
+ // and a shelf named "downloaded songs" holding one of the hundred and
+ // ninety on the phone is a shelf that lies. The playlists are listed
+ // beside it either way, so this is the one place that answers "what can
+ // I play right now" without picking through them.
+ val shelf = container.downloads.files.value.keys.takeIf { it.isNotEmpty() }?.let {
CatalogPlaylist(
uri = DownloadStore.SINGLES,
name = string(R.string.downloaded_tracks),
@@ -2229,6 +2292,24 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
return
}
+ // The shelf of downloaded songs is not a context at all: its uri
+ // belongs to this app rather than to Spotify, and asking the access
+ // point to resolve it answered "invalid argument". This app keeps the
+ // list, so this app answers for it — online as much as offline, and
+ // with everything on the phone rather than only the loose songs.
+ if (playlist.uri == DownloadStore.SINGLES) {
+ // Newest first: a shelf of everything is read from the top, and
+ // what was just downloaded is what somebody came looking for.
+ openDownloadedContext(
+ playlist,
+ container.downloads.files.value
+ .entries
+ .sortedByDescending { it.value.downloadedAt }
+ .map { it.key },
+ )
+ return
+ }
+
// Offline, a downloaded playlist is answered from the index too. Not a
// fallback after a failed request but instead of one: with no session
// the request cannot even be attempted, and the whole list is already
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/Artwork.kt b/app/src/main/java/dev/lelonio/square/ui/components/Artwork.kt
index 49b31cb..0870663 100644
--- a/app/src/main/java/dev/lelonio/square/ui/components/Artwork.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/components/Artwork.kt
@@ -19,7 +19,7 @@ import androidx.compose.ui.graphics.Color
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.Regular
-import com.adamglin.phosphoricons.fill.ArrowCircleDown
+import com.adamglin.phosphoricons.regular.ArrowCircleDown
import com.adamglin.phosphoricons.regular.FolderSimple
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
@@ -140,10 +140,14 @@ private fun DownloadsCover() {
.background(LocalFilesTile),
contentAlignment = Alignment.Center,
) {
+ // Drawn like the local files shelf beside it: the same tile, the same
+ // size, an outlined glyph rather than a filled disc. The two are the
+ // same kind of thing — music that is already on the phone — and they
+ // should read as a pair rather than as one shelf and one badge.
Icon(
- PhosphorIcons.Fill.ArrowCircleDown,
+ PhosphorIcons.Regular.ArrowCircleDown,
contentDescription = null,
- tint = androidx.compose.material3.MaterialTheme.colorScheme.primary,
+ tint = DownloadsGlyph,
modifier = Modifier.fillMaxSize(0.44f),
)
}
@@ -152,6 +156,9 @@ private fun DownloadsCover() {
private val LocalFilesTile = Color(0xFF20306E)
private val LocalFilesGlyph = Color(0xFF2ECC57)
+/** The downloads shelf's own glyph colour; see [LocalFilesGlyph] beside it. */
+private val DownloadsGlyph = Color(0xFF35B7E8)
+
@Composable
private fun GeneratedCover(title: String, corner: Dp) {
val seed = remember(title) { title.hashCode().absoluteValue }
diff --git a/native/src/engine.rs b/native/src/engine.rs
index d986c25..e1d0aaf 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -420,6 +420,12 @@ pub fn start(
// than handed over as a list, since downloads come and go while the
// player is running; see downloads::lookup.
download_lookup: Some(crate::downloads::lookup()),
+ // And whether anything else may be played at all. Offline — by the
+ // listener's own switch, or because the engine has no session — a track
+ // with no file fails to load rather than being fetched.
+ downloads_only: Some(Arc::new(|| {
+ OFFLINE_ONLY.load(Ordering::SeqCst) || OFFLINE.load(Ordering::SeqCst)
+ })),
// Chosen by the caller. The bitrate is read when a track is loaded but
// the player owns its config for its whole life, so changing this means
// building a new engine: see PlaybackService.
@@ -780,6 +786,20 @@ fn local_load(uris: &[String], index: u32, play: bool, position_ms: u32) -> Engi
with_bundle(|e| e.player.load(parsed, play, position_ms))
}
+/// Set by the app when only downloads may be played.
+///
+/// Distinct from [`OFFLINE`], which is about how the engine started: this is
+/// what the listener asked for, or what a connection that has gone means for a
+/// session that was built while it was there. Read on every load.
+static OFFLINE_ONLY: AtomicBool = AtomicBool::new(false);
+
+/// Says whether the player may reach for the network at all.
+pub fn set_offline_only(only: bool) {
+ if OFFLINE_ONLY.swap(only, Ordering::SeqCst) != only {
+ log::info!("playing {}", if only { "from downloads only" } else { "from anywhere" });
+ }
+}
+
/// Whether the engine came up with no connection; see [`OFFLINE`].
pub fn is_offline() -> bool {
OFFLINE.load(Ordering::SeqCst)
@@ -1599,7 +1619,15 @@ pub fn load_queue(
// back for the next one when this ends. Everything above still runs, so
// what the app believes about the queue is unchanged either way — the only
// difference is who advances it.
- if with_bundle(|e| e.spirc.is_none())? {
+ //
+ // The same road is taken when there is a device but it cannot be reached,
+ // which is what a connection dropping mid-listen looks like. A load handed
+ // to Connect is resolved on Spotify's side before the player is ever asked,
+ // 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() {
+ log::info!("no usable connect device; loading through the player");
return local_load(&uris, index, start_playing, position_ms);
}
@@ -1876,6 +1904,15 @@ pub fn stop() -> EngineResult<()> {
}
pub fn seek(position_ms: u32) -> EngineResult<()> {
+ // The player itself when there is no device to ask.
+ //
+ // Every other command already had this fallback; seeking did not, so
+ // 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() {
+ 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}"))
}
diff --git a/native/src/ffi.rs b/native/src/ffi.rs
index 643611d..a0d63e8 100644
--- a/native/src/ffi.rs
+++ b/native/src/ffi.rs
@@ -745,6 +745,17 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeIsO
if engine::is_offline() { JNI_TRUE } else { JNI_FALSE }
}
+/// Whether the player may only use what is on the phone; see
+/// `engine::set_offline_only`.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSetOfflineOnly(
+ _env: JNIEnv,
+ _class: JClass,
+ only: jboolean,
+) {
+ engine::set_offline_only(only == JNI_TRUE);
+}
+
// --------------------------------------------------------------- downloads
/// Where downloads are kept. Called before anything is downloaded, and again
diff --git a/native/vendor/librespot-playback/src/config.rs b/native/vendor/librespot-playback/src/config.rs
index 20757ca..8a9de90 100644
--- a/native/vendor/librespot-playback/src/config.rs
+++ b/native/vendor/librespot-playback/src/config.rs
@@ -49,6 +49,15 @@ pub struct DownloadedTrack {
/// schema it has no other reason to know.
pub type DownloadLookup = Arc<dyn Fn(&SpotifyId) -> Option<DownloadedTrack> + Send + Sync>;
+/// LOCAL PATCH: whether only downloaded tracks may be played, asked per load.
+///
+/// A function rather than a flag because the answer changes while the player
+/// lives: the listener turns offline on in Settings, or the network goes. When
+/// it says yes, a track with no file on disk fails to load instead of being
+/// fetched — which is the whole of what "offline" has to mean, or the mode is
+/// a label on a player that goes on using the network.
+pub type DownloadsOnly = Arc<dyn Fn() -> bool + Send + Sync>;
+
#[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq, Default)]
pub enum Bitrate {
Bitrate96,
@@ -181,6 +190,9 @@ pub struct PlayerConfig {
///
/// `None`, the default, is upstream behaviour: every track is fetched.
pub download_lookup: Option<DownloadLookup>,
+
+ /// LOCAL PATCH: asked before falling back to the network; see [`DownloadsOnly`].
+ pub downloads_only: Option<DownloadsOnly>,
}
impl Default for PlayerConfig {
@@ -202,6 +214,7 @@ impl Default for PlayerConfig {
local_file_directories: Vec::new(),
crossfade_duration_ms: 0,
download_lookup: None,
+ downloads_only: None,
}
}
}
diff --git a/native/vendor/librespot-playback/src/player.rs b/native/vendor/librespot-playback/src/player.rs
index 8da2723..2e88b31 100644
--- a/native/vendor/librespot-playback/src/player.rs
+++ b/native/vendor/librespot-playback/src/player.rs
@@ -1129,6 +1129,23 @@ impl PlayerTrackLoader {
if let Some(loaded) = self.load_downloaded_track(&track_uri, position_ms) {
return Some(loaded);
}
+ // LOCAL PATCH: offline, there is no second chance.
+ //
+ // Streaming this would be the app quietly using the network the
+ // listener asked it not to use — on a metered connection, or on
+ // none, where it fails after a wait instead. A track with no
+ // file simply does not load, and the queue was built out of the
+ // ones that have one.
+ if self
+ .config
+ .downloads_only
+ .as_ref()
+ .map(|only| only())
+ .unwrap_or(false)
+ {
+ warn!("<{track_uri}> is not downloaded and this player is offline");
+ return None;
+ }
self.load_remote_track(track_uri, position_ms).await
}
SpotifyUri::Local { .. } => self.load_local_track(track_uri, position_ms).await,