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.

Music that stays on the phone, and a home page worth opening

Lelonioafcd13cb8f35
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index ae6698c..583546f 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -52,6 +52,7 @@ android {
targetSdk = 35
versionCode = 23
versionName = "2.0.1"
+ buildConfigField("boolean", "VERBOSE_LOG", "false")
ndk {
abiFilters += nativeAbis
@@ -108,6 +109,11 @@ android {
initWith(getByName("release"))
isMinifyEnabled = false
isShrinkResources = false
+ // This build type is release-shaped, so BuildConfig.DEBUG is false
+ // here and anything gated on it stays off — including the log the
+ // vendored InnerTube module writes through Timber, which is the
+ // only view there is of a page that came back in the wrong shape.
+ buildConfigField("boolean", "VERBOSE_LOG", "true")
// The real key when there is one: a build signed with a different
// key than the copy already on the phone cannot replace it, and
// uninstalling first would take the login and the saved queue with
@@ -161,6 +167,7 @@ android {
}
dependencies {
+ implementation(libs.timber)
implementation(libs.androidx.core.ktx)
// Installs baseline-prof.txt on first run, so the code the bar and the
// player use is compiled before it is needed rather than while it runs.
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 10a5b88..7937b58 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -101,6 +101,16 @@
The download of a new version, which has to be allowed to finish:
see UpdateService.
-->
+ <!--
+ Its own service, not a second job for the player's: a playlist can be
+ downloading with nothing playing, and music can play with nothing left
+ to fetch. Not exported — only this app ever starts it.
+ -->
+ <service
+ android:name=".download.DownloadService"
+ android:exported="false"
+ android:foregroundServiceType="dataSync" />
+
<service
android:name=".update.UpdateService"
android:exported="false"
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
index f85c1f8..dc95542 100644
--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt
+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
@@ -7,6 +7,7 @@ import dev.lelonio.square.data.ContextCacheStore
import dev.lelonio.square.data.LanguageStore
import dev.lelonio.square.data.PlaylistOrderStore
import dev.lelonio.square.data.PreferencesStore
+import kotlinx.coroutines.launch
import dev.lelonio.square.data.RecentStore
import dev.lelonio.square.playback.EffectPresetStore
import dev.lelonio.square.data.ApiFactory
@@ -23,12 +24,39 @@ class SquareApplication : Application() {
override fun onCreate() {
super.onCreate()
+ // The vendored InnerTube module logs through Timber, and with nothing
+ // planted every one of those lines went nowhere — which is why a
+ // YouTube page that came back in an unexpected shape could only be
+ // guessed at. Debug builds only: a release build has no business
+ // writing what the account is doing to the system log.
+ if (BuildConfig.DEBUG || BuildConfig.VERBOSE_LOG) {
+ timber.log.Timber.plant(timber.log.Timber.DebugTree())
+ }
// Before anything can read or write them. The service used to do this on
// creation, which is late: the player screen and the media session both
// exist by then and either can announce a default that would be saved
// over what the listener had set.
dev.lelonio.square.playback.AudioEffects.load(this)
+ // Where the extras live, and which tracks are worth keeping them for.
+ // Attached here rather than in the service: Catalog reaches for it on
+ // any thread and long before anything has started playing.
+ dev.lelonio.square.download.DownloadExtras.attach(downloads.root) {
+ downloads.isDownloaded(it)
+ }
+
+ // 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
+ // being involved.
+ kotlinx.coroutines.CoroutineScope(
+ kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.Default,
+ ).launch {
+ downloadSettings.offlineMode.collect(
+ dev.lelonio.square.playback.OfflineMode::setManual,
+ )
+ }
+
// Not a feature: a line in the log saying whether this install has been
// compiled ahead of time yet. See reportProfileStatus.
reportProfileStatus(
@@ -38,6 +66,27 @@ class SquareApplication : Application() {
val tokenStore: TokenStore by lazy { TokenStore(this) }
+ /**
+ * What is downloaded and who asked for it.
+ *
+ * One instance, like the token store and for the same reason: the index is
+ * a file, and two of these would write over each other. The audio it points
+ * at belongs to the engine, which finds it without going through here.
+ */
+ val downloads: dev.lelonio.square.data.DownloadStore by lazy {
+ dev.lelonio.square.data.DownloadStore(this)
+ }
+
+ /** Download quality, Wi-Fi only, the offline switch. */
+ val downloadSettings: dev.lelonio.square.data.DownloadSettingsStore by lazy {
+ dev.lelonio.square.data.DownloadSettingsStore(this)
+ }
+
+ /** Works through what [downloads] says is still owed. */
+ val downloadQueue: dev.lelonio.square.download.DownloadQueue by lazy {
+ dev.lelonio.square.download.DownloadQueue(this, downloads, downloadSettings)
+ }
+
/**
* Whether Spotify can be used, which is not the same as holding a token.
*
diff --git a/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt b/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt
index 961490f..89582c3 100644
--- a/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt
@@ -3,6 +3,7 @@ package dev.lelonio.square.backend
import androidx.media3.common.Player
import dev.lelonio.square.data.CatalogPlaylist
import dev.lelonio.square.data.CatalogTrack
+import dev.lelonio.square.data.SearchItem
import dev.lelonio.square.data.SearchResults
import kotlinx.coroutines.flow.StateFlow
@@ -41,10 +42,40 @@ data class HomeRow(
val tracks: List<CatalogTrack> = emptyList(),
/** Playlists, albums and artists alike: all of them open a track list. */
val items: List<CatalogPlaylist> = emptyList(),
+ /**
+ * The small line above the title — "MIX", an artist's name, a genre.
+ *
+ * YouTube writes it for about half its shelves and it is most of what tells
+ * two rows called "Radio" apart.
+ */
+ val strapline: String? = null,
) {
val isEmpty: Boolean get() = tracks.isEmpty() && items.isEmpty()
}
+/**
+ * One of the filters above a home page: "Relax", "Workout", "Feel good".
+ *
+ * [params] is the service's own token for that view, passed straight back when
+ * the chip is picked. Null on the chip that clears the filter.
+ */
+data class HomeChip(val title: String, val params: String?)
+
+/**
+ * A home page as it arrives: some shelves, and where the next ones are.
+ *
+ * The page is paged on purpose. YouTube's home opens with four or five shelves
+ * and holds the other twenty behind a continuation token, which is why a home
+ * read in one call looks like an app with nothing in it.
+ */
+data class HomeFeed(
+ val rows: List<HomeRow> = emptyList(),
+ /** Opaque, and handed back to fetch what comes after these rows. */
+ val cursor: String? = null,
+ /** Only on the first page; a continuation carries no chips of its own. */
+ val chips: List<HomeChip> = emptyList(),
+)
+
/**
* A source of music: catalogue reads plus a [Player] that can play what the
* catalogue points at.
@@ -91,8 +122,22 @@ interface MusicBackend {
*
* Empty by default: a backend whose home is assembled from the account's
* own data elsewhere has no use for it.
+ *
+ * @param cursor from a previous [HomeFeed], to read the next shelves.
+ * @param params the token of a chip the user picked, to read that view.
*/
- suspend fun homeRows(): List<HomeRow> = emptyList()
+ suspend fun homeFeed(cursor: String? = null, params: String? = null): HomeFeed = HomeFeed()
+
+ /**
+ * The albums the account has saved, for the library's own shelf of them.
+ *
+ * Apart from [playlists] because the library filters by kind, and a shelf
+ * that cannot say which is which has nothing to filter by.
+ */
+ suspend fun savedAlbums(): List<CatalogPlaylist> = emptyList()
+
+ /** The artists the account follows, for the same shelf's artists chip. */
+ suspend fun followedArtists(): List<SearchItem> = emptyList()
/** Tracks of a playlist, album, or artist URI this backend owns. */
suspend fun tracksOf(uri: String): List<CatalogTrack>
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeAccount.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeAccount.kt
index 37db256..114a5a6 100644
--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeAccount.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeAccount.kt
@@ -4,6 +4,7 @@ import android.content.Context
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import com.metrolist.innertube.YouTube
+import com.metrolist.innertube.models.YouTubeChannel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -37,6 +38,16 @@ class YouTubeAccount(context: Context) {
val isSignedIn: Boolean get() = prefs.getString(KEY_COOKIE, null) != null
+ /**
+ * True once the stored session has been refused.
+ *
+ * A cookie that has stopped working looks exactly like an empty library
+ * from the outside, which is the worst way for this to fail: nothing on
+ * screen says the account came loose. This is what lets a screen say it.
+ */
+ private val _expired = MutableStateFlow(false)
+ val expired: StateFlow<Boolean> = _expired.asStateFlow()
+
init {
// Before anything asks the module for a page: the cookie is what turns
// its calls from "the anonymous catalogue" into "this account's".
@@ -55,6 +66,46 @@ class YouTubeAccount(context: Context) {
YouTube.cookie = prefs.getString(KEY_COOKIE, null)
YouTube.visitorData = prefs.getString(KEY_VISITOR_DATA, null).orEmpty()
YouTube.dataSyncId = prefs.getString(KEY_DATA_SYNC_ID, null).orEmpty()
+ // Which of the account's channels is answering. Null is the personal
+ // one, which is what the cookie alone reads as.
+ YouTube.pageId = prefs.getString(KEY_PAGE_ID, null)
+ }
+
+ /**
+ * The channels this Google account can act as.
+ *
+ * A Google account is not one YouTube identity: there is the personal
+ * channel and any brand channel it owns — a channel with its own
+ * subscriptions, its own library, its own history. The official app has a
+ * switcher for exactly this, and until now a session here always answered
+ * as whichever one Google considered active.
+ */
+ suspend fun channels(): List<YouTubeChannel> =
+ if (!isSignedIn) emptyList() else YouTube.accounts().getOrElse {
+ android.util.Log.w(TAG, "channel list unavailable: $it")
+ emptyList()
+ }
+
+ /** Which one is being read, by page id; null is the personal channel. */
+ private val _pageId = MutableStateFlow(prefs.getString(KEY_PAGE_ID, null))
+ val pageId: StateFlow<String?> = _pageId.asStateFlow()
+
+ /**
+ * Reads the account as this channel from now on.
+ *
+ * The page id and the datasync id go together: the first says which
+ * channel the request is for, the second which library to sync it against,
+ * and a mismatched pair reads the right name over the wrong music.
+ */
+ fun useChannel(channel: YouTubeChannel) {
+ prefs.edit()
+ .putString(KEY_PAGE_ID, channel.pageId)
+ .putString(KEY_DATA_SYNC_ID, channel.dataSyncId.orEmpty())
+ .putString(KEY_NAME, channel.name)
+ .apply()
+ _pageId.value = channel.pageId
+ _accountName.value = channel.name
+ applyToInnerTube()
}
fun save(cookie: String, visitorData: String, dataSyncId: String, name: String) {
@@ -68,9 +119,83 @@ class YouTubeAccount(context: Context) {
applyToInnerTube()
}
+ /**
+ * Keeps the stored session current, and says whether it still works.
+ *
+ * Three things happen here, in the order that matters.
+ *
+ * The cookie first. Google rewrites it as it goes — a new `SID` after a
+ * password change, a refreshed `__Secure-3PSID` — and the web view's own
+ * store is where those land, since InnerTube sends a fixed header and
+ * never reads a `Set-Cookie` back. Copying the web view's copy over the
+ * saved one is what makes a session outlive the day it was created.
+ *
+ * Then `visitorData`, which YouTube expires on its own schedule. It is not
+ * a credential and can simply be asked for again.
+ *
+ * Then the session is used, once, for the cheapest signed-in call there
+ * is. What comes back is the difference between "the library is empty" and
+ * "the account is gone", which is the whole reason to do this at startup
+ * rather than waiting for a page to look broken.
+ */
+ suspend fun revalidate() {
+ if (!isSignedIn) return
+
+ webViewCookie()?.let { fresh ->
+ if (fresh != prefs.getString(KEY_COOKIE, null)) {
+ prefs.edit().putString(KEY_COOKIE, fresh).apply()
+ applyToInnerTube()
+ }
+ }
+
+ if (YouTube.visitorData.isNullOrBlank()) {
+ YouTube.visitorData()
+ .onSuccess { fresh ->
+ prefs.edit().putString(KEY_VISITOR_DATA, fresh).apply()
+ YouTube.visitorData = fresh
+ }
+ }
+
+ YouTube.accountInfo()
+ .onSuccess { info ->
+ _expired.value = false
+ if (info.name != _accountName.value) {
+ prefs.edit().putString(KEY_NAME, info.name).apply()
+ _accountName.value = info.name
+ }
+ }
+ .onFailure {
+ // Only a refusal means the session is done. A phone with no
+ // network would otherwise sign the user out for being on a
+ // train.
+ val refused = it.message.orEmpty().let { message ->
+ "401" in message || "403" in message
+ }
+ android.util.Log.w(TAG, "youtube session check failed (refused=$refused): $it")
+ _expired.value = refused
+ }
+ }
+
+ /**
+ * What the web view holds for `music.youtube.com` right now.
+ *
+ * That store is the one Google writes to, and it survives restarts, so it
+ * is where a renewed cookie shows up first.
+ */
+ private fun webViewCookie(): String? =
+ runCatching { android.webkit.CookieManager.getInstance().getCookie(MUSIC_URL) }
+ .getOrNull()
+ ?.takeIf { it.isNotBlank() }
+
fun signOut() {
prefs.edit().clear().apply()
_accountName.value = null
+ _expired.value = false
+ // The web view's store too, or the next sign-in would walk straight
+ // back into the account that was just left.
+ runCatching {
+ android.webkit.CookieManager.getInstance().removeAllCookies(null)
+ }
applyToInnerTube()
}
@@ -80,5 +205,8 @@ class YouTubeAccount(context: Context) {
const val KEY_VISITOR_DATA = "visitor_data"
const val KEY_DATA_SYNC_ID = "data_sync_id"
const val KEY_NAME = "name"
+ const val KEY_PAGE_ID = "page_id"
+ const val MUSIC_URL = "https://music.youtube.com"
+ const val TAG = "SquareYouTubeAccount"
}
}
diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt
index 4227dda..e18cbe4 100644
--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt
@@ -21,9 +21,14 @@ import kotlinx.coroutines.withContext
import com.metrolist.innertube.YouTube
import com.metrolist.innertube.models.AlbumItem
import com.metrolist.innertube.models.ArtistItem
+import com.metrolist.innertube.models.EpisodeItem
+import com.metrolist.innertube.models.PodcastItem
import com.metrolist.innertube.models.PlaylistItem
import com.metrolist.innertube.models.SongItem
import com.metrolist.innertube.models.YTItem
+import com.metrolist.innertube.pages.HomePage
+import dev.lelonio.square.backend.HomeChip
+import dev.lelonio.square.backend.HomeFeed
import dev.lelonio.square.backend.HomeRow
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
@@ -58,6 +63,9 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {
override val isReady = true
override suspend fun refreshAuth() {
+ // Brings the stored cookie up to date and finds out whether it still
+ // works; see [YouTubeAccount.revalidate].
+ account.revalidate()
_authState.value = account.accountName.value?.let(BackendAuthState::LoggedIn) ?: ANONYMOUS
}
@@ -147,6 +155,49 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {
}
}
+ /**
+ * The albums in the account's library.
+ *
+ * Its own browse page rather than a filter over the playlists: YouTube
+ * keeps saved albums on a page of their own, exactly as it keeps saved
+ * playlists on theirs.
+ */
+ override suspend fun savedAlbums(): List<CatalogPlaylist> = withContext(Dispatchers.IO) {
+ if (!account.isSignedIn) return@withContext emptyList()
+ runCatching {
+ YouTube.library(SAVED_ALBUMS_BROWSE_ID)
+ .getOrThrow()
+ .items
+ .filterIsInstance<AlbumItem>()
+ .mapNotNull(::toCatalogPlaylist)
+ }.getOrElse {
+ android.util.Log.w(LOG_TAG, "saved albums unavailable: $it")
+ emptyList()
+ }
+ }
+
+ /** The artists the account subscribed to, from the library page of them. */
+ override suspend fun followedArtists(): List<SearchItem> = withContext(Dispatchers.IO) {
+ if (!account.isSignedIn) return@withContext emptyList()
+ runCatching {
+ YouTube.library(FOLLOWED_ARTISTS_BROWSE_ID)
+ .getOrThrow()
+ .items
+ .filterIsInstance<ArtistItem>()
+ .map { artist ->
+ SearchItem(
+ uri = "$ARTIST_PREFIX${artist.id}",
+ title = artist.title,
+ subtitle = "",
+ artworkUrl = artist.thumbnail?.atSize(COVER_SIZE),
+ )
+ }
+ }.getOrElse {
+ android.util.Log.w(LOG_TAG, "followed artists unavailable: $it")
+ emptyList()
+ }
+ }
+
/**
* YouTube Music's own home page, shelf by shelf.
*
@@ -155,24 +206,45 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {
* around what the account listens to, signed out it is charts and moods.
* Either way the shelves arrive already titled, so nothing here has to
* invent a name for them.
+ *
+ * A page at a time, because that is how it is served. The first response
+ * carries four or five shelves and a token; the twenty that follow — the
+ * mixes, the artists, the charts, the moods — only exist behind it. Reading
+ * one response and stopping is what made this page look like an app with
+ * nothing in it.
*/
- override suspend fun homeRows(): List<HomeRow> = withContext(Dispatchers.IO) {
- YouTube.home()
- .getOrThrow()
- .sections
- .map { section ->
- val songs = section.items.filterIsInstance<SongItem>()
- HomeRow(
- title = section.title,
- tracks = songs.map(::toCatalogTrack),
- // Everything that is not a song opens something: an album,
- // a playlist, an artist. They travel as one list because
- // the row draws them identically.
- items = section.items.filterNot { it is SongItem }
- .mapNotNull(::toCatalogPlaylist),
- )
- }
- .filterNot { it.isEmpty }
+ override suspend fun homeFeed(cursor: String?, params: String?): HomeFeed =
+ withContext(Dispatchers.IO) {
+ val page = YouTube.home(continuation = cursor, params = params).getOrThrow()
+ HomeFeed(
+ rows = page.sections.map(::toHomeRow).filterNot { it.isEmpty },
+ cursor = page.continuation,
+ chips = page.chips.orEmpty().map { chip ->
+ HomeChip(
+ title = chip.title,
+ // The chip that clears the filter has no view of its
+ // own: it is the home page, which is what null asks for.
+ params = chip.endpoint?.params,
+ )
+ },
+ )
+ }
+
+ private fun toHomeRow(section: HomePage.Section): HomeRow {
+ val songs = section.items.filterIsInstance<SongItem>()
+ // An episode plays like a song and is listed like one; the only
+ // difference the queue would notice is its length.
+ val episodes = section.items.filterIsInstance<EpisodeItem>()
+ return HomeRow(
+ title = section.title,
+ strapline = section.label,
+ tracks = songs.map(::toCatalogTrack) + episodes.map(::toCatalogTrack),
+ // Everything that is not a song opens something: an album, a
+ // playlist, an artist. They travel as one list because the row
+ // draws them identically.
+ items = section.items.filterNot { it is SongItem || it is EpisodeItem }
+ .mapNotNull(::toCatalogPlaylist),
+ )
}
private fun toCatalogPlaylist(item: YTItem): CatalogPlaylist? {
@@ -180,15 +252,41 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {
is AlbumItem -> "$PLAYLIST_PREFIX${item.playlistId}"
is PlaylistItem -> "$PLAYLIST_PREFIX${item.id}"
is ArtistItem -> "$ARTIST_PREFIX${item.id}"
+ // A show is a playlist of episodes, and opens as one.
+ is PodcastItem -> "$PLAYLIST_PREFIX${item.id}"
else -> return null
}
return CatalogPlaylist(
uri = uri,
name = item.title,
artworkUrl = item.thumbnail?.atSize(COVER_SIZE),
+ // What the official app writes under the name: who made it, or how
+ // many listen to it. Without it half a shelf of mixes is a column
+ // of covers with interchangeable titles.
+ subtitle = when (item) {
+ is AlbumItem -> item.artists?.joinToString(", ") { it.name }
+ is PlaylistItem -> item.author?.name
+ is PodcastItem -> item.author?.name
+ // An artist has no line worth writing: the portrait and the
+ // name are the whole of it, and YouTube's own shelf says the
+ // same nothing under theirs.
+ is ArtistItem -> null
+ else -> null
+ }?.takeIf { it.isNotBlank() },
+ isArtist = item is ArtistItem,
)
}
+ private fun toCatalogTrack(item: EpisodeItem) = CatalogTrack(
+ uri = "$TRACK_PREFIX${item.id}",
+ name = item.title,
+ artist = item.author?.name.orEmpty(),
+ album = item.podcast?.name.orEmpty(),
+ durationMs = item.duration?.takeIf { it > 0 }?.times(1000L) ?: 0L,
+ explicit = item.explicit,
+ artworkUrl = item.thumbnail,
+ )
+
private fun toCatalogTrack(item: SongItem) = CatalogTrack(
uri = "$TRACK_PREFIX${item.id}",
name = item.title,
@@ -271,7 +369,10 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {
const val ARTIST_PREFIX = "ytmusic:artist:"
/** YouTube Music's own browse id for the account's playlist library. */
+ private const val LOG_TAG = "SquareYouTube"
private const val LIKED_PLAYLISTS_BROWSE_ID = "FEmusic_liked_playlists"
+ private const val SAVED_ALBUMS_BROWSE_ID = "FEmusic_liked_albums"
+ private const val FOLLOWED_ARTISTS_BROWSE_ID = "FEmusic_library_corpus_track_artists"
/** The `list=` id of a playlist URL. */
private fun playlistIdOf(url: String?): String? =
diff --git a/app/src/main/java/dev/lelonio/square/data/Catalog.kt b/app/src/main/java/dev/lelonio/square/data/Catalog.kt
index 9aa9cd1..e9f2048 100644
--- a/app/src/main/java/dev/lelonio/square/data/Catalog.kt
+++ b/app/src/main/java/dev/lelonio/square/data/Catalog.kt
@@ -94,6 +94,20 @@ data class CatalogPlaylist(
val name: String,
/** Null when the playlist has no custom cover; the UI draws a tile instead. */
val artworkUrl: String? = null,
+ /**
+ * Who it is by, or what it is: the line a home shelf writes under the name.
+ *
+ * Null in the account's own library, where every row is the user's and the
+ * line would say nothing.
+ */
+ val subtitle: String? = null,
+ /**
+ * An artist rather than a record.
+ *
+ * The only thing the tile does differently, and it does matter: a round
+ * portrait among square covers is how a shelf says "these are people".
+ */
+ val isArtist: Boolean = false,
)
/** One credited artist: what to write, and where it leads. */
diff --git a/app/src/main/java/dev/lelonio/square/data/DownloadSettingsStore.kt b/app/src/main/java/dev/lelonio/square/data/DownloadSettingsStore.kt
new file mode 100644
index 0000000..25e1e49
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/DownloadSettingsStore.kt
@@ -0,0 +1,103 @@
+package dev.lelonio.square.data
+
+import android.content.Context
+import androidx.annotation.StringRes
+import dev.lelonio.square.R
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/**
+ * What a download should be, and when one is allowed to happen.
+ *
+ * Separate from [QualityStore] on purpose. Streaming quality is a running
+ * negotiation with the connection — [Quality.Auto] moves it up and down as the
+ * link changes — and a download is the opposite: it happens once, it is kept,
+ * and dropping it to 96 kbps because the Wi-Fi was briefly poor would leave a
+ * bad copy on the phone for good. So there is no Auto here.
+ */
+enum class DownloadQuality(
+ val key: String,
+ @StringRes val label: Int,
+ val kbps: Int,
+) {
+ High("high", R.string.quality_high, 320),
+ Medium("medium", R.string.quality_medium, 160),
+ Low("low", R.string.quality_low, 96),
+ ;
+
+ companion object {
+ fun from(key: String?): DownloadQuality =
+ entries.firstOrNull { it.key == key } ?: High
+ }
+}
+
+class DownloadSettingsStore(context: Context) {
+
+ private val prefs = context.applicationContext
+ .getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
+
+ private val _quality = MutableStateFlow(DownloadQuality.from(prefs.getString(KEY_QUALITY, null)))
+
+ /** Defaults to the best available: a download is kept, so it may as well be good. */
+ val quality: StateFlow<DownloadQuality> = _quality.asStateFlow()
+
+ fun setQuality(value: DownloadQuality) {
+ if (value == _quality.value) return
+ _quality.value = value
+ prefs.edit().putString(KEY_QUALITY, value.key).apply()
+ }
+
+ private val _wifiOnly = MutableStateFlow(prefs.getBoolean(KEY_WIFI_ONLY, true))
+
+ /**
+ * On by default.
+ *
+ * A playlist is hundreds of megabytes, and the tap that starts it looks
+ * exactly like every other tap in the app. Someone who means to download on
+ * mobile data can say so; someone who does not should not find out from
+ * their bill.
+ */
+ val wifiOnly: StateFlow<Boolean> = _wifiOnly.asStateFlow()
+
+ fun setWifiOnly(value: Boolean) {
+ if (value == _wifiOnly.value) return
+ _wifiOnly.value = value
+ prefs.edit().putBoolean(KEY_WIFI_ONLY, value).apply()
+ }
+
+ private val _likedSongs = MutableStateFlow(prefs.getBoolean(KEY_LIKED, false))
+
+ /** Whether the whole of Liked Songs is kept offline, and kept in step. */
+ val downloadLikedSongs: StateFlow<Boolean> = _likedSongs.asStateFlow()
+
+ fun setDownloadLikedSongs(value: Boolean) {
+ if (value == _likedSongs.value) return
+ _likedSongs.value = value
+ prefs.edit().putBoolean(KEY_LIKED, value).apply()
+ }
+
+ private val _offline = MutableStateFlow(prefs.getBoolean(KEY_OFFLINE, false))
+
+ /**
+ * The listener's own switch, which beats anything the app works out for
+ * itself. Persisted, so a phone put into offline mode is still in it after
+ * a restart — the alternative is an app that quietly starts streaming again
+ * on mobile data overnight.
+ */
+ val offlineMode: StateFlow<Boolean> = _offline.asStateFlow()
+
+ fun setOfflineMode(value: Boolean) {
+ if (value == _offline.value) return
+ _offline.value = value
+ prefs.edit().putBoolean(KEY_OFFLINE, value).apply()
+ }
+
+ private companion object {
+ const val FILE_NAME = "square_downloads"
+ const val KEY_QUALITY = "quality"
+ const val KEY_WIFI_ONLY = "wifi_only"
+ const val KEY_LIKED = "liked_songs"
+ const val KEY_OFFLINE = "offline_mode"
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt b/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt
new file mode 100644
index 0000000..f13dbfa
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt
@@ -0,0 +1,588 @@
+package dev.lelonio.square.data
+
+import android.content.Context
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.stateIn
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+import java.io.File
+
+/**
+ * What is downloaded, and who asked for it.
+ *
+ * The audio itself is the engine's business — `native/src/downloads.rs` writes
+ * one encrypted file and one sidecar per track, and the player finds them
+ * without ever asking this class. What lives here is everything the engine has
+ * no opinion about: which playlists wanted a track, what a track is called so
+ * it can be drawn with no connection, and which downloads have yet to happen.
+ *
+ * ### Owners, and why a track is not simply "downloaded"
+ *
+ * The requirement this whole class exists for is that a song in two downloaded
+ * playlists is one file that both playlists know about. So nothing records "the
+ * listener downloaded this track". What is recorded is a set of *owners* — a
+ * playlist, an album, an artist, the loose collection of singles, the liked
+ * songs — each holding the tracks it asked for, in order.
+ *
+ * Everything follows from that. Downloading a playlist that shares tracks with
+ * one already downloaded costs no bytes. Removing a playlist removes an owner,
+ * and the file goes only once no owner is left ([pruneOrphans]). A track shows
+ * as downloaded inside the playlist it belongs to because that is the question
+ * being asked, not because of a flag on the track.
+ *
+ * ### The queue is not stored
+ *
+ * There is no list of pending downloads on disk. What is pending is whatever an
+ * owner asked for and has no file yet ([pending]), which means an app killed
+ * mid-playlist works out what it still owes the moment it starts, and a
+ * download interrupted halfway resumes from the `.part` file the engine left.
+ * A queue file would have been a second truth to keep in step with this one.
+ */
+class DownloadStore(context: Context) {
+
+ /**
+ * A file that is actually on disk, as the engine reported it.
+ *
+ * Present only for completed downloads: the entry is written after
+ * `downloadTrack` returns, so an entry here and a sidecar there mean the
+ * same thing.
+ */
+ @Serializable
+ data class FileRecord(
+ val trackId: String,
+ val format: String,
+ val bytes: Long,
+ /** The quality actually stored, so a re-download at 320 knows to run. */
+ val kbps: Int,
+ val downloadedAt: Long,
+ )
+
+ /** Enough to draw a downloaded playlist with no connection. */
+ @Serializable
+ data class OwnerLabel(
+ val name: String,
+ val artworkUrl: String? = null,
+ val kind: String = KIND_PLAYLIST,
+ )
+
+ @Serializable
+ data class Failure(val reason: String, val attempts: Int, val at: Long) {
+ /**
+ * When this track is worth trying again: two seconds, then four, then
+ * eight, up to five minutes.
+ *
+ * The first failure of a batch is almost always the connection going,
+ * and the whole batch recovers together — so the early waits are short
+ * enough that the listener never sees the pause, and the late ones long
+ * enough that a track Spotify genuinely will not serve stops costing
+ * anything.
+ */
+ fun readyAt(): Long =
+ at + (BASE_BACKOFF_MS shl (attempts - 1).coerceIn(0, 8)).coerceAtMost(MAX_BACKOFF_MS)
+
+ private companion object {
+ const val BASE_BACKOFF_MS = 2_000L
+ const val MAX_BACKOFF_MS = 5L * 60 * 1000
+ }
+ }
+
+ @Serializable
+ private data class Index(
+ val version: Int = 1,
+ val files: Map<String, FileRecord> = emptyMap(),
+ val owners: Map<String, List<String>> = emptyMap(),
+ /**
+ * Metadata for every track any owner asked for.
+ *
+ * Kept here rather than read from [ContextCacheStore] because that
+ * cache expires after a week and is trimmed to forty contexts, and a
+ * download is meant to outlive both. Offline, this is what the rows are
+ * drawn from.
+ */
+ val tracks: Map<String, CatalogTrack> = emptyMap(),
+ val labels: Map<String, OwnerLabel> = emptyMap(),
+ val failures: Map<String, Failure> = emptyMap(),
+ )
+
+ /** Where the engine keeps the audio. Handed to it once, at startup. */
+ val root: File = File(context.applicationContext.filesDir, DIR_NAME)
+
+ private val indexFile = File(root, INDEX_NAME)
+ private val json = Json { ignoreUnknownKeys = true }
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val writeLock = Mutex()
+
+ private val _index = MutableStateFlow(Index())
+ private val _progress = MutableStateFlow<Map<String, Float>>(emptyMap())
+
+ /** What is on disk, by track URI. */
+ val files: StateFlow<Map<String, FileRecord>>
+ get() = _files.asStateFlow()
+ private val _files = MutableStateFlow<Map<String, FileRecord>>(emptyMap())
+
+ /** Who asked for what, by owner URI, in the order the owner lists them. */
+ val owners: StateFlow<Map<String, List<String>>>
+ get() = _owners.asStateFlow()
+ private val _owners = MutableStateFlow<Map<String, List<String>>>(emptyMap())
+
+ /** Downloads in flight, as a fraction. Never persisted. */
+ val progress: StateFlow<Map<String, Float>> = _progress.asStateFlow()
+
+ val failures: StateFlow<Map<String, Failure>>
+ get() = _failures.asStateFlow()
+ private val _failures = MutableStateFlow<Map<String, Failure>>(emptyMap())
+
+ /**
+ * [ownerState] for every owner, ready for a screen to read.
+ *
+ * A flow, so a page redraws its button as the queue moves. Only the owners
+ * are computed this way — there are tens of them. The per-track answer is
+ * left to the caller, which reads [files] and [progress] and asks about the
+ * rows it is actually drawing: building a map of several thousand tracks
+ * several times a second, to mark the dozen on screen, is the version of
+ * this that makes a playlist scroll badly.
+ */
+ val ownerStates: StateFlow<Map<String, OwnerState>> =
+ combine(_owners, _files, _progress, _failures) { owners, _, _, _ ->
+ owners.keys.associateWith(::ownerState)
+ }.stateIn(scope, SharingStarted.Eagerly, emptyMap())
+
+ // ------------------------------------------------------------- lifecycle
+
+ /**
+ * Reads the index. Safe to call more than once; the second call is a no-op.
+ *
+ * A missing or unreadable index is an empty one rather than a failure. The
+ * files on disk are still there and [reconcile] will find them, which is a
+ * better answer than refusing to start because a JSON file got truncated.
+ */
+ suspend fun load() = withContext(Dispatchers.IO) {
+ if (loaded) return@withContext
+ loaded = true
+ root.mkdirs()
+ val stored = runCatching {
+ if (indexFile.exists()) json.decodeFromString(Index.serializer(), indexFile.readText())
+ else Index()
+ }.getOrElse { Index() }
+ publish(stored)
+ }
+
+ private var loaded = false
+
+ /**
+ * Drops index entries whose audio has gone, and forgets tracks and labels
+ * nothing points at any more.
+ *
+ * The two halves of this can drift for reasons neither side controls: the
+ * listener can clear the app's storage from Android's settings, which takes
+ * the audio and leaves the index, and a crash between the rename and the
+ * index write leaves a file nothing claims. Cheap enough to run at startup.
+ */
+ suspend fun reconcile() = withContext(Dispatchers.IO) {
+ val current = _index.value
+ val surviving = current.files.filterKeys { uri ->
+ val record = current.files[uri] ?: return@filterKeys false
+ audioFile(record.trackId).exists()
+ }
+ if (surviving.size != current.files.size) {
+ publish(current.copy(files = surviving))
+ save()
+ }
+ }
+
+ // ------------------------------------------------------------- questions
+
+ fun isDownloaded(trackUri: String): Boolean = _files.value.containsKey(trackUri)
+
+ /**
+ * How a single row should draw itself.
+ *
+ * [DownloadState.None] for anything the listener has not asked for, which
+ * is deliberately indistinguishable from "not started": a row shows nothing
+ * at all until a download for it exists, so an undownloaded playlist looks
+ * exactly as it did before this feature.
+ */
+ fun stateOf(trackUri: String): DownloadState = when {
+ _files.value.containsKey(trackUri) -> DownloadState.Done
+ _progress.value.containsKey(trackUri) ->
+ DownloadState.Running(_progress.value.getValue(trackUri))
+ _failures.value.containsKey(trackUri) ->
+ DownloadState.Failed(_failures.value.getValue(trackUri).reason)
+ isWanted(trackUri) -> DownloadState.Queued
+ else -> DownloadState.None
+ }
+
+ /** Whether any owner still asks for this track. */
+ fun isWanted(trackUri: String): Boolean =
+ _owners.value.values.any { tracks -> tracks.contains(trackUri) }
+
+ /**
+ * How a playlist, album or artist page should draw its button.
+ *
+ * `Partial` is not a failure. Some tracks are not available on the account's
+ * market and never will be, and a playlist that says "38 of 40" is telling
+ * the truth about something the app cannot fix.
+ */
+ fun ownerState(ownerUri: String): OwnerState {
+ val wanted = _owners.value[ownerUri] ?: return OwnerState.None
+ if (wanted.isEmpty()) return OwnerState.None
+
+ val files = _files.value
+ val progress = _progress.value
+ val failures = _failures.value
+
+ val done = wanted.count(files::containsKey)
+ if (done == wanted.size) return OwnerState.Complete
+
+ val running = wanted.filter(progress::containsKey)
+ val outstanding = wanted.filterNot(files::containsKey)
+ val stuck = outstanding.count(failures::containsKey)
+
+ // Everything left has already failed as far as it is going to, so the
+ // owner is as complete as it will get. Saying "downloading" for ever
+ // would be the alternative, and the ring would never stop turning.
+ if (stuck == outstanding.size) return OwnerState.Partial(done, wanted.size)
+
+ // The share of the whole, not of what is left: a ring that restarts
+ // every time a track finishes is worse than one that creeps.
+ val fraction =
+ (done + running.sumOf { progress[it]?.toDouble() ?: 0.0 }) / wanted.size
+ return OwnerState.Running(fraction.toFloat().coerceIn(0f, 1f), done, wanted.size)
+ }
+
+ /**
+ * Tracks an owner asked for that have no file yet and are worth trying now,
+ * in the order their owners list them.
+ *
+ * Failures are held back rather than dropped: a track that failed once is
+ * offered again after a wait that doubles each time, and only stops being
+ * offered after [MAX_ATTEMPTS]. Without the wait a track Spotify does not
+ * serve on this account would be retried in a tight loop for as long as the
+ * queue ran; without the ceiling it would be retried for ever, on every
+ * launch, and the queue would never report itself finished.
+ */
+ fun pending(now: Long = System.currentTimeMillis()): List<String> {
+ val files = _files.value
+ val failures = _failures.value
+ val ordered = LinkedHashSet<String>()
+ for (tracks in _owners.value.values) {
+ for (uri in tracks) {
+ if (files.containsKey(uri)) continue
+ val failure = failures[uri]
+ if (failure != null && failure.attempts >= MAX_ATTEMPTS) continue
+ if (failure != null && failure.readyAt() > now) continue
+ ordered.add(uri)
+ }
+ }
+ return ordered.toList()
+ }
+
+ /**
+ * When the next track held back by a failure becomes worth trying again, or
+ * null when nothing is waiting.
+ *
+ * The queue sleeps until this rather than polling, so a phone with one
+ * stubborn track in a playlist is not woken every few seconds for it.
+ */
+ fun retryAt(): Long? {
+ val files = _files.value
+ val claimed = _owners.value.values.flatten().toSet()
+ return _failures.value
+ .filterKeys { it in claimed && !files.containsKey(it) }
+ .values
+ .filter { it.attempts < MAX_ATTEMPTS }
+ .minOfOrNull { it.readyAt() }
+ }
+
+ /** Tracks that will not be tried again unless the listener asks. */
+ fun givenUp(): List<String> {
+ val claimed = _owners.value.values.flatten().toSet()
+ val files = _files.value
+ return _failures.value
+ .filter { (uri, failure) ->
+ uri in claimed && !files.containsKey(uri) && failure.attempts >= MAX_ATTEMPTS
+ }
+ .keys
+ .toList()
+ }
+
+ /** Metadata for a downloaded track, for drawing it with no connection. */
+ fun trackOf(trackUri: String): CatalogTrack? = _index.value.tracks[trackUri]
+
+ fun labelOf(ownerUri: String): OwnerLabel? = _index.value.labels[ownerUri]
+
+ fun totalBytes(): Long = _files.value.values.sumOf { it.bytes }
+
+ fun bytesOf(ownerUri: String): Long {
+ val files = _files.value
+ return _owners.value[ownerUri].orEmpty().sumOf { files[it]?.bytes ?: 0L }
+ }
+
+ // ------------------------------------------------------------ what to own
+
+ /**
+ * Records that [ownerUri] wants these tracks, replacing whatever it wanted
+ * before.
+ *
+ * Replacing rather than merging is what keeps a downloaded playlist honest
+ * as it changes: a track removed from the playlist upstream stops being
+ * wanted here on the next sync, and its file goes once nothing else claims
+ * it.
+ */
+ suspend fun setOwner(
+ ownerUri: String,
+ tracks: List<CatalogTrack>,
+ label: OwnerLabel?,
+ ) = writeLock.withLock {
+ val current = _index.value
+ publish(
+ current.copy(
+ owners = current.owners + (ownerUri to tracks.map { it.uri }),
+ tracks = current.tracks + tracks.associateBy { it.uri },
+ labels = label?.let { current.labels + (ownerUri to it) } ?: current.labels,
+ // Asking again is the listener saying "try this", so the record
+ // of past failures for these tracks goes.
+ failures = current.failures - tracks.map { it.uri }.toSet(),
+ ),
+ )
+ save()
+ }
+
+ /** Adds one track to the loose collection of singles. */
+ suspend fun addSingle(track: CatalogTrack) {
+ val existing = _owners.value[SINGLES].orEmpty()
+ if (existing.contains(track.uri)) return
+ writeLock.withLock {
+ val current = _index.value
+ publish(
+ current.copy(
+ owners = current.owners + (SINGLES to existing + track.uri),
+ tracks = current.tracks + (track.uri to track),
+ failures = current.failures - track.uri,
+ ),
+ )
+ save()
+ }
+ }
+
+ suspend fun removeSingle(trackUri: String) {
+ val existing = _owners.value[SINGLES].orEmpty()
+ if (!existing.contains(trackUri)) return
+ writeLock.withLock {
+ val current = _index.value
+ publish(current.copy(owners = current.owners + (SINGLES to existing - trackUri)))
+ save()
+ }
+ }
+
+ /**
+ * Forgets an owner. What it was alone in wanting is left for [pruneOrphans].
+ *
+ * Deliberately two steps. Pruning here would drop the files from the index
+ * with nobody left holding a list of what to delete, and the audio would
+ * stay on disk for good — several hundred megabytes that nothing in the app
+ * could ever see again, let alone remove.
+ */
+ suspend fun removeOwner(ownerUri: String) = writeLock.withLock {
+ val current = _index.value
+ publish(
+ current.copy(
+ owners = current.owners - ownerUri,
+ labels = current.labels - ownerUri,
+ ),
+ )
+ save()
+ }
+
+ // ---------------------------------------------------- what the queue says
+
+ fun onProgress(trackUri: String, fraction: Float) {
+ _progress.value = _progress.value + (trackUri to fraction.coerceIn(0f, 1f))
+ }
+
+ /**
+ * Forgets that a track was in flight, without recording anything against
+ * it. For a download that stopped for a reason the track had no part in —
+ * the engine going, or the queue being told to stop.
+ */
+ fun clearProgress(trackUri: String) {
+ if (!_progress.value.containsKey(trackUri)) return
+ _progress.value = _progress.value - trackUri
+ }
+
+ suspend fun onCompleted(trackUri: String, record: FileRecord) {
+ writeLock.withLock {
+ val current = _index.value
+ publish(
+ current.copy(
+ files = current.files + (trackUri to record),
+ failures = current.failures - trackUri,
+ ),
+ )
+ _progress.value = _progress.value - trackUri
+ save()
+ }
+ }
+
+ suspend fun onFailed(trackUri: String, reason: String) {
+ writeLock.withLock {
+ val current = _index.value
+ val before = current.failures[trackUri]
+ publish(
+ current.copy(
+ failures = current.failures + (
+ trackUri to Failure(
+ reason = reason,
+ attempts = (before?.attempts ?: 0) + 1,
+ at = System.currentTimeMillis(),
+ )
+ ),
+ ),
+ )
+ _progress.value = _progress.value - trackUri
+ save()
+ }
+ }
+
+ /** Forgets past failures so [pending] offers those tracks again. */
+ suspend fun retryFailed() = writeLock.withLock {
+ publish(_index.value.copy(failures = emptyMap()))
+ save()
+ }
+
+ // ------------------------------------------------------------ tidying up
+
+ /**
+ * Deletes files, metadata and labels nothing claims any more.
+ *
+ * This is the other half of the owner model: [removeOwner] only forgets who
+ * wanted a track, and this is what notices that nobody does. Deliberately
+ * separate, so removing one playlist never deletes a file another playlist
+ * is still holding.
+ *
+ * Returns the tracks whose audio was deleted, so the caller can tell the
+ * engine to drop them.
+ */
+ suspend fun pruneOrphans(): List<String> = writeLock.withLock {
+ val current = _index.value
+ val claimed = current.owners.values.flatten().toSet()
+
+ val orphaned = current.files.keys.filterNot(claimed::contains)
+ val strandedTracks = current.tracks.keys.filterNot(claimed::contains)
+ if (orphaned.isEmpty() && strandedTracks.isEmpty()) return@withLock emptyList()
+
+ publish(
+ current.copy(
+ files = current.files - orphaned.toSet(),
+ tracks = current.tracks - strandedTracks.toSet(),
+ failures = current.failures - strandedTracks.toSet(),
+ ),
+ )
+ save()
+ orphaned
+ }
+
+ /** Everything goes: the index, and the whole store the engine writes into. */
+ suspend fun clearAll() = withContext(Dispatchers.IO) {
+ writeLock.withLock {
+ publish(Index())
+ _progress.value = emptyMap()
+ runCatching { root.deleteRecursively() }
+ root.mkdirs()
+ // The extras live under the same root and go with it; this is only
+ // to drop whatever the object is holding on to.
+ dev.lelonio.square.download.DownloadExtras.clear()
+ save()
+ }
+ }
+
+ // ------------------------------------------------------------- internals
+
+ private fun audioFile(trackId: String): File =
+ File(File(root, "audio"), trackId.take(2)).resolve(trackId.drop(2))
+
+ private fun publish(index: Index) {
+ _index.value = index
+ _files.value = index.files
+ _owners.value = index.owners
+ _failures.value = index.failures
+ }
+
+ /**
+ * Writes the index through a temporary file.
+ *
+ * Not debounced: every caller here is a whole-playlist change or the end of
+ * a download, which is at most one write every few seconds even with the
+ * queue running flat out. Progress ticks, which arrive several times a
+ * second, never reach this — they live only in [progress].
+ */
+ private fun save() {
+ val snapshot = _index.value
+ scope.launch {
+ runCatching {
+ root.mkdirs()
+ val tmp = File(root, "$INDEX_NAME.tmp")
+ tmp.writeText(json.encodeToString(Index.serializer(), snapshot))
+ if (!tmp.renameTo(indexFile)) {
+ indexFile.delete()
+ tmp.renameTo(indexFile)
+ }
+ }
+ }
+ }
+
+ companion object {
+ /**
+ * How many times one track is tried before it is left alone.
+ *
+ * Reached, it is not an error state to recover from: some tracks are
+ * simply not served to this account, and a playlist that stops at 38 of
+ * 40 is telling the truth. The listener can ask again from the
+ * downloads panel, which is what [retryFailed] is for.
+ */
+ const val MAX_ATTEMPTS = 5
+
+ const val DIR_NAME = "downloads"
+ private const val INDEX_NAME = "index.json"
+
+ /** The owner every single track downloaded on its own belongs to. */
+ const val SINGLES = "downloads:tracks"
+
+ /** The owner the automatic download of the liked songs writes to. */
+ const val LIKED = "downloads:liked"
+
+ const val KIND_PLAYLIST = "playlist"
+ const val KIND_ALBUM = "album"
+ const val KIND_ARTIST = "artist"
+ }
+}
+
+/** How one track should draw itself. */
+sealed interface DownloadState {
+ /** Not asked for. Draws nothing at all — see [DownloadStore.stateOf]. */
+ data object None : DownloadState
+ data object Queued : DownloadState
+ data class Running(val progress: Float) : DownloadState
+ data object Done : DownloadState
+ data class Failed(val reason: String) : DownloadState
+}
+
+/** How a playlist, album or artist should draw its button. */
+sealed interface OwnerState {
+ data object None : OwnerState
+ data class Running(val progress: Float, val done: Int, val total: Int) : OwnerState
+ data object Complete : OwnerState
+ /** Everything that could be fetched was; the rest is not available here. */
+ data class Partial(val done: Int, val total: Int) : OwnerState
+}
diff --git a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
index 2a31157..0ea1806 100644
--- a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
@@ -108,6 +108,25 @@ class PreferencesStore(context: Context) {
val backendChosen: StateFlow<Boolean> = _backendChosen.asStateFlow()
/** When GitHub was last asked about a newer release. See [UpdateChecker]. */
+ /**
+ * The account's name and picture, as they were last read.
+ *
+ * Kept because they are the one part of the library that has nothing to do
+ * with the network and was being fetched anyway: offline the header used to
+ * go blank, which reads as being signed out of an app that is doing exactly
+ * what it was asked to. The picture is a URL, and the copy of it saved
+ * beside the downloads is what Artwork actually draws; see DownloadExtras.
+ */
+ fun profile(): Pair<String, String?> =
+ prefs.getString(KEY_PROFILE_NAME, null).orEmpty() to prefs.getString(KEY_PROFILE_ART, null)
+
+ fun setProfile(name: String, artworkUrl: String?) {
+ prefs.edit()
+ .putString(KEY_PROFILE_NAME, name)
+ .putString(KEY_PROFILE_ART, artworkUrl)
+ .apply()
+ }
+
fun lastUpdateCheck(): Long = prefs.getLong(KEY_LAST_UPDATE_CHECK, 0L)
fun setLastUpdateCheck(value: Long) {
@@ -134,6 +153,8 @@ class PreferencesStore(context: Context) {
const val KEY_ONBOARDED = "onboarded"
const val KEY_PLAYER_OPEN = "player_open"
const val KEY_BACKEND = "backend"
+ const val KEY_PROFILE_NAME = "profile_name"
+ const val KEY_PROFILE_ART = "profile_art"
const val KEY_LAST_UPDATE_CHECK = "last_update_check"
const val KEY_SKIPPED_UPDATE = "skipped_update"
}
diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadEvents.kt b/app/src/main/java/dev/lelonio/square/download/DownloadEvents.kt
new file mode 100644
index 0000000..bc42c71
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/download/DownloadEvents.kt
@@ -0,0 +1,61 @@
+package dev.lelonio.square.download
+
+import kotlinx.coroutines.channels.BufferOverflow
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.SharedFlow
+import kotlinx.coroutines.flow.asSharedFlow
+
+/**
+ * Progress ticks on their way out of the engine.
+ *
+ * The engine has one listener and one permanent JVM attachment, so a download
+ * says how far along it is on the same channel the player says where it is.
+ * That is an implementation detail of the boundary, not a relationship between
+ * the two, and this is where the two are separated again: [accept] takes the
+ * download events off the wire before the player ever sees them.
+ *
+ * An object rather than something injected, for the same reason
+ * [dev.lelonio.square.data.RemoteConnect] is one: there is a single engine
+ * behind it, and the listener it pushes into belongs to the player.
+ */
+object DownloadEvents {
+
+ data class Progress(val uri: String, val fraction: Float)
+
+ private val _progress = MutableSharedFlow<Progress>(
+ extraBufferCapacity = 64,
+ // A tick nobody read is a ring that did not move by a percent. Dropping
+ // the oldest keeps the newest, which is the only one worth drawing.
+ onBufferOverflow = BufferOverflow.DROP_OLDEST,
+ )
+
+ val progress: SharedFlow<Progress> = _progress.asSharedFlow()
+
+ /**
+ * Takes a download event off the engine's event channel.
+ *
+ * @return true when the event was a download's and the player should not
+ * see it.
+ */
+ fun accept(type: String, uri: String, value: Long): Boolean = when (type) {
+ PROGRESS -> {
+ // Per mille on the wire: the event carries one number, and a
+ // fraction would not have survived the trip as a long.
+ _progress.tryEmit(Progress(uri, (value / 1000f).coerceIn(0f, 1f)))
+ true
+ }
+
+ // The queue already knows a track finished — `downloadTrack` returned to
+ // it — but the ring should reach the end before the row changes shape,
+ // and the last progress tick lands a chunk short of the whole.
+ DONE -> {
+ _progress.tryEmit(Progress(uri, 1f))
+ true
+ }
+
+ else -> false
+ }
+
+ private const val PROGRESS = "download_progress"
+ private const val DONE = "download_done"
+}
diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt b/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt
new file mode 100644
index 0000000..7261bef
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/download/DownloadExtras.kt
@@ -0,0 +1,271 @@
+package dev.lelonio.square.download
+
+import kotlinx.coroutines.Dispatchers
+import org.json.JSONObject
+import kotlinx.coroutines.withContext
+import java.io.File
+import java.net.URL
+
+/**
+ * Everything about a downloaded song that is not the song.
+ *
+ * The words, the Canvas, the cover and what the artist is. Offline these are
+ * the difference between a player that works and a player that looks broken:
+ * the audio plays either way, but a blank cover over a track with no lyrics and
+ * an empty artist page reads as an app that has lost its connection to itself.
+ *
+ * ### Where it plugs in
+ *
+ * Inside [dev.lelonio.square.data.Catalog], which is the one funnel every one of
+ * these already goes through. A successful answer is written down on the way
+ * past; a failed one is looked up here. So nothing else in the app has to know
+ * this exists, and no screen grew an offline branch of its own.
+ *
+ * ### What is kept, and what is not
+ *
+ * Only for tracks that are actually downloaded — see [isKept], which the
+ * container wires to the download index. Caching the lyrics of everything ever
+ * opened would be a second, unbounded store with no owner and nothing to sweep
+ * it, which is exactly the shape of thing that quietly fills a phone.
+ *
+ * A stored answer is a fallback and never a preference. Online the request is
+ * still made and its answer still wins: lyrics get corrected, Canvases get
+ * replaced, and a cache that shadowed them would keep showing yesterday's.
+ * The one exception is the cover, where the bytes cannot differ — the URL names
+ * the image — so a local copy is used straight away and saves the round trip.
+ */
+object DownloadExtras {
+
+ private var root: File? = null
+
+ /** Whether a track is downloaded, and therefore worth keeping extras for. */
+ private var kept: (String) -> Boolean = { false }
+
+ fun attach(downloadsRoot: File, isKept: (String) -> Boolean) {
+ root = File(downloadsRoot, "extras")
+ kept = isKept
+ forgetArtAnswers()
+ }
+
+ // ------------------------------------------------------------ the answers
+
+ fun rememberLyrics(trackUri: String, raw: String) = remember("lyrics", trackUri, raw)
+
+ fun lyrics(trackUri: String): String? = recall("lyrics", trackUri)
+
+ fun rememberCanvas(trackUri: String, raw: String) = remember("canvas", trackUri, raw)
+
+ fun canvas(trackUri: String): String? = recall("canvas", trackUri)
+
+ /**
+ * Artist descriptions are kept for anyone with a downloaded track, so the
+ * page behind a song is not empty offline. Not gated on [isKept]: the URI
+ * here is the artist's, and the track it was reached from is long out of
+ * scope by the time this is called.
+ */
+ fun rememberArtist(artistUri: String, raw: String) {
+ val file = fileFor("artist", artistUri) ?: return
+ runCatching { file.parentFile?.mkdirs(); file.writeText(raw) }
+ }
+
+ fun artist(artistUri: String): String? = recall("artist", artistUri)
+
+ private fun remember(kind: String, uri: String, raw: String) {
+ if (!kept(uri)) return
+ val file = fileFor(kind, uri) ?: return
+ runCatching { file.parentFile?.mkdirs(); file.writeText(raw) }
+ }
+
+ private fun recall(kind: String, uri: String): String? {
+ val file = fileFor(kind, uri) ?: return null
+ return runCatching { file.takeIf(File::exists)?.readText() }.getOrNull()
+ }
+
+ // -------------------------------------------------------------- the files
+
+ /**
+ * The local copy of an image or a Canvas, if there is one.
+ *
+ * Named after the URL rather than the track, because both are addressed
+ * that way and the same cover is shared by every song on a record: keying
+ * on the track would store one album's art a dozen times.
+ */
+ fun fileOf(url: String, kind: String): File? =
+ if (kind == "art") artCache.computeIfAbsent(url) { Kept(look(kind, it)) }.value
+ else look(kind, url)
+
+ private fun look(kind: String, key: String): File? =
+ fileFor(kind, key)?.takeIf(File::exists)
+
+ /**
+ * Answers about covers, remembered.
+ *
+ * This one is asked from inside composition — every artwork in every row
+ * checks whether it has a local copy before deciding what to load — and the
+ * answer costs a stat on the filesystem. On a list being flung that is disk
+ * I/O on the frame's own thread, dozens of times a second, for an answer
+ * that changes when a download finishes and at no other moment.
+ *
+ * A wrapper rather than a nullable value, because a map cannot remember
+ * that the answer was "there is none".
+ */
+ private class Kept(val value: File?)
+
+ private val artCache = java.util.concurrent.ConcurrentHashMap<String, Kept>()
+
+ /** Called whenever a cover appears or goes, so the answers stay true. */
+ private fun forgetArtAnswers() = artCache.clear()
+
+ /**
+ * Fetches and keeps one file. Answers with what is already there.
+ *
+ * Deliberately plain: a CDN GET with no headers, no client to configure and
+ * no cache of its own. Everything this fetches is immutable and addressed
+ * by content — Spotify's image and Canvas URLs name the file — so there is
+ * nothing for a smarter client to be smarter about.
+ */
+ suspend fun keep(url: String, kind: String): File? = withContext(Dispatchers.IO) {
+ if (url.isBlank()) return@withContext null
+ val file = fileFor(kind, url) ?: return@withContext null
+ if (file.exists() && file.length() > 0) return@withContext file
+
+ runCatching {
+ file.parentFile?.mkdirs()
+ // Through a part file, so an interrupted fetch never leaves
+ // something half-written where a reader would take it for whole.
+ val part = File(file.parentFile, "${file.name}.part")
+ URL(url).openStream().use { input ->
+ part.outputStream().use(input::copyTo)
+ }
+ if (!part.renameTo(file)) {
+ part.delete()
+ return@runCatching null
+ }
+ if (kind == "art") forgetArtAnswers()
+ file
+ }.getOrNull()
+ }
+
+ /**
+ * What a cover URL is really about, so every size of it lands on one file.
+ *
+ * A Spotify image id is forty hex characters: sixteen that say what size it
+ * is, then twenty-four that say which picture. `ab67616d00001e02…` is the
+ * 300px print and `ab67616d0000b273…` the 640px one, and everything after
+ * those first sixteen is identical.
+ *
+ * Keyed on the whole URL, the row thumbnail and the player cover would be
+ * two files for one picture, and neither would be found by code holding the
+ * other spelling — which is exactly what happened: the covers were saved
+ * under the large URL and looked up under the small one, so offline the
+ * notification had no picture at all. Keyed on the tail, one download
+ * answers for every size of it.
+ */
+ private fun coverKey(url: String): String {
+ val id = url.substringAfterLast('/')
+ return if (id.length == ID_LENGTH && id.all { it.isDigit() || it in 'a'..'f' }) {
+ id.takeLast(ID_LENGTH - SIZE_PREFIX)
+ } else {
+ url
+ }
+ }
+
+ /** A Spotify image id, and how much of the front of it is the size. */
+ private const val ID_LENGTH = 40
+ private const val SIZE_PREFIX = 16
+
+ /**
+ * The cover as a `file://` for anything that wants a URI rather than a
+ * file — the media session's metadata, above all, which is what draws the
+ * picture in the notification and the quick settings panel.
+ */
+ fun artworkUri(url: String?): android.net.Uri? {
+ val kept = url?.let { fileOf(it, "art") } ?: return null
+ return android.net.Uri.fromFile(kept)
+ }
+
+ /** Drops everything kept for a track that is no longer downloaded. */
+ fun forget(trackUri: String) {
+ listOf("lyrics", "canvas").forEach { kind ->
+ fileFor(kind, trackUri)?.let { runCatching { it.delete() } }
+ }
+ }
+
+ /**
+ * What the extras take up, in bytes.
+ *
+ * Worth counting separately from the audio: the Canvases are video, and a
+ * few hundred songs' worth of them is not a rounding error next to the
+ * music. Walks the directory, so it belongs off the main thread.
+ */
+ fun bytes(): Long =
+ root?.walkTopDown()?.filter(File::isFile)?.sumOf(File::length) ?: 0L
+
+ /**
+ * Deletes what belongs to songs that are no longer downloaded.
+ *
+ * The audio has an index to be reconciled against; the extras have only
+ * their file names, which are hashes and cannot be read backwards. So the
+ * set of names that *should* exist is rebuilt from the tracks that survive,
+ * and anything else in the directory goes.
+ *
+ * It matters most for the Canvases. A cover is tens of kilobytes and a
+ * Canvas is a few megabytes of video, so a library that has been added to
+ * and removed from a few times leaves far more behind here than the index
+ * ever accounted for — measured on the test phone at a hundred and thirty
+ * megabytes for songs that were long gone.
+ *
+ * Artist descriptions are left alone: they are keyed by artist rather than
+ * by track, they are a few kilobytes each, and an artist with nothing
+ * downloaded today may well have something tomorrow.
+ */
+ fun sweep(trackUris: Collection<String>, coverUrls: Collection<String>) {
+ if (root == null) return
+
+ val keepLyrics = trackUris.mapNotNullTo(mutableSetOf()) { fileFor("lyrics", it)?.name }
+ val keepCanvas = trackUris.mapNotNullTo(mutableSetOf()) { fileFor("canvas", it)?.name }
+ val keepArt = coverUrls.mapNotNullTo(mutableSetOf()) { fileFor("art", it)?.name }
+
+ // Read before the Canvas answers are pruned: a video is named after the
+ // URL inside the answer that points at it, so the answers are the only
+ // way to know which videos are still wanted.
+ val keepVideo = trackUris.mapNotNullTo(mutableSetOf()) { uri ->
+ recall("canvas", uri)
+ ?.let { raw -> runCatching { JSONObject(raw).optString("url") }.getOrNull() }
+ ?.takeIf { it.isNotBlank() }
+ ?.let { fileFor("video", it)?.name }
+ }
+
+ forgetArtAnswers()
+ prune("lyrics", keepLyrics)
+ prune("canvas", keepCanvas)
+ prune("art", keepArt)
+ prune("video", keepVideo)
+ }
+
+ private fun prune(kind: String, keep: Set<String>) {
+ val dir = root?.let { File(it, kind) } ?: return
+ dir.listFiles()?.forEach { file ->
+ if (file.name !in keep) runCatching { file.delete() }
+ }
+ }
+
+ /** Everything goes, when the downloads do. */
+ fun clear() {
+ forgetArtAnswers()
+ root?.let { runCatching { it.deleteRecursively() } }
+ }
+
+ private fun fileFor(kind: String, key: String): File? {
+ val root = root ?: return null
+ // Hashed rather than sanitised: a URI is not a legal file name, and any
+ // escaping scheme would have to survive the characters it escapes.
+ val name = (if (kind == "art") coverKey(key) else key).hashCode().toUInt().toString(16)
+ val extension = when (kind) {
+ "art" -> "jpg"
+ "video" -> "mp4"
+ else -> "json"
+ }
+ return File(File(root, kind), "$name.$extension")
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt b/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt
new file mode 100644
index 0000000..b30a51b
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt
@@ -0,0 +1,529 @@
+package dev.lelonio.square.download
+
+import android.content.Context
+import android.net.ConnectivityManager
+import android.net.Network
+import android.net.NetworkCapabilities
+import dev.lelonio.square.data.DownloadSettingsStore
+import dev.lelonio.square.data.DownloadStore
+import dev.lelonio.square.nativecore.NativeBridge
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import org.json.JSONObject
+
+/**
+ * Works through what the downloads store says is owed.
+ *
+ * There is no list of jobs here. The queue asks [DownloadStore.pending] what is
+ * still wanted and has no file, downloads some of it, and asks again — so
+ * adding a playlist, removing one, or killing the app mid-way all need no
+ * special handling: the next question gets the right answer. [wake] exists only
+ * to say "the answer may have changed", never to hand over work.
+ *
+ * Two reasons to stop are kept apart, because they mean opposite things to the
+ * listener:
+ *
+ * - **The track failed.** Recorded against the track, retried with a growing
+ * wait, and eventually given up on. One unavailable song does not stop a
+ * playlist.
+ * - **We cannot download at all** — no connection, mobile data while the
+ * listener asked for Wi-Fi only, or no engine yet. Nothing is recorded
+ * against any track; the queue waits and carries on where it left off. This
+ * is the distinction that stops a tunnel from burning five attempts on every
+ * remaining track of a playlist.
+ */
+class DownloadQueue(
+ context: Context,
+ private val store: DownloadStore,
+ private val settings: DownloadSettingsStore,
+) {
+
+ data class Status(
+ val running: Boolean = false,
+ val done: Int = 0,
+ val total: Int = 0,
+ /** Why nothing is happening, when nothing is happening. */
+ val waiting: Waiting? = null,
+ )
+
+ enum class Waiting { NETWORK, WIFI, ENGINE }
+
+ private val appContext = context.applicationContext
+ private val connectivity = appContext.getSystemService(ConnectivityManager::class.java)
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ private val _status = MutableStateFlow(Status())
+ val status: StateFlow<Status> = _status.asStateFlow()
+
+ private val _link = MutableStateFlow(link())
+ private var pump: Job? = null
+ private var watching = false
+
+ /** Set when the last attempt was turned away by the key limiter. */
+ private var throttled = false
+
+ /**
+ * How long to wait between tracks, learnt rather than chosen.
+ *
+ * Spotify refuses audio keys to a session that asks for them too quickly,
+ * and a refusal is expensive: the engine holds off three seconds, then six,
+ * then twelve, so a queue that keeps tripping the limiter spends half a
+ * minute waiting for every track it fetches in ten seconds. Measured on a
+ * fixed 350 ms gap: one song every 37 seconds, thirty of them idle.
+ *
+ * The engine reports how long it waited for each key, so this backs off
+ * when that number says the limiter was hit and creeps down again after a
+ * run of clean fetches. Slower on purpose than the fixed value it replaces
+ * — but a two-second pause that never trips the limiter finishes a playlist
+ * several times faster than a third of a second that always does.
+ */
+ private var gap = TRACK_GAP_MS
+
+ /** Clean fetches in a row, which is what earns the gap back down. */
+ private var clean = 0
+
+ private fun noteKeyWait(waitMs: Long) {
+ if (waitMs >= KEY_WAIT_SLOW_MS) {
+ clean = 0
+ gap = (gap * 2).coerceAtMost(MAX_GAP_MS)
+ } else if (++clean >= CLEAN_RUN) {
+ clean = 0
+ gap = (gap / 2).coerceAtLeast(TRACK_GAP_MS)
+ }
+ }
+
+ private val networkCallback = object : ConnectivityManager.NetworkCallback() {
+ override fun onAvailable(network: Network) {
+ _link.value = link()
+ }
+
+ override fun onLost(network: Network) {
+ _link.value = link()
+ }
+
+ override fun onCapabilitiesChanged(
+ network: Network,
+ capabilities: NetworkCapabilities,
+ ) {
+ _link.value = link()
+ }
+ }
+
+ /**
+ * Reconsiders what there is to do.
+ *
+ * Cheap and idempotent: a pump already running is left alone, because it
+ * will ask the store again the moment it finishes what it is on.
+ */
+ fun wake() {
+ if (pump?.isActive == true) return
+ // Published before the coroutine is scheduled, not inside it. The
+ // foreground service watches this flow and stops itself the moment it
+ // reads "not running" — which, with the pump still queued on a
+ // dispatcher, is the very first thing it read.
+ _status.value = Status(running = true)
+ pump = scope.launch { drain() }
+ }
+
+ fun stop() {
+ pump?.cancel()
+ pump = null
+ releaseWatch()
+ _status.value = Status()
+ }
+
+ // ----------------------------------------------------------------- the pump
+
+ private suspend fun drain() = coroutineScope {
+ holdWatch()
+ // Progress ticks come off the engine's event channel; see DownloadEvents.
+ val ticks = launch {
+ DownloadEvents.progress.collect { store.onProgress(it.uri, it.fraction) }
+ }
+ try {
+ while (isActive) {
+ val blocked = allowed()
+ if (blocked != null) {
+ publish(waiting = blocked)
+ awaitAllowed()
+ continue
+ }
+
+ val pending = store.pending()
+ // Covers before everything else, including before the rest of
+ // the extras: they are the one thing whose absence is visible
+ // the moment it happens.
+ if (pending.isEmpty() && backfillCovers()) continue
+ if (pending.isEmpty() && backfillExtras()) continue
+ if (pending.isEmpty()) {
+ // Nothing to do now, but something may be waiting out a
+ // failure. Sleeping until then rather than spinning is the
+ // difference between a queue that idles and one that keeps
+ // the phone awake for a track it cannot have.
+ val retryAt = store.retryAt() ?: break
+ val wait = retryAt - System.currentTimeMillis()
+ if (wait <= 0) continue
+ publish(waiting = null)
+ delay(wait.coerceAtMost(MAX_SLEEP_MS))
+ continue
+ }
+
+ publish(waiting = null)
+ val batch = pending.take(PARALLEL)
+ val outcomes = batch
+ .map { uri -> async { attempt(uri) } }
+ .awaitAll()
+
+ // Nothing was wrong with these tracks — the engine was not
+ // there to fetch them, or Spotify asked us to slow down.
+ // Without this the pump would find them pending again
+ // immediately and spin at full speed against whatever said no.
+ if (outcomes.all { it == Outcome.NOT_NOW }) {
+ publish(waiting = Waiting.ENGINE)
+ delay(if (throttled) THROTTLED_WAIT_MS else ENGINE_POLL_MS)
+ throttled = false
+ } else {
+ // A breath between songs, as long as this queue has learnt
+ // it needs to be; see [gap].
+ delay(gap)
+ }
+ }
+ } finally {
+ ticks.cancel()
+ releaseWatch()
+ _status.value = Status()
+ }
+ }
+
+ /** Tracks whose extras were attempted this run, successfully or not. */
+ private val extrasTried = mutableSetOf<String>()
+
+ private val coversTried = mutableSetOf<String>()
+
+ /**
+ * Catches up the album covers of songs that were downloaded without them.
+ *
+ * Its own pass, ahead of the rest. A cover is a few tens of kilobytes and a
+ * Canvas is a few megabytes of video, so a single loop that fetched both
+ * per track delivered covers at about one a minute — while the thing the
+ * listener actually sees missing is the blank tile in the notification.
+ *
+ * @return true when it did something, so the caller comes back for more.
+ */
+ private suspend fun backfillCovers(): Boolean {
+ val missing = store.files.value.keys.asSequence()
+ .filterNot(coversTried::contains)
+ .filter { needsExtras(it) }
+ .take(COVER_BATCH)
+ .toList()
+ if (missing.isEmpty()) return false
+
+ for (uri in missing) {
+ coversTried += uri
+ val cover = runCatching { NativeBridge.downloadState(uri) }
+ .getOrNull()
+ ?.let { runCatching { JSONObject(it).optString("coverUrl") }.getOrNull() }
+ ?.takeIf { it.isNotBlank() }
+ ?: continue
+ DownloadExtras.keep(cover, "art")
+ // No audio key is asked for here, so the pace that keeps the key
+ // limiter happy does not apply: this is an ordinary CDN image.
+ delay(COVER_GAP_MS)
+ }
+ return true
+ }
+
+ /**
+ * Fetches the words, cover and Canvas of songs that were downloaded without
+ * them.
+ *
+ * Extras are normally taken as each track lands, which covers everything
+ * downloaded from now on and nothing downloaded before — including every
+ * track fetched by a build of this app that had no extras yet. Offline that
+ * shows up as the one thing a listener notices immediately: a song playing
+ * fine with a blank cover in the notification.
+ *
+ * Runs only once the queue has nothing left to fetch, so the music always
+ * comes first, and a few at a time so a large library does not turn into a
+ * burst of requests. A track is tried once per run whatever the outcome:
+ * some songs simply have no Canvas and no lyrics, and asking about them
+ * again on every turn of the loop would be a loop.
+ *
+ * @return true when it did something, so the caller comes back for more.
+ */
+ private suspend fun backfillExtras(): Boolean {
+ val missing = store.files.value.keys.asSequence()
+ .filterNot(extrasTried::contains)
+ .filter { needsExtras(it) }
+ .take(EXTRAS_BATCH)
+ .toList()
+ if (missing.isEmpty()) return false
+
+ for (uri in missing) {
+ extrasTried += uri
+ val sidecar = runCatching { NativeBridge.downloadState(uri) }.getOrNull() ?: continue
+ keepExtras(uri, sidecar)
+ delay(TRACK_GAP_MS)
+ }
+ return true
+ }
+
+ /** Whether the cover of a downloaded track is missing from the phone. */
+ private fun needsExtras(trackUri: String): Boolean {
+ val cover = store.trackOf(trackUri)?.artworkUrl ?: return false
+ return DownloadExtras.fileOf(cover, "art") == null
+ }
+
+ private enum class Outcome { DONE, FAILED, NOT_NOW }
+
+ private suspend fun attempt(trackUri: String): Outcome {
+ val kbps = settings.quality.value.kbps
+ val outcome = runCatching {
+ withContext(Dispatchers.IO) { NativeBridge.downloadTrack(trackUri, kbps) }
+ }
+
+ outcome.onSuccess { sidecar ->
+ // How long the engine waited for the audio key, which is the one
+ // measurement that says whether this queue is going too fast; see
+ // [gap].
+ noteKeyWait(runCatching { JSONObject(sidecar).optLong("keyWaitMs", 0L) }.getOrDefault(0L))
+ store.onCompleted(trackUri, recordOf(sidecar, kbps))
+ keepExtras(trackUri, sidecar)
+ return Outcome.DONE
+ }
+
+ val reason = outcome.exceptionOrNull()?.message.orEmpty()
+ // Not the track's fault, so nothing is held against it: the pump will
+ // find the same track pending on its next turn, once whatever went
+ // missing is back.
+ if (reason.isTransport()) {
+ if (reason.isThrottled()) throttled = true
+ store.clearProgress(trackUri)
+ return Outcome.NOT_NOW
+ }
+ store.onFailed(trackUri, reason.ifEmpty { "download failed" })
+ return Outcome.FAILED
+ }
+
+ /**
+ * The words, the Canvas, the cover and the artist behind the song.
+ *
+ * Everything here fails quietly. A track with no lyrics is the ordinary
+ * case, a Canvas that will not fetch is a still cover, and neither is worth
+ * failing a download that has already succeeded — the music is on the
+ * phone, which is what was asked for.
+ *
+ * Calling the catalogue is the whole of the caching: `Catalog` writes every
+ * answer down on the way past for a track that is downloaded, which this
+ * one now is. Only the two binaries have to be fetched by name.
+ */
+ private suspend fun keepExtras(trackUri: String, sidecar: String) {
+ runCatching {
+ // The cover first, and deliberately. It is a few tens of kilobytes
+ // and it is the one extra that is missed the moment it is absent —
+ // a song playing with a blank tile in the notification. The Canvas
+ // below is megabytes of video; behind it, covers arrived at about
+ // one a minute.
+ //
+ // The size the engine recorded is the large one, which is what the
+ // player screen wants. The row thumbnail finds it too: covers are
+ // keyed on the picture rather than the size. See DownloadExtras.
+ runCatching { JSONObject(sidecar).optString("coverUrl") }
+ .getOrNull()
+ ?.takeIf { it.isNotBlank() }
+ ?.let { DownloadExtras.keep(it, "art") }
+
+ // Asking is the whole of the caching: the catalogue writes every
+ // answer down on the way past, so a track that is downloaded has
+ // its words on the phone too.
+ dev.lelonio.square.data.Catalog.lyrics(trackUri)
+
+ dev.lelonio.square.data.Catalog.canvas(trackUri)?.let { clip ->
+ DownloadExtras.keep(clip.url, if (clip.isVideo) "video" else "art")
+ }
+ }.onFailure {
+ android.util.Log.i("SquareDownloads", "extras for $trackUri: $it")
+ }
+ }
+
+ /**
+ * Whether a failure was about the app's own footing rather than the track.
+ *
+ * Matched on the engine's own words, which are stable strings on the Rust
+ * side for exactly this reason.
+ */
+ private fun String.isTransport(): Boolean =
+ contains("engine not started") ||
+ contains("engine is reconnecting") ||
+ contains("cancelled") ||
+ isThrottled()
+
+ /**
+ * Whether Spotify is refusing to hand out keys.
+ *
+ * Says nothing about the track — the same song downloads fine a minute
+ * later — so it must never count against it. The string is the engine's
+ * own; see `KEY_THROTTLED` in downloads.rs.
+ */
+ private fun String.isThrottled(): Boolean = contains("audio keys are being refused")
+
+ private fun recordOf(sidecar: String, requestedKbps: Int): DownloadStore.FileRecord {
+ val json = runCatching { JSONObject(sidecar) }.getOrNull()
+ val format = json?.optString("format").orEmpty()
+ return DownloadStore.FileRecord(
+ trackId = json?.optString("trackId").orEmpty(),
+ format = format,
+ bytes = json?.optLong("bytes") ?: 0L,
+ // What was actually stored, not what was asked for. A track that
+ // only exists at 160 must not look like a 320 download, or asking
+ // for 320 again would never re-fetch anything.
+ kbps = kbpsOf(format) ?: requestedKbps,
+ downloadedAt = json?.optLong("downloadedAt") ?: System.currentTimeMillis(),
+ )
+ }
+
+ private fun kbpsOf(format: String): Int? = when {
+ format.endsWith("_96") -> 96
+ format.endsWith("_160") || format.endsWith("_160_ENC") -> 160
+ format.endsWith("_256") -> 256
+ format.endsWith("_320") -> 320
+ else -> null
+ }
+
+ // -------------------------------------------------------------- the link
+
+ private enum class Link { NONE, METERED, UNMETERED }
+
+ private fun link(): Link {
+ val manager = connectivity ?: return Link.NONE
+ val capabilities = manager.activeNetwork
+ ?.let(manager::getNetworkCapabilities)
+ ?: return Link.NONE
+ if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
+ return Link.NONE
+ }
+ // Not validated means a captive portal or a network that is up but goes
+ // nowhere. Treated as no network, because that is what it is for us.
+ if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
+ return Link.NONE
+ }
+ return if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
+ Link.UNMETERED
+ } else {
+ Link.METERED
+ }
+ }
+
+ /** Null when downloading may go ahead, otherwise what it is waiting for. */
+ private fun allowed(): Waiting? = when (_link.value) {
+ Link.NONE -> Waiting.NETWORK
+ Link.METERED -> if (settings.wifiOnly.value) Waiting.WIFI else null
+ Link.UNMETERED -> null
+ }
+
+ private suspend fun awaitAllowed() {
+ // The setting can change as well as the link, and a StateFlow of one
+ // will not report the other. Combining them would mean building a flow
+ // for a wait that ends either way, so this simply waits on whichever
+ // moves and re-asks.
+ val before = _link.value
+ val wifiBefore = settings.wifiOnly.value
+ while (_link.value == before && settings.wifiOnly.value == wifiBefore) {
+ delay(NETWORK_POLL_MS)
+ }
+ }
+
+ private fun holdWatch() {
+ if (watching) return
+ watching = true
+ runCatching { connectivity?.registerDefaultNetworkCallback(networkCallback) }
+ _link.value = link()
+ }
+
+ private fun releaseWatch() {
+ if (!watching) return
+ watching = false
+ runCatching { connectivity?.unregisterNetworkCallback(networkCallback) }
+ }
+
+ private fun publish(waiting: Waiting?) {
+ val wanted = store.owners.value.values.flatten().toSet()
+ val files = store.files.value
+ _status.value = Status(
+ running = true,
+ done = wanted.count(files::containsKey),
+ total = wanted.size,
+ waiting = waiting,
+ )
+ }
+
+ private companion object {
+ /**
+ * One at a time, with a pause between tracks.
+ *
+ * Not a throughput decision — two were comfortably faster. Spotify
+ * hands out one decryption key per file and refuses them when a session
+ * asks too quickly, and a playlist fetched two at a time with no pause
+ * tripped that within a dozen songs: librespot then sat out hold-offs
+ * of twenty and thirty seconds, and the whole queue was slower than if
+ * it had never hurried. This pace stays under it.
+ */
+ const val PARALLEL = 1
+
+ /** Between one track and the next, to stay under the key limiter. */
+ const val TRACK_GAP_MS = 1_200L
+
+ /** A key that took this long was one the limiter held back. */
+ const val KEY_WAIT_SLOW_MS = 1_500L
+
+ /**
+ * As slow as the pacing is ever allowed to get.
+ *
+ * Higher than it looks reasonable on purpose: a refusal costs the
+ * session a hold of three seconds, then six, then twelve, so a gap that
+ * trips the limiter is far more expensive than one that waits. Twenty
+ * seconds of patience beats twenty-one seconds of holds and a queue
+ * that also stops the music from starting.
+ */
+ const val MAX_GAP_MS = 20_000L
+
+ /** Clean fetches before the gap is allowed to halve again. */
+ const val CLEAN_RUN = 3
+
+ /** How many songs' extras are caught up on in one turn of the loop. */
+ const val EXTRAS_BATCH = 5
+
+ /** Covers are small, so more of them fit in a turn. */
+ const val COVER_BATCH = 12
+ const val COVER_GAP_MS = 80L
+
+ /**
+ * How long to sit out a refusal that has already arrived.
+ *
+ * Longer than the gap because by this point Spotify has said no, and
+ * librespot's own hold-off is already counting; asking again inside it
+ * only confirms the pace it objected to.
+ */
+ const val THROTTLED_WAIT_MS = 20_000L
+
+ const val NETWORK_POLL_MS = 1_500L
+
+ /** How long to leave the engine alone before asking it again. */
+ const val ENGINE_POLL_MS = 3_000L
+
+ /** So a queue asleep on a long backoff still notices a new playlist. */
+ const val MAX_SLEEP_MS = 30_000L
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadService.kt b/app/src/main/java/dev/lelonio/square/download/DownloadService.kt
new file mode 100644
index 0000000..a050fc1
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/download/DownloadService.kt
@@ -0,0 +1,199 @@
+package dev.lelonio.square.download
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.content.pm.ServiceInfo
+import android.os.Build
+import android.os.IBinder
+import androidx.core.app.NotificationCompat
+import androidx.core.app.ServiceCompat
+import dev.lelonio.square.R
+import dev.lelonio.square.SquareApplication
+import dev.lelonio.square.playback.PlaybackService
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.launch
+
+/**
+ * Keeps the download queue alive and says what it is doing.
+ *
+ * Separate from [PlaybackService] because the two have different lifetimes: a
+ * playlist can be downloading with nothing playing, and music can play with
+ * nothing left to download. Sharing one service would have meant either
+ * notification saying the wrong thing, and a queue that died whenever the
+ * listener stopped the music.
+ *
+ * It does need the engine, though — the audio comes down a librespot session —
+ * so starting this also asks [PlaybackService] to connect. The engine belongs
+ * to the process rather than to either service, so whichever asks first gets it
+ * and the other simply finds it there.
+ */
+class DownloadService : android.app.Service() {
+
+ private val container get() = application as SquareApplication
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+ private var watcher: Job? = null
+ private var foreground = false
+
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onCreate() {
+ super.onCreate()
+ createChannel()
+ }
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ if (intent?.action == ACTION_STOP) {
+ container.downloadQueue.stop()
+ stop()
+ return START_NOT_STICKY
+ }
+
+ // Up front and unconditionally: Android gives a service started into
+ // the foreground a few seconds to say so, and the queue's first answer
+ // may take longer than that if it has to wait for a session.
+ goForeground(container.downloadQueue.status.value)
+
+ // The audio comes down the librespot session, so there has to be one.
+ // Harmless when there already is: the service guards its own repeated
+ // connects.
+ PlaybackService.connect(this)
+
+ container.downloadQueue.wake()
+ watch()
+ // Re-created after a kill, the queue works out what it still owes from
+ // the store; there is nothing in the intent worth keeping.
+ return START_STICKY
+ }
+
+ private fun watch() {
+ if (watcher?.isActive == true) return
+ watcher = scope.launch {
+ container.downloadQueue.status.collectLatest { status ->
+ if (!status.running) {
+ stop()
+ return@collectLatest
+ }
+ notify(status)
+ }
+ }
+ }
+
+ private fun stop() {
+ watcher?.cancel()
+ watcher = null
+ ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
+ foreground = false
+ stopSelf()
+ }
+
+ override fun onDestroy() {
+ scope.cancel()
+ super.onDestroy()
+ }
+
+ // --------------------------------------------------------- the notification
+
+ private fun goForeground(status: DownloadQueue.Status) {
+ if (foreground) return
+ foreground = true
+ ServiceCompat.startForeground(
+ this,
+ NOTIFICATION_ID,
+ build(status),
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
+ ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
+ } else {
+ 0
+ },
+ )
+ }
+
+ private fun notify(status: DownloadQueue.Status) {
+ val manager = getSystemService(NotificationManager::class.java) ?: return
+ // Posting is allowed to fail: without the notification permission there
+ // is no notification, and the download is none the worse for it.
+ runCatching { manager.notify(NOTIFICATION_ID, build(status)) }
+ }
+
+ private fun build(status: DownloadQueue.Status): Notification {
+ val text = when (status.waiting) {
+ DownloadQueue.Waiting.WIFI -> getString(R.string.download_waiting_wifi)
+ DownloadQueue.Waiting.NETWORK -> getString(R.string.download_waiting_network)
+ DownloadQueue.Waiting.ENGINE -> getString(R.string.download_waiting_engine)
+ null -> getString(R.string.download_progress_count, status.done, status.total)
+ }
+
+ val stop = PendingIntent.getService(
+ this,
+ 0,
+ Intent(this, DownloadService::class.java).setAction(ACTION_STOP),
+ PendingIntent.FLAG_IMMUTABLE,
+ )
+
+ return NotificationCompat.Builder(this, CHANNEL_ID)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle(getString(R.string.downloading))
+ .setContentText(text)
+ // Indeterminate while waiting: a bar frozen at 30% reads as a stuck
+ // download, and the reason is in the text right beside it.
+ .setProgress(
+ status.total.coerceAtLeast(1),
+ status.done,
+ status.waiting != null || status.total == 0,
+ )
+ .setOngoing(true)
+ .setSilent(true)
+ .setCategory(NotificationCompat.CATEGORY_PROGRESS)
+ .addAction(0, getString(android.R.string.cancel), stop)
+ .build()
+ }
+
+ private fun createChannel() {
+ val manager = getSystemService(NotificationManager::class.java) ?: return
+ if (manager.getNotificationChannel(CHANNEL_ID) != null) return
+ manager.createNotificationChannel(
+ NotificationChannel(
+ CHANNEL_ID,
+ getString(R.string.downloads),
+ // Low: this is a progress bar, not news. It should be findable
+ // in the shade and never interrupt anything.
+ NotificationManager.IMPORTANCE_LOW,
+ ).apply {
+ setShowBadge(false)
+ },
+ )
+ }
+
+ companion object {
+ private const val CHANNEL_ID = "downloads"
+ private const val NOTIFICATION_ID = 42
+ private const val ACTION_STOP = "dev.lelonio.square.action.STOP_DOWNLOADS"
+
+ /**
+ * Starts working through whatever the store says is owed.
+ *
+ * Safe to call whenever that might have changed — adding a playlist,
+ * removing one, the app starting. A service already running simply
+ * wakes its queue, which was going to ask the store again anyway.
+ */
+ fun start(context: Context) {
+ val intent = Intent(context, DownloadService::class.java)
+ runCatching {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ context.startForegroundService(intent)
+ } else {
+ context.startService(intent)
+ }
+ }
+ }
+ }
+}
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 1df57c5..df91ade 100644
--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
@@ -488,6 +488,60 @@ object NativeBridge {
private external fun nativeRemoteCommand(deviceId: String, body: String)
private external fun nativeRemoteVolume(deviceId: String, volume: Int)
private external fun nativeShutdown()
+ /**
+ * True when the handshake could not be made and there were downloads to
+ * play instead.
+ *
+ * The engine still exists in that state, and so does the player: what is
+ * missing is the session and the Connect device, which is why nothing can
+ * be streamed and everything already on the phone still plays.
+ */
+ val isOffline: Boolean get() = nativeIsOffline()
+
+ /**
+ * Where downloaded tracks are kept.
+ *
+ * Call before downloading anything, and again if the listener moves the
+ * store to a memory card. Until it is called the engine simply has no
+ * downloads, so playback is unaffected by the order this happens in.
+ */
+ fun setDownloadRoot(path: String) = nativeSetDownloadRoot(path)
+
+ /**
+ * Downloads one track and returns the sidecar JSON that was written.
+ *
+ * **Blocks for the length of the download.** Call it from the download
+ * queue's worker, never from the main thread or from anything holding the
+ * player. Throws with `cancelled` if [cancelDownload] was called for this
+ * track, and with a message worth showing for anything else.
+ *
+ * Doing nothing is a valid outcome: a track already downloaded at this
+ * quality or better returns its existing sidecar immediately, which is what
+ * lets two playlists share a track without fetching it twice.
+ *
+ * @param bitrateKbps the quality to ask for; 96, 160 or 320
+ */
+ fun downloadTrack(trackUri: String, bitrateKbps: Int): String =
+ nativeDownloadTrack(trackUri, bitrateKbps)
+
+ /**
+ * The sidecar of a downloaded track as JSON, or the string `null` when the
+ * track is not downloaded.
+ */
+ fun downloadState(trackUri: String): String = nativeDownloadState(trackUri)
+
+ /** Deletes a download. Not being there is not an error. */
+ fun removeDownload(trackUri: String) = nativeRemoveDownload(trackUri)
+
+ /**
+ * Asks a download in progress to stop at the end of its current chunk.
+ *
+ * What has already been fetched is kept, so resuming later costs only the
+ * remainder — cancelling a queue because it started on mobile data should
+ * not throw away what it already paid for.
+ */
+ fun cancelDownload(trackUri: String) = nativeCancelDownload(trackUri)
+
private external fun nativeUsername(): String
private external fun nativeCollectionUri(): String
private external fun nativeRootlist(): String
@@ -496,4 +550,10 @@ object NativeBridge {
private external fun nativeLyrics(trackUri: String): String
private external fun nativeTrackRelatives(trackUri: String): String
private external fun nativeCanvas(trackUri: String): String
+ private external fun nativeIsOffline(): Boolean
+ private external fun nativeSetDownloadRoot(path: String)
+ private external fun nativeDownloadTrack(trackUri: String, bitrateKbps: Int): String
+ private external fun nativeDownloadState(trackUri: String): String
+ private external fun nativeRemoveDownload(trackUri: String)
+ private external fun nativeCancelDownload(trackUri: 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 e8e2681..57f4689 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -1156,6 +1156,12 @@ class LibrespotPlayer(
// --- NativeEvents: arrives on a tokio worker thread ---
override fun onEvent(type: String, uri: String, positionMs: Long) {
+ // Downloads travel on this channel because the engine has one listener
+ // and one JVM attachment, not because they have anything to do with
+ // what is playing. Taken off here rather than posted to the player's
+ // handler, where a progress tick several times a second would queue
+ // behind whatever the player is in the middle of.
+ if (dev.lelonio.square.download.DownloadEvents.accept(type, uri, positionMs)) return
handler.post { applyEvent(type, uri, positionMs) }
}
diff --git a/app/src/main/java/dev/lelonio/square/playback/OfflineMode.kt b/app/src/main/java/dev/lelonio/square/playback/OfflineMode.kt
new file mode 100644
index 0000000..3fa76a8
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/playback/OfflineMode.kt
@@ -0,0 +1,86 @@
+package dev.lelonio.square.playback
+
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/**
+ * Whether the app is playing from the phone rather than from Spotify.
+ *
+ * An object rather than something injected, for the same reason
+ * [dev.lelonio.square.data.RemoteConnect] is one: there is a single engine
+ * behind it and the answer is wanted from the service, the player and half the
+ * screens.
+ *
+ * ### Three ways in, and only one of them is about the engine
+ *
+ * - [Reason.MANUAL] — the listener asked for it in Settings. Beats everything.
+ * - [Reason.NO_SESSION] — the handshake could not be made and the engine came
+ * up with no Spirc at all. This is the real one: nothing can be streamed
+ * because there is nothing to stream from.
+ * - [Reason.SLOW] — the connection is there but worse than the copies on the
+ * phone. Deliberately **does not** tear the session down. Going offline for
+ * real over a bad minute would cost the Connect device and the way back, for
+ * a problem that fixes itself; what this changes is only what the app offers
+ * to play, which is the whole of what the listener asked for. A downloaded
+ * track already plays from disk in every mode — see `load_downloaded_track`
+ * — so the streamed ones are the only ones this decides about.
+ */
+object OfflineMode {
+
+ enum class Reason { MANUAL, NO_SESSION, SLOW }
+
+ private val _manual = MutableStateFlow(false)
+ private val _noSession = MutableStateFlow(false)
+ private val _slow = MutableStateFlow(false)
+
+ private val _reason = MutableStateFlow<Reason?>(null)
+ private val _active = MutableStateFlow(false)
+
+ /** Why the app is offline, or null when it is not. */
+ val reason: StateFlow<Reason?> = _reason.asStateFlow()
+
+ /**
+ * Whether only downloaded music should be offered.
+ *
+ * Its own flow rather than a mapping of [reason], so a row being drawn can
+ * read `active.value` without collecting anything: the answer is wanted
+ * once per row and it changes a handful of times a day.
+ */
+ val active: StateFlow<Boolean> = _active.asStateFlow()
+
+ fun setManual(on: Boolean) {
+ 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
+ recompute()
+ }
+
+ /**
+ * Told by the service when the link would stream worse than the phone
+ * already holds. See `PlaybackService.watchConnection`.
+ */
+ fun setSlow(on: Boolean) {
+ if (_slow.value == on) return
+ _slow.value = on
+ recompute()
+ }
+
+ private fun recompute() {
+ val next = when {
+ _manual.value -> Reason.MANUAL
+ _noSession.value -> Reason.NO_SESSION
+ _slow.value -> Reason.SLOW
+ else -> null
+ }
+ if (_reason.value == next) return
+ _reason.value = next
+ _active.value = next != null
+ }
+}
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 26d803a..3a05352 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -967,6 +967,18 @@ class PlaybackService : MediaLibraryService() {
val engine = librespot ?: return@launch
engineStarted = true
+ // Before the engine plays anything. The player asks this store on every
+ // load, and setting it later would leave a window in which a downloaded
+ // track streamed instead of playing from the phone.
+ withContext(Dispatchers.IO) {
+ container.downloads.load()
+ runCatching {
+ NativeBridge.setDownloadRoot(container.downloads.root.absolutePath)
+ }.onFailure {
+ android.util.Log.w(TAG, "downloads have no home: $it")
+ }
+ }
+
runCatching {
// Empty is a real answer here. The engine keeps the credential the
// access point issued and prefers it, so a token is only needed by a
@@ -1036,7 +1048,14 @@ class PlaybackService : MediaLibraryService() {
).show()
}
}.onSuccess {
- android.util.Log.i(TAG, "engine connected")
+ // Started is not the same as connected any more. With music on the
+ // phone the engine comes up even when the handshake failed, with a
+ // player and no session, and the app has to know which of the two
+ // it got: everything that streams is unavailable in the second, and
+ // the downloads play exactly as they always did.
+ 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")
if (restoreQueue) restoreQueue()
observeForSaving()
}
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 4a6b674..815130b 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -8,10 +8,13 @@ import dev.lelonio.square.SquareApplication
import dev.lelonio.square.auth.SpotifyOAuth
import dev.lelonio.square.backend.BackendAuthState
import dev.lelonio.square.backend.BackendId
+import dev.lelonio.square.backend.HomeChip
import dev.lelonio.square.backend.HomeRow
import dev.lelonio.square.backend.SearchLabels
import dev.lelonio.square.R
import dev.lelonio.square.data.Catalog
+import dev.lelonio.square.data.DownloadStore
+import dev.lelonio.square.download.DownloadService
import dev.lelonio.square.data.AddTracksRequestDto
import dev.lelonio.square.data.RemoveTracksRequestDto
import dev.lelonio.square.data.TrackUriDto
@@ -197,12 +200,22 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val feed: StateFlow<FeedState> = _feed.asStateFlow()
private var feedJob: Job? = null
- /** YouTube Music's own home page, as it laid it out; see [MusicBackend.homeRows]. */
+ /** YouTube Music's own home page, as it laid it out; see [MusicBackend.homeFeed]. */
data class YouTubeHomeState(
val rows: List<HomeRow> = emptyList(),
+ val chips: List<HomeChip> = emptyList(),
+ /** Which filter is on, by title; null is the home page itself. */
+ val chip: String? = null,
val loading: Boolean = false,
+ /** A page after the first, on its way. */
+ val loadingMore: Boolean = false,
val error: String? = null,
- )
+ /** Where the next shelves are; null when the page has run out. */
+ val cursor: String? = null,
+ ) {
+ /** True while there are more shelves to ask for. */
+ val hasMore: Boolean get() = cursor != null
+ }
private val _youtubeHome = MutableStateFlow(YouTubeHomeState())
val youtubeHome: StateFlow<YouTubeHomeState> = _youtubeHome.asStateFlow()
@@ -221,15 +234,85 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
if (youtubeHomeJob?.isActive == true) return
if (!force && _youtubeHome.value.rows.isNotEmpty()) return
- _youtubeHome.value = _youtubeHome.value.copy(loading = true, error = null)
- youtubeHomeJob = viewModelScope.launch {
- runCatching { backend.homeRows() }
- .onSuccess { _youtubeHome.value = YouTubeHomeState(rows = it, loading = false) }
- .onFailure {
- android.util.Log.e(TAG, "youtube home failed: ${chain(it)}", it)
- _youtubeHome.value = YouTubeHomeState(loading = false, error = describe(it))
- }
+ youtubeParams = null
+ _youtubeHome.value = _youtubeHome.value.copy(loading = true, error = null, chip = null)
+ youtubeHomeJob = viewModelScope.launch { readYouTubeHome(replace = true) }
+ }
+
+ /**
+ * The next shelves, asked for as the page runs out.
+ *
+ * The home page is served four or five shelves at a time and the list is
+ * what says when more are wanted, so this is called from the bottom of it
+ * rather than on a timer: what the listener never scrolls to is never
+ * fetched.
+ */
+ fun loadMoreYouTubeHome() {
+ val state = _youtubeHome.value
+ if (!state.hasMore || state.loading || state.loadingMore) return
+ if (youtubeHomeJob?.isActive == true) return
+
+ _youtubeHome.value = state.copy(loadingMore = true)
+ youtubeHomeJob = viewModelScope.launch { readYouTubeHome(replace = false) }
+ }
+
+ /**
+ * Picks one of the filters above the page, or clears it.
+ *
+ * The chips are the service's own views of the same home — "Relax",
+ * "Workout" — and each is a page in its own right, continuation and all,
+ * so choosing one starts over rather than filtering what is already here.
+ */
+ fun selectYouTubeChip(chip: HomeChip?) {
+ if (chip?.title == _youtubeHome.value.chip) return
+ youtubeHomeJob?.cancel()
+ youtubeParams = chip?.params
+ _youtubeHome.value = _youtubeHome.value.copy(
+ rows = emptyList(),
+ chip = chip?.title,
+ loading = true,
+ loadingMore = false,
+ error = null,
+ )
+ youtubeHomeJob = viewModelScope.launch { readYouTubeHome(replace = true) }
+ }
+
+ private var youtubeParams: String? = null
+
+ private suspend fun readYouTubeHome(replace: Boolean) {
+ val backend = container.activeBackend
+ val before = _youtubeHome.value
+ runCatching {
+ backend.homeFeed(
+ cursor = if (replace) null else before.cursor,
+ params = youtubeParams,
+ )
}
+ .onSuccess { feed ->
+ val rows = if (replace) feed.rows else before.rows + feed.rows
+ _youtubeHome.value = before.copy(
+ rows = rows,
+ // A continuation carries no chips, so the ones already on
+ // screen stay where they are.
+ chips = feed.chips.ifEmpty { before.chips },
+ loading = false,
+ loadingMore = false,
+ error = null,
+ cursor = feed.cursor,
+ )
+ }
+ .onFailure {
+ if (it is kotlinx.coroutines.CancellationException) throw it
+ android.util.Log.e(TAG, "youtube home failed: ${chain(it)}", it)
+ _youtubeHome.value = before.copy(
+ loading = false,
+ loadingMore = false,
+ // A page that failed after the first leaves what is already
+ // read on screen: the shelves above it are still good.
+ error = if (before.rows.isEmpty()) describe(it) else null,
+ cursor = if (replace) null else before.cursor,
+ )
+ }
}
/**
@@ -1296,6 +1379,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// No access point to wait for and no Premium account to check: this
// backend is usable at once, and signing in only adds the library.
_state.value = UiState.Loading
+ // Before the library is asked for: a session that has come loose
+ // reads as an empty library otherwise, with nothing on screen to
+ // say the account is the thing that needs attention.
+ runCatching { backend.refreshAuth() }
val name = (backend.authState.value as? BackendAuthState.LoggedIn)?.displayName
runCatching { backend.playlists() }
.onSuccess { playlists ->
@@ -1312,6 +1399,11 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
_state.value =
UiState.Ready(displayName = name.orEmpty(), playlists = withLocalFiles(emptyList()))
}
+ // The other two shelves of the same library. They read the active
+ // backend and empty themselves for one that keeps neither, which is
+ // also what clears Spotify's off the screen when the source changes.
+ loadSavedAlbums()
+ loadFollowedArtists()
return@launch
}
@@ -1322,6 +1414,13 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
_state.value = UiState.Connecting
if (!awaitEngine()) {
+ // A library with no session is not an empty library. Everything
+ // that was downloaded is still here and still playable, and the
+ // shelf for it is the one thing the listener came for.
+ offlineLibrary()?.let {
+ _state.value = it
+ return@launch
+ }
_state.value = if (container.spotifySignedIn) {
UiState.Failed(string(R.string.cannot_connect))
} else {
@@ -1344,7 +1443,9 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
.onFailure {
android.util.Log.e(TAG, "library load failed: ${chain(it)}", it)
- _state.value = UiState.Failed(describe(it))
+ // The same fallback: the session came up but the catalogue
+ // could not be read, and the downloads are unaffected by that.
+ _state.value = offlineLibrary() ?: UiState.Failed(describe(it))
}
}
@@ -1355,6 +1456,46 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* already on screen with the account name by the time this runs, and an
* account with no Web API application connected simply keeps it.
*/
+ /**
+ * The library as the download index knows it, for when Spotify cannot be
+ * asked.
+ *
+ * Built from the labels stored beside every download — name, cover, kind —
+ * rather than from the context cache, which expires and holds only the last
+ * few things opened. A download is meant to outlive both, and a phone in a
+ * tunnel should find its playlists exactly where it left them.
+ *
+ * Null when there is nothing downloaded, which is the one case where an
+ * error really is the honest answer.
+ */
+ private suspend fun offlineLibrary(): UiState.Ready? {
+ container.downloads.load()
+ val owners = container.downloads.owners.value
+ val labelled = owners.keys.mapNotNull { uri ->
+ container.downloads.labelOf(uri)?.let {
+ CatalogPlaylist(uri = uri, name = it.name, artworkUrl = it.artworkUrl)
+ }
+ }
+ val singles = owners[DownloadStore.SINGLES].orEmpty()
+ val shelf = singles.takeIf { it.isNotEmpty() }?.let {
+ CatalogPlaylist(
+ uri = DownloadStore.SINGLES,
+ name = string(R.string.downloaded_tracks),
+ artworkUrl = dev.lelonio.square.ui.components.DOWNLOADS_COVER,
+ )
+ }
+ val everything = listOfNotNull(shelf) + labelled
+ if (everything.isEmpty()) return null
+
+ android.util.Log.i(TAG, "offline library: ${everything.size} downloaded")
+ // The name and the picture from the last time there was a connection.
+ // They cost nothing to keep and their absence reads as being signed
+ // out, which is not what has happened.
+ val (name, avatar) = container.preferences.profile()
+ // The phone's own files belong here as much as they do online.
+ return UiState.Ready(name, withLocalFiles(everything), avatarUrl = avatar)
+ }
+
/**
* The account's library, as the active backend assembles it.
*
@@ -1437,6 +1578,17 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// list mine. The id, not the display name — two accounts can
// be called the same thing and only one of them owns it.
meId = profile.id
+ // And kept on disk, for the next time there is no network to
+ // ask with; see [offlineLibrary].
+ container.preferences.setProfile(
+ _state.value.let { (it as? UiState.Ready)?.displayName.orEmpty() },
+ profile.images.lastOrNull()?.url,
+ )
+ // The picture itself, beside the downloads, so it is a file
+ // rather than a URL that cannot be fetched.
+ profile.images.lastOrNull()?.url?.let {
+ launch { dev.lelonio.square.download.DownloadExtras.keep(it, "art") }
+ }
}
.onFailure { android.util.Log.w(TAG, "profile unavailable: ${describe(it)}") }
}
@@ -1663,6 +1815,67 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
.getOrNull()
}
+ /**
+ * Shows a station that has already been resolved.
+ *
+ * The radio button asks for the tracks before it does anything else — it
+ * has to, since an empty station is a button that should do nothing — so
+ * this publishes what is already in hand rather than sending the page off
+ * to fetch the same list a second time. A station is not a context that can
+ * be reopened later anyway: ask twice and Spotify builds two different ones.
+ */
+ /**
+ * Tries to reach Spotify again, and says whether it worked.
+ *
+ * The switch first, because a listener who turned offline on and then asks
+ * to go back online means the switch: leaving it set and rebuilding the
+ * session would reconnect an app that immediately declares itself offline
+ * again.
+ *
+ * Then the handshake. A failure is not an error worth showing — the banner
+ * is already saying the thing it would say — so this reports it by leaving
+ * the app exactly as it was.
+ */
+ suspend fun retryOnline(): Boolean {
+ container.downloadSettings.setOfflineMode(false)
+ withContext(Dispatchers.IO) {
+ runCatching { NativeBridge.reconnect() }
+ .onFailure { android.util.Log.w(TAG, "retry failed: ${describe(it)}") }
+ }
+ val offline = runCatching { NativeBridge.isOffline }.getOrDefault(true)
+ dev.lelonio.square.playback.OfflineMode.setNoSession(offline)
+ if (!offline) {
+ // The library was built from the download index while there was no
+ // session; now there is one, and it is a different library.
+ refresh()
+ loadHomeShelves()
+ }
+ return !offline
+ }
+
+ fun showStation(
+ uri: String,
+ name: String,
+ artworkUrl: String?,
+ tracks: List<CatalogTrack>,
+ ) {
+ playlistJob?.cancel()
+ // Kept so the source line in the player can come back to it. Asking
+ // Spotify for the same station again would build a different one, and
+ // the page would then disagree with what is playing.
+ lastStation = PlaylistState(
+ uri = uri,
+ name = name,
+ artworkUrl = artworkUrl,
+ kind = DetailKind.PLAYLIST,
+ tracks = tracks,
+ )
+ lastStation?.let(::publishPlaylist)
+ }
+
+ /** The station last shown, so the player's source line can reopen it. */
+ private var lastStation: PlaylistState? = null
+
fun openContext(uri: String, name: String, artworkUrl: String? = null) =
openPlaylist(CatalogPlaylist(uri = uri, name = name, artworkUrl = artworkUrl))
@@ -1865,7 +2078,145 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
size > CONTEXT_CACHE_SIZE
}
+ // ------------------------------------------------------------ downloads
+
+ /** What is on the phone, per track; see DownloadStore. */
+ val downloadedFiles = container.downloads.files
+
+ /** What is being fetched right now, 0f..1f per track. */
+ val downloadProgress = container.downloads.progress
+
+ /** Per playlist, album or artist: whether it is kept, and how far along. */
+ val downloadOwners = container.downloads.ownerStates
+
+ /**
+ * Tracks downloaded on their own rather than as part of a page.
+ *
+ * The difference matters to the track menu: a song kept because a playlist
+ * wants it cannot be removed by itself — the file is still owed to that
+ * playlist — so offering to remove it there would be offering something
+ * that does nothing.
+ */
+ val downloadSingles: StateFlow<Set<String>> =
+ container.downloads.owners
+ .map { it[DownloadStore.SINGLES].orEmpty().toSet() }
+ .stateIn(viewModelScope, SharingStarted.Eagerly, emptySet())
+
+ /**
+ * Keeps a whole page on the phone, or stops keeping it.
+ *
+ * The page is the unit rather than the track because that is how a listener
+ * thinks about it — a playlist goes on the plane, not forty songs — and
+ * because it is what lets a shared track cost nothing: the store records
+ * who wanted each file, so a song two playlists both keep is fetched once
+ * and only leaves when the last of them lets go of it.
+ */
+ fun toggleDownload(page: PlaylistState) {
+ val uri = page.uri ?: return
+ if (page.tracks.isEmpty()) return
+ viewModelScope.launch {
+ if (container.downloads.owners.value.containsKey(uri)) {
+ // Only what is actually being fetched. Cancelling every track
+ // of the playlist would work — the engine clears the mark
+ // before each download — but it would also be several hundred
+ // JNI calls to stop the one or two that are running.
+ val inFlight = container.downloads.progress.value.keys.toList()
+ container.downloads.removeOwner(uri)
+ inFlight.forEach { runCatching { NativeBridge.cancelDownload(it) } }
+ sweepOrphans()
+ } else {
+ container.downloads.setOwner(
+ ownerUri = uri,
+ tracks = page.tracks,
+ label = DownloadStore.OwnerLabel(
+ name = page.name,
+ artworkUrl = page.artworkUrl,
+ kind = when (page.kind) {
+ DetailKind.ALBUM -> DownloadStore.KIND_ALBUM
+ DetailKind.ARTIST -> DownloadStore.KIND_ARTIST
+ DetailKind.PLAYLIST -> DownloadStore.KIND_PLAYLIST
+ },
+ ),
+ )
+ DownloadService.start(getApplication())
+ }
+ }
+ }
+
+ /**
+ * One track, kept on its own.
+ *
+ * Filed under a owner of its own so that the answer to "why is this here"
+ * stays honest: a song downloaded by itself does not disappear because a
+ * playlist it also belongs to was let go of.
+ */
+ fun toggleTrackDownload(track: CatalogTrack) {
+ viewModelScope.launch {
+ val singles = container.downloads.owners.value[DownloadStore.SINGLES].orEmpty()
+ if (track.uri in singles) {
+ container.downloads.removeSingle(track.uri)
+ runCatching { NativeBridge.cancelDownload(track.uri) }
+ sweepOrphans()
+ } else {
+ container.downloads.addSingle(track)
+ DownloadService.start(getApplication())
+ }
+ }
+ }
+
+ /** Everything, gone. The files first, then what pointed at them. */
+ /**
+ * Deletes the files nothing wants any more.
+ *
+ * Letting go of a playlist only says the playlist no longer wants its
+ * songs; it does not say the songs can go, because another playlist may
+ * want the same ones. So the two halves are separate: the index works out
+ * what is now unclaimed, and this is what takes those off the disk.
+ *
+ * Without it the index kept every file it had ever fetched — the rows went
+ * on showing the download mark for a playlist that had just been let go of,
+ * and the space was never given back.
+ */
+ private suspend fun sweepOrphans() {
+ container.downloads.pruneOrphans().forEach {
+ runCatching { NativeBridge.removeDownload(it) }
+ dev.lelonio.square.download.DownloadExtras.forget(it)
+ }
+ // And whatever is left in the extras that no surviving track can
+ // explain: covers, words and Canvases of songs that are gone.
+ withContext(Dispatchers.IO) {
+ val tracks = container.downloads.files.value.keys
+ dev.lelonio.square.download.DownloadExtras.sweep(
+ trackUris = tracks,
+ coverUrls = tracks.mapNotNull { container.downloads.trackOf(it)?.artworkUrl },
+ )
+ }
+ }
+
+ fun clearDownloads() {
+ viewModelScope.launch {
+ container.downloads.progress.value.keys.forEach {
+ runCatching { NativeBridge.cancelDownload(it) }
+ }
+ container.downloads.clearAll()
+ }
+ }
+
+ fun retryFailedDownloads() {
+ viewModelScope.launch {
+ container.downloads.retryFailed()
+ DownloadService.start(getApplication())
+ }
+ }
+
fun openPlaylist(playlist: CatalogPlaylist) {
+ // A station reopens as the list it already is; see [showStation].
+ lastStation?.takeIf { it.uri == playlist.uri }?.let {
+ playlistJob?.cancel()
+ publishPlaylist(it)
+ return
+ }
+
// Reopening one counts as opening it, and that is exactly the playlist
// the home page should keep at the front.
container.playlistOrder.record(playlist.uri)
@@ -1878,6 +2229,19 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
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
+ // here — in the order the playlist had when it was downloaded, which is
+ // the order it should still be in.
+ if (dev.lelonio.square.playback.OfflineMode.active.value) {
+ val wanted = container.downloads.owners.value[playlist.uri]
+ if (wanted != null) {
+ openDownloadedContext(playlist, wanted)
+ return
+ }
+ }
+
val kind = kindOf(playlist.uri)
playlistJob?.cancel()
// Reassigned when the picture arrives late; every state published below
@@ -2007,6 +2371,25 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* it is the only case in the app where an empty list is something to act
* on rather than to report.
*/
+ /** A downloaded list, read out of the index rather than off the network. */
+ private fun openDownloadedContext(playlist: CatalogPlaylist, wanted: List<String>) {
+ playlistJob?.cancel()
+ val label = container.downloads.labelOf(playlist.uri)
+ publishPlaylist(
+ PlaylistState(
+ uri = playlist.uri,
+ name = playlist.name.ifEmpty { label?.name.orEmpty() },
+ artworkUrl = playlist.artworkUrl ?: label?.artworkUrl,
+ kind = when (label?.kind) {
+ DownloadStore.KIND_ALBUM -> DetailKind.ALBUM
+ DownloadStore.KIND_ARTIST -> DetailKind.ARTIST
+ else -> DetailKind.PLAYLIST
+ },
+ tracks = wanted.mapNotNull(container.downloads::trackOf),
+ ),
+ )
+ }
+
private fun openLocalFiles(playlist: CatalogPlaylist) {
playlistJob?.cancel()
val base = PlaylistState(
@@ -2542,7 +2925,15 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val savedAlbums: StateFlow<List<CatalogPlaylist>> = _savedAlbums.asStateFlow()
fun loadSavedAlbums() = viewModelScope.launch {
- if (!container.webApi.isReady || container.activeBackend.id != BackendId.SPOTIFY) {
+ // Whichever service is on. What follows is Spotify's own paging; every
+ // other backend answers for itself, and one that keeps no albums
+ // answers with none.
+ if (container.activeBackend.id != BackendId.SPOTIFY) {
+ _savedAlbums.value = runCatching { container.activeBackend.savedAlbums() }
+ .getOrDefault(emptyList())
+ return@launch
+ }
+ if (!container.webApi.isReady) {
_savedAlbums.value = emptyList()
return@launch
}
@@ -2575,7 +2966,12 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val followedArtists: StateFlow<List<SearchItem>> = _followedArtists.asStateFlow()
fun loadFollowedArtists() = viewModelScope.launch {
- if (!container.webApi.isReady || container.activeBackend.id != BackendId.SPOTIFY) {
+ if (container.activeBackend.id != BackendId.SPOTIFY) {
+ _followedArtists.value = runCatching { container.activeBackend.followedArtists() }
+ .getOrDefault(emptyList())
+ return@launch
+ }
+ if (!container.webApi.isReady) {
_followedArtists.value = emptyList()
return@launch
}
@@ -2631,6 +3027,14 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// and then report a connection problem, when the real answer is
// that the user has to log in again.
if (!container.spotifySignedIn) return@withTimeoutOrNull false
+ // An engine that came up offline is never going to report itself
+ // connected, and waiting for it to is thirty seconds of spinner on
+ // a phone that has the music already. There is a player behind this
+ // — see build_offline_bundle — so the answer is "ready", and what
+ // it is ready for is what the library below works out.
+ if (runCatching { NativeBridge.isOffline }.getOrDefault(false)) {
+ return@withTimeoutOrNull false
+ }
delay(POLL_INTERVAL_MS)
}
true
diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
index bacd4e0..a49866a 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -157,6 +157,8 @@ import dev.lelonio.square.ui.theme.rememberArtworkColor
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import com.adamglin.PhosphorIcons
+import com.adamglin.phosphoricons.fill.ArrowCircleDown
+import com.adamglin.phosphoricons.fill.Check
import com.adamglin.phosphoricons.fill.Play
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.Regular
@@ -491,10 +493,32 @@ fun SquareApp(
val backendChosen by preferences.backendChosen.collectAsStateWithLifecycle()
val backend by preferences.backend.collectAsStateWithLifecycle()
val youtubeHome by viewModel.youtubeHome.collectAsStateWithLifecycle()
+ // What is kept on the phone. Read here rather than inside the pages that
+ // draw it, because the same answer is wanted by the playlist button, the
+ // track rows and the track menu, and one collection is one recomposition.
+ val downloadOwners by viewModel.downloadOwners.collectAsStateWithLifecycle()
+ val downloadedFiles by viewModel.downloadedFiles.collectAsStateWithLifecycle()
+ val downloadProgress by viewModel.downloadProgress.collectAsStateWithLifecycle()
+ val downloadSingles by viewModel.downloadSingles.collectAsStateWithLifecycle()
+ // Whether only what is on the phone can be played. Read once here: half the
+ // screens ask, and every one of them asks the same question.
+ val offlineNow by dev.lelonio.square.playback.OfflineMode.active
+ .collectAsStateWithLifecycle()
// Once the source is YouTube Music. Keyed on the backend so switching to it
// at runtime fills the page rather than leaving yesterday's empty one.
- LaunchedEffect(backend) { viewModel.loadYouTubeHome() }
+ //
+ // And the library with it, which is read from whichever backend is active:
+ // switching source used to leave the other service's playlists on screen
+ // until the app was restarted.
+ var loadedBackend by remember { mutableStateOf(backend) }
+ LaunchedEffect(backend) {
+ viewModel.loadYouTubeHome()
+ if (backend != loadedBackend) {
+ loadedBackend = backend
+ viewModel.refresh()
+ }
+ }
// How far the player is open, 0 to 1. A value rather than a destination:
// see NowPlayingSheet for why the player stopped being a route.
@@ -615,17 +639,35 @@ fun SquareApp(
// Behind the song as well; see awaitAudible. The panel shows its own
// spinner meanwhile, so the wait is visible rather than blank.
awaitAudible(localState)
+
+ // Read again here, rather than used as they were when this started.
+ //
+ // The id and the metadata do not arrive together: the player reports
+ // the new item as soon as it has one, and the title and artist land a
+ // moment later. Asking with what was in hand at launch meant asking for
+ // the *previous* song's words and then filing them under this song's
+ // id, which is why the panel kept showing the last track's lyrics until
+ // it was opened again.
+ //
+ // The two providers this ends up in — the TTML archive keyed by id, and
+ // LrcLib keyed by title and artist — disagree about which is authority,
+ // so both halves have to describe the same song.
+ val now = localState.value
+ if (now.mediaId != uri) return@LaunchedEffect
lyrics = runCatching {
(context.applicationContext as dev.lelonio.square.SquareApplication)
.activeBackend
.lyrics(
uri = uri,
- title = playback.title,
- artist = playback.artist,
- durationMs = playback.durationMs,
+ title = now.title,
+ artist = now.artist,
+ durationMs = now.durationMs,
)
}.getOrNull()
- lyricsFor = uri
+ // Only if this is still the song being played. A slow answer for a
+ // track the listener has already skipped past would otherwise replace
+ // the words of the one they are on now.
+ if (localState.value.mediaId == uri) lyricsFor = uri else lyrics = null
}
// The language the app is read in. Changing it re-creates the activity,
@@ -650,6 +692,12 @@ fun SquareApp(
val trendingLabel = stringResource(R.string.trending_now)
val searchLabel = stringResource(R.string.search)
val radioLabel = stringResource(R.string.radio)
+ // Resolved here rather than at the tap: a composable's resources are not
+ // reachable from inside a coroutine started by a click.
+ val radioOfTemplate = stringResource(R.string.radio_of)
+ val radioOf: (String) -> String = { title ->
+ if (title.isBlank()) radioLabel else radioOfTemplate.format(title)
+ }
val inPip by YouTubeVideoMode.pictureInPicture.collectAsStateWithLifecycle()
@@ -987,11 +1035,14 @@ fun SquareApp(
backdrop = artBackdrop,
youtubeMode =
backend == dev.lelonio.square.backend.BackendId.YOUTUBE_MUSIC,
+ onRetryOnline = viewModel::retryOnline,
youtubeHome = youtubeHome,
shelves = homeShelves,
onPlayTrending = { tracks, index ->
onPlay(tracks, index, null, false, trendingLabel, 0L)
},
+ onPickYouTubeChip = viewModel::selectYouTubeChip,
+ onLoadMoreYouTube = viewModel::loadMoreYouTubeHome,
onOpenSettings = { navController.navigate(Routes.SETTINGS) },
friends = friends,
onOpenFriends = {
@@ -1018,6 +1069,7 @@ fun SquareApp(
},
history = searchHistory,
onClearHistory = viewModel::clearSearchHistory,
+ offline = offlineNow,
onEnqueue = onEnqueue,
onTrackMenu = { track ->
trackMenu = TrackMenuRequest(
@@ -1050,6 +1102,7 @@ fun SquareApp(
onPlaylistMenu = { playlistMenu = it },
artists = followedArtists,
albums = savedAlbums,
+ onRetryOnline = viewModel::retryOnline,
onOpenArtist = { artist ->
viewModel.openContext(
artist.uri,
@@ -1078,6 +1131,13 @@ fun SquareApp(
onLanguage = setLanguage,
onBack = { navController.popBackStack() },
onYouTubeSignIn = { showYouTubeLogin = true },
+ onYouTubeChannelChange = {
+ // A different channel is a different
+ // library and a different home: both were
+ // read for the one before it.
+ viewModel.refresh()
+ viewModel.loadYouTubeHome(force = true)
+ },
)
}
@@ -1094,6 +1154,37 @@ fun SquareApp(
SquareTheme(seed = detailAccent) {
PlaylistScreen(
state = playlist,
+ downloadState = playlist.uri
+ ?.let { downloadOwners[it] }
+ ?: dev.lelonio.square.data.OwnerState.None,
+ onToggleDownload = { viewModel.toggleDownload(playlist) },
+ // The store belongs to the librespot
+ // engine, so only Spotify pages can be
+ // kept — and the local-files shelf is
+ // already on the phone.
+ canDownload = backend ==
+ dev.lelonio.square.backend.BackendId.SPOTIFY &&
+ playlist.uri?.startsWith("spotify:") == true &&
+ // Nothing can be fetched with no
+ // network, so the button would only
+ // ever queue work that cannot start.
+ !offlineNow,
+ offline = offlineNow,
+ // Read per row rather than handed over as a
+ // map: the progress map changes several
+ // times a second while a playlist is being
+ // fetched, and a new map is a new list.
+ trackDownload = { track ->
+ when {
+ track.uri in downloadedFiles ->
+ dev.lelonio.square.data.DownloadState.Done
+ downloadProgress[track.uri] != null ->
+ dev.lelonio.square.data.DownloadState.Running(
+ downloadProgress.getValue(track.uri),
+ )
+ else -> dev.lelonio.square.data.DownloadState.None
+ }
+ },
contentPadding = listPadding,
nowPlayingUri = playback.mediaId,
onBack = { navController.popBackStack() },
@@ -1658,16 +1749,51 @@ fun SquareApp(
{
scope.launch {
val tracks = viewModel.radioFor(uri)
- if (tracks.isNotEmpty()) {
- onPlay(tracks, 0, null, false, radioLabel, 0L)
- }
+ if (tracks.isEmpty()) return@launch
+ // The station as a page, not
+ // just as a queue. A radio the
+ // listener cannot look at is a
+ // shuffle with a different
+ // name: the point of it is
+ // seeing what it built.
+ val station =
+ "spotify:station:track:" +
+ uri.substringAfterLast(':')
+ // Named after the song it grew
+ // from: two stations are told
+ // apart by nothing else, and
+ // "Radio" alone says which
+ // feature it is rather than
+ // which station this is.
+ val name = radioOf(playback.title)
+ viewModel.showStation(
+ uri = station,
+ name = name,
+ artworkUrl = playback.artworkUrl,
+ tracks = tracks,
+ )
+ expand.animateTo(0f, expandSpec)
+ navController.navigate(Routes.PLAYLIST)
+ onPlay(
+ tracks,
+ 0,
+ station,
+ true,
+ name,
+ 0L,
+ )
}
Unit
}
},
onOpenDevices = viewModel::openDevices,
connectAvailable =
- backend == dev.lelonio.square.backend.BackendId.SPOTIFY,
+ backend == dev.lelonio.square.backend.BackendId.SPOTIFY &&
+ // Offline there is no device to hand
+ // playback to, and no list to draw: the
+ // engine came up without a Connect
+ // device at all.
+ !offlineNow,
onCloseDevices = viewModel::closeDevices,
onRefreshDevices = viewModel::refreshDevices,
// The position goes with the request: a
@@ -1846,13 +1972,43 @@ fun SquareApp(
onEnqueue(menu.track)
}
// Writing to a playlist is the Spotify Web API's; on
- // another source the entry would only ever fail.
- if (backend == dev.lelonio.square.backend.BackendId.SPOTIFY) {
+ // another source, or with no network, the entry would
+ // only ever fail.
+ if (backend == dev.lelonio.square.backend.BackendId.SPOTIFY && !offlineNow) {
TrackSheetAction(stringResource(R.string.add_to_playlist), PhosphorIcons.Regular.Plus) {
trackMenu = null
viewModel.openAddToPlaylist(menu.track.uri, menu.track.name)
}
}
+ // Keeping one song, as opposed to keeping the list it
+ // came from. Spotify only: this is the engine's own
+ // store, and the other backend streams from elsewhere.
+ // Removing is offered only for a song kept on its
+ // own. One that is here because a playlist wants it
+ // cannot be let go of from this menu — the file is
+ // still owed to that playlist — and a row that looks
+ // like it removes something and removes nothing is
+ // worse than no row.
+ val onItsOwn = menu.track.uri in downloadSingles
+ val here = menu.track.uri in downloadedFiles
+ if (backend == dev.lelonio.square.backend.BackendId.SPOTIFY &&
+ (onItsOwn || (!here && !offlineNow))
+ ) {
+ val kept = onItsOwn
+ TrackSheetAction(
+ stringResource(
+ if (kept) R.string.remove_download else R.string.download,
+ ),
+ if (kept) {
+ PhosphorIcons.Fill.ArrowCircleDown
+ } else {
+ PhosphorIcons.Regular.Download
+ },
+ ) {
+ trackMenu = null
+ viewModel.toggleTrackDownload(menu.track)
+ }
+ }
TrackSheetAction(stringResource(R.string.copy_link), PhosphorIcons.Regular.LinkSimple) {
trackMenu = null
clipboard.setText(AnnotatedString(menu.track.openLink()))
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 d48e259..49b31cb 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
@@ -17,7 +17,9 @@ import androidx.compose.foundation.background
import androidx.compose.material3.Icon
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.FolderSimple
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
@@ -56,7 +58,9 @@ fun Artwork(
val density = LocalDensity.current
Box(modifier.clip(shape), contentAlignment = Alignment.Center) {
- if (url == dev.lelonio.square.data.LocalLibrary.COVER) {
+ if (url == DOWNLOADS_COVER) {
+ DownloadsCover()
+ } else if (url == dev.lelonio.square.data.LocalLibrary.COVER) {
LocalFilesCover()
} else if (url != null) {
val request = remember(url, decodeSize) {
@@ -125,6 +129,26 @@ private fun LocalFilesCover() {
}
/** The two colours of that tile, deep enough to sit in a grid of covers. */
+/** The shelf of songs downloaded on their own; see DownloadStore.SINGLES. */
+const val DOWNLOADS_COVER = "square:downloads-cover"
+
+@Composable
+private fun DownloadsCover() {
+ Box(
+ Modifier
+ .fillMaxSize()
+ .background(LocalFilesTile),
+ contentAlignment = Alignment.Center,
+ ) {
+ Icon(
+ PhosphorIcons.Fill.ArrowCircleDown,
+ contentDescription = null,
+ tint = androidx.compose.material3.MaterialTheme.colorScheme.primary,
+ modifier = Modifier.fillMaxSize(0.44f),
+ )
+ }
+}
+
private val LocalFilesTile = Color(0xFF20306E)
private val LocalFilesGlyph = Color(0xFF2ECC57)
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/ConfirmSheet.kt b/app/src/main/java/dev/lelonio/square/ui/components/ConfirmSheet.kt
new file mode 100644
index 0000000..e1ae98f
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/components/ConfirmSheet.kt
@@ -0,0 +1,161 @@
+package dev.lelonio.square.ui.components
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.core.tween
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.scaleIn
+import androidx.compose.animation.scaleOut
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+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.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+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.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import dev.lelonio.square.ui.glass.LocalGlassEffectConfig
+import dev.lelonio.square.ui.glass.backdrop.Backdrop
+import dev.lelonio.square.ui.glass.liquidGlass
+import dev.lelonio.square.ui.glass.pressable
+import dev.lelonio.square.ui.glass.shapes.ContinuousCapsule
+import dev.lelonio.square.ui.glass.shapes.ContinuousRoundedRectangle
+import dev.lelonio.square.ui.player.GlassInk
+import dev.lelonio.square.ui.player.GlassInkDim
+
+/**
+ * One question with two answers, in the app's own glass.
+ *
+ * The same panel the update alert is built from, without the parts that made
+ * that one specific: a title, a line saying what is about to happen, and two
+ * capsules. Deleting a library's worth of downloaded music is exactly the kind
+ * of act that deserves a moment's pause, and a system dialog in the middle of a
+ * page made of glass would look like it came from another app.
+ */
+@Composable
+fun ConfirmSheet(
+ visible: Boolean,
+ title: String,
+ message: String,
+ confirmLabel: String,
+ cancelLabel: String,
+ backdrop: Backdrop,
+ onConfirm: () -> Unit,
+ onDismiss: () -> Unit,
+ /** Red rather than accent, for an answer that takes something away. */
+ destructive: Boolean = false,
+) {
+ AnimatedVisibility(
+ visible = visible,
+ enter = fadeIn(tween(200)),
+ exit = fadeOut(tween(160)),
+ ) {
+ Box(
+ Modifier
+ .fillMaxSize()
+ .background(DIM)
+ .pressable(onClick = onDismiss),
+ contentAlignment = Alignment.Center,
+ ) {
+ AnimatedVisibility(
+ visible = visible,
+ enter = scaleIn(tween(220), initialScale = 0.93f) + fadeIn(tween(220)),
+ exit = scaleOut(tween(150), targetScale = 0.95f) + fadeOut(tween(150)),
+ ) {
+ Column(
+ Modifier
+ .padding(horizontal = 32.dp)
+ .fillMaxWidth()
+ .liquidGlass(
+ config = LocalGlassEffectConfig.current,
+ shape = PANEL,
+ ownBackdrop = backdrop,
+ onDrawTint = { drawRect(LIFT) },
+ )
+ // Nothing behind the panel takes a tap through it.
+ .pressable(onClick = {}),
+ ) {
+ Text(
+ title,
+ style = MaterialTheme.typography.titleLarge,
+ fontWeight = FontWeight.Medium,
+ color = GlassInk,
+ modifier = Modifier.padding(start = 26.dp, end = 26.dp, top = 24.dp),
+ )
+ Text(
+ message,
+ style = MaterialTheme.typography.bodyMedium,
+ color = GlassInkDim,
+ modifier = Modifier.padding(start = 26.dp, end = 26.dp, top = 8.dp),
+ )
+ Row(
+ Modifier
+ .padding(start = 22.dp, end = 22.dp, top = 22.dp, bottom = 22.dp)
+ .fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(14.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Action(
+ label = cancelLabel,
+ container = FILM,
+ content = GlassInk,
+ onClick = onDismiss,
+ modifier = Modifier.weight(1f),
+ )
+ Action(
+ label = confirmLabel,
+ container = if (destructive) {
+ MaterialTheme.colorScheme.error
+ } else {
+ MaterialTheme.colorScheme.primary
+ },
+ content = Color.White,
+ onClick = onConfirm,
+ modifier = Modifier.weight(1f),
+ )
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun Action(
+ label: String,
+ container: Color,
+ content: Color,
+ onClick: () -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ Box(
+ modifier
+ .clip(ContinuousCapsule)
+ .background(container)
+ .pressable(onClick, pressedScale = 0.96f)
+ .height(48.dp),
+ contentAlignment = Alignment.Center,
+ ) {
+ Text(
+ label,
+ style = MaterialTheme.typography.bodyLarge,
+ fontWeight = FontWeight.Medium,
+ color = content,
+ )
+ }
+}
+
+private val DIM = Color(0xFF121212).copy(alpha = 0.62f)
+private val FILM = Color(0xFF121212).copy(alpha = 0.4f)
+private val LIFT = Color.White.copy(alpha = 0.08f)
+private val PANEL = ContinuousRoundedRectangle(40.dp)
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/OfflineNotice.kt b/app/src/main/java/dev/lelonio/square/ui/components/OfflineNotice.kt
new file mode 100644
index 0000000..f32d29d
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/components/OfflineNotice.kt
@@ -0,0 +1,143 @@
+package dev.lelonio.square.ui.components
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.expandVertically
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.shrinkVertically
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Icon
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import kotlinx.coroutines.launch
+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.res.stringResource
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import com.adamglin.PhosphorIcons
+import com.adamglin.phosphoricons.Regular
+import com.adamglin.phosphoricons.regular.CloudSlash
+import dev.lelonio.square.R
+import dev.lelonio.square.playback.OfflineMode
+import dev.lelonio.square.ui.glass.pressable
+
+/**
+ * A line saying the app is offline, and why.
+ *
+ * Present rather than modal on purpose. Offline is a state the listener browses
+ * in for as long as it lasts, not an error to acknowledge, and a dialog in the
+ * way of a library that still works would be the wrong shape entirely.
+ *
+ * Saying *why* is the whole point of it. "No connection", "the connection is
+ * worse than your downloads" and "you turned this on" call for three different
+ * things from the person reading, and an app that only says "offline" leaves
+ * them to guess which one they are in.
+ */
+@Composable
+fun OfflineNotice(
+ modifier: Modifier = Modifier,
+ /**
+ * Tries the servers again, and answers whether it worked.
+ *
+ * Suspending because the whole point is the wait: a handshake takes a
+ * second or two, and a button that returns instantly and changes nothing
+ * looks broken whichever way it went.
+ */
+ onRetry: (suspend () -> Boolean)? = null,
+) {
+ val reason by OfflineMode.reason.collectAsStateWithLifecycle()
+ val scope = rememberCoroutineScope()
+ var trying by remember { mutableStateOf(false) }
+
+ AnimatedVisibility(
+ visible = reason != null,
+ enter = fadeIn() + expandVertically(),
+ exit = fadeOut() + shrinkVertically(),
+ modifier = modifier,
+ ) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 18.dp, vertical = 6.dp)
+ .clip(RoundedCornerShape(12.dp))
+ .background(Color.White.copy(alpha = 0.08f))
+ .padding(horizontal = 12.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ ) {
+ Icon(
+ PhosphorIcons.Regular.CloudSlash,
+ contentDescription = null,
+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.size(16.dp),
+ )
+ Text(
+ stringResource(
+ when (reason) {
+ OfflineMode.Reason.MANUAL -> R.string.offline_banner_manual
+ OfflineMode.Reason.SLOW -> R.string.offline_banner_slow
+ else -> R.string.offline_banner_no_network
+ },
+ ),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.weight(1f),
+ )
+
+ // The way back. It really does try the servers rather than only
+ // clearing the flag: offline because the network went is the common
+ // case, and a phone that has since found a signal has no other way
+ // of being told to look again.
+ onRetry?.let { retry ->
+ Text(
+ stringResource(
+ if (trying) R.string.offline_retrying else R.string.go_online,
+ ),
+ style = MaterialTheme.typography.labelLarge,
+ color = if (trying) {
+ MaterialTheme.colorScheme.onSurfaceVariant
+ } else {
+ MaterialTheme.colorScheme.primary
+ },
+ modifier = Modifier
+ .clip(RoundedCornerShape(8.dp))
+ .then(
+ // Inert while it is already trying, so a second tap
+ // does not start a second handshake.
+ if (trying) {
+ Modifier
+ } else {
+ Modifier.pressable(
+ onClick = {
+ trying = true
+ scope.launch {
+ retry()
+ trying = false
+ }
+ },
+ shape = RoundedCornerShape(8.dp),
+ pressedScale = 0.96f,
+ )
+ },
+ )
+ .padding(horizontal = 8.dp, vertical = 4.dp),
+ )
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt b/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt
index 60d6a3d..6547e86 100644
--- a/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt
@@ -18,6 +18,7 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.foundation.gestures.snapping.rememberSnapFlingBehavior
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
@@ -55,6 +56,7 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.ui.unit.lerp
import dev.lelonio.square.ui.glass.backdrop.Backdrop
import com.adamglin.PhosphorIcons
@@ -63,6 +65,7 @@ import com.adamglin.phosphoricons.regular.SpotifyLogo
import com.adamglin.phosphoricons.regular.YoutubeLogo
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
+import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.material3.Icon
@@ -143,8 +146,14 @@ fun HomeScreen(
* what it genuinely has instead.
*/
youtubeMode: Boolean = false,
+ /** Tries the servers again from the offline banner; null hides the button. */
+ onRetryOnline: (suspend () -> Boolean)? = null,
youtubeHome: MainViewModel.YouTubeHomeState = MainViewModel.YouTubeHomeState(),
onPlayTrending: (List<CatalogTrack>, Int) -> Unit = { _, _ -> },
+ /** One of YouTube's own filters above the page, or null to clear it. */
+ onPickYouTubeChip: (dev.lelonio.square.backend.HomeChip?) -> Unit = {},
+ /** Called from the bottom of the page: the next shelves, if there are any. */
+ onLoadMoreYouTube: () -> Unit = {},
/**
* Spotify's own personalised shelves, empty when the gateway said nothing.
*
@@ -165,6 +174,8 @@ fun HomeScreen(
onPlayTrending = onPlayTrending,
onOpenPlaylist = onOpenPlaylist,
onOpenSettings = onOpenSettings,
+ onPickChip = onPickYouTubeChip,
+ onLoadMore = onLoadMoreYouTube,
)
return
}
@@ -234,6 +245,9 @@ fun HomeScreen(
// untouched. Past the first item the header is simply fully
// collapsed — asking for the exact offset of something scrolled far
// off screen means measuring items that no longer exist.
+ val offline by dev.lelonio.square.playback.OfflineMode.active
+ .collectAsStateWithLifecycle()
+
val collapse by remember {
derivedStateOf {
if (listState.firstVisibleItemIndex > 0) 1f
@@ -330,6 +344,19 @@ fun HomeScreen(
bottom = contentPadding.calculateBottomPadding(),
),
) {
+ // Why the page is shorter than usual, before the page.
+ //
+ // Added to the list only while it is actually offline, not
+ // added always and left to draw nothing: an item of zero height
+ // is still an item, so the first scrolled pixel moved the list
+ // past it and the header — which reads its collapse off the
+ // first visible item — snapped shut instead of easing.
+ if (offline) {
+ item(key = "offline") {
+ dev.lelonio.square.ui.components.OfflineNotice(onRetry = onRetryOnline)
+ }
+ }
+
// Spotify's own shelves come first, because they are what the
// listener recognises as their home and the only rows here that
// this app could not have built itself. What the account has
@@ -861,6 +888,9 @@ private fun ArtistTile(artist: SearchItem, onClick: () -> Unit) {
@Composable
private fun PlaylistTile(playlist: CatalogPlaylist, onClick: () -> Unit) {
+ // A portrait among covers: the one shape difference a shelf of people
+ // needs, and the reason an artist row reads as people at a glance.
+ val corner = if (playlist.isArtist) 76.dp else 20.dp
Column(
Modifier
.width(152.dp)
@@ -871,16 +901,28 @@ private fun PlaylistTile(playlist: CatalogPlaylist, onClick: () -> Unit) {
title = playlist.name,
modifier = Modifier
.size(152.dp)
- .softShadow(RoundedCornerShape(20.dp), elevation = 18.dp),
- corner = 20.dp,
+ .softShadow(RoundedCornerShape(corner), elevation = 18.dp),
+ corner = corner,
)
Text(
playlist.name,
style = MaterialTheme.typography.titleMedium,
- maxLines = 2,
+ // One line where there is something written under it, or the two
+ // together push the next shelf off its own baseline.
+ maxLines = if (playlist.subtitle == null) 2 else 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 10.dp, start = 2.dp, end = 2.dp),
)
+ playlist.subtitle?.let {
+ Text(
+ it,
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(start = 2.dp, end = 2.dp),
+ )
+ }
}
}
@@ -1043,12 +1085,127 @@ private fun <T> Carousel(
}
@Composable
-private fun Heading(text: String) {
- Text(
- text,
- style = MaterialTheme.typography.headlineLarge,
- modifier = Modifier.padding(start = 24.dp, end = 24.dp, top = 30.dp),
- )
+private fun Heading(text: String, strapline: String? = null) {
+ Column(Modifier.padding(start = 24.dp, end = 24.dp, top = 30.dp)) {
+ // Above the title, smaller and quieter, the way the service writes it:
+ // "MIX", "START RADIO FROM A SONG", an artist's name. It is most of
+ // what tells two shelves with the same title apart.
+ strapline?.takeIf { it.isNotBlank() }?.let {
+ Text(
+ it.uppercase(),
+ style = MaterialTheme.typography.labelMedium,
+ color = InkDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(bottom = 2.dp),
+ )
+ }
+ Text(text, style = MaterialTheme.typography.headlineLarge)
+ }
+}
+
+/**
+ * A shelf of songs as a block rather than a row.
+ *
+ * Four to a column, and the columns scroll a screen at a time — the shape the
+ * official app gives its longest shelves. A song here is a line, not a tile:
+ * small art, the title, who it is by. Twenty of these as tiles would be a
+ * carousel nobody reaches the end of.
+ */
+@Composable
+private fun QuickPicks(tracks: List<CatalogTrack>, onPlay: (Int) -> Unit) {
+ val columns = tracks.chunked(QUICK_PICK_ROWS)
+ val width = LocalConfiguration.current.screenWidthDp.dp - 44.dp
+ LazyRow(
+ contentPadding = PaddingValues(horizontal = 20.dp),
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ flingBehavior = rememberSnapFlingBehavior(rememberLazyListState()),
+ modifier = Modifier.padding(top = 14.dp),
+ ) {
+ itemsIndexed(columns, key = { _, column -> column.first().uri }) { columnIndex, column ->
+ Column(
+ Modifier.width(width),
+ verticalArrangement = Arrangement.spacedBy(4.dp),
+ ) {
+ column.forEachIndexed { rowIndex, track ->
+ QuickPickRow(track) {
+ onPlay(columnIndex * QUICK_PICK_ROWS + rowIndex)
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun QuickPickRow(track: CatalogTrack, onClick: () -> Unit) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .clip(RoundedCornerShape(14.dp))
+ .pressable(onClick)
+ .padding(vertical = 6.dp, horizontal = 4.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Artwork(
+ url = track.artworkUrl,
+ title = track.name,
+ modifier = Modifier.size(52.dp),
+ corner = 10.dp,
+ decodeSize = 52.dp,
+ )
+ Column(Modifier.padding(start = 12.dp)) {
+ Text(
+ track.name,
+ style = MaterialTheme.typography.titleMedium,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ Text(
+ track.artist,
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+}
+
+/** The service's own filters, drawn as the app's own chips. */
+@Composable
+private fun ChipRow(
+ chips: List<dev.lelonio.square.backend.HomeChip>,
+ selected: String?,
+ backdrop: Backdrop,
+ onPick: (dev.lelonio.square.backend.HomeChip?) -> Unit,
+) {
+ LazyRow(
+ contentPadding = PaddingValues(horizontal = 20.dp),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier.padding(top = 16.dp),
+ ) {
+ items(chips, key = { it.title }) { chip ->
+ val isSelected = chip.title == selected
+ LiquidButton(
+ // Pressing the chip that is already on takes the filter off,
+ // which is what the service's own deselect does.
+ onClick = { onPick(if (isSelected) null else chip) },
+ backdrop = backdrop,
+ flat = true,
+ contentHeight = 38.dp,
+ contentPadding = 18.dp,
+ surfaceColor = if (isSelected) SelectedFilm else Color.Unspecified,
+ wash = dev.lelonio.square.ui.glass.chipWash(isSelected),
+ ) {
+ Text(
+ chip.title,
+ style = MaterialTheme.typography.bodyMedium,
+ color = if (isSelected) Ink else InkDim,
+ )
+ }
+ }
+ }
}
/** A glass pill, for the handful of places that need a button at all. */
@@ -1087,6 +1244,8 @@ private fun YouTubeHome(
onPlayTrending: (List<CatalogTrack>, Int) -> Unit,
onOpenPlaylist: (CatalogPlaylist) -> Unit,
onOpenSettings: () -> Unit,
+ onPickChip: (dev.lelonio.square.backend.HomeChip?) -> Unit,
+ onLoadMore: () -> Unit,
) {
val empty = home.rows.isEmpty() && recent.isEmpty()
if (empty) {
@@ -1166,20 +1325,43 @@ private fun YouTubeHome(
bottom = contentPadding.calculateBottomPadding(),
),
) {
+ // YouTube's own filters, where it sent any: each is a page in its own
+ // right rather than a sieve over this one.
+ if (home.chips.isNotEmpty()) {
+ item(key = "chips") {
+ ChipRow(
+ chips = home.chips,
+ selected = home.chip,
+ backdrop = backdrop,
+ onPick = onPickChip,
+ )
+ }
+ }
+
// Whatever shelves YouTube sent, in its own order and under its own
// titles. Not reshaped into a fixed set of rows: the page is different
// signed in and signed out, and it changes on its own besides.
- home.rows.forEach { row ->
- item(key = "head-${row.title}") { Heading(row.title) }
+ home.rows.forEachIndexed { index, row ->
+ item(key = "head-$index-${row.title}") { Heading(row.title, row.strapline) }
if (row.tracks.isNotEmpty()) {
- item(key = "tracks-${row.title}") {
- TrackRow(row.tracks) { index -> onPlayTrending(row.tracks, index) }
+ item(key = "tracks-$index-${row.title}") {
+ // A shelf of songs long enough to be a list is drawn as
+ // one: four rows deep, scrolling sideways a screen at a
+ // time, which is what "quick picks" is in the app this
+ // page is copying. A handful of songs stays a row of
+ // tiles, because three of these stacked would be a
+ // column with two holes in it.
+ if (row.tracks.size >= QUICK_PICK_MINIMUM) {
+ QuickPicks(row.tracks) { i -> onPlayTrending(row.tracks, i) }
+ } else {
+ TrackRow(row.tracks) { i -> onPlayTrending(row.tracks, i) }
+ }
}
}
if (row.items.isNotEmpty()) {
- item(key = "items-${row.title}") {
+ item(key = "items-$index-${row.title}") {
LazyRow(
contentPadding = PaddingValues(horizontal = 20.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
@@ -1193,6 +1375,25 @@ private fun YouTubeHome(
}
}
+ // The end of the page, which is where the next one is asked for.
+ if (home.hasMore) {
+ item(key = "more") {
+ LaunchedEffect(home.rows.size) { onLoadMore() }
+ Box(
+ Modifier
+ .fillMaxWidth()
+ .padding(vertical = 28.dp),
+ contentAlignment = Alignment.Center,
+ ) {
+ CircularProgressIndicator(
+ color = InkDim,
+ strokeWidth = 2.dp,
+ modifier = Modifier.size(22.dp),
+ )
+ }
+ }
+ }
+
// Last: the rows above change on their own, this one only changes
// because the user did something.
if (recent.isNotEmpty()) {
@@ -1333,3 +1534,9 @@ private fun FriendFaces(
/** One face, and how much of the one behind it is left showing. */
private val FACE = 30.dp
private val FACE_PEEK = 20.dp
+
+/** A shelf of at least this many songs is drawn as a block; see [QuickPicks]. */
+private const val QUICK_PICK_MINIMUM = 8
+
+/** How deep that block goes before it starts a new column. */
+private const val QUICK_PICK_ROWS = 4
diff --git a/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt
index 2cdef54..35014df 100644
--- a/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt
@@ -129,6 +129,8 @@ fun LibraryScreen(
onOpenArtist: (dev.lelonio.square.data.SearchItem) -> Unit = {},
/** The albums the account has saved; see MainViewModel.savedAlbums. */
albums: List<CatalogPlaylist> = emptyList(),
+ /** Tries the servers again from the offline banner; null hides the button. */
+ onRetryOnline: (suspend () -> Boolean)? = null,
backdrop: Backdrop,
) {
when (state) {
@@ -271,6 +273,13 @@ fun LibraryScreen(
.fillMaxSize()
.layerBackdrop(listBackdrop),
) {
+ // Why the library is shorter than usual, at the top
+ // of the library. Nothing at all when there is a
+ // connection; see OfflineNotice.
+ item(span = { GridItemSpan(maxLineSpan) }, key = "offline") {
+ dev.lelonio.square.ui.components.OfflineNotice(onRetry = onRetryOnline)
+ }
+
if (artists.isNotEmpty() && filter == Filter.ALL) {
item(span = { GridItemSpan(maxLineSpan) }, key = "artists") {
ArtistShelf(artists, onOpenArtist)
@@ -298,6 +307,10 @@ fun LibraryScreen(
.fillMaxSize()
.layerBackdrop(listBackdrop),
) {
+ item(key = "offline") {
+ dev.lelonio.square.ui.components.OfflineNotice(onRetry = onRetryOnline)
+ }
+
if (artists.isNotEmpty() && filter == Filter.ALL) {
item(key = "artists") { ArtistShelf(artists, onOpenArtist) }
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt
index de1d6a9..8d91bb7 100644
--- a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt
@@ -92,6 +92,7 @@ import java.util.concurrent.TimeUnit
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.Regular
+import com.adamglin.phosphoricons.fill.ArrowCircleDown
import com.adamglin.phosphoricons.fill.Check
import com.adamglin.phosphoricons.fill.MagnifyingGlass
import com.adamglin.phosphoricons.fill.Play
@@ -100,6 +101,7 @@ import com.adamglin.phosphoricons.regular.ArrowLeft
import com.adamglin.phosphoricons.regular.ArrowsDownUp
import com.adamglin.phosphoricons.regular.Check
import com.adamglin.phosphoricons.regular.DotsThree
+import com.adamglin.phosphoricons.regular.Download
import com.adamglin.phosphoricons.regular.Export
import com.adamglin.phosphoricons.regular.LinkSimple
import com.adamglin.phosphoricons.regular.Plus
@@ -144,6 +146,29 @@ fun PlaylistScreen(
onOpenItem: (dev.lelonio.square.data.SearchItem) -> Unit = {},
/** Follows or unfollows the artist this page is about. */
onToggleFollow: () -> Unit = {},
+ /** Whether this page is kept on the phone, and how far along that is. */
+ downloadState: dev.lelonio.square.data.OwnerState = dev.lelonio.square.data.OwnerState.None,
+ onToggleDownload: () -> Unit = {},
+ /** False where a download makes no sense: the local files shelf, YouTube. */
+ canDownload: Boolean = false,
+ /**
+ * No connection, so only what is on the phone can be played.
+ *
+ * Rows for tracks that are not downloaded stay visible and go quiet: a
+ * playlist that silently lost half its songs would be a worse answer than
+ * one that shows what it has and what it is missing.
+ */
+ offline: Boolean = false,
+ /**
+ * What each row should say about itself.
+ *
+ * A lambda rather than a map, because the map changes several times a
+ * second while a playlist downloads and threading a new one through the
+ * screen would recompose the whole list for one row's ring.
+ */
+ trackDownload: (CatalogTrack) -> dev.lelonio.square.data.DownloadState = {
+ dev.lelonio.square.data.DownloadState.None
+ },
/** Hands the page's own link to whoever wants it. */
onShare: () -> Unit = {},
/**
@@ -166,12 +191,26 @@ fun PlaylistScreen(
) {
var query by remember { mutableStateOf("") }
var searching by remember { mutableStateOf(false) }
+ // Asked before a downloaded page is given back to the network. Pressing the
+ // button that says "this is on your phone" is how a listener takes it off
+ // again — the same control both ways — so the question is what stops a
+ // mis-tap from deleting a hundred songs.
+ var confirmingRemoval by remember { mutableStateOf(false) }
// Seeded from the stored choice and written back on change: picking an
// order and finding it gone on the next playlist is the kind of thing that
// makes a setting feel like it did not take.
- var sort by remember(storedSort) {
+ // A station is the one list whose order is the whole of it: Spotify built
+ // this sequence for this listener a minute ago, and sorting it by title
+ // throws away the only thing that made it a radio rather than a bag of
+ // songs. So the stored preference does not reach it.
+ val isStation = state.uri?.startsWith("spotify:station:") == true
+ var sort by remember(storedSort, isStation) {
mutableStateOf(
- TrackSort.entries.firstOrNull { it.name == storedSort } ?: TrackSort.ORIGINAL,
+ if (isStation) {
+ TrackSort.ORIGINAL
+ } else {
+ TrackSort.entries.firstOrNull { it.name == storedSort } ?: TrackSort.ORIGINAL
+ },
)
}
var descending by remember(storedSortDescending) { mutableStateOf(storedSortDescending) }
@@ -311,6 +350,13 @@ fun PlaylistScreen(
state.kind == MainViewModel.DetailKind.ARTIST
},
onToggleFollow = onToggleFollow,
+ download = downloadState,
+ onToggleDownload = {
+ val kept = downloadState is dev.lelonio.square.data.OwnerState.Complete ||
+ downloadState is dev.lelonio.square.data.OwnerState.Partial
+ if (kept) confirmingRemoval = true else onToggleDownload()
+ },
+ canDownload = canDownload,
trackCount = state.tracks.size,
totalMs = state.tracks.sumOf { it.durationMs },
backdrop = pageBackdrop,
@@ -452,6 +498,13 @@ fun PlaylistScreen(
isCurrent = track.uri == nowPlayingUri,
onClick = { onPlay(visible, index, asContext) },
onMenu = { onTrackMenu(track) },
+ download = trackDownload(track),
+ // The phone's own files play offline like anything
+ // else — they were never coming over the network.
+ unavailable = offline &&
+ !track.uri.startsWith("local:") &&
+ trackDownload(track) !=
+ dev.lelonio.square.data.DownloadState.Done,
)
}
}
@@ -628,6 +681,25 @@ fun PlaylistScreen(
onSortDescendingChange(descending)
}
}
+
+ // Last inside the page, so it is drawn over it. Mounted before the
+ // Box it used to sit above, where the page covered it completely:
+ // the question never appeared, and with nothing to answer, nothing
+ // was ever removed either.
+ dev.lelonio.square.ui.components.ConfirmSheet(
+ visible = confirmingRemoval,
+ title = stringResource(R.string.remove_download),
+ message = stringResource(R.string.remove_download_confirm, state.name),
+ confirmLabel = stringResource(R.string.remove_download_confirm_action),
+ cancelLabel = stringResource(R.string.cancel),
+ backdrop = pageBackdrop,
+ destructive = true,
+ onConfirm = {
+ confirmingRemoval = false
+ onToggleDownload()
+ },
+ onDismiss = { confirmingRemoval = false },
+ )
}
}
@@ -673,6 +745,10 @@ private fun DetailHeader(
*/
following: Boolean?,
onToggleFollow: () -> Unit,
+ /** Kept on the phone, being kept, or not; see the button below. */
+ download: dev.lelonio.square.data.OwnerState,
+ onToggleDownload: () -> Unit,
+ canDownload: Boolean,
trackCount: Int,
totalMs: Long,
backdrop: Backdrop,
@@ -734,9 +810,18 @@ private fun DetailHeader(
modifier = Modifier.padding(top = 4.dp),
)
+ // Three controls and two labels do not fit across a phone, so the
+ // row tightens once there is more than one thing beside Play.
+ // Counted rather than asked of any one control: this used to key
+ // off the follow pill alone, and adding the download button let a
+ // playlist overflow — the button went off the edge and the tap
+ // landed on Play, which started the music instead.
+ val extras = listOfNotNull(saved, following).size + if (canDownload) 1 else 0
+ val tight = extras >= 2
+
Row(
Modifier.padding(top = 16.dp),
- horizontalArrangement = Arrangement.spacedBy(if (following != null) 10.dp else 14.dp),
+ horizontalArrangement = Arrangement.spacedBy(if (tight) 10.dp else 14.dp),
verticalAlignment = Alignment.CenterVertically,
) {
CircleAction(
@@ -759,7 +844,7 @@ private fun DetailHeader(
// and two labels do not fit across a phone at the width
// this has to itself on every other page.
.padding(
- horizontal = if (following != null) 26.dp else 40.dp,
+ horizontal = if (tight) 26.dp else 40.dp,
vertical = 14.dp,
),
horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -799,6 +884,18 @@ private fun DetailHeader(
if (following != null) {
FollowPill(following = following, onClick = onToggleFollow)
}
+
+ // Keeping the music itself, next to keeping the page. Always
+ // present where a download is possible, unlike the two above:
+ // its off state is what starts one, so hiding it until there
+ // was something to show would leave no way in.
+ if (canDownload) {
+ DownloadAction(
+ state = download,
+ backdrop = backdrop,
+ onClick = onToggleDownload,
+ )
+ }
}
// What the list is, in its own words. Only the sources that carry
@@ -1003,6 +1100,61 @@ private fun CapsuleAction(
}
}
+/**
+ * Keeping the page on the phone, in one control.
+ *
+ * Three answers rather than a toggle, because a download has a middle: not
+ * kept, being kept, kept. The middle one draws its own progress around the
+ * icon — the ring is the only thing on the page that says the fetching is
+ * still happening, since it runs in a service with the screen off.
+ *
+ * Partial is drawn as done deliberately. It means every track that could be
+ * fetched was, and the rest are not available to this account at all; a page
+ * that sat forever at nine tenths with no way to finish would be a fault the
+ * listener cannot act on.
+ */
+@Composable
+private fun DownloadAction(
+ state: dev.lelonio.square.data.OwnerState,
+ backdrop: Backdrop,
+ onClick: () -> Unit,
+) {
+ val kept = state is dev.lelonio.square.data.OwnerState.Complete ||
+ state is dev.lelonio.square.data.OwnerState.Partial
+ val running = state as? dev.lelonio.square.data.OwnerState.Running
+
+ Box(contentAlignment = Alignment.Center) {
+ CircleAction(
+ // The filled arrow-in-a-circle, which is what every music app
+ // means by "this is on your phone". A tick says "done", which is
+ // about the act rather than about the song.
+ icon = if (kept) {
+ PhosphorIcons.Fill.ArrowCircleDown
+ } else {
+ PhosphorIcons.Regular.Download
+ },
+ description = stringResource(
+ if (kept) R.string.remove_download else R.string.download,
+ ),
+ size = 52.dp,
+ backdrop = backdrop,
+ onClick = onClick,
+ )
+ // Around the button rather than inside it: the icon still has to be
+ // legible while this turns.
+ running?.let {
+ CircularProgressIndicator(
+ progress = { it.progress },
+ color = Color.White,
+ trackColor = Color.White.copy(alpha = 0.22f),
+ strokeWidth = 2.dp,
+ gapSize = 0.dp,
+ modifier = Modifier.size(52.dp),
+ )
+ }
+ }
+}
+
@Composable
private fun CircleAction(
icon: androidx.compose.ui.graphics.vector.ImageVector,
@@ -1141,6 +1293,80 @@ private val PageFloor = Color(0xFF0A0A0C)
private fun pageColorFor(accent: Color?): Color =
accent?.let { lerp(it, PageFloor, 0.78f) } ?: PageFloor
+/**
+ * The little mark in a row that says this song is here.
+ *
+ * Nothing at all until a download exists for the track. That is the whole rule:
+ * an ordinary playlist reads exactly as it did before this feature, and the
+ * mark appearing is itself the news. There is no "not downloaded" state to draw
+ * because a row full of empty placeholders would be worse than no marks.
+ */
+@Composable
+private fun DownloadMark(state: dev.lelonio.square.data.DownloadState) {
+ val running = state as? dev.lelonio.square.data.DownloadState.Running
+ // Queued deliberately draws nothing. A playlist of four hundred songs would
+ // otherwise sprout four hundred marks the instant the button is pressed,
+ // which says "all downloaded" a good ten minutes before it is true.
+ if (state !is dev.lelonio.square.data.DownloadState.Done && running == null) return
+
+ val accent = MaterialTheme.colorScheme.primary
+ Box(
+ modifier = Modifier
+ .padding(end = 6.dp)
+ .size(14.dp),
+ contentAlignment = Alignment.Center,
+ ) {
+ if (state is dev.lelonio.square.data.DownloadState.Done) {
+ Icon(
+ PhosphorIcons.Fill.ArrowCircleDown,
+ contentDescription = stringResource(R.string.downloaded),
+ tint = accent,
+ modifier = Modifier.size(14.dp),
+ )
+ } else {
+ // A thin ring rather than the app's spinner: at fourteen density
+ // pixels inside a scrolling list, anything with a label or a fill
+ // is a smudge.
+ val progress by animateFloatAsState(
+ targetValue = running?.progress ?: 0f,
+ animationSpec = tween(320),
+ label = "row download",
+ )
+ androidx.compose.foundation.Canvas(Modifier.size(12.dp)) {
+ val stroke = 1.6.dp.toPx()
+ val inset = androidx.compose.ui.geometry.Offset(stroke / 2f, stroke / 2f)
+ val ring = androidx.compose.ui.geometry.Size(
+ this.size.width - stroke,
+ this.size.height - stroke,
+ )
+ drawArc(
+ color = accent.copy(alpha = 0.28f),
+ startAngle = 0f,
+ sweepAngle = 360f,
+ useCenter = false,
+ topLeft = inset,
+ size = ring,
+ style = androidx.compose.ui.graphics.drawscope.Stroke(width = stroke),
+ )
+ drawArc(
+ color = accent,
+ startAngle = -90f,
+ // A stub of ring even at zero, so a track that has only
+ // just started still reads as busy.
+ sweepAngle = (360f * progress).coerceAtLeast(24f),
+ useCenter = false,
+ topLeft = inset,
+ size = ring,
+ style = androidx.compose.ui.graphics.drawscope.Stroke(
+ width = stroke,
+ cap = androidx.compose.ui.graphics.StrokeCap.Round,
+ ),
+ )
+ }
+ }
+ }
+}
+
@Composable
private fun TrackRow(
track: CatalogTrack,
@@ -1148,8 +1374,22 @@ private fun TrackRow(
isCurrent: Boolean,
onClick: () -> Unit,
onMenu: () -> Unit,
+ /** Nothing is drawn until a download for this track exists; see below. */
+ download: dev.lelonio.square.data.DownloadState =
+ dev.lelonio.square.data.DownloadState.None,
+ /**
+ * Offline, and this one is not on the phone.
+ *
+ * Dimmed and inert rather than hidden: a playlist that quietly loses two
+ * songs in three is a playlist the listener no longer recognises, and the
+ * missing ones are exactly what they might want to download later.
+ */
+ unavailable: Boolean = false,
) {
val shape = RoundedCornerShape(14.dp)
+ // Everything in the row fades together, artwork included, so it reads as
+ // one thing being unavailable rather than a list of greyed-out words.
+ val dim = if (unavailable) 0.38f else 1f
// Eased rather than snapped: rows change state on every track advance, and
// a hard cut in the middle of a list draws the eye more than the change
// deserves.
@@ -1174,7 +1414,14 @@ private fun TrackRow(
alpha = MaterialTheme.colorScheme.surface.alpha * highlight,
),
)
- .pressable(onClick, shape = shape, pressedScale = 0.985f)
+ .then(
+ if (unavailable) {
+ Modifier
+ } else {
+ Modifier.pressable(onClick, shape = shape, pressedScale = 0.985f)
+ },
+ )
+ .graphicsLayer { alpha = dim }
.padding(horizontal = 12.dp, vertical = 11.dp),
verticalAlignment = Alignment.CenterVertically,
) {
@@ -1225,17 +1472,27 @@ private fun TrackRow(
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
- Text(
- // Artist and length on one line, as the reference has it: two
- // stacked grey lines under every title turn the list into a wall
- // of secondary text.
- text = "${track.artist} · ${formatDuration(track.durationMs)}",
- style = MaterialTheme.typography.bodySmall,
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 2.dp),
- )
+ ) {
+ // The mark, and only once there is something to mark. A row for
+ // a track nobody has asked for looks exactly as it did before
+ // downloads existed — no greyed-out placeholder, nothing to
+ // read past. Starting a download is the row menu's job, so this
+ // never needs to be a target.
+ DownloadMark(download)
+ Text(
+ // Artist and length on one line, as the reference has it:
+ // two stacked grey lines under every title turn the list
+ // into a wall of secondary text.
+ text = "${track.artist} · ${formatDuration(track.durationMs)}",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
}
IconButton(onClick = onMenu, modifier = Modifier.size(32.dp)) {
diff --git a/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt b/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt
index 42a7a17..9287c96 100644
--- a/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt
@@ -87,6 +87,8 @@ fun SearchScreen(
*/
history: List<CatalogTrack>,
onClearHistory: () -> Unit,
+ /** No connection: the catalogue cannot be searched at all. */
+ offline: Boolean = false,
onEnqueue: (CatalogTrack) -> Unit,
/** Opens the same track sheet the library rows open. */
onTrackMenu: (CatalogTrack) -> Unit,
@@ -113,6 +115,13 @@ fun SearchScreen(
}
when {
+ // Nothing here can be answered without a connection: the catalogue
+ // is Spotify's and none of it is on the phone. Said plainly rather
+ // than left to a query that returns an error a moment later.
+ offline -> item(contentType = "status") {
+ StatusBox { Message(stringResource(R.string.search_offline)) }
+ }
+
state.needsSetup -> item(contentType = "setup") {
WebApiSetup(webApi, backdrop, onClientIdChange, onConnectWebApi)
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
index 818dc24..3b70504 100644
--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
@@ -21,6 +21,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -97,6 +98,8 @@ fun SettingsScreen(
onBack: () -> Unit,
/** Opens the Google sign-in web view; see YouTubeLoginScreen. */
onYouTubeSignIn: () -> Unit = {},
+ /** After switching channel: the library and the home belong to the new one. */
+ onYouTubeChannelChange: () -> Unit = {},
) {
val ready = state as? MainViewModel.UiState.Ready
val context = LocalContext.current
@@ -246,7 +249,17 @@ fun SettingsScreen(
}
if (open == SettingsPage.Account) item("youtube-account") {
- YouTubeAccountSection(onSignIn = onYouTubeSignIn)
+ YouTubeAccountSection(
+ onSignIn = onYouTubeSignIn,
+ onChannelChange = onYouTubeChannelChange,
+ )
+ }
+
+ // What is kept on the phone. Under Playback rather than Account: it is
+ // about how the music arrives, and it belongs beside the bitrate it
+ // shares its wording with.
+ if (open == SettingsPage.Playback && showSpotify) item("downloads") {
+ DownloadsSection(backdrop)
}
// The bitrate is librespot's; ExoPlayer takes what YouTube serves.
@@ -502,7 +515,7 @@ private fun BackendSection() {
* without it; what it adds is the user's own playlists.
*/
@Composable
-private fun YouTubeAccountSection(onSignIn: () -> Unit) {
+private fun YouTubeAccountSection(onSignIn: () -> Unit, onChannelChange: () -> Unit) {
val context = LocalContext.current
val app = remember(context) {
context.applicationContext as dev.lelonio.square.SquareApplication
@@ -512,8 +525,19 @@ private fun YouTubeAccountSection(onSignIn: () -> Unit) {
val account = remember(app) { app.youtubeAccount }
val name by account.accountName.collectAsStateWithLifecycle()
+ val expired by account.expired.collectAsStateWithLifecycle()
+ val pageId by account.pageId.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
+ // Asked for once the account is there, and only then: it is a signed-in
+ // call, and there is nothing to switch between while signed out.
+ var channels by remember {
+ mutableStateOf<List<com.metrolist.innertube.models.YouTubeChannel>>(emptyList())
+ }
+ LaunchedEffect(name) {
+ channels = if (name == null) emptyList() else account.channels()
+ }
+
Section(stringResource(R.string.youtube_account)) {
if (name == null) {
ChoiceRow(
@@ -535,13 +559,56 @@ private fun YouTubeAccountSection(onSignIn: () -> Unit) {
.padding(horizontal = 18.dp, vertical = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
+ Column(Modifier.weight(1f)) {
+ Text(
+ name.orEmpty(),
+ style = MaterialTheme.typography.titleMedium,
+ overflow = TextOverflow.Ellipsis,
+ maxLines = 1,
+ )
+ // A cookie Google has stopped accepting. Said here rather
+ // than left to be guessed from a library that went empty.
+ if (expired) {
+ Text(
+ stringResource(R.string.youtube_session_expired),
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ )
+ }
+ }
+ }
+ if (expired) {
+ RowDivider()
+ ChoiceRow(
+ label = stringResource(R.string.youtube_sign_in_again),
+ selected = false,
+ onClick = onSignIn,
+ )
+ }
+
+ // The channels this Google account owns. One of them is the
+ // personal account nobody uses and another is the channel with the
+ // subscriptions on it, and until this list existed there was no
+ // way to say which one the app was reading.
+ if (channels.size > 1) {
+ RowDivider()
Text(
- name.orEmpty(),
- style = MaterialTheme.typography.titleMedium,
- modifier = Modifier.weight(1f),
- overflow = TextOverflow.Ellipsis,
- maxLines = 1,
+ stringResource(R.string.youtube_channel),
+ style = MaterialTheme.typography.labelMedium,
+ color = InkDim,
+ modifier = Modifier.padding(start = 18.dp, end = 18.dp, top = 14.dp),
)
+ channels.forEach { channel ->
+ ChoiceRow(
+ label = channel.handle?.takeIf { it.isNotBlank() }
+ ?.let { "${channel.name} · $it" }
+ ?: channel.name,
+ selected = channel.pageId == pageId,
+ ) {
+ account.useChannel(channel)
+ onChannelChange()
+ }
+ }
}
RowDivider()
ChoiceRow(
@@ -768,6 +835,164 @@ private fun Licences() {
}
}
+/**
+ * What is kept on the phone, and the rules for keeping it.
+ *
+ * The numbers first, because the question a downloads screen is opened with is
+ * almost always how much room this is taking.
+ */
+@Composable
+private fun DownloadsSection(backdrop: Backdrop) {
+ val context = LocalContext.current
+ val app = remember(context) {
+ context.applicationContext as dev.lelonio.square.SquareApplication
+ }
+ val store = app.downloads
+ val settings = app.downloadSettings
+
+ val files by store.files.collectAsStateWithLifecycle()
+ val failures by store.failures.collectAsStateWithLifecycle()
+ val quality by settings.quality.collectAsStateWithLifecycle()
+ val wifiOnly by settings.wifiOnly.collectAsStateWithLifecycle()
+ val offline by settings.offlineMode.collectAsStateWithLifecycle()
+ val scope = rememberCoroutineScope()
+
+ // Two taps rather than a dialog, and the row says so in between: deleting a
+ // library is worth a moment's thought, and a page of settings is the wrong
+ // place to grow a modal.
+ var confirmingClear by remember { mutableStateOf(false) }
+
+ Section(stringResource(R.string.downloads)) {
+ // The audio plus everything kept beside it. Counted rather than summed
+ // from the index, because the Canvases are video and a library of them
+ // is not a rounding error next to the music.
+ val extrasBytes by androidx.compose.runtime.produceState(0L, files.size) {
+ value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ dev.lelonio.square.download.DownloadExtras.bytes()
+ }
+ }
+ InfoRow(
+ stringResource(R.string.download_storage),
+ stringResource(
+ R.string.download_storage_used,
+ android.text.format.Formatter.formatShortFileSize(
+ context,
+ files.values.sumOf { it.bytes } + extrasBytes,
+ ),
+ ),
+ )
+ RowDivider()
+ InfoRow(stringResource(R.string.downloaded_tracks), files.size.toString())
+
+ RowDivider()
+ Text(
+ stringResource(R.string.download_quality),
+ style = MaterialTheme.typography.labelLarge,
+ color = InkDim,
+ modifier = Modifier.padding(start = 18.dp, end = 18.dp, top = 14.dp),
+ )
+ dev.lelonio.square.data.DownloadQuality.entries.forEach { entry ->
+ ChoiceRow(
+ label = stringResource(entry.label),
+ selected = entry == quality,
+ ) { settings.setQuality(entry) }
+ }
+ Text(
+ stringResource(R.string.download_quality_note),
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 10.dp),
+ )
+
+ RowDivider()
+ DownloadSwitch(
+ label = stringResource(R.string.download_wifi_only),
+ note = stringResource(R.string.download_wifi_only_note),
+ checked = wifiOnly,
+ backdrop = backdrop,
+ onChange = settings::setWifiOnly,
+ )
+
+ RowDivider()
+ DownloadSwitch(
+ label = stringResource(R.string.offline_mode),
+ note = stringResource(R.string.offline_mode_note),
+ checked = offline,
+ backdrop = backdrop,
+ onChange = settings::setOfflineMode,
+ )
+
+ // Only when there is something to say. A row reporting zero failures is
+ // a row about nothing, on a screen that is already long.
+ val givenUp = failures.count {
+ it.value.attempts >= dev.lelonio.square.data.DownloadStore.MAX_ATTEMPTS
+ }
+ if (givenUp > 0) {
+ RowDivider()
+ InfoRow(
+ stringResource(R.string.downloads),
+ stringResource(R.string.download_failed_count, givenUp),
+ )
+ ActionRow(stringResource(R.string.download_retry_failed), destructive = false) {
+ scope.launch {
+ store.retryFailed()
+ dev.lelonio.square.download.DownloadService.start(context)
+ }
+ }
+ }
+
+ if (files.isNotEmpty()) {
+ RowDivider()
+ ActionRow(
+ if (confirmingClear) {
+ stringResource(R.string.remove_all_downloads_confirm)
+ } else {
+ stringResource(R.string.remove_all_downloads)
+ },
+ destructive = true,
+ ) {
+ if (confirmingClear) {
+ confirmingClear = false
+ scope.launch { store.clearAll() }
+ } else {
+ confirmingClear = true
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun DownloadSwitch(
+ label: String,
+ note: String?,
+ checked: Boolean,
+ backdrop: Backdrop,
+ onChange: (Boolean) -> Unit,
+) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .clickable { onChange(!checked) }
+ .padding(start = 18.dp, end = 12.dp, top = 12.dp, bottom = 12.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ Column(Modifier.weight(1f)) {
+ Text(label, style = MaterialTheme.typography.bodyLarge)
+ if (note != null) {
+ Text(note, style = MaterialTheme.typography.bodySmall, color = InkDim)
+ }
+ }
+ dev.lelonio.square.ui.glass.LiquidToggle(
+ selected = { checked },
+ onSelect = onChange,
+ backdrop = backdrop,
+ accent = MaterialTheme.colorScheme.primary,
+ )
+ }
+}
+
@Composable
private fun Section(title: String?, content: @Composable () -> Unit) {
Column(Modifier.padding(horizontal = 20.dp, vertical = 10.dp)) {
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index e8dc974..eb88bf8 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -252,6 +252,9 @@
<string name="popular_playlists">Beliebte Playlists</string>
<string name="youtube_account">YouTube-Konto</string>
<string name="youtube_sign_in">Mit Google anmelden</string>
+ <string name="youtube_channel">Kanal</string>
+ <string name="youtube_session_expired">Sitzung abgelaufen</string>
+ <string name="youtube_sign_in_again">Erneut anmelden</string>
<string name="youtube_sign_in_note">Optional. Suche und Wiedergabe gehen auch ohne; die Anmeldung ergänzt deine eigenen Playlists.</string>
<string name="youtube_sign_out">Abmelden</string>
<string name="quality_auto">Automatisch</string>
@@ -331,4 +334,40 @@
<string name="quality_link">Verbindung</string>
<string name="quality_link_value">%1$d kbps, also Ton mit %2$d kbps</string>
<string name="quality_link_unknown">unbekannt, also Ton mit %1$d kbps</string>
+ <string name="download">Herunterladen</string>
+ <string name="remove_download">Download entfernen</string>
+ <string name="downloaded">Heruntergeladen</string>
+ <string name="downloading">Wird heruntergeladen</string>
+ <string name="downloads">Downloads</string>
+ <string name="download_count">%1$d heruntergeladen</string>
+ <string name="download_progress_count">%1$d von %2$d</string>
+ <string name="download_partial">%1$d von %2$d verfügbar</string>
+ <string name="download_waiting_wifi">Wartet auf WLAN</string>
+ <string name="download_waiting_network">Wartet auf eine Verbindung</string>
+ <string name="download_waiting_engine">Wartet auf Spotify</string>
+ <string name="download_quality">Downloadqualität</string>
+ <string name="download_quality_note">In welcher Qualität ein Download gespeichert wird. Hier gibt es kein Automatisch: ein Download passiert einmal und bleibt, also sollte er nicht die Kopie sein, die die Verbindung gerade zuließ.</string>
+ <string name="download_wifi_only">Nur über WLAN herunterladen</string>
+ <string name="download_wifi_only_note">Über Mobilfunk warten Downloads und starten von selbst wieder, sobald WLAN da ist.</string>
+ <string name="download_liked_songs">Lieblingssongs offline behalten</string>
+ <string name="download_liked_songs_note">Lädt alles herunter, was du geliked hast, und folgt jedem Herz, das dazukommt oder verschwindet.</string>
+ <string name="download_storage">Speicher</string>
+ <string name="download_storage_used">%1$s von Downloads belegt</string>
+ <string name="remove_all_downloads">Alle Downloads entfernen</string>
+ <string name="remove_all_downloads_confirm">Alles Heruntergeladene wird gelöscht. Deine Playlists bleiben unberührt.</string>
+ <string name="download_artist_confirm">%1$d Titel von %2$s herunterladen? Das sind etwa %3$s.</string>
+ <string name="download_failed_count">%1$d konnten nicht heruntergeladen werden</string>
+ <string name="download_retry_failed">Erneut versuchen</string>
+ <string name="downloaded_tracks">Heruntergeladene Songs</string>
+ <string name="offline_mode">Offlinemodus</string>
+ <string name="offline_mode_note">Nur abspielen, was heruntergeladen ist, und Spotify nach nichts fragen.</string>
+ <string name="offline_banner_manual">Offline — von dir eingeschaltet</string>
+ <string name="offline_banner_slow">Offline — die Verbindung ist schlechter als deine Downloads</string>
+ <string name="offline_banner_no_network">Offline — keine Verbindung</string>
+ <string name="search_offline">Die Suche braucht eine Verbindung.</string>
+ <string name="go_online">Online gehen</string>
+ <string name="offline_retrying">Versuch läuft…</string>
+ <string name="radio_of">Radio zu %1$s</string>
+ <string name="remove_download_confirm">Die heruntergeladenen Songs von „%1$s“ von diesem Telefon entfernen?</string>
+ <string name="remove_download_confirm_action">Entfernen</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 7e2980a..d3e8084 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -252,6 +252,9 @@
<string name="popular_playlists">Listas populares</string>
<string name="youtube_account">Cuenta de YouTube</string>
<string name="youtube_sign_in">Iniciar sesión con Google</string>
+ <string name="youtube_channel">Canal</string>
+ <string name="youtube_session_expired">Sesión caducada</string>
+ <string name="youtube_sign_in_again">Vuelve a acceder</string>
<string name="youtube_sign_in_note">Opcional. La búsqueda y la reproducción funcionan sin ello; al iniciar sesión se añaden tus listas.</string>
<string name="youtube_sign_out">Cerrar sesión</string>
<string name="quality_auto">Automática</string>
@@ -331,4 +334,40 @@
<string name="quality_link">Conexión</string>
<string name="quality_link_value">%1$d kbps, así que audio a %2$d kbps</string>
<string name="quality_link_unknown">desconocida, así que audio a %1$d kbps</string>
+ <string name="download">Descargar</string>
+ <string name="remove_download">Quitar descarga</string>
+ <string name="downloaded">Descargado</string>
+ <string name="downloading">Descargando</string>
+ <string name="downloads">Descargas</string>
+ <string name="download_count">%1$d descargados</string>
+ <string name="download_progress_count">%1$d de %2$d</string>
+ <string name="download_partial">%1$d de %2$d disponibles</string>
+ <string name="download_waiting_wifi">Esperando al Wi‑Fi</string>
+ <string name="download_waiting_network">Esperando una conexión</string>
+ <string name="download_waiting_engine">Esperando a Spotify</string>
+ <string name="download_quality">Calidad de las descargas</string>
+ <string name="download_quality_note">Con qué calidad se guarda una descarga. Aquí no hay automático: una descarga se hace una vez y se queda, así que no debería ser la copia que la conexión permitió ese minuto.</string>
+ <string name="download_wifi_only">Descargar solo con Wi‑Fi</string>
+ <string name="download_wifi_only_note">Con datos móviles las descargas esperan, y vuelven a empezar solas cuando hay Wi‑Fi.</string>
+ <string name="download_liked_songs">Guardar Tus me gusta sin conexión</string>
+ <string name="download_liked_songs_note">Descarga todo lo que te ha gustado, y sigue cada corazón que añades o quitas.</string>
+ <string name="download_storage">Almacenamiento</string>
+ <string name="download_storage_used">%1$s ocupados por las descargas</string>
+ <string name="remove_all_downloads">Quitar todas las descargas</string>
+ <string name="remove_all_downloads_confirm">Se borrará todo lo descargado. Tus playlists no se tocan.</string>
+ <string name="download_artist_confirm">¿Descargar %1$d canciones de %2$s? Son unos %3$s.</string>
+ <string name="download_failed_count">%1$d no se pudieron descargar</string>
+ <string name="download_retry_failed">Reintentar</string>
+ <string name="downloaded_tracks">Canciones descargadas</string>
+ <string name="offline_mode">Modo sin conexión</string>
+ <string name="offline_mode_note">Reproduce solo lo descargado, sin pedirle nada a Spotify.</string>
+ <string name="offline_banner_manual">Sin conexión — lo activaste tú</string>
+ <string name="offline_banner_slow">Sin conexión — la red es peor que tus descargas</string>
+ <string name="offline_banner_no_network">Sin conexión — no hay red</string>
+ <string name="search_offline">La búsqueda necesita conexión.</string>
+ <string name="go_online">Volver a conectar</string>
+ <string name="offline_retrying">Probando…</string>
+ <string name="radio_of">Radio de %1$s</string>
+ <string name="remove_download_confirm">¿Quitar de este teléfono las canciones descargadas de «%1$s»?</string>
+ <string name="remove_download_confirm_action">Quitar</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 14fcd96..41ae04c 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -252,6 +252,9 @@
<string name="popular_playlists">Playlists populaires</string>
<string name="youtube_account">Compte YouTube</string>
<string name="youtube_sign_in">Se connecter avec Google</string>
+ <string name="youtube_channel">Chaîne</string>
+ <string name="youtube_session_expired">Session expirée</string>
+ <string name="youtube_sign_in_again">Se reconnecter</string>
<string name="youtube_sign_in_note">Facultatif. La recherche et la lecture fonctionnent sans ; la connexion ajoute vos playlists.</string>
<string name="youtube_sign_out">Se déconnecter</string>
<string name="quality_auto">Automatique</string>
@@ -331,4 +334,40 @@
<string name="quality_link">Connexion</string>
<string name="quality_link_value">%1$d kbps, donc audio à %2$d kbps</string>
<string name="quality_link_unknown">inconnue, donc audio à %1$d kbps</string>
+ <string name="download">Télécharger</string>
+ <string name="remove_download">Retirer le téléchargement</string>
+ <string name="downloaded">Téléchargé</string>
+ <string name="downloading">Téléchargement</string>
+ <string name="downloads">Téléchargements</string>
+ <string name="download_count">%1$d téléchargés</string>
+ <string name="download_progress_count">%1$d sur %2$d</string>
+ <string name="download_partial">%1$d sur %2$d disponibles</string>
+ <string name="download_waiting_wifi">En attente du Wi‑Fi</string>
+ <string name="download_waiting_network">En attente d\'une connexion</string>
+ <string name="download_waiting_engine">En attente de Spotify</string>
+ <string name="download_quality">Qualité des téléchargements</string>
+ <string name="download_quality_note">La qualité à laquelle un téléchargement est gardé. Pas d\'automatique ici : un téléchargement se fait une fois et reste, il ne devrait donc pas être la copie que la connexion permettait à cette minute.</string>
+ <string name="download_wifi_only">Télécharger uniquement en Wi‑Fi</string>
+ <string name="download_wifi_only_note">En données mobiles les téléchargements patientent, et repartent seuls dès que le Wi‑Fi revient.</string>
+ <string name="download_liked_songs">Garder les Titres likés hors connexion</string>
+ <string name="download_liked_songs_note">Télécharge tout ce que vous avez liké, et suit chaque cœur ajouté ou retiré.</string>
+ <string name="download_storage">Stockage</string>
+ <string name="download_storage_used">%1$s occupés par les téléchargements</string>
+ <string name="remove_all_downloads">Retirer tous les téléchargements</string>
+ <string name="remove_all_downloads_confirm">Tout ce qui est téléchargé sera supprimé. Vos playlists ne sont pas touchées.</string>
+ <string name="download_artist_confirm">Télécharger %1$d titres de %2$s ? Cela représente environ %3$s.</string>
+ <string name="download_failed_count">%1$d n\'ont pas pu être téléchargés</string>
+ <string name="download_retry_failed">Réessayer</string>
+ <string name="downloaded_tracks">Titres téléchargés</string>
+ <string name="offline_mode">Mode hors connexion</string>
+ <string name="offline_mode_note">Ne lire que ce qui est téléchargé, sans rien demander à Spotify.</string>
+ <string name="offline_banner_manual">Hors connexion — vous l\'avez activé</string>
+ <string name="offline_banner_slow">Hors connexion — le réseau est moins bon que vos téléchargements</string>
+ <string name="offline_banner_no_network">Hors connexion — aucune connexion</string>
+ <string name="search_offline">La recherche nécessite une connexion.</string>
+ <string name="go_online">Repasser en ligne</string>
+ <string name="offline_retrying">Tentative…</string>
+ <string name="radio_of">Radio de %1$s</string>
+ <string name="remove_download_confirm">Retirer de ce téléphone les titres téléchargés de « %1$s » ?</string>
+ <string name="remove_download_confirm_action">Retirer</string>
</resources>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index d5b86a5..ea3a59b 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -267,6 +267,9 @@
<string name="popular_playlists">लोकप्रिय प्लेलिस्ट</string>
<string name="youtube_account">YouTube खाता</string>
<string name="youtube_sign_in">Google से साइन इन करें</string>
+ <string name="youtube_channel">चैनल</string>
+ <string name="youtube_session_expired">सत्र समाप्त हो गया</string>
+ <string name="youtube_sign_in_again">फिर से साइन इन करें</string>
<string name="youtube_sign_in_note">वैकल्पिक। खोज और प्लेबैक इसके बिना भी चलते हैं; साइन इन करने पर आपकी प्लेलिस्ट जुड़ जाती हैं।</string>
<string name="youtube_sign_out">साइन आउट</string>
<string name="quality_auto">स्वचालित</string>
@@ -346,4 +349,40 @@
<string name="quality_link">कनेक्शन</string>
<string name="quality_link_value">%1$d kbps, इसलिए %2$d kbps ऑडियो</string>
<string name="quality_link_unknown">अज्ञात, इसलिए %1$d kbps ऑडियो</string>
+ <string name="download">डाउनलोड</string>
+ <string name="remove_download">डाउनलोड हटाएँ</string>
+ <string name="downloaded">डाउनलोड किया</string>
+ <string name="downloading">डाउनलोड हो रहा है</string>
+ <string name="downloads">डाउनलोड</string>
+ <string name="download_count">%1$d डाउनलोड</string>
+ <string name="download_progress_count">%2$d में से %1$d</string>
+ <string name="download_partial">%2$d में से %1$d उपलब्ध</string>
+ <string name="download_waiting_wifi">Wi‑Fi का इंतज़ार</string>
+ <string name="download_waiting_network">कनेक्शन का इंतज़ार</string>
+ <string name="download_waiting_engine">Spotify का इंतज़ार</string>
+ <string name="download_quality">डाउनलोड क्वालिटी</string>
+ <string name="download_quality_note">डाउनलोड किस क्वालिटी में रखा जाएगा। यहाँ ऑटोमैटिक नहीं है: डाउनलोड एक बार होता है और रह जाता है।</string>
+ <string name="download_wifi_only">केवल Wi‑Fi पर डाउनलोड करें</string>
+ <string name="download_wifi_only_note">मोबाइल डेटा पर डाउनलोड रुके रहते हैं और Wi‑Fi आते ही खुद शुरू हो जाते हैं।</string>
+ <string name="download_liked_songs">पसंद किए गीत ऑफ़लाइन रखें</string>
+ <string name="download_liked_songs_note">जो भी आपने पसंद किया है सब डाउनलोड करता है।</string>
+ <string name="download_storage">स्टोरेज</string>
+ <string name="download_storage_used">डाउनलोड ने %1$s लिया</string>
+ <string name="remove_all_downloads">सभी डाउनलोड हटाएँ</string>
+ <string name="remove_all_downloads_confirm">डाउनलोड किया सब कुछ मिट जाएगा। आपकी प्लेलिस्ट वैसी ही रहेंगी।</string>
+ <string name="download_artist_confirm">%2$s के %1$d गाने डाउनलोड करें? लगभग %3$s।</string>
+ <string name="download_failed_count">%1$d डाउनलोड नहीं हो सके</string>
+ <string name="download_retry_failed">फिर कोशिश करें</string>
+ <string name="downloaded_tracks">डाउनलोड किए गीत</string>
+ <string name="offline_mode">ऑफ़लाइन मोड</string>
+ <string name="offline_mode_note">केवल डाउनलोड किया हुआ चलाएँ, Spotify से कुछ न मांगें।</string>
+ <string name="offline_banner_manual">ऑफ़लाइन — आपने चालू किया</string>
+ <string name="offline_banner_slow">ऑफ़लाइन — कनेक्शन डाउनलोड से ख़राब है</string>
+ <string name="offline_banner_no_network">ऑफ़लाइन — कोई कनेक्शन नहीं</string>
+ <string name="search_offline">खोज के लिए कनेक्शन चाहिए।</string>
+ <string name="go_online">ऑनलाइन जाएँ</string>
+ <string name="offline_retrying">कोशिश हो रही है…</string>
+ <string name="radio_of">%1$s का रेडियो</string>
+ <string name="remove_download_confirm">“%1$s” के डाउनलोड किए गए गाने इस फ़ोन से हटाएँ?</string>
+ <string name="remove_download_confirm_action">हटाएँ</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 07c6811..bfd8e3e 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -253,6 +253,9 @@
<string name="popular_playlists">Playlist popolari</string>
<string name="youtube_account">Account YouTube</string>
<string name="youtube_sign_in">Accedi con Google</string>
+ <string name="youtube_channel">Canale</string>
+ <string name="youtube_session_expired">Sessione scaduta</string>
+ <string name="youtube_sign_in_again">Accedi di nuovo</string>
<string name="youtube_sign_in_note">Facoltativo. Ricerca e riproduzione funzionano anche senza; accedendo si aggiungono le tue playlist.</string>
<string name="youtube_sign_out">Esci</string>
<string name="quality_auto">Automatica</string>
@@ -332,4 +335,40 @@
<string name="quality_link">Connessione</string>
<string name="quality_link_value">%1$d kbps, quindi audio a %2$d kbps</string>
<string name="quality_link_unknown">sconosciuta, quindi audio a %1$d kbps</string>
+ <string name="download">Scarica</string>
+ <string name="remove_download">Rimuovi download</string>
+ <string name="downloaded">Scaricato</string>
+ <string name="downloading">Download in corso</string>
+ <string name="downloads">Download</string>
+ <string name="download_count">%1$d scaricati</string>
+ <string name="download_progress_count">%1$d di %2$d</string>
+ <string name="download_partial">%1$d di %2$d disponibili</string>
+ <string name="download_waiting_wifi">In attesa del Wi‑Fi</string>
+ <string name="download_waiting_network">In attesa di una connessione</string>
+ <string name="download_waiting_engine">In attesa di Spotify</string>
+ <string name="download_quality">Qualità dei download</string>
+ <string name="download_quality_note">A che qualità viene tenuto un download. Qui non c\'è l\'automatico: un download si fa una volta e resta, quindi non deve essere la copia che la connessione permetteva in quel minuto.</string>
+ <string name="download_wifi_only">Scarica solo su Wi‑Fi</string>
+ <string name="download_wifi_only_note">Con i dati mobili i download restano in attesa e ripartono da soli quando torni sul Wi‑Fi.</string>
+ <string name="download_liked_songs">Tieni offline i Brani che ti piacciono</string>
+ <string name="download_liked_songs_note">Scarica tutto quello a cui hai messo mi piace, e segue ogni cuore che aggiungi o togli.</string>
+ <string name="download_storage">Spazio</string>
+ <string name="download_storage_used">%1$s usati dai download</string>
+ <string name="remove_all_downloads">Rimuovi tutti i download</string>
+ <string name="remove_all_downloads_confirm">Tutto quello che hai scaricato verrà eliminato. Le tue playlist non vengono toccate.</string>
+ <string name="download_artist_confirm">Scaricare %1$d brani di %2$s? Sono circa %3$s.</string>
+ <string name="download_failed_count">%1$d non si sono potuti scaricare</string>
+ <string name="download_retry_failed">Riprova</string>
+ <string name="downloaded_tracks">Brani scaricati</string>
+ <string name="offline_mode">Modalità offline</string>
+ <string name="offline_mode_note">Riproduci solo ciò che è scaricato, senza chiedere niente a Spotify.</string>
+ <string name="offline_banner_manual">Offline — l\'hai attivato tu</string>
+ <string name="offline_banner_slow">Offline — la connessione è peggiore dei tuoi download</string>
+ <string name="offline_banner_no_network">Offline — nessuna connessione</string>
+ <string name="search_offline">La ricerca richiede una connessione.</string>
+ <string name="go_online">Torna online</string>
+ <string name="offline_retrying">Sto provando…</string>
+ <string name="radio_of">Radio di %1$s</string>
+ <string name="remove_download_confirm">Vuoi togliere da questo telefono i brani scaricati di “%1$s”?</string>
+ <string name="remove_download_confirm_action">Rimuovi</string>
</resources>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index 481343a..659a32d 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -252,6 +252,9 @@
<string name="popular_playlists">Playlists populares</string>
<string name="youtube_account">Conta YouTube</string>
<string name="youtube_sign_in">Iniciar sessão com Google</string>
+ <string name="youtube_channel">Canal</string>
+ <string name="youtube_session_expired">Sessão expirada</string>
+ <string name="youtube_sign_in_again">Iniciar sessão de novo</string>
<string name="youtube_sign_in_note">Opcional. A pesquisa e a reprodução funcionam sem isto; iniciar sessão acrescenta as tuas playlists.</string>
<string name="youtube_sign_out">Terminar sessão</string>
<string name="quality_auto">Automática</string>
@@ -331,4 +334,40 @@
<string name="quality_link">Ligação</string>
<string name="quality_link_value">%1$d kbps, portanto áudio a %2$d kbps</string>
<string name="quality_link_unknown">desconhecida, portanto áudio a %1$d kbps</string>
+ <string name="download">Baixar</string>
+ <string name="remove_download">Remover download</string>
+ <string name="downloaded">Baixado</string>
+ <string name="downloading">Baixando</string>
+ <string name="downloads">Downloads</string>
+ <string name="download_count">%1$d baixados</string>
+ <string name="download_progress_count">%1$d de %2$d</string>
+ <string name="download_partial">%1$d de %2$d disponíveis</string>
+ <string name="download_waiting_wifi">Aguardando o Wi‑Fi</string>
+ <string name="download_waiting_network">Aguardando uma conexão</string>
+ <string name="download_waiting_engine">Aguardando o Spotify</string>
+ <string name="download_quality">Qualidade dos downloads</string>
+ <string name="download_quality_note">Com que qualidade um download é guardado. Aqui não existe automático: um download acontece uma vez e fica, então não deveria ser a cópia que a conexão permitiu naquele minuto.</string>
+ <string name="download_wifi_only">Baixar somente no Wi‑Fi</string>
+ <string name="download_wifi_only_note">Nos dados móveis os downloads esperam, e recomeçam sozinhos quando o Wi‑Fi volta.</string>
+ <string name="download_liked_songs">Manter as Músicas Curtidas offline</string>
+ <string name="download_liked_songs_note">Baixa tudo o que você curtiu, e acompanha cada coração que você adiciona ou tira.</string>
+ <string name="download_storage">Armazenamento</string>
+ <string name="download_storage_used">%1$s usados pelos downloads</string>
+ <string name="remove_all_downloads">Remover todos os downloads</string>
+ <string name="remove_all_downloads_confirm">Tudo o que foi baixado será apagado. Suas playlists não são tocadas.</string>
+ <string name="download_artist_confirm">Baixar %1$d faixas de %2$s? São cerca de %3$s.</string>
+ <string name="download_failed_count">%1$d não puderam ser baixadas</string>
+ <string name="download_retry_failed">Tentar de novo</string>
+ <string name="downloaded_tracks">Músicas baixadas</string>
+ <string name="offline_mode">Modo offline</string>
+ <string name="offline_mode_note">Toca só o que está baixado, sem pedir nada ao Spotify.</string>
+ <string name="offline_banner_manual">Offline — você ativou isso</string>
+ <string name="offline_banner_slow">Offline — a conexão está pior que seus downloads</string>
+ <string name="offline_banner_no_network">Offline — sem conexão</string>
+ <string name="search_offline">A pesquisa precisa de ligação.</string>
+ <string name="go_online">Voltar a ficar online</string>
+ <string name="offline_retrying">A tentar…</string>
+ <string name="radio_of">Rádio de %1$s</string>
+ <string name="remove_download_confirm">Remover deste telemóvel as músicas transferidas de “%1$s”?</string>
+ <string name="remove_download_confirm_action">Remover</string>
</resources>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index 6368363..2897a8b 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -267,6 +267,9 @@
<string name="popular_playlists">Popüler çalma listeleri</string>
<string name="youtube_account">YouTube hesabı</string>
<string name="youtube_sign_in">Google ile giriş yap</string>
+ <string name="youtube_channel">Kanal</string>
+ <string name="youtube_session_expired">Oturum sona erdi</string>
+ <string name="youtube_sign_in_again">Yeniden giriş yap</string>
<string name="youtube_sign_in_note">İsteğe bağlı. Arama ve çalma bunsuz da işler; giriş yapmak kendi çalma listelerini ekler.</string>
<string name="youtube_sign_out">Çıkış yap</string>
<string name="quality_auto">Otomatik</string>
@@ -346,4 +349,40 @@
<string name="quality_link">Bağlantı</string>
<string name="quality_link_value">%1$d kbps, yani %2$d kbps ses</string>
<string name="quality_link_unknown">bilinmiyor, yani %1$d kbps ses</string>
+ <string name="download">İndir</string>
+ <string name="remove_download">İndirmeyi kaldır</string>
+ <string name="downloaded">İndirildi</string>
+ <string name="downloading">İndiriliyor</string>
+ <string name="downloads">İndirilenler</string>
+ <string name="download_count">%1$d indirildi</string>
+ <string name="download_progress_count">%2$d içinden %1$d</string>
+ <string name="download_partial">%2$d içinden %1$d mevcut</string>
+ <string name="download_waiting_wifi">Wi‑Fi bekleniyor</string>
+ <string name="download_waiting_network">Bağlantı bekleniyor</string>
+ <string name="download_waiting_engine">Spotify bekleniyor</string>
+ <string name="download_quality">İndirme kalitesi</string>
+ <string name="download_quality_note">Bir indirmenin hangi kalitede saklanacağı. Burada otomatik yok: indirme bir kez yapılır ve kalır, o yüzden bağlantının o dakika izin verdiği kopya olmamalı.</string>
+ <string name="download_wifi_only">Yalnızca Wi‑Fi ile indir</string>
+ <string name="download_wifi_only_note">Mobil veride indirmeler bekler ve Wi‑Fi geldiğinde kendiliğinden devam eder.</string>
+ <string name="download_liked_songs">Beğenilen Şarkıları çevrimdışı tut</string>
+ <string name="download_liked_songs_note">Beğendiğin her şeyi indirir ve eklediğin ya da kaldırdığın her kalbi takip eder.</string>
+ <string name="download_storage">Depolama</string>
+ <string name="download_storage_used">İndirmeler %1$s kullanıyor</string>
+ <string name="remove_all_downloads">Tüm indirmeleri kaldır</string>
+ <string name="remove_all_downloads_confirm">İndirilen her şey silinecek. Çalma listelerine dokunulmaz.</string>
+ <string name="download_artist_confirm">%2$s sanatçısından %1$d parça indirilsin mi? Yaklaşık %3$s.</string>
+ <string name="download_failed_count">%1$d tanesi indirilemedi</string>
+ <string name="download_retry_failed">Yeniden dene</string>
+ <string name="downloaded_tracks">İndirilen şarkılar</string>
+ <string name="offline_mode">Çevrimdışı mod</string>
+ <string name="offline_mode_note">Yalnızca indirilenleri çal, Spotify\'dan hiçbir şey isteme.</string>
+ <string name="offline_banner_manual">Çevrimdışı — sen açtın</string>
+ <string name="offline_banner_slow">Çevrimdışı — bağlantı indirmelerinden kötü</string>
+ <string name="offline_banner_no_network">Çevrimdışı — bağlantı yok</string>
+ <string name="search_offline">Arama için bağlantı gerekir.</string>
+ <string name="go_online">Çevrimiçi ol</string>
+ <string name="offline_retrying">Deneniyor…</string>
+ <string name="radio_of">%1$s radyosu</string>
+ <string name="remove_download_confirm">“%1$s” içindeki indirilmiş şarkılar bu telefondan kaldırılsın mı?</string>
+ <string name="remove_download_confirm_action">Kaldır</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index e507a9f..a594c33 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -273,6 +273,9 @@
<string name="popular_playlists">Popular playlists</string>
<string name="youtube_account">YouTube account</string>
<string name="youtube_sign_in">Sign in with Google</string>
+ <string name="youtube_channel">Channel</string>
+ <string name="youtube_session_expired">Session expired</string>
+ <string name="youtube_sign_in_again">Sign in again</string>
<string name="youtube_sign_in_note">Optional. Search and playback work without it; signing in adds your own playlists.</string>
<string name="youtube_sign_out">Sign out</string>
<string name="quality_auto">Automatic</string>
@@ -352,4 +355,40 @@
<string name="quality_link">Connection</string>
<string name="quality_link_value">%1$d kbps, so %2$d kbps audio</string>
<string name="quality_link_unknown">unknown, so %1$d kbps audio</string>
+ <string name="download">Download</string>
+ <string name="remove_download">Remove download</string>
+ <string name="downloaded">Downloaded</string>
+ <string name="downloading">Downloading</string>
+ <string name="downloads">Downloads</string>
+ <string name="download_count">%1$d downloaded</string>
+ <string name="download_progress_count">%1$d of %2$d</string>
+ <string name="download_partial">%1$d of %2$d available</string>
+ <string name="download_waiting_wifi">Waiting for Wi‑Fi</string>
+ <string name="download_waiting_network">Waiting for a connection</string>
+ <string name="download_waiting_engine">Waiting for Spotify</string>
+ <string name="download_quality">Download quality</string>
+ <string name="download_quality_note">What a download is kept at. There is no automatic setting here: a download happens once and stays, so it should not be the copy your connection happened to allow that minute.</string>
+ <string name="download_wifi_only">Download over Wi‑Fi only</string>
+ <string name="download_wifi_only_note">On mobile data downloads wait, and start again by themselves once you are on Wi‑Fi.</string>
+ <string name="download_liked_songs">Keep Liked Songs offline</string>
+ <string name="download_liked_songs_note">Downloads everything you have liked, and follows every heart you add or remove.</string>
+ <string name="download_storage">Storage</string>
+ <string name="download_storage_used">%1$s used by downloads</string>
+ <string name="remove_all_downloads">Remove all downloads</string>
+ <string name="remove_all_downloads_confirm">Everything downloaded will be deleted. Your playlists are not touched.</string>
+ <string name="download_artist_confirm">Download %1$d tracks by %2$s? That is about %3$s.</string>
+ <string name="download_failed_count">%1$d could not be downloaded</string>
+ <string name="download_retry_failed">Try again</string>
+ <string name="downloaded_tracks">Downloaded songs</string>
+ <string name="offline_mode">Offline mode</string>
+ <string name="offline_mode_note">Play only what is downloaded, and ask Spotify for nothing.</string>
+ <string name="offline_banner_manual">Offline — you turned this on</string>
+ <string name="offline_banner_slow">Offline — the connection is worse than your downloads</string>
+ <string name="offline_banner_no_network">Offline — no connection</string>
+ <string name="search_offline">Search needs a connection.</string>
+ <string name="go_online">Go online</string>
+ <string name="offline_retrying">Trying…</string>
+ <string name="radio_of">Radio of %1$s</string>
+ <string name="remove_download_confirm">Take the downloaded songs of “%1$s” off this phone?</string>
+ <string name="remove_download_confirm_action">Remove</string>
</resources>
diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt b/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt
index 6df7870..2aa1ade 100644
--- a/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt
+++ b/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt
@@ -48,6 +48,15 @@ class InnerTube {
)
var visitorData: String? = null
var dataSyncId: String? = null
+ /**
+ * Vendored addition: which channel of the account is being asked about.
+ *
+ * A brand channel is reached by sending its page id alongside the same
+ * cookie; without it every call answers as the personal channel, whatever
+ * the listener picked.
+ */
+ var pageId: String? = null
+
var cookie: String? = null
set(value) {
field = value
@@ -162,6 +171,10 @@ class InnerTube {
val currentTime = System.currentTimeMillis() / 1000
val sapisidHash = sha1("$currentTime ${cookieMap["SAPISID"]} ${YouTubeClient.ORIGIN_YOUTUBE_MUSIC}")
append("Authorization", "SAPISIDHASH ${currentTime}_${sapisidHash}")
+ // Vendored: the channel within that account, where one was
+ // chosen. Absent for the personal channel, which is what
+ // the account answers as by default.
+ pageId?.takeIf { it.isNotBlank() }?.let { append("X-Goog-PageId", it) }
}
}
}
@@ -399,6 +412,14 @@ class InnerTube {
}
}
+ /** Vendored: the channels this account can act as; see AccountsListResponse. */
+ suspend fun accountsList(client: YouTubeClient) = withRetry {
+ httpClient.post("account/accounts_list") {
+ ytClient(client, setLogin = true)
+ setBody(AccountMenuBody(client.toContext(locale, visitorData, dataSyncId)))
+ }
+ }
+
suspend fun likeVideo(
client: YouTubeClient,
videoId: String,
diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt b/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt
index df5c15d..8ea66c2 100644
--- a/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt
+++ b/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt
@@ -1,6 +1,8 @@
package com.metrolist.innertube
import com.metrolist.innertube.models.AccountInfo
+import com.metrolist.innertube.models.YouTubeChannel
+import com.metrolist.innertube.models.response.AccountsListResponse
import com.metrolist.innertube.models.AlbumItem
import com.metrolist.innertube.models.Artist
import com.metrolist.innertube.models.ArtistItem
@@ -1570,13 +1572,13 @@ object YouTube {
?.content
?.sectionListRenderer
Timber.d("home() sectionListRender contents size: ${sectionListRender?.contents?.size ?: 0}")
- val carousels = sectionListRender?.contents?.mapNotNull { it.musicCarouselShelfRenderer } ?: emptyList()
- Timber.d("home() carousels count: ${carousels.size}")
- val sections =
- carousels
- .mapNotNull {
- HomePage.Section.fromMusicCarouselShelfRenderer(it)
- }.toMutableList()
+ // Vendored change: not only carousels. The music home is built of
+ // them, but the chips above it answer with grids and list shelves,
+ // and reading just one kind returned an empty page for those.
+ val sections = sectionListRender?.contents.orEmpty()
+ .mapNotNull { it.toHomeSection() }
+ .toMutableList()
+ Timber.d("home() sections from contents: ${sections.size}")
Timber.d("home() sections parsed: ${sections.size}")
val chips =
sectionListRender
@@ -1588,6 +1590,18 @@ object YouTube {
HomePage(chips, sections, continuation)
}
+ /**
+ * Vendored addition: one shelf, whatever renderer it arrived as.
+ *
+ * The home page is carousels and the chip pages are grids and list
+ * shelves; both are shelves with a title and some items, which is all a
+ * home row is.
+ */
+ private fun SectionListRenderer.Content.toHomeSection(): HomePage.Section? =
+ musicCarouselShelfRenderer?.let { HomePage.Section.fromMusicCarouselShelfRenderer(it) }
+ ?: gridRenderer?.let { HomePage.Section.fromGridRenderer(it) }
+ ?: musicShelfRenderer?.let { HomePage.Section.fromMusicShelfRenderer(it) }
+
private suspend fun homeContinuation(continuation: String): Result<HomePage> =
runCatching {
val response =
@@ -1602,10 +1616,8 @@ object YouTube {
response.continuationContents
?.sectionListContinuation
?.contents
- ?.mapNotNull { it.musicCarouselShelfRenderer }
- ?.mapNotNull {
- HomePage.Section.fromMusicCarouselShelfRenderer(it)
- }.orEmpty(),
+ ?.mapNotNull { it.toHomeSection() }
+ .orEmpty(),
continuation,
)
}
@@ -3342,6 +3354,59 @@ object YouTube {
}.jsonPrimitive.content
}
+ /**
+ * Vendored addition: every channel the signed-in account can act as.
+ *
+ * The personal channel, then any brand channels — the same list the
+ * official app's account switcher shows. [YouTubeChannel.pageId] is what
+ * selects one; the personal channel has none.
+ */
+ suspend fun accounts(): Result<List<YouTubeChannel>> =
+ runCatching {
+ val raw = innerTube.accountsList(WEB_REMIX).bodyAsText()
+ val parsed = Json { ignoreUnknownKeys = true }
+ .decodeFromString<AccountsListResponse>(raw)
+ val channels = parsed
+ .contents
+ ?.accountSectionListRenderer
+ ?.contents
+ .orEmpty()
+ .mapNotNull { it.accountItemSectionRenderer }
+ .flatMap { it.contents.orEmpty() }
+ .mapNotNull { it.accountItem }
+ .mapNotNull { item ->
+ val tokens = item.serviceEndpoint?.selectActiveIdentityEndpoint?.supportedTokens
+ YouTubeChannel(
+ name = item.accountName?.runs?.firstOrNull()?.text ?: return@mapNotNull null,
+ handle = item.accountByline?.runs?.firstOrNull()?.text,
+ thumbnailUrl = item.accountPhoto?.thumbnails?.lastOrNull()?.url,
+ pageId = tokens?.firstNotNullOfOrNull { it.pageIdToken?.pageId },
+ dataSyncId = tokens?.firstNotNullOfOrNull { it.datasyncIdToken?.datasyncIdToken },
+ selected = item.isSelected,
+ )
+ }
+ if (channels.isEmpty()) {
+ // Which renderers came back, so a response shaped differently
+ // from the one this was written against can be read from a log
+ // rather than guessed at. Names only: the values are the
+ // account's own.
+ val renderers = Regex("\"([A-Za-z]+Renderer)\"")
+ .findAll(raw)
+ .map { it.groupValues[1] }
+ .distinct()
+ .joinToString(", ")
+ Timber.d("accounts(): none parsed; ${raw.length} bytes, renderers: $renderers")
+ }
+ channels
+ }
+
+ /** Which channel of the account calls are made as; see [accounts]. */
+ var pageId: String?
+ get() = innerTube.pageId
+ set(value) {
+ innerTube.pageId = value
+ }
+
suspend fun accountInfo(): Result<AccountInfo> =
runCatching {
innerTube
diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeChannel.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeChannel.kt
new file mode 100644
index 0000000..af5cfac
--- /dev/null
+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeChannel.kt
@@ -0,0 +1,20 @@
+package com.metrolist.innertube.models
+
+/**
+ * Vendored addition: one identity a signed-in Google account can act as.
+ *
+ * The personal channel, or one of the brand channels the account owns. Both
+ * live behind the same cookie; which one answers is decided by [pageId] and
+ * [dataSyncId], which is why they travel together.
+ */
+data class YouTubeChannel(
+ val name: String,
+ /** The @handle, where the channel has one. */
+ val handle: String?,
+ val thumbnailUrl: String?,
+ /** Null on the personal channel, which needs no page id to be reached. */
+ val pageId: String?,
+ val dataSyncId: String?,
+ /** True on the one the session is currently reading. */
+ val selected: Boolean,
+)
diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AccountsListResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AccountsListResponse.kt
new file mode 100644
index 0000000..791f99e
--- /dev/null
+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AccountsListResponse.kt
@@ -0,0 +1,78 @@
+package com.metrolist.innertube.models.response
+
+import com.metrolist.innertube.models.Runs
+import com.metrolist.innertube.models.Thumbnails
+import kotlinx.serialization.Serializable
+
+/**
+ * Vendored addition: every channel a Google account can act as.
+ *
+ * A Google account is not one YouTube identity but several — the personal
+ * channel, and any brand channels it owns — and the official apps let the
+ * listener pick between them. The library that ships here only ever asked for
+ * the active one, so a session opened on the wrong identity showed the wrong
+ * library with no way to change it.
+ *
+ * Each entry carries the tokens that select it: a page id for a brand channel,
+ * and the datasync id that tells the rest of the API which library to read.
+ */
+@Serializable
+data class AccountsListResponse(
+ val contents: Contents?,
+) {
+ @Serializable
+ data class Contents(
+ val accountSectionListRenderer: AccountSectionListRenderer?,
+ )
+
+ @Serializable
+ data class AccountSectionListRenderer(
+ val contents: List<Content>?,
+ ) {
+ @Serializable
+ data class Content(
+ val accountItemSectionRenderer: AccountItemSectionRenderer?,
+ )
+ }
+
+ @Serializable
+ data class AccountItemSectionRenderer(
+ val contents: List<Content>?,
+ ) {
+ @Serializable
+ data class Content(
+ val accountItem: AccountItem?,
+ )
+ }
+
+ @Serializable
+ data class AccountItem(
+ val accountName: Runs?,
+ val accountByline: Runs?,
+ val accountPhoto: Thumbnails?,
+ val isSelected: Boolean = false,
+ val serviceEndpoint: ServiceEndpoint?,
+ )
+
+ @Serializable
+ data class ServiceEndpoint(
+ val selectActiveIdentityEndpoint: SelectActiveIdentityEndpoint?,
+ )
+
+ @Serializable
+ data class SelectActiveIdentityEndpoint(
+ val supportedTokens: List<SupportedToken>?,
+ )
+
+ @Serializable
+ data class SupportedToken(
+ val pageIdToken: PageIdToken? = null,
+ val datasyncIdToken: DatasyncIdToken? = null,
+ )
+
+ @Serializable
+ data class PageIdToken(val pageId: String? = null)
+
+ @Serializable
+ data class DatasyncIdToken(val datasyncIdToken: String? = null)
+}
diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/HomePage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/HomePage.kt
index 03b26e1..884d1c9 100644
--- a/innertube/src/main/kotlin/com/metrolist/innertube/pages/HomePage.kt
+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/HomePage.kt
@@ -6,7 +6,9 @@ import com.metrolist.innertube.models.Artist
import com.metrolist.innertube.models.ArtistItem
import com.metrolist.innertube.models.BrowseEndpoint
import com.metrolist.innertube.models.EpisodeItem
+import com.metrolist.innertube.models.GridRenderer
import com.metrolist.innertube.models.MusicCarouselShelfRenderer
+import com.metrolist.innertube.models.MusicShelfRenderer
import com.metrolist.innertube.models.MusicMultiRowListItemRenderer
import com.metrolist.innertube.models.MusicResponsiveListItemRenderer
import com.metrolist.innertube.models.MusicTwoRowItemRenderer
@@ -101,6 +103,43 @@ data class HomePage(
)
}
+ /**
+ * A shelf laid out as a grid rather than a carousel.
+ *
+ * Vendored addition. The music home is carousels, but several of
+ * the chips above it — Podcasts first among them — answer with
+ * grids, and a parser that only knew carousels returned an empty
+ * page for those: the chip looked broken when the response was
+ * fine.
+ */
+ fun fromGridRenderer(renderer: GridRenderer): Section? {
+ val title = renderer.header?.gridHeaderRenderer?.title?.runs?.firstOrNull()?.text
+ ?: return null
+ val items = renderer.items
+ .mapNotNull { it.musicTwoRowItemRenderer }
+ .mapNotNull { fromMusicTwoRowItemRenderer(it) }
+ if (items.isEmpty()) return null
+ return Section(title = title, label = null, thumbnail = null, endpoint = null, items = items)
+ }
+
+ /**
+ * A shelf laid out as a list of rows.
+ *
+ * Vendored addition, and the other half of the same problem: the
+ * episode and song shelves under a chip arrive this way.
+ */
+ fun fromMusicShelfRenderer(renderer: MusicShelfRenderer): Section? {
+ val title = renderer.title?.runs?.firstOrNull()?.text ?: return null
+ val items = renderer.contents.orEmpty().let { contents ->
+ contents.mapNotNull { it.musicResponsiveListItemRenderer }
+ .mapNotNull { fromMusicResponsiveListItemRenderer(it) } +
+ contents.mapNotNull { it.musicMultiRowListItemRenderer }
+ .mapNotNull { fromMusicMultiRowListItemRenderer(it) }
+ }
+ if (items.isEmpty()) return null
+ return Section(title = title, label = null, thumbnail = null, endpoint = null, items = items)
+ }
+
private fun fromMusicMultiRowListItemRenderer(renderer: MusicMultiRowListItemRenderer): EpisodeItem? {
val subtitleRuns = renderer.subtitle?.runs?.splitBySeparator()
val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)
diff --git a/native/Cargo.lock b/native/Cargo.lock
index e386c8d..4659dda 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -2333,6 +2333,7 @@ dependencies = [
"bytes",
"futures-util",
"http",
+ "http-body-util",
"jni",
"librespot-audio",
"librespot-connect",
diff --git a/native/Cargo.toml b/native/Cargo.toml
index 1daab3c..c5c1560 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -32,6 +32,8 @@ log = "0.4"
once_cell = "1"
# Same major as librespot-core, so `Method` is the type spclient expects.
http = "1.3"
+# Reading a CDN response body in chunks; see src/downloads.rs.
+http-body-util = "0.1"
# The body type librespot's own HTTP client takes.
bytes = "1"
serde_json = "1"
diff --git a/native/src/downloads.rs b/native/src/downloads.rs
new file mode 100644
index 0000000..bb41f08
--- /dev/null
+++ b/native/src/downloads.rs
@@ -0,0 +1,796 @@
+//! Keeping tracks on the phone, and finding them again.
+//!
+//! A download here is the file Spotify's CDN serves, byte for byte, still
+//! encrypted with its own AES key — plus a small JSON sidecar holding that key
+//! and the handful of metadata fields the player would otherwise have gone to
+//! the network for. Nothing is decrypted on the way in.
+//!
+//! That choice is what keeps the feature small. `player.rs` already knows how
+//! to turn one of these files into sound: it is exactly what arrives when a
+//! track is streamed, and what librespot's own cache stores. So the offline
+//! path is the online path with the first three steps removed, rather than a
+//! second decoder, a second normalisation rule and a second set of bugs. It
+//! also means a download is no more extractable than the cache already was.
+//!
+//! Layout under the root the Kotlin side chooses:
+//!
+//! ```text
+//! <root>/.nomedia
+//! <root>/audio/<xx>/<rest of the track id> the encrypted file
+//! <root>/meta/<xx>/<rest of the track id>.json the sidecar
+//! ```
+//!
+//! Sharded on the first byte of the id for the same reason librespot's cache
+//! is: several thousand files in one directory is a directory nothing
+//! enumerates quickly, and a library of downloads gets there.
+//!
+//! The sidecar is written last and atomically, so its presence is the single
+//! signal that a download is complete. A `.part` file beside the audio is a
+//! download in progress or an interrupted one, and either way it is where the
+//! next attempt resumes from.
+
+use crate::engine::{self, EngineResult};
+use http::{header::RANGE, Method, Request, StatusCode};
+use http_body_util::BodyExt;
+use librespot_core::{cdn_url::CdnUrl, session::Session, spotify_uri::SpotifyUri, SpotifyId};
+use librespot_metadata::audio::{AudioFileFormat, AudioItem, UniqueFields};
+use librespot_playback::config::{DownloadLookup, DownloadedTrack};
+use serde_json::{json, Value};
+use std::{
+ collections::HashSet,
+ fs,
+ io::Write,
+ path::{Path, PathBuf},
+ sync::{Arc, Mutex},
+};
+
+/// How much is asked for in one request.
+///
+/// Small enough that a cancellation is acted on promptly and the progress ring
+/// moves, large enough that a three-minute track is a couple of dozen requests
+/// rather than hundreds.
+const CHUNK: usize = 512 * 1024;
+
+/// How many times one chunk is retried before the download gives up.
+///
+/// The CDN URL is re-resolved between attempts: the usual reason a chunk fails
+/// on a phone is that the signed URL expired while the queue was working
+/// through a long playlist, and that is fixed by asking for a new one rather
+/// than by waiting.
+const CHUNK_ATTEMPTS: u32 = 3;
+
+/// How long after playback asks for a key a download may ask for one.
+///
+/// Long enough to cover a track starting and its successor being preloaded,
+/// which is the pair of requests a skip makes.
+const PLAYBACK_PRIORITY: std::time::Duration = std::time::Duration::from_secs(12);
+
+/// A chunk that has not arrived in this long is not going to.
+const CHUNK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
+
+/// What a download says when Spotify is refusing to hand out audio keys.
+///
+/// Matched by the Kotlin queue, so it stays a stable string.
+pub const KEY_THROTTLED: &str = "audio keys are being refused";
+
+/// Where downloads live. Set from Kotlin before the engine starts, and again if
+/// the listener moves them to a memory card.
+static ROOT: Mutex<Option<PathBuf>> = Mutex::new(None);
+
+/// Track ids whose download has been asked to stop.
+///
+/// Checked between chunks. A cancelled download keeps its `.part` file: the
+/// listener may have cancelled a whole queue because it started on mobile data,
+/// and throwing away what was already paid for would be a poor answer to that.
+static CANCELLED: Mutex<Option<HashSet<String>>> = Mutex::new(None);
+
+pub fn set_root(path: &str) -> EngineResult<()> {
+ let root = PathBuf::from(path);
+ fs::create_dir_all(root.join("audio")).map_err(|e| format!("download dir failed: {e}"))?;
+ fs::create_dir_all(root.join("meta")).map_err(|e| format!("download dir failed: {e}"))?;
+
+ // Only matters on a memory card, where the store sits under a path a media
+ // scanner will walk. Harmless on internal storage, and cheaper than
+ // deciding which of the two this is.
+ let _ = fs::File::create(root.join(".nomedia"));
+
+ *ROOT.lock().map_err(|_| "download root poisoned")? = Some(root);
+ Ok(())
+}
+
+fn root() -> Option<PathBuf> {
+ ROOT.lock().ok()?.clone()
+}
+
+/// `<root>/<kind>/<xx>/<rest>`, with the id split the way librespot splits it.
+fn shard(root: &Path, kind: &str, id: &str, suffix: &str) -> Option<PathBuf> {
+ if id.len() < 3 {
+ return None;
+ }
+ let mut path = root.join(kind).join(&id[0..2]);
+ path.push(format!("{}{suffix}", &id[2..]));
+ Some(path)
+}
+
+fn audio_path(root: &Path, id: &str) -> Option<PathBuf> {
+ shard(root, "audio", id, "")
+}
+
+fn meta_path(root: &Path, id: &str) -> Option<PathBuf> {
+ shard(root, "meta", id, ".json")
+}
+
+/// The base-16 track id, which is what everything here is keyed on.
+///
+/// Not the URI: the same track reached through a different market carries the
+/// same id, and the id is also what the audio-key request is made with.
+fn track_key(uri: &SpotifyUri) -> EngineResult<String> {
+ let id: SpotifyId = uri.try_into().map_err(|_| "not a playable uri".to_string())?;
+ id.to_base16().map_err(|e| format!("bad track id: {e}"))
+}
+
+fn hex_to_bytes(hex: &str) -> Option<Vec<u8>> {
+ if hex.len() % 2 != 0 {
+ return None;
+ }
+ (0..hex.len())
+ .step_by(2)
+ .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).ok())
+ .collect()
+}
+
+fn bytes_to_hex(bytes: &[u8]) -> String {
+ bytes.iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// The name a format is stored under, and back again.
+///
+/// Spelled out rather than stored as the protobuf number, because the sidecar
+/// outlives this build of the app: a number that shifted meaning in a later
+/// version of the protocol would quietly make old downloads play as something
+/// else, while a name that is no longer recognised simply fails the lookup and
+/// the track streams as it always did.
+fn format_name(format: AudioFileFormat) -> &'static str {
+ match format {
+ AudioFileFormat::OGG_VORBIS_96 => "OGG_VORBIS_96",
+ AudioFileFormat::OGG_VORBIS_160 => "OGG_VORBIS_160",
+ AudioFileFormat::OGG_VORBIS_320 => "OGG_VORBIS_320",
+ AudioFileFormat::MP3_96 => "MP3_96",
+ AudioFileFormat::MP3_160 => "MP3_160",
+ AudioFileFormat::MP3_160_ENC => "MP3_160_ENC",
+ AudioFileFormat::MP3_256 => "MP3_256",
+ AudioFileFormat::MP3_320 => "MP3_320",
+ AudioFileFormat::AAC_24 => "AAC_24",
+ AudioFileFormat::AAC_48 => "AAC_48",
+ AudioFileFormat::AAC_160 => "AAC_160",
+ AudioFileFormat::AAC_320 => "AAC_320",
+ AudioFileFormat::MP4_128 => "MP4_128",
+ AudioFileFormat::FLAC_FLAC => "FLAC_FLAC",
+ AudioFileFormat::FLAC_FLAC_24BIT => "FLAC_FLAC_24BIT",
+ AudioFileFormat::XHE_AAC_12 => "XHE_AAC_12",
+ AudioFileFormat::XHE_AAC_16 => "XHE_AAC_16",
+ AudioFileFormat::XHE_AAC_24 => "XHE_AAC_24",
+ AudioFileFormat::OTHER5 => "OTHER5",
+ }
+}
+
+fn format_from_name(name: &str) -> Option<AudioFileFormat> {
+ Some(match name {
+ "OGG_VORBIS_96" => AudioFileFormat::OGG_VORBIS_96,
+ "OGG_VORBIS_160" => AudioFileFormat::OGG_VORBIS_160,
+ "OGG_VORBIS_320" => AudioFileFormat::OGG_VORBIS_320,
+ "MP3_96" => AudioFileFormat::MP3_96,
+ "MP3_160" => AudioFileFormat::MP3_160,
+ "MP3_160_ENC" => AudioFileFormat::MP3_160_ENC,
+ "MP3_256" => AudioFileFormat::MP3_256,
+ "MP3_320" => AudioFileFormat::MP3_320,
+ "AAC_24" => AudioFileFormat::AAC_24,
+ "AAC_48" => AudioFileFormat::AAC_48,
+ "AAC_160" => AudioFileFormat::AAC_160,
+ "AAC_320" => AudioFileFormat::AAC_320,
+ "MP4_128" => AudioFileFormat::MP4_128,
+ "FLAC_FLAC" => AudioFileFormat::FLAC_FLAC,
+ "FLAC_FLAC_24BIT" => AudioFileFormat::FLAC_FLAC_24BIT,
+ "XHE_AAC_12" => AudioFileFormat::XHE_AAC_12,
+ "XHE_AAC_16" => AudioFileFormat::XHE_AAC_16,
+ "XHE_AAC_24" => AudioFileFormat::XHE_AAC_24,
+ "OTHER5" => AudioFileFormat::OTHER5,
+ _ => return None,
+ })
+}
+
+/// Roughly what a format is worth, so a download can be compared with the copy
+/// already on disk without the caller knowing anything about codecs.
+///
+/// Only the ordering matters. A track already downloaded at 320 is not fetched
+/// again because some playlist asked for it at 160.
+fn format_rank(format: AudioFileFormat) -> u32 {
+ match format {
+ AudioFileFormat::XHE_AAC_12 => 12,
+ AudioFileFormat::XHE_AAC_16 => 16,
+ AudioFileFormat::AAC_24 | AudioFileFormat::XHE_AAC_24 => 24,
+ AudioFileFormat::AAC_48 => 48,
+ AudioFileFormat::OGG_VORBIS_96 | AudioFileFormat::MP3_96 => 96,
+ AudioFileFormat::MP4_128 => 128,
+ AudioFileFormat::OGG_VORBIS_160
+ | AudioFileFormat::MP3_160
+ | AudioFileFormat::MP3_160_ENC
+ | AudioFileFormat::AAC_160 => 160,
+ AudioFileFormat::MP3_256 => 256,
+ AudioFileFormat::OGG_VORBIS_320
+ | AudioFileFormat::MP3_320
+ | AudioFileFormat::AAC_320
+ | AudioFileFormat::OTHER5 => 320,
+ AudioFileFormat::FLAC_FLAC => 1000,
+ AudioFileFormat::FLAC_FLAC_24BIT => 1100,
+ }
+}
+
+/// Formats in the order this download would like them.
+///
+/// The same shape as the table in `player.rs`, and deliberately so: a
+/// downloaded track should be the track that would have been streamed, not a
+/// different master. Ogg leads at every rung, because it is what carries
+/// Spotify's normalisation packet.
+fn preferred_formats(kbps: i32) -> [AudioFileFormat; 7] {
+ match kbps {
+ k if k <= 96 => [
+ AudioFileFormat::OGG_VORBIS_96,
+ AudioFileFormat::MP3_96,
+ AudioFileFormat::OGG_VORBIS_160,
+ AudioFileFormat::MP3_160,
+ AudioFileFormat::MP3_256,
+ AudioFileFormat::OGG_VORBIS_320,
+ AudioFileFormat::MP3_320,
+ ],
+ k if k <= 160 => [
+ AudioFileFormat::OGG_VORBIS_160,
+ AudioFileFormat::MP3_160,
+ AudioFileFormat::OGG_VORBIS_96,
+ AudioFileFormat::MP3_96,
+ AudioFileFormat::MP3_256,
+ AudioFileFormat::OGG_VORBIS_320,
+ AudioFileFormat::MP3_320,
+ ],
+ _ => [
+ AudioFileFormat::OGG_VORBIS_320,
+ AudioFileFormat::MP3_320,
+ AudioFileFormat::MP3_256,
+ AudioFileFormat::OGG_VORBIS_160,
+ AudioFileFormat::MP3_160,
+ AudioFileFormat::OGG_VORBIS_96,
+ AudioFileFormat::MP3_96,
+ ],
+ }
+}
+
+// ---------------------------------------------------------------- the sidecar
+
+fn read_sidecar(path: &Path) -> Option<Value> {
+ serde_json::from_str(&fs::read_to_string(path).ok()?).ok()
+}
+
+/// Writes the sidecar through a temporary file, so it is either the old one or
+/// the new one and never half of either.
+fn write_sidecar(path: &Path, value: &Value) -> Result<(), String> {
+ let parent = path.parent().ok_or("sidecar has no directory")?;
+ fs::create_dir_all(parent).map_err(|e| format!("sidecar dir failed: {e}"))?;
+ let tmp = path.with_extension("json.tmp");
+ fs::write(&tmp, value.to_string().as_bytes())
+ .map_err(|e| format!("sidecar write failed: {e}"))?;
+ fs::rename(&tmp, path).map_err(|e| format!("sidecar rename failed: {e}"))
+}
+
+/// What the player needs to play a downloaded track, or `None` if there is not
+/// a complete download for it.
+///
+/// Deliberately reads from disk on every call. See `DownloadLookup` in
+/// `librespot-playback`'s `config.rs` for why a cached map would be worse.
+fn lookup_track(track_id: &SpotifyId) -> Option<DownloadedTrack> {
+ let root = root()?;
+ let id = track_id.to_base16().ok()?;
+ let meta = meta_path(&root, &id)?;
+ let path = audio_path(&root, &id)?;
+
+ let value = read_sidecar(&meta)?;
+ let format = format_from_name(value.get("format")?.as_str()?)?;
+
+ let key = value
+ .get("key")
+ .and_then(Value::as_str)
+ .and_then(hex_to_bytes)
+ .and_then(|bytes| <[u8; 16]>::try_from(bytes.as_slice()).ok());
+
+ let strings = |field: &str| -> Vec<String> {
+ value
+ .get(field)
+ .and_then(Value::as_array)
+ .map(|list| {
+ list.iter()
+ .filter_map(Value::as_str)
+ .map(str::to_string)
+ .collect()
+ })
+ .unwrap_or_default()
+ };
+
+ Some(DownloadedTrack {
+ path,
+ key,
+ format,
+ name: value
+ .get("name")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string(),
+ duration_ms: value.get("durationMs").and_then(Value::as_u64)? as u32,
+ is_explicit: value
+ .get("isExplicit")
+ .and_then(Value::as_bool)
+ .unwrap_or(false),
+ album: value
+ .get("album")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string(),
+ album_artists: strings("albumArtists"),
+ number: value.get("number").and_then(Value::as_u64).unwrap_or(0) as u32,
+ disc_number: value.get("discNumber").and_then(Value::as_u64).unwrap_or(0) as u32,
+ })
+}
+
+/// Whether there is anything downloaded at all.
+///
+/// The question the engine asks before deciding that a failed handshake is
+/// worth carrying on through. Stops at the first sidecar it finds rather than
+/// counting: a library of five thousand songs and one are the same answer.
+pub fn any() -> bool {
+ let Some(root) = root() else { return false };
+ let Ok(shards) = fs::read_dir(root.join("meta")) else {
+ return false;
+ };
+ for shard in shards.flatten() {
+ if let Ok(entries) = fs::read_dir(shard.path()) {
+ if entries.flatten().next().is_some() {
+ return true;
+ }
+ }
+ }
+ false
+}
+
+/// The lookup handed to `PlayerConfig` when the engine is built.
+pub fn lookup() -> DownloadLookup {
+ Arc::new(lookup_track)
+}
+
+// -------------------------------------------------------------- what is there
+
+/// The sidecar for a track as JSON, or `"null"` when it is not downloaded.
+pub fn stored(uri: &str) -> EngineResult<String> {
+ let parsed = SpotifyUri::from_uri(uri).map_err(|e| format!("bad uri {uri}: {e}"))?;
+ let id = track_key(&parsed)?;
+ let Some(root) = root() else {
+ return Ok("null".to_string());
+ };
+ let Some(meta) = meta_path(&root, &id) else {
+ return Ok("null".to_string());
+ };
+ match read_sidecar(&meta) {
+ Some(value) => Ok(value.to_string()),
+ None => Ok("null".to_string()),
+ }
+}
+
+/// Removes a download. Missing is not an error: the caller is asking for the
+/// track to be gone, and it is.
+pub fn remove_track(uri: &str) -> EngineResult<()> {
+ let parsed = SpotifyUri::from_uri(uri).map_err(|e| format!("bad uri {uri}: {e}"))?;
+ let id = track_key(&parsed)?;
+ let Some(root) = root() else { return Ok(()) };
+
+ // The sidecar goes first. It is what the player looks for, so removing it
+ // first means a load happening at this moment falls back to streaming
+ // rather than opening a file that is about to disappear underneath it.
+ if let Some(meta) = meta_path(&root, &id) {
+ let _ = fs::remove_file(meta);
+ }
+ if let Some(audio) = audio_path(&root, &id) {
+ let _ = fs::remove_file(&audio);
+ let _ = fs::remove_file(audio.with_extension("part"));
+ }
+ Ok(())
+}
+
+fn cancelled(id: &str) -> bool {
+ CANCELLED
+ .lock()
+ .ok()
+ .and_then(|guard| guard.as_ref().map(|set| set.contains(id)))
+ .unwrap_or(false)
+}
+
+fn clear_cancel(id: &str) {
+ if let Ok(mut guard) = CANCELLED.lock() {
+ if let Some(set) = guard.as_mut() {
+ set.remove(id);
+ }
+ }
+}
+
+/// Asks a download in progress to stop at the end of the current chunk.
+pub fn cancel(uri: &str) -> EngineResult<()> {
+ let parsed = SpotifyUri::from_uri(uri).map_err(|e| format!("bad uri {uri}: {e}"))?;
+ let id = track_key(&parsed)?;
+ let mut guard = CANCELLED.lock().map_err(|_| "cancel set poisoned")?;
+ guard.get_or_insert_with(HashSet::new).insert(id);
+ Ok(())
+}
+
+// ------------------------------------------------------------------ the fetch
+
+/// One ranged request against the CDN: the bytes, and the size of the whole
+/// file as the response reports it.
+async fn get_range(
+ session: &Session,
+ url: &str,
+ offset: usize,
+ length: usize,
+) -> Result<(bytes::Bytes, usize), String> {
+ let request = Request::builder()
+ .method(&Method::GET)
+ .uri(url)
+ .header(RANGE, format!("bytes={}-{}", offset, offset + length - 1))
+ .body(bytes::Bytes::new())
+ .map_err(|e| format!("bad range request: {e}"))?;
+
+ let response = tokio::time::timeout(CHUNK_TIMEOUT, session.http_client().request(request))
+ .await
+ .map_err(|_| "the CDN did not answer in time".to_string())?
+ .map_err(|e| format!("CDN request failed: {e}"))?;
+
+ let status = response.status();
+ if status != StatusCode::PARTIAL_CONTENT {
+ return Err(format!("CDN answered {status}, expected partial content"));
+ }
+
+ // `bytes 0-524287/8912345`: the part after the slash is the only place the
+ // size of the whole file is stated, which is why this asks for a range even
+ // for a file it intends to read in full.
+ let range = response
+ .headers()
+ .get(http::header::CONTENT_RANGE)
+ .and_then(|value| value.to_str().ok())
+ .ok_or("the CDN did not say how big the file is")?;
+ let total: usize = range
+ .rsplit('/')
+ .next()
+ .and_then(|size| size.parse().ok())
+ .ok_or_else(|| format!("could not read the file size out of {range:?}"))?;
+
+ let body = response
+ .into_body()
+ .collect()
+ .await
+ .map_err(|e| format!("CDN body failed: {e}"))?
+ .to_bytes();
+
+ Ok((body, total))
+}
+
+/// The track to actually download, following Spotify's relinking if the one
+/// asked for is not the one this account can play.
+///
+/// The same walk `player.rs` does before streaming. Without it, the tracks that
+/// are silently swapped on playback would be the tracks that refuse to
+/// download, which is a difference the listener would have no way to explain.
+async fn resolve_item(session: &Session, uri: SpotifyUri) -> Result<AudioItem, String> {
+ let item = AudioItem::get_file(session, uri)
+ .await
+ .map_err(|e| format!("metadata failed: {e}"))?;
+
+ if item.availability.is_err() {
+ return Err("this track is not available on this account".to_string());
+ }
+ if !item.files.is_empty() {
+ return Ok(item);
+ }
+
+ let Some(librespot_metadata::track::Tracks(alternatives)) = item.alternatives.clone() else {
+ return Err("the track has no playable file".to_string());
+ };
+
+ for alternative in alternatives {
+ if let Ok(other) = AudioItem::get_file(session, alternative).await {
+ if other.availability.is_ok() && !other.files.is_empty() {
+ return Ok(other);
+ }
+ }
+ }
+
+ Err("no alternative of this track can be played".to_string())
+}
+
+/// Downloads one track, resuming a part-finished one, and answers with the
+/// sidecar it wrote.
+///
+/// Blocking: this is called from the Kotlin download queue's own worker thread,
+/// which knows nothing about tokio. The runtime handle is taken before
+/// blocking, exactly as the catalogue lookups do, so a download in progress
+/// never holds up play or pause.
+pub fn download_track(uri: &str, kbps: i32) -> EngineResult<String> {
+ let session = engine::with_session(|session| session.clone())?;
+ let uri = uri.to_string();
+ engine::runtime_handle()?.block_on(fetch(session, uri, kbps))
+}
+
+async fn fetch(session: Session, uri_text: String, kbps: i32) -> Result<String, String> {
+ let uri = SpotifyUri::from_uri(&uri_text).map_err(|e| format!("bad uri {uri_text}: {e}"))?;
+ let id = track_key(&uri)?;
+ let root = root().ok_or("downloads have no home yet")?;
+ let audio = audio_path(&root, &id).ok_or("bad download path")?;
+ let meta = meta_path(&root, &id).ok_or("bad download path")?;
+
+ clear_cancel(&id);
+
+ let wanted = format_rank(preferred_formats(kbps)[0]);
+
+ // Already here, and no worse than what was asked for. Answering with the
+ // sidecar rather than an error is what makes the whole feature idempotent:
+ // the queue can re-add a playlist, or two playlists can share a track, and
+ // neither costs anything.
+ if let Some(existing) = read_sidecar(&meta) {
+ let good = existing
+ .get("format")
+ .and_then(Value::as_str)
+ .and_then(format_from_name)
+ .map(|format| format_rank(format) >= wanted)
+ .unwrap_or(false);
+ if good && audio.exists() {
+ return Ok(existing.to_string());
+ }
+ }
+
+ let item = resolve_item(&session, uri.clone()).await?;
+ let (format, file_id) = preferred_formats(kbps)
+ .iter()
+ .find_map(|format| item.files.get(format).map(|file| (*format, *file)))
+ .ok_or("this track exists in no format the app can play")?;
+
+ let track_id: SpotifyId = (&uri)
+ .try_into()
+ .map_err(|_| "not a playable uri".to_string())?;
+ // Spotify hands out one AES key per file, and it refuses them when it
+ // decides a session is asking too fast. That is a fact about the pace of
+ // the queue, not about this track — librespot has already waited and tried
+ // again by the time the error arrives here — so it is reported as its own
+ // thing and the queue answers by slowing down rather than by giving up on
+ // the song. See DownloadQueue, which treats this as a reason to wait.
+ // Timed, and reported in the sidecar. Spotify refuses keys when a session
+ // asks for them faster than it likes, and a refusal costs the whole cool-off
+ // — three of them in a row is half a minute of a download queue doing
+ // nothing. The queue cannot see any of that from here, so this is how it
+ // finds out that it is going too fast; see DownloadQueue's own pacing.
+ // Playback goes first, always.
+ //
+ // Spotify allows a session so many audio keys, and a refusal puts a hold on
+ // the whole session — so a download asking at the wrong moment does not
+ // merely wait its turn, it stops the next track from starting and keeps the
+ // player waiting through the same backoff. Measured while downloading a
+ // playlist: every track loaded for playback was followed by three refusals,
+ // twenty-one seconds of holds, and a queue that crawled.
+ //
+ // So a download waits until playback has been quiet for a while. The
+ // listener never waits for a download; a download always waits for the
+ // listener.
+ loop {
+ if cancelled(&id) {
+ clear_cancel(&id);
+ return Err("cancelled".to_string());
+ }
+ let quiet = librespot_core::audio_key::since_playback_request()
+ .map(|since| since >= PLAYBACK_PRIORITY)
+ .unwrap_or(true);
+ if quiet {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ }
+
+ let key_began = std::time::Instant::now();
+ let audio_key = match session.audio_key().request(track_id, file_id).await {
+ Ok(key) => key,
+ Err(e) => {
+ let refused = matches!(
+ e.error
+ .downcast_ref::<librespot_core::audio_key::AudioKeyError>(),
+ Some(librespot_core::audio_key::AudioKeyError::AesKey)
+ | Some(librespot_core::audio_key::AudioKeyError::Timeout)
+ );
+ return Err(if refused {
+ format!("{KEY_THROTTLED}: {e}")
+ } else {
+ format!("no key for this track: {e}")
+ });
+ }
+ };
+
+ let part = audio.with_extension("part");
+ if let Some(parent) = part.parent() {
+ fs::create_dir_all(parent).map_err(|e| format!("download dir failed: {e}"))?;
+ }
+ let mut done = fs::metadata(&part).map(|meta| meta.len()).unwrap_or(0) as usize;
+ let mut file = fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(&part)
+ .map_err(|e| format!("could not open the download: {e}"))?;
+
+ let mut cdn = CdnUrl::new(file_id)
+ .resolve_audio(&session)
+ .await
+ .map_err(|e| format!("could not find the file: {e}"))?;
+
+ let mut total = 0usize;
+ loop {
+ if cancelled(&id) {
+ clear_cancel(&id);
+ return Err("cancelled".to_string());
+ }
+ if total > 0 && done >= total {
+ break;
+ }
+
+ let mut attempt = 0;
+ let chunk = loop {
+ // Spotify hands out several mirrors for a file. Every one of them
+ // is tried before concluding the problem is the URLs rather than
+ // the mirror, which is what librespot's own opener does.
+ let urls: Vec<String> = cdn
+ .try_get_urls()
+ .map_err(|e| format!("no CDN url: {e}"))?
+ .into_iter()
+ .map(str::to_string)
+ .collect();
+
+ let mut last = "the CDN offered no url".to_string();
+ let mut got = None;
+ for url in &urls {
+ match get_range(&session, url, done, CHUNK).await {
+ Ok(chunk) => {
+ got = Some(chunk);
+ break;
+ }
+ Err(e) => last = e,
+ }
+ }
+ if let Some(chunk) = got {
+ break chunk;
+ }
+
+ attempt += 1;
+ if attempt >= CHUNK_ATTEMPTS {
+ return Err(last);
+ }
+ log::warn!("download of <{uri_text}> stumbled at {done}: {last}; asking again");
+ // A fresh set of URLs, not a fresh wait: a signed URL that expired
+ // while the queue worked through a long playlist is the common
+ // failure here, and sleeping does not fix it.
+ cdn = CdnUrl::new(file_id)
+ .resolve_audio(&session)
+ .await
+ .map_err(|e| format!("could not find the file again: {e}"))?;
+ };
+
+ let (bytes, size) = chunk;
+ total = size;
+ if bytes.is_empty() {
+ break;
+ }
+ file.write_all(&bytes)
+ .map_err(|e| format!("could not write the download: {e}"))?;
+ done += bytes.len();
+
+ // Per mille rather than bytes: the one number the event carries has to
+ // be enough to draw a ring, and the size is not known on the Kotlin
+ // side until the sidecar lands.
+ let permille = if total > 0 {
+ (done as u64 * 1000 / total as u64) as i64
+ } else {
+ 0
+ };
+ engine::emit_app("download_progress", &uri_text, permille.min(1000));
+ }
+
+ file.flush()
+ .map_err(|e| format!("could not finish the download: {e}"))?;
+ drop(file);
+
+ if done < total {
+ return Err(format!("the download stopped short: {done} of {total} bytes"));
+ }
+
+ fs::rename(&part, &audio).map_err(|e| format!("could not store the download: {e}"))?;
+
+ // The same bytes may well be sitting in the 512 MB playback cache from the
+ // last time this track was heard. Keeping both is paying twice for one
+ // song, and the download is the copy that is meant to survive.
+ if let Some(cache) = session.cache() {
+ let _ = cache.remove_file(file_id);
+ }
+
+ let (album, album_artists, artists, number, disc_number) = match item.unique_fields {
+ UniqueFields::Track {
+ album,
+ album_artists,
+ artists,
+ number,
+ disc_number,
+ ..
+ } => {
+ let artists = artists
+ .0
+ .into_iter()
+ .map(|artist| {
+ json!({
+ "name": artist.name,
+ "uri": artist.id.to_uri().unwrap_or_default(),
+ })
+ })
+ .collect::<Vec<_>>();
+ (album, album_artists, artists, number, disc_number)
+ }
+ _ => (String::new(), Vec::new(), Vec::new(), 0, 0),
+ };
+
+ // The biggest cover, kept as a URL. Offline the app reads the copy it
+ // saved beside the track; this is what tells it which one that was, and
+ // what it falls back to the moment there is a connection again.
+ let cover = item
+ .covers
+ .iter()
+ .max_by_key(|cover| cover.width.max(cover.height))
+ .map(|cover| cover.url.clone())
+ .unwrap_or_default();
+
+ let key_wait_ms = key_began.elapsed().as_millis() as u64;
+ let sidecar = json!({
+ "v": 1,
+ "keyWaitMs": key_wait_ms,
+ "uri": uri_text,
+ "trackId": id,
+ "fileId": file_id.to_base16().unwrap_or_default(),
+ "format": format_name(format),
+ "bytes": done,
+ "key": bytes_to_hex(&audio_key.0),
+ "name": item.name,
+ "durationMs": item.duration_ms,
+ "isExplicit": item.is_explicit,
+ "artists": artists,
+ "album": album,
+ "albumArtists": album_artists,
+ "number": number,
+ "discNumber": disc_number,
+ "coverUrl": cover,
+ "downloadedAt": now_ms(),
+ });
+
+ write_sidecar(&meta, &sidecar)?;
+
+ log::info!(
+ "downloaded <{}> as {} ({} bytes)",
+ item.name,
+ format_name(format),
+ done
+ );
+ engine::emit_app("download_done", &uri_text, done as i64);
+
+ Ok(sidecar.to_string())
+}
+
+fn now_ms() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|since| since.as_millis() as u64)
+ .unwrap_or(0)
+}
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 7d8acff..d986c25 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -219,7 +219,26 @@ struct Bundle {
session: Session,
player: Arc<Player>,
/// The Connect device. Every transport command goes through it; see [`load`].
- spirc: Spirc,
+ ///
+ /// `None` for an offline bundle: with no connection there is no device to
+ /// register, no account to publish state to, and nothing on the other end
+ /// of a command. The player is still there, and a downloaded track still
+ /// plays through it — which is the whole of what offline means here.
+ spirc: Option<Spirc>,
+}
+
+impl Bundle {
+ /// The Connect device, or the error a command on a missing one becomes.
+ ///
+ /// Every transport call goes through this rather than testing for offline
+ /// first: the callers already handle a Spirc that refuses — that is what a
+ /// lost device looks like — and refusing is exactly the right answer when
+ /// there is no device at all.
+ fn spirc(&self) -> Result<&Spirc, librespot_core::Error> {
+ self.spirc
+ .as_ref()
+ .ok_or_else(|| librespot_core::Error::unavailable("no connect device: offline"))
+ }
}
/// The inputs to a [`Bundle`], all of them cheap to clone.
@@ -246,6 +265,12 @@ enum Pump {
Session(Session),
/// Something changed on another of the account's devices; see `remote`.
Cluster,
+ /// Something the engine says that the player did not: download progress.
+ ///
+ /// The same channel as everything else so it arrives on the same thread and
+ /// in order with the rest, rather than a second JNI path attaching worker
+ /// threads of its own.
+ App { kind: String, uri: String, value: i64 },
}
/// Errors are flattened to a string because they cross the JNI boundary and the
@@ -391,6 +416,10 @@ pub fn start(
mixer.set_volume(u16::MAX);
let player_config = PlayerConfig {
+ // Downloaded tracks play from the phone. Read on every load rather
+ // 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()),
// 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.
@@ -469,7 +498,30 @@ pub fn start(
cache_dir.to_string(),
);
- let bundle = build_bundle(&rt, &recipe, &mixer, &events_tx)?;
+ // The handshake, and what to do when it cannot be made.
+ //
+ // A failure here used to be the end of the app: no session, no player, no
+ // sound, whatever was already on the phone. With downloads that is the
+ // wrong answer — the music is right there — so a failed connection falls
+ // back to a session that was never connected and a player that only ever
+ // reads from disk. See [`build_offline_bundle`].
+ //
+ // A refused account is not covered: that is Spotify saying no, not the
+ // network being absent, and starting anyway would hide it behind an app
+ // that plays a few downloaded songs and explains nothing.
+ let bundle = match build_bundle(&rt, &recipe, &mixer, &events_tx) {
+ Ok(bundle) => {
+ OFFLINE.store(false, Ordering::SeqCst);
+ bundle
+ }
+ Err(e) if e == PREMIUM_REQUIRED => return Err(e),
+ Err(e) if crate::downloads::any() => {
+ log::warn!("{e}; starting offline with what is on the phone");
+ OFFLINE.store(true, Ordering::SeqCst);
+ build_offline_bundle(&rt, &recipe, &mixer, &events_tx)?
+ }
+ Err(e) => return Err(e),
+ };
*guard = Some(Engine {
rt,
@@ -702,7 +754,86 @@ fn build_bundle(
Ok(Bundle {
session,
player,
- spirc,
+ spirc: Some(spirc),
+ })
+}
+
+/// True while the engine is running on downloads alone.
+///
+/// An atomic rather than a field of the bundle because it is read from the
+/// Kotlin side on any thread, and because it survives the moment between two
+/// bundles: a reconnection that fails leaves this on, which is what stops the
+/// app from offering music it cannot fetch.
+static OFFLINE: AtomicBool = AtomicBool::new(false);
+
+/// Plays one track through the player, with no Connect device in the way.
+///
+/// The offline half of [`load_queue`]. Nothing about the queue changes: the app
+/// still holds the list and still says what comes next, and this is only how
+/// the track that was asked for starts.
+fn local_load(uris: &[String], index: u32, play: bool, position_ms: u32) -> EngineResult<()> {
+ let uri = uris
+ .get(index as usize)
+ .ok_or_else(|| "nothing at that index".to_string())?;
+ let parsed = SpotifyUri::from_uri(uri).map_err(|e| format!("bad uri {uri}: {e}"))?;
+ log::info!("offline: loading {uri} at {position_ms}ms, play={play}");
+ with_bundle(|e| e.player.load(parsed, play, position_ms))
+}
+
+/// Whether the engine came up with no connection; see [`OFFLINE`].
+pub fn is_offline() -> bool {
+ OFFLINE.load(Ordering::SeqCst)
+}
+
+/// A player and a session that never connected, for a phone with no network.
+///
+/// Everything a bundle normally gets from the handshake is missing here, and
+/// that is the point: no Connect device to register, no account to publish
+/// state to, no catalogue. What remains is the player, which is all a
+/// downloaded track needs — [`load_downloaded_track`] reads it off the disk
+/// without asking the session for anything.
+fn build_offline_bundle(
+ rt: &Runtime,
+ recipe: &Recipe,
+ mixer: &Arc<SoftMixer>,
+ events_tx: &std::sync::mpsc::Sender<Pump>,
+) -> EngineResult<Bundle> {
+ let cache = Cache::new(
+ Some(std::path::Path::new(&recipe.credentials_dir)),
+ None,
+ Some(std::path::Path::new(&recipe.cache_dir)),
+ Some(AUDIO_CACHE_LIMIT),
+ )
+ .map_err(|e| format!("cache failed: {e}"))?;
+
+ let generation = GENERATION.fetch_add(1, Ordering::SeqCst) + 1;
+
+ // Inside the runtime, not beside it. `Session::new` registers tasks of its
+ // own the moment it is built, and off a runtime thread that is not an error
+ // but a panic — which, taken while `start` holds the engine lock, poisons it
+ // and leaves every later call answering "engine mutex poisoned". The online
+ // path never hit this because it does all of its building inside a
+ // `block_on`; this one has nothing to await, so it has to say so.
+ let _runtime = rt.enter();
+
+ let session = Session::new(recipe.session_config.clone(), Some(cache));
+ let player = Player::new(
+ recipe.player_config.clone(),
+ session.clone(),
+ mixer.get_soft_volume(),
+ move || Box::new(crate::sink::AndroidSink::new(AudioFormat::S16, generation)),
+ );
+
+ // No `Pump::Session`: history is reported over the session, and this one
+ // cannot carry anything. What was heard offline is kept by the app and
+ // sent when there is a connection again.
+ spawn_event_forwarder(rt, player.clone(), events_tx.clone(), generation);
+ SPIRC_LOST.store(false, Ordering::SeqCst);
+
+ Ok(Bundle {
+ session,
+ player,
+ spirc: None,
})
}
@@ -860,8 +991,10 @@ pub fn reconnect() -> EngineResult<()> {
if let Some(old) = engine.bundle.take() {
log::info!("discarding the old session");
crate::remote::clear();
- let _ = old.spirc.disconnect(true);
- let _ = old.spirc.shutdown();
+ if let Some(spirc) = old.spirc.as_ref() {
+ let _ = spirc.disconnect(true);
+ let _ = spirc.shutdown();
+ }
old.player.stop();
old.session.shutdown();
// The device is emptied here rather than left to the player's own
@@ -871,9 +1004,27 @@ pub fn reconnect() -> EngineResult<()> {
crate::sink::silence();
}
- let bundle = build_bundle(&engine.rt, &engine.recipe, &engine.mixer, &engine.events_tx)?;
+ // The same fallback the first start has, and for a sharper reason: the
+ // old bundle is already gone by this point, so a failure here used to
+ // leave the engine with no bundle at all — no session and no player,
+ // which takes the downloads away too. A retry that cannot reach the
+ // network puts the offline player back instead.
+ let bundle = match build_bundle(&engine.rt, &engine.recipe, &engine.mixer, &engine.events_tx)
+ {
+ Ok(bundle) => {
+ OFFLINE.store(false, Ordering::SeqCst);
+ log::info!("reconnected");
+ bundle
+ }
+ Err(e) if e == PREMIUM_REQUIRED => return Err(e),
+ Err(e) if crate::downloads::any() => {
+ log::warn!("{e}; staying offline with what is on the phone");
+ OFFLINE.store(true, Ordering::SeqCst);
+ build_offline_bundle(&engine.rt, &engine.recipe, &engine.mixer, &engine.events_tx)?
+ }
+ Err(e) => return Err(e),
+ };
engine.bundle = Some(bundle);
- log::info!("reconnected");
Ok(())
})();
RECONNECTING.store(false, Ordering::SeqCst);
@@ -929,6 +1080,12 @@ fn spawn_event_pump(
}
continue;
}
+ Pump::App { kind, uri, value } => {
+ if let Err(e) = emit(&listener, &kind, &uri, value) {
+ log::warn!("dropping {kind}: {e}");
+ }
+ continue;
+ }
Pump::Session(session) => {
match history.as_mut() {
// The listen in progress survives: the same person
@@ -1261,6 +1418,23 @@ fn uri_string(uri: &SpotifyUri) -> String {
uri.to_uri().unwrap_or_default()
}
+/// Says something to the Kotlin listener from outside the player.
+///
+/// Best effort on purpose. A progress tick that cannot be delivered — because
+/// the engine is between two sessions, or because the pump has already been
+/// torn down — is a ring that does not move for a moment. That is not a reason
+/// to fail the download it belongs to.
+pub fn emit_app(kind: &str, uri: &str, value: i64) {
+ let Ok(sender) = with_engine(|engine| engine.events_tx.clone()) else {
+ return;
+ };
+ let _ = sender.send(Pump::App {
+ kind: kind.to_string(),
+ uri: uri.to_string(),
+ value,
+ });
+}
+
/// Invoke `NativeEvents.onEvent` from a tokio worker thread.
fn emit(listener: &GlobalRef, kind: &str, uri: &str, position_ms: i64) -> Result<(), String> {
let vm = JAVA_VM.get().ok_or("JNI_OnLoad did not run")?;
@@ -1420,6 +1594,15 @@ pub fn load_queue(
*stored = uris.clone();
}
+ // Offline there is no Connect device to hand a queue to, so there is no
+ // queue to hand over: the player is given the one track, and the app comes
+ // 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())? {
+ return local_load(&uris, index, start_playing, position_ms);
+ }
+
let options = LoadRequestOptions {
start_playing,
seek_to: position_ms,
@@ -1488,7 +1671,7 @@ pub fn load_queue(
// Without this the device is registered but idle, and a load is
// ignored: playback belongs to whichever device the account has
// active, and taking that over is an explicit step.
- e.spirc.activate()?;
+ e.spirc()?.activate()?;
// Shuffle off before the list goes in, every time.
//
// The order handed over here is the order the app is showing, shuffled
@@ -1500,8 +1683,8 @@ pub fn load_queue(
// The engine then played its own order while the screen followed
// another, so a skip stepped somewhere the listener could not see and
// whole tracks appeared to be missed.
- e.spirc.shuffle(false)?;
- e.spirc.load(request)
+ e.spirc()?.shuffle(false)?;
+ e.spirc()?.load(request)
})?
.inspect_err(|_| {
// A load has no way around Spirc: choosing what to decode next is the
@@ -1560,9 +1743,9 @@ fn transport(
});
}
- if spirc_lost() {
+ if OFFLINE.load(Ordering::SeqCst) || spirc_lost() {
return with_bundle(|engine| {
- log::warn!("{what}: the connect device is gone, going straight to the player");
+ log::warn!("{what}: no connect device, going straight to the player");
via_player(engine);
});
}
@@ -1576,7 +1759,7 @@ fn transport(
// back as an error, so the app saw a pause that had been accepted and a
// player that went on regardless. The load path has taken this step
// since it was written; the transport path never did.
- let _ = engine.spirc.activate();
+ let _ = engine.spirc().map(|spirc| spirc.activate());
via_spirc(engine)
} {
Ok(()) => Ok(()),
@@ -1618,7 +1801,7 @@ pub fn elsewhere_active() -> bool {
return false;
}
- match with_bundle(|bundle| bundle.spirc.is_active()) {
+ match with_bundle(|bundle| bundle.spirc().map(|spirc| spirc.is_active()).unwrap_or(false)) {
Ok(true) => false,
Ok(false) => crate::remote::elsewhere_active(),
Err(_) => crate::remote::elsewhere_active(),
@@ -1638,7 +1821,9 @@ pub fn elsewhere_active() -> bool {
/// the Connect state itself, which is the same thing the other devices are
/// shown.
pub fn playing_here() -> EngineResult<String> {
- let playing = with_bundle(|bundle| bundle.spirc.playing())?;
+ let playing = with_bundle(|bundle| {
+ bundle.spirc().map(|spirc| spirc.playing()).unwrap_or_default()
+ })?;
let escape = |value: &str| serde_json::to_string(value).unwrap_or_else(|_| "\"\"".into());
let tracks: Vec<String> = playing.tracks.iter().map(|uri| escape(uri)).collect();
// `videoId` rides along rather than getting a call of its own: it changes
@@ -1664,7 +1849,7 @@ pub fn play() -> EngineResult<()> {
log::info!("play: another device has playback, ignoring");
return Ok(());
}
- transport("play", |e| e.spirc.play(), |e| e.player.play())
+ transport("play", |e| e.spirc()?.play(), |e| e.player.play())
}
pub fn pause() -> EngineResult<()> {
@@ -1679,7 +1864,7 @@ pub fn pause() -> EngineResult<()> {
// because the music is on another device, costs nothing.
let _ = with_bundle(|engine| engine.player.pause());
- transport("pause", |e| e.spirc.pause(), |e| e.player.pause())
+ transport("pause", |e| e.spirc()?.pause(), |e| e.player.pause())
}
pub fn stop() -> EngineResult<()> {
@@ -1687,11 +1872,11 @@ pub fn stop() -> EngineResult<()> {
// device has given up playback, which is what makes it disappear from the
// device list instead of lingering as a paused phantom. The fallback does
// stop the player, because a stop that leaves audio running is not a stop.
- transport("stop", |e| e.spirc.disconnect(true), |e| e.player.stop())
+ transport("stop", |e| e.spirc()?.disconnect(true), |e| e.player.stop())
}
pub fn seek(position_ms: u32) -> EngineResult<()> {
- with_bundle(|e| e.spirc.set_position_ms(position_ms))?.map_err(|e| format!("seek failed: {e}"))
+ with_bundle(|e| e.spirc()?.set_position_ms(position_ms))?.map_err(|e| format!("seek failed: {e}"))
}
// Skipping is a Spirc command like the rest, and it was the one left out of
@@ -1702,12 +1887,12 @@ pub fn seek(position_ms: u32) -> EngineResult<()> {
// that is certainly wrong: the listener asked for something else.
pub fn next() -> EngineResult<()> {
leaving();
- transport("next", |e| e.spirc.next(), |e| e.player.stop())
+ transport("next", |e| e.spirc()?.next(), |e| e.player.stop())
}
pub fn previous() -> EngineResult<()> {
leaving();
- transport("previous", |e| e.spirc.prev(), |e| e.player.stop())
+ transport("previous", |e| e.spirc()?.prev(), |e| e.player.stop())
}
@@ -1778,8 +1963,8 @@ pub fn publish_context(position_ms: u32) -> EngineResult<bool> {
);
with_bundle(|e| {
- e.spirc.activate()?;
- e.spirc.load(request)
+ e.spirc()?.activate()?;
+ e.spirc()?.load(request)
})?
.map_err(|e| format!("could not republish the context: {e}"))?;
Ok(true)
@@ -1819,8 +2004,8 @@ pub fn resume_here(context_uri: &str, track_uri: &str, position_ms: u32) -> Engi
);
with_bundle(|e| {
- e.spirc.activate()?;
- e.spirc.load(request)
+ e.spirc()?.activate()?;
+ e.spirc()?.load(request)
})?
.map_err(|e| format!("could not resume here: {e}"))
}
@@ -1832,7 +2017,7 @@ pub fn resume_here(context_uri: &str, track_uri: &str, position_ms: u32) -> Engi
/// a command sent from a device to itself goes out to the access point and
/// comes back refused. Activating is the same thing done directly.
pub fn take_over() -> EngineResult<()> {
- with_bundle(|e| e.spirc.activate())?.map_err(|e| format!("could not take over: {e}"))
+ with_bundle(|e| e.spirc()?.activate())?.map_err(|e| format!("could not take over: {e}"))
}
/// Hands the device a new running order without touching what is playing.
@@ -1853,19 +2038,19 @@ pub fn set_queue_order(uris: Vec<String>, index: u32) -> EngineResult<()> {
*stored = uris;
}
- with_bundle(|e| e.spirc.set_queue_tracks(prev, next))?
+ with_bundle(|e| e.spirc()?.set_queue_tracks(prev, next))?
.map_err(|e| format!("queue order failed: {e}"))
}
pub fn set_shuffle(shuffle: bool) -> EngineResult<()> {
- with_bundle(|e| e.spirc.shuffle(shuffle))?.map_err(|e| format!("shuffle failed: {e}"))
+ with_bundle(|e| e.spirc()?.shuffle(shuffle))?.map_err(|e| format!("shuffle failed: {e}"))
}
/// `repeat_track` takes precedence: the two are separate flags in the protocol.
pub fn set_repeat(repeat_context: bool, repeat_track: bool) -> EngineResult<()> {
with_bundle(|e| {
- e.spirc.repeat_track(repeat_track)?;
- e.spirc.repeat(repeat_context)
+ e.spirc()?.repeat_track(repeat_track)?;
+ e.spirc()?.repeat(repeat_context)
})?
.map_err(|e| format!("repeat failed: {e}"))
}
@@ -1895,6 +2080,13 @@ pub fn volume() -> EngineResult<u16> {
/// of a handshake, and both are asked from the playback looper: waiting there
/// would be seconds of a frozen app for a question that has an answer already.
pub fn spirc_lost() -> bool {
+ // Offline there is no device to lose, and saying one was lost would send
+ // the Kotlin side off rebuilding a session every thirty seconds against a
+ // network that is not there. The app is told it is offline instead, which
+ // is a different question with a different answer; see [`is_offline`].
+ if OFFLINE.load(Ordering::SeqCst) {
+ return false;
+ }
if RECONNECTING.load(Ordering::SeqCst) {
// True in the strict sense: there is no device at this instant. It is
// also the useful answer, because a command issued now would find no
@@ -1908,7 +2100,9 @@ pub fn spirc_lost() -> bool {
}
pub fn is_connected() -> bool {
- !RECONNECTING.load(Ordering::SeqCst) && session_invalid().map(|bad| !bad) == Some(true)
+ !OFFLINE.load(Ordering::SeqCst)
+ && !RECONNECTING.load(Ordering::SeqCst)
+ && session_invalid().map(|bad| !bad) == Some(true)
}
/// Whether the current session has been invalidated, or `None` if asking would
@@ -1930,8 +2124,10 @@ pub fn shutdown() {
// Told to the account before the socket goes: a device that
// vanishes without disconnecting stays in the user's list until it
// times out.
- let _ = bundle.spirc.disconnect(true);
- let _ = bundle.spirc.shutdown();
+ if let Some(spirc) = bundle.spirc.as_ref() {
+ let _ = spirc.disconnect(true);
+ let _ = spirc.shutdown();
+ }
bundle.player.stop();
bundle.session.shutdown();
}
diff --git a/native/src/ffi.rs b/native/src/ffi.rs
index cd68c7b..643611d 100644
--- a/native/src/ffi.rs
+++ b/native/src/ffi.rs
@@ -4,7 +4,7 @@
//! `java.lang.IllegalStateException` with the engine's error message. Kotlin
//! therefore never has to check return codes.
-use crate::{catalog, engine, sink};
+use crate::{catalog, downloads, engine, sink};
use jni::objects::{JClass, JObject, JString};
use jni::sys::{jboolean, jint, jlong, jstring, JNI_FALSE, JNI_TRUE};
use jni::JNIEnv;
@@ -734,3 +734,89 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeShu
) {
let _ = std::panic::catch_unwind(engine::shutdown);
}
+
+/// True when the engine came up with no connection and is running on the
+/// downloads alone; see `engine::is_offline`.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeIsOffline(
+ _env: JNIEnv,
+ _class: JClass,
+) -> jboolean {
+ if engine::is_offline() { JNI_TRUE } else { JNI_FALSE }
+}
+
+// --------------------------------------------------------------- downloads
+
+/// Where downloads are kept. Called before anything is downloaded, and again
+/// if the listener moves the store to a memory card.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeSetDownloadRoot(
+ mut env: JNIEnv,
+ _class: JClass,
+ path: JString,
+) {
+ let path = read_string(&mut env, &path);
+ guard(&mut env, "SetDownloadRoot", || downloads::set_root(&path?));
+}
+
+/// Downloads one track and answers with the sidecar that was written.
+///
+/// Blocks for as long as the download takes, which is why the Kotlin side calls
+/// it from the download queue's own worker rather than from anything the
+/// listener is waiting on.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeDownloadTrack(
+ mut env: JNIEnv,
+ _class: JClass,
+ track_uri: JString,
+ bitrate_kbps: jint,
+) -> jstring {
+ let uri = match read_string(&mut env, &track_uri) {
+ Ok(value) => value,
+ Err(message) => {
+ let _ = env.throw_new(EXCEPTION, message);
+ return JObject::null().into_raw() as jstring;
+ }
+ };
+ guard_string(&mut env, "DownloadTrack", || {
+ downloads::download_track(&uri, bitrate_kbps)
+ })
+}
+
+/// The sidecar of a downloaded track as JSON, or `null` if it is not here.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeDownloadState(
+ mut env: JNIEnv,
+ _class: JClass,
+ track_uri: JString,
+) -> jstring {
+ let uri = match read_string(&mut env, &track_uri) {
+ Ok(value) => value,
+ Err(message) => {
+ let _ = env.throw_new(EXCEPTION, message);
+ return JObject::null().into_raw() as jstring;
+ }
+ };
+ guard_string(&mut env, "DownloadState", || downloads::stored(&uri))
+}
+
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeRemoveDownload(
+ mut env: JNIEnv,
+ _class: JClass,
+ track_uri: JString,
+) {
+ let uri = read_string(&mut env, &track_uri);
+ guard(&mut env, "RemoveDownload", || downloads::remove_track(&uri?));
+}
+
+/// Asks a download in progress to stop at the end of its current chunk.
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeCancelDownload(
+ mut env: JNIEnv,
+ _class: JClass,
+ track_uri: JString,
+) {
+ let uri = read_string(&mut env, &track_uri);
+ guard(&mut env, "CancelDownload", || downloads::cancel(&uri?));
+}
diff --git a/native/src/lib.rs b/native/src/lib.rs
index 062d734..40c3224 100644
--- a/native/src/lib.rs
+++ b/native/src/lib.rs
@@ -6,6 +6,7 @@
//! ownership to reason about.
mod catalog;
+mod downloads;
mod engine;
mod events;
mod ffi;
diff --git a/native/vendor/librespot-core/src/audio_key.rs b/native/vendor/librespot-core/src/audio_key.rs
index aefcf97..08f0ed3 100644
--- a/native/vendor/librespot-core/src/audio_key.rs
+++ b/native/vendor/librespot-core/src/audio_key.rs
@@ -1,6 +1,7 @@
use std::{
collections::HashMap,
io::Write,
+ sync::Mutex,
time::{Duration, Instant},
};
@@ -64,6 +65,32 @@ component! {
///
/// So a refusal puts the whole session on hold, doubling until the cap, and one
/// key that comes back clears it.
+/// LOCAL PATCH: when playback last asked for a key.
+///
+/// Spotify limits audio keys per session, and a download queue asking for one
+/// spends the same allowance a track starting needs. Without somewhere to look
+/// this up, a library being downloaded quietly starved playback: the queue took
+/// the refusals, the session-wide hold that follows them applied to everything,
+/// and pressing play did nothing for half a minute.
+///
+/// Only playback writes here. Downloads read it and wait; see `downloads.rs`.
+static PLAYBACK_AT: Mutex<Option<Instant>> = Mutex::new(None);
+
+/// Called by the player before it asks for a key.
+pub fn note_playback_request() {
+ if let Ok(mut at) = PLAYBACK_AT.lock() {
+ *at = Some(Instant::now());
+ }
+}
+
+/// How long ago playback last asked, or `None` if it never has.
+pub fn since_playback_request() -> Option<Duration> {
+ PLAYBACK_AT
+ .lock()
+ .ok()?
+ .map(|at| Instant::now().saturating_duration_since(at))
+}
+
const FIRST_COOL_OFF: Duration = Duration::from_secs(3);
const MAX_COOL_OFF: Duration = Duration::from_secs(30);
diff --git a/native/vendor/librespot-playback/src/config.rs b/native/vendor/librespot-playback/src/config.rs
index 057442a..20757ca 100644
--- a/native/vendor/librespot-playback/src/config.rs
+++ b/native/vendor/librespot-playback/src/config.rs
@@ -1,8 +1,54 @@
-use std::{mem, path::PathBuf, str::FromStr, time::Duration};
+use std::{mem, path::PathBuf, str::FromStr, sync::Arc, time::Duration};
+
+use librespot_core::SpotifyId;
+use librespot_metadata::audio::AudioFileFormat;
pub use crate::dither::{DithererBuilder, TriangularDitherer, mk_ditherer};
use crate::{convert::i24, player::duration_to_coefficient};
+/// LOCAL PATCH: a copy of a track kept on disk, to be played instead of fetched.
+///
+/// The bytes are the file exactly as the CDN served it — still encrypted with
+/// the per-file AES key, which travels here beside them. Keeping it that way is
+/// not caution for its own sake: it means the loader can hand the file to the
+/// same `AudioDecrypt` the streaming path uses, and everything after that point
+/// — the Ogg header offset, the normalisation packet, the decoder, the
+/// crossfade — is byte for byte the code that already runs. A decrypted file
+/// would have needed a second path through all of it.
+///
+/// Everything except `path` and `key` is metadata the loader would otherwise
+/// have asked the network for. It is here so a downloaded track can be loaded
+/// with no connection at all.
+#[derive(Clone)]
+pub struct DownloadedTrack {
+ pub path: PathBuf,
+ /// `None` for the rare unencrypted file, matching `AudioDecrypt`'s own
+ /// convention that a missing key means "pass the bytes through".
+ pub key: Option<[u8; 16]>,
+ pub format: AudioFileFormat,
+ pub name: String,
+ pub duration_ms: u32,
+ pub is_explicit: bool,
+ pub album: String,
+ pub album_artists: Vec<String>,
+ pub number: u32,
+ pub disc_number: u32,
+}
+
+/// LOCAL PATCH: how the player asks whether a track has been downloaded.
+///
+/// A closure rather than a map because the answer lives on disk, and disk is
+/// the only place it can be correct: downloads are written by another thread,
+/// finished with an atomic rename, and removed while the player is running. A
+/// map handed over at build time would go stale within seconds of the first
+/// download, and keeping one in step would mean a lock on the hot path of every
+/// load. Reading a small file is cheaper than being wrong.
+///
+/// Owning the closure also keeps the sidecar format in one place — the engine
+/// writes it and the engine parses it — instead of teaching this crate a JSON
+/// schema it has no other reason to know.
+pub type DownloadLookup = Arc<dyn Fn(&SpotifyId) -> Option<DownloadedTrack> + Send + Sync>;
+
#[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq, Default)]
pub enum Bitrate {
Bitrate96,
@@ -130,6 +176,11 @@ pub struct PlayerConfig {
/// Zero, the default, is upstream behaviour: tracks follow one another with
/// nothing between them. See `player.rs`.
pub crossfade_duration_ms: u32,
+
+ /// LOCAL PATCH: where the loader asks whether a track is already on disk.
+ ///
+ /// `None`, the default, is upstream behaviour: every track is fetched.
+ pub download_lookup: Option<DownloadLookup>,
}
impl Default for PlayerConfig {
@@ -150,6 +201,7 @@ impl Default for PlayerConfig {
position_update_interval: None,
local_file_directories: Vec::new(),
crossfade_duration_ms: 0,
+ download_lookup: None,
}
}
}
diff --git a/native/vendor/librespot-playback/src/player.rs b/native/vendor/librespot-playback/src/player.rs
index 678ff74..8da2723 100644
--- a/native/vendor/librespot-playback/src/player.rs
+++ b/native/vendor/librespot-playback/src/player.rs
@@ -1112,6 +1112,23 @@ impl PlayerTrackLoader {
) -> Option<PlayerLoadedTrackData> {
match track_uri {
SpotifyUri::Track { .. } | SpotifyUri::Episode { .. } => {
+ // LOCAL PATCH: a downloaded track is played from disk.
+ //
+ // Before anything else, because the point of the branch is that
+ // it touches nothing: no metadata request, no storage resolve,
+ // no audio key, no CDN. That is what makes a downloaded track
+ // start instantly on a bad connection and play at all on none.
+ //
+ // A failure here falls through to the network rather than
+ // failing the load. The file could have been removed between
+ // the lookup and the open, or be a truncated leftover from a
+ // crash mid-write; either way the track is still playable the
+ // ordinary way, and the alternative is a song that refuses to
+ // play because of a housekeeping problem the listener cannot
+ // see.
+ if let Some(loaded) = self.load_downloaded_track(&track_uri, position_ms) {
+ return Some(loaded);
+ }
self.load_remote_track(track_uri, position_ms).await
}
SpotifyUri::Local { .. } => self.load_local_track(track_uri, position_ms).await,
@@ -1122,6 +1139,179 @@ impl PlayerTrackLoader {
}
}
+ /// LOCAL PATCH: loads a track from the copy the engine has downloaded.
+ ///
+ /// Deliberately not `async`: there is nothing here to await. Every step is
+ /// a local file operation, which is the whole reason this path exists.
+ ///
+ /// Below the first few lines it is the streaming path, unchanged — and it
+ /// is unchanged on purpose. The downloaded file is the file the CDN served,
+ /// still encrypted, so the same `AudioDecrypt` runs over it, the Ogg header
+ /// still ends at the same offset, and the normalisation packet is still
+ /// read out of the same place. Anything that behaved differently when a
+ /// track is downloaded would be a bug the listener hears.
+ ///
+ /// Returns `None` when there is no download for this track — the ordinary
+ /// answer — and also when there is one that cannot be read, so the caller
+ /// falls back to the network.
+ fn load_downloaded_track(
+ &self,
+ track_uri: &SpotifyUri,
+ position_ms: u32,
+ ) -> Option<PlayerLoadedTrackData> {
+ let lookup = self.config.download_lookup.as_ref()?;
+ let track_id: SpotifyId = track_uri.try_into().ok()?;
+ let downloaded = lookup(&track_id)?;
+
+ let began = Instant::now();
+
+ let file = match File::open(&downloaded.path) {
+ Ok(file) => file,
+ Err(e) => {
+ warn!(
+ "download for <{}> could not be opened, fetching it instead: {e}",
+ downloaded.name
+ );
+ return None;
+ }
+ };
+ let file_size = match file.metadata() {
+ Ok(meta) => meta.len(),
+ Err(e) => {
+ warn!("download for <{}> has no size: {e}", downloaded.name);
+ return None;
+ }
+ };
+
+ let key = downloaded.key.map(librespot_core::audio_key::AudioKey);
+ let mut decrypted_file = AudioDecrypt::new(key, file);
+
+ let is_ogg_vorbis = AudioFiles::is_ogg_vorbis(downloaded.format);
+ let (offset, mut normalisation_data) = if is_ogg_vorbis {
+ let normalisation_data = NormalisationData::parse_from_ogg(&mut decrypted_file).ok();
+ (SPOTIFY_OGG_HEADER_END, normalisation_data)
+ } else {
+ (0, None)
+ };
+
+ let audio_file = match Subfile::new(decrypted_file, offset, file_size) {
+ Ok(audio_file) => audio_file,
+ Err(e) => {
+ warn!("download for <{}> is too short to play: {e}", downloaded.name);
+ return None;
+ }
+ };
+
+ let mut hint = Hint::new();
+ if let Some(mime_type) = AudioFiles::mime_type(downloaded.format) {
+ hint.mime_type(mime_type);
+ }
+
+ let mut decoder: Decoder = match SymphoniaDecoder::new(audio_file, hint) {
+ Ok(mut decoder) => {
+ // Same as the streaming path: outside Ogg Vorbis the loudness
+ // comes from ReplayGain tags rather than Spotify's own packet.
+ if normalisation_data.is_none() {
+ normalisation_data = decoder.normalisation_data();
+ }
+ Box::new(decoder)
+ }
+ Err(e) => {
+ // A file that will not decode is a broken download, not a
+ // broken track. Say so and let the caller stream it.
+ warn!(
+ "download for <{}> will not decode, fetching it instead: {e}",
+ downloaded.name
+ );
+ return None;
+ }
+ };
+
+ let duration_ms = downloaded.duration_ms;
+ let position_ms = if position_ms > duration_ms {
+ warn!(
+ "Invalid start position of {position_ms} ms exceeds track's duration of {duration_ms} ms, starting track from the beginning"
+ );
+ 0
+ } else {
+ position_ms
+ };
+
+ // Unlike the streaming path this seek is cheap — symphonia's bisection
+ // reads from disk, not from the CDN — but it is still skipped at the
+ // start of a track, where a fresh decoder already sits on the first
+ // audio packet.
+ let stream_position_ms = if position_ms == 0 {
+ 0
+ } else {
+ match decoder.seek(position_ms) {
+ Ok(new_position_ms) => new_position_ms,
+ Err(e) => {
+ error!(
+ "PlayerTrackLoader::load_downloaded_track error seeking to starting position {position_ms}: {e}"
+ );
+ return None;
+ }
+ }
+ };
+
+ // Only used to pace the fetcher, which has nothing to fetch here. Kept
+ // honest anyway because the sink reads it, and guarded because a
+ // sub-second track would divide by zero.
+ let bytes_per_second = if duration_ms > 0 {
+ (file_size as u128 * 1000 / duration_ms as u128) as usize
+ } else {
+ file_size as usize
+ };
+
+ info!(
+ "<{}> ({} ms) loaded in {} ms, from a download",
+ downloaded.name,
+ duration_ms,
+ began.elapsed().as_millis(),
+ );
+
+ Some(PlayerLoadedTrackData {
+ decoder,
+ normalisation_data: normalisation_data.unwrap_or_else(|| {
+ warn!("Unable to get normalisation data, continuing with defaults.");
+ NormalisationData::default()
+ }),
+ stream_loader_controller: StreamLoaderController::from_local_file(file_size),
+ bytes_per_second,
+ duration_ms,
+ stream_position_ms,
+ is_explicit: downloaded.is_explicit,
+ audio_item: AudioItem {
+ duration_ms,
+ uri: track_uri.to_uri().unwrap_or_default(),
+ track_id: track_uri.clone(),
+ // Empty because this item is never fetched: naming the files
+ // the track exists in would describe what is on the CDN, not
+ // what is being played.
+ files: Default::default(),
+ name: downloaded.name,
+ covers: vec![],
+ language: vec![],
+ is_explicit: downloaded.is_explicit,
+ availability: Ok(()),
+ alternatives: None,
+ unique_fields: UniqueFields::Track {
+ // Names only, and the roles are not kept: the app draws its
+ // track lists from its own catalogue rather than from the
+ // player, and the one field anything downstream reads out
+ // of an `AudioItem` is the duration.
+ artists: Default::default(),
+ album: downloaded.album,
+ album_artists: downloaded.album_artists,
+ popularity: 0,
+ number: downloaded.number,
+ disc_number: downloaded.disc_number,
+ },
+ },
+ })
+ }
+
async fn load_remote_track(
&self,
track_uri: SpotifyUri,
@@ -1258,6 +1448,11 @@ impl PlayerTrackLoader {
// treated this way; any other key failure keeps upstream's
// behaviour, since a file that is genuinely unencrypted has to go
// on playing.
+ // LOCAL PATCH: said before asking, so a download queue running
+ // alongside knows to keep out of the way. Audio keys are limited
+ // per session, and a queue spending that allowance is a queue
+ // stopping the music from starting; see `downloads.rs`.
+ librespot_core::audio_key::note_playback_request();
let key = match self.session.audio_key().request(track_id, file_id).await {
Ok(key) => Some(key),
Err(e) => {