diff --git a/assets/icons/circle-check.svg b/assets/icons/circle-check.svg
new file mode 100644
index 0000000..49afe81
--- /dev/null
+++ b/assets/icons/circle-check.svg
@@ -0,0 +1,16 @@
+
+
+
+
+
diff --git a/assets/icons/download.svg b/assets/icons/download.svg
new file mode 100644
index 0000000..2977130
--- /dev/null
+++ b/assets/icons/download.svg
@@ -0,0 +1,17 @@
+
+
+
+
+
+
diff --git a/assets/icons/wifi-off.svg b/assets/icons/wifi-off.svg
new file mode 100644
index 0000000..6e9129c
--- /dev/null
+++ b/assets/icons/wifi-off.svg
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/core/src/main/java/it/panov/musyx/api/Models.kt b/core/src/main/java/it/panov/musyx/api/Models.kt
index bff4484..faed7e6 100644
--- a/core/src/main/java/it/panov/musyx/api/Models.kt
+++ b/core/src/main/java/it/panov/musyx/api/Models.kt
@@ -3,6 +3,11 @@
package it.panov.musyx.api
import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.buildJsonArray
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import kotlinx.serialization.json.putJsonObject
/** Absolute URL for a `%%`-templated image uri at `size`×`size` pixels. */
fun coverUrl(uri: String?, size: Int): String? {
@@ -21,6 +26,12 @@ fun joinNames(artists: List): String? =
data class ArtistRef(val id: Long?, val name: String, private val coverUri: String? = null) {
fun coverUrl(size: Int): String? = coverUrl(coverUri, size)
+
+ internal fun toJson(): JsonObject = buildJsonObject {
+ id?.let { put("id", it) }
+ put("name", name)
+ coverUri?.let { putJsonObject("cover") { put("uri", it) } }
+ }
}
data class AlbumRef(val id: Long, val title: String, val year: Int? = null)
@@ -55,6 +66,29 @@ data class Track(
val hues: Pair get() = CoverHues.track(id, album?.id)
+ /** The track in the API's own shape, so [from] reads it back; for keeping it on disk. */
+ fun toJson(): JsonObject = buildJsonObject {
+ put("id", id)
+ put("title", title)
+ version?.let { put("version", it) }
+ put("artists", buildJsonArray { artists.forEach { add(it.toJson()) } })
+ album?.let { a ->
+ put("albums", buildJsonArray {
+ add(buildJsonObject {
+ put("id", a.id)
+ put("title", a.title)
+ a.year?.let { put("year", it) }
+ })
+ })
+ }
+ put("durationMs", durationMs)
+ coverUri?.let { put("coverUri", it) }
+ put("available", available)
+ put("explicit", explicit)
+ put("lyricsAvailable", lyricsAvailable)
+ if (spoken) put("type", "podcast-episode")
+ }
+
companion object {
fun from(t: JsonElement?): Track? {
val id = t.str("id") ?: return null
diff --git a/core/src/main/java/it/panov/musyx/api/Transport.kt b/core/src/main/java/it/panov/musyx/api/Transport.kt
index 12316f1..2ecfdad 100644
--- a/core/src/main/java/it/panov/musyx/api/Transport.kt
+++ b/core/src/main/java/it/panov/musyx/api/Transport.kt
@@ -15,6 +15,7 @@ import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
+import java.io.InputStream
import java.util.concurrent.TimeUnit
import kotlin.random.Random
@@ -111,6 +112,19 @@ internal class Transport(private val token: String?, val language: ContentLangua
}
}
+ /** A streamed fetch (audio files), handed to `read` on an IO thread. No retry. */
+ suspend fun file(url: String, read: (InputStream, Long) -> T): T = withContext(Dispatchers.IO) {
+ val request = Request.Builder().url(url).identity(url).get().build()
+ try {
+ Http.client.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) throw statusError(response.code, JsonNull, url.toHttpUrl().encodedPath)
+ read(response.body.byteStream(), response.body.contentLength())
+ }
+ } catch (e: IOException) {
+ throw YmError.Network(e.message ?: e.javaClass.simpleName)
+ }
+ }
+
private suspend fun send(request: Request): JsonElement = withContext(Dispatchers.IO) {
try {
Http.api.newCall(request).execute().use { response ->
diff --git a/core/src/main/java/it/panov/musyx/api/YmClient.kt b/core/src/main/java/it/panov/musyx/api/YmClient.kt
index 40a31ba..fc2540e 100644
--- a/core/src/main/java/it/panov/musyx/api/YmClient.kt
+++ b/core/src/main/java/it/panov/musyx/api/YmClient.kt
@@ -11,6 +11,7 @@ import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
+import java.io.InputStream
/** How many featured podcasts to resolve. */
const val FEATURED_PODCASTS = 48
@@ -101,6 +102,9 @@ class YmClient private constructor(
return stream(trackId, null)
}
+ /** Reads the file at `url`, a link from [stream] or [losslessStream], as its host sends it. */
+ suspend fun file(url: String, read: (InputStream, contentLength: Long) -> T): T = http.file(url, read)
+
// ---- Library ----
/** Albums the user liked, newest first, with full details. */
diff --git a/core/src/main/java/it/panov/musyx/data/Downloads.kt b/core/src/main/java/it/panov/musyx/data/Downloads.kt
new file mode 100644
index 0000000..c22feab
--- /dev/null
+++ b/core/src/main/java/it/panov/musyx/data/Downloads.kt
@@ -0,0 +1,508 @@
+// Music kept on the device for listening offline: single tracks, and whole albums, playlists
+// and liked tracks. What's wanted is written down first and fetched after, one file at a
+// time, so a download cut short by a lost connection or a killed app carries on later.
+// Files are stored decrypted, so they play like any local file. Everything here runs on
+// the main thread except the file work, which hops to IO.
+package it.panov.musyx.data
+
+import android.content.Context
+import android.util.Log
+import androidx.compose.runtime.Immutable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import it.panov.musyx.api.Stream
+import it.panov.musyx.api.Track
+import it.panov.musyx.api.YmClient
+import it.panov.musyx.api.YmError
+import it.panov.musyx.player.ctrCipher
+import it.panov.musyx.player.hexKey
+import it.panov.musyx.player.resolveStream
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.NonCancellable
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import java.io.File
+import java.io.FileOutputStream
+import java.io.InputStream
+import java.security.MessageDigest
+
+/** A downloaded track: its metadata, and its file once fetched. */
+@Immutable
+data class OfflineTrack(
+ val track: Track,
+ /** The file's name in the downloads folder; null while it's still to be fetched. */
+ val file: String? = null,
+ val codec: String = "",
+ val bitrateKbps: Int = 0,
+ val bytes: Long = 0,
+) {
+ val done: Boolean get() = file != null
+}
+
+/** An album, a playlist or liked tracks, downloaded as a whole. */
+@Immutable
+data class OfflineSet(
+ /** [Downloads.albumKey], [Downloads.playlistKey] or [Downloads.LIKED]. */
+ val key: String,
+ val title: String,
+ val cover: String?,
+ val hues: Pair,
+ val trackIds: List,
+) {
+ val kind: Kind
+ get() = when {
+ key == Downloads.LIKED -> Kind.Liked
+ key.startsWith(ALBUM) -> Kind.Album
+ else -> Kind.Playlist
+ }
+
+ enum class Kind { Album, Playlist, Liked }
+}
+
+/** Where the current run stands, for a notification. */
+data class DownloadProgress(val done: Int, val total: Int, val title: String?)
+
+private const val ALBUM = "album:"
+private const val PLAYLIST = "playlist:"
+/** Network failures in a row before waiting for the connection to come back. */
+private const val MAX_STRIKES = 3
+
+class Downloads(
+ context: Context,
+ private val scope: CoroutineScope,
+ private val client: () -> YmClient?,
+ private val quality: () -> Quality,
+ /** Cover sizes the interface asks for, kept beside the files. */
+ private val coverSizes: List = emptyList(),
+) {
+ private val dir = File(context.filesDir, "offline")
+ private val coverDir = File(dir, "covers")
+ private val indexFile = File(dir, "index.json")
+
+ /** Writes the index one at a time, in the order asked. */
+ @OptIn(ExperimentalCoroutinesApi::class)
+ private val writer = Dispatchers.IO.limitedParallelism(1)
+
+ /** Every track wanted, in the order it was asked for. */
+ var tracks: Map by mutableStateOf(emptyMap())
+ private set
+ /** Tracks downloaded on their own, not as part of a set. */
+ var singles: List by mutableStateOf(emptyList())
+ private set
+ var sets: List by mutableStateOf(emptyList())
+ private set
+ /** The track being fetched and how far along it is, 0 to 1. */
+ var current: Pair? by mutableStateOf(null)
+ private set
+ /** Tracks that couldn't be fetched this run; tried again on [retry] or the next launch. */
+ var failed: Set by mutableStateOf(emptySet())
+ private set
+ /** The index has been read from disk. */
+ var loaded: Boolean by mutableStateOf(false)
+ private set
+
+ /** Hears when a run starts, moves to the next track, or ends (null). On the main thread. */
+ var onProgress: ((DownloadProgress?) -> Unit)? = null
+
+ /** The account the files belong to; another account signing in starts afresh. */
+ private var uid: Long? = null
+ private var pendingUid: Long? = null
+ private var job: Job? = null
+ /** Tracks fetched since the current run started, for the notification's count. */
+ private var fetchedThisRun = 0
+
+ init {
+ scope.launch {
+ val index = withContext(writer) { readIndex() }
+ if (index != null) {
+ uid = index.uid
+ tracks = index.tracks.mapNotNull { (id, saved) -> saved.toOffline()?.let { id to it } }.toMap()
+ singles = index.singles
+ sets = index.sets.map { it.toOffline() }
+ }
+ loaded = true
+ pendingUid?.let { attach(it) } ?: kick()
+ }
+ }
+
+ // ---- Reading ----
+
+ val hasAny: Boolean get() = tracks.isNotEmpty()
+
+ /** Downloaded tracks, newest first. */
+ val doneTracks: List get() = tracks.values.filter { it.done }.map { it.track }.asReversed()
+
+ val bytes: Long get() = tracks.values.sumOf { it.bytes }
+
+ /** Tracks still to fetch, not counting failures. */
+ val queued: Int get() = tracks.count { (id, t) -> !t.done && id !in failed }
+
+ fun isDone(trackId: String): Boolean = tracks[trackId]?.done == true
+
+ fun isWanted(trackId: String): Boolean = trackId in tracks
+
+ fun set(key: String): OfflineSet? = sets.firstOrNull { it.key == key }
+
+ /** A set's tracks, in its own order. */
+ fun tracksOf(set: OfflineSet): List = set.trackIds.mapNotNull { tracks[it]?.track }
+
+ /** How many of a set's tracks are on the device, of how many. */
+ fun progressOf(set: OfflineSet): Pair = set.trackIds.count { isDone(it) } to set.trackIds.size
+
+ /** A downloaded track as a stream to play; null when it isn't on the device. */
+ fun stream(trackId: String): Stream? {
+ val t = tracks[trackId] ?: return null
+ val file = File(dir, t.file ?: return null)
+ if (!file.isFile) return null
+ return Stream(listOf(file.toURI().toString()), t.codec, t.bitrateKbps, preview = false, key = null)
+ }
+
+ /** The kept copy of a cover, when there is one. */
+ fun coverFile(url: String): File? = File(coverDir, coverName(url)).takeIf { it.isFile }
+
+ // ---- Changing ----
+
+ /** The account signed in: fetching may start, and another account's downloads go. */
+ fun attach(uid: Long) {
+ if (!loaded) {
+ pendingUid = uid
+ return
+ }
+ pendingUid = null
+ if (this.uid != null && this.uid != uid) clear()
+ if (this.uid != uid) {
+ this.uid = uid
+ save()
+ }
+ kick()
+ }
+
+ fun addTrack(track: Track) {
+ if (!track.available) return
+ if (track.id !in singles) singles = singles + track.id
+ want(listOf(track))
+ }
+
+ /** Downloads `list` as the set `key`, or brings a downloaded set up to date with it. */
+ fun addSet(key: String, title: String, cover: String?, hues: Pair, list: List) {
+ val playable = list.filter { it.available }.distinctBy { it.id }
+ val set = OfflineSet(key, title, cover, hues, playable.map { it.id })
+ sets = sets.filter { it.key != key } + set
+ want(playable)
+ prune()
+ // The set's own cover, which no track shares.
+ val c = client()
+ if (cover != null && c != null && coverFile(cover) == null) scope.launch { saveCovers(c, listOf(cover)) }
+ }
+
+ /** Keeps a downloaded set in step with the tracks it has now; nothing if it isn't downloaded. */
+ fun sync(key: String, list: List) {
+ val set = set(key) ?: return
+ val ids = list.filter { it.available }.map { it.id }.distinct()
+ if (ids == set.trackIds) return
+ addSet(key, set.title, set.cover, set.hues, list)
+ }
+
+ fun removeSet(key: String) {
+ sets = sets.filter { it.key != key }
+ prune()
+ }
+
+ /** Removes a track's file, wherever it was downloaded from. */
+ fun removeTrack(trackId: String) {
+ singles = singles - trackId
+ sets = sets.map { s -> if (trackId in s.trackIds) s.copy(trackIds = s.trackIds - trackId) else s }
+ prune()
+ }
+
+ fun clear() {
+ job?.cancel()
+ tracks = emptyMap()
+ singles = emptyList()
+ sets = emptyList()
+ failed = emptySet()
+ current = null
+ save()
+ scope.launch(writer) { dir.listFiles()?.forEach { if (it != indexFile) it.deleteRecursively() } }
+ }
+
+ /** Tries the tracks that failed again. */
+ fun retry() {
+ failed = emptySet()
+ kick()
+ }
+
+ /** Starts fetching what's missing, if it isn't already; e.g. when the connection returns. */
+ fun kick() {
+ if (!loaded || job?.isActive == true || client() == null) return
+ if (nextPending() == null) return
+ fetchedThisRun = 0
+ val run = scope.launch { work() }
+ job = run
+ run.invokeOnCompletion {
+ scope.launch {
+ if (job === run) {
+ job = null
+ current = null
+ onProgress?.invoke(null)
+ }
+ }
+ }
+ }
+
+ private fun want(list: List) {
+ val next = LinkedHashMap(tracks)
+ for (t in list) if (t.id !in next) next[t.id] = OfflineTrack(t)
+ tracks = next
+ save()
+ kick()
+ }
+
+ /** Drops tracks nothing wants any more, with their files and covers. */
+ private fun prune() {
+ val wanted = (singles + sets.flatMap { it.trackIds }).toSet()
+ val gone = tracks.filterKeys { it !in wanted }
+ if (gone.isNotEmpty()) {
+ if (current?.first in gone) job?.cancel()
+ tracks = tracks.filterKeys { it in wanted }
+ failed = failed - gone.keys
+ }
+ save()
+ val files = gone.values.mapNotNull { it.file }
+ val covers = coverUrls().map(::coverName).toSet()
+ scope.launch(writer) {
+ files.forEach { File(dir, it).delete() }
+ coverDir.listFiles()?.forEach { if (it.name !in covers) it.delete() }
+ }
+ kick()
+ }
+
+ // ---- Fetching ----
+
+ private fun nextPending(): String? {
+ val order = singles + sets.flatMap { it.trackIds }
+ return order.firstOrNull { id -> tracks[id]?.done == false && id !in failed }
+ }
+
+ private suspend fun work() {
+ var strikes = 0
+ while (true) {
+ val c = client() ?: return
+ val id = nextPending() ?: return
+ val entry = tracks[id] ?: return
+ current = id to 0f
+ onProgress?.invoke(DownloadProgress(fetchedThisRun, fetchedThisRun + queued, entry.track.fullTitle))
+ try {
+ val saved = fetch(c, entry.track)
+ strikes = 0
+ // Removed while it was on its way: the file isn't wanted.
+ if (id !in tracks) {
+ withContext(writer) { File(dir, saved.file!!).delete() }
+ continue
+ }
+ tracks = tracks + (id to saved)
+ fetchedThisRun += 1
+ save()
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Throwable) {
+ val err = YmError.of(e)
+ Log.w(TAG, "download ${entry.track.id}: $err")
+ when {
+ err is YmError.Unauthorized -> return
+ // A server error is about this file; a network one, about the connection.
+ err is YmError.Network -> {
+ strikes += 1
+ // Offline: wait for the connection to come back and kick again.
+ if (strikes >= MAX_STRIKES) return
+ delay(5_000L * strikes)
+ }
+ else -> failed = failed + id
+ }
+ }
+ }
+ }
+
+ /** Fetches one track to its file, then its covers. */
+ private suspend fun fetch(c: YmClient, track: Track): OfflineTrack {
+ val stream = resolveStream(c, track.id, quality())
+ if (stream.preview) throw YmError.Api("only a preview is available")
+ val key = stream.key?.let { hexKey(it) ?: throw YmError.Api("unreadable key") }
+ val name = "${fileName(track.id)}.${stream.container}"
+ val part = File(dir, "$name.part")
+ val run = currentCoroutineContext()[Job]
+ var lastProgress = 0f
+ var error: YmError? = null
+ for (url in stream.urls) {
+ try {
+ val bytes = c.file(url) { input, length ->
+ write(input, part, key) { written ->
+ if (run?.isActive == false) throw CancellationException("download removed")
+ if (length > 0) {
+ val f = written.toFloat() / length
+ if (f - lastProgress >= 0.02f) {
+ lastProgress = f
+ scope.launch { if (current?.first == track.id) current = track.id to f }
+ }
+ }
+ }
+ }
+ withContext(Dispatchers.IO) {
+ val target = File(dir, name)
+ if (!part.renameTo(target)) throw YmError.Api("couldn't keep $name")
+ }
+ saveCovers(c, track.coverUrls())
+ return OfflineTrack(track, name, stream.codec, stream.bitrateKbps, bytes)
+ } catch (e: YmError) {
+ withContext(Dispatchers.IO) { part.delete() }
+ if (e is YmError.Unauthorized) throw e
+ error = e
+ } catch (e: Throwable) {
+ withContext(Dispatchers.IO + NonCancellable) { part.delete() }
+ throw e
+ }
+ }
+ throw error ?: YmError.Api("no mirrors")
+ }
+
+ /** Copies `input` to `to`, decrypting with `key`; reports bytes written as it goes. */
+ private fun write(input: InputStream, to: File, key: ByteArray?, progress: (Long) -> Unit): Long {
+ to.parentFile?.mkdirs()
+ val cipher = key?.let { ctrCipher(it, 0) }
+ var total = 0L
+ FileOutputStream(to).use { out ->
+ val buf = ByteArray(64 * 1024)
+ while (true) {
+ val n = input.read(buf)
+ if (n < 0) break
+ // CTR never buffers, so the output is exactly as long as the input.
+ cipher?.update(buf, 0, n, buf, 0)
+ out.write(buf, 0, n)
+ total += n
+ progress(total)
+ }
+ }
+ return total
+ }
+
+ /** Keeps covers beside the files; a missing one only means placeholder art offline. */
+ private suspend fun saveCovers(c: YmClient, urls: List) {
+ for (url in urls) {
+ val file = File(coverDir, coverName(url))
+ if (file.isFile) continue
+ try {
+ c.file(url) { input, _ ->
+ coverDir.mkdirs()
+ val part = File(coverDir, "${file.name}.part")
+ FileOutputStream(part).use { input.copyTo(it) }
+ part.renameTo(file)
+ }
+ } catch (e: YmError) {
+ Log.w(TAG, "cover: $e")
+ }
+ }
+ }
+
+ private fun Track.coverUrls(): List = coverSizes.mapNotNull { coverUrl(it) }
+
+ /** Every cover a wanted track or set uses. */
+ private fun coverUrls(): List =
+ tracks.values.flatMap { it.track.coverUrls() } + sets.mapNotNull { it.cover }
+
+ // ---- The index on disk ----
+
+ private fun save() {
+ val index = Index(
+ uid = uid,
+ tracks = tracks.mapValues { (_, t) -> Saved(t.track.toJson(), t.file, t.codec, t.bitrateKbps, t.bytes) },
+ singles = singles,
+ sets = sets.map { SavedSet(it.key, it.title, it.cover, it.hues.first, it.hues.second, it.trackIds) },
+ )
+ scope.launch(writer) {
+ runCatching {
+ dir.mkdirs()
+ val tmp = File(dir, "index.json.part")
+ tmp.writeText(JSON.encodeToString(Index.serializer(), index))
+ if (!tmp.renameTo(indexFile)) error("rename failed")
+ }.onFailure { Log.w(TAG, "saving downloads: $it") }
+ }
+ }
+
+ /** The saved index, with files that went missing marked to fetch again and leftovers cleared. */
+ private fun readIndex(): Index? {
+ if (!indexFile.isFile) return null
+ val index = runCatching { JSON.decodeFromString(Index.serializer(), indexFile.readText()) }
+ .onFailure { Log.w(TAG, "reading downloads: $it") }
+ .getOrNull() ?: return null
+ val kept = index.tracks.values.mapNotNull { it.file }.toSet()
+ dir.listFiles()?.forEach { f ->
+ if (f.isFile && f != indexFile && f.name !in kept) f.delete()
+ }
+ return index.copy(
+ tracks = index.tracks.mapValues { (_, s) ->
+ if (s.file != null && !File(dir, s.file).isFile) s.copy(file = null, bytes = 0) else s
+ },
+ )
+ }
+
+ @Serializable
+ private data class Index(
+ val uid: Long? = null,
+ val tracks: Map = emptyMap(),
+ val singles: List = emptyList(),
+ val sets: List = emptyList(),
+ )
+
+ @Serializable
+ private data class Saved(
+ val track: JsonObject,
+ val file: String? = null,
+ val codec: String = "",
+ val bitrate: Int = 0,
+ val bytes: Long = 0,
+ ) {
+ fun toOffline(): OfflineTrack? = Track.from(track)?.let { OfflineTrack(it, file, codec, bitrate, bytes) }
+ }
+
+ @Serializable
+ private data class SavedSet(
+ val key: String,
+ val title: String,
+ val cover: String? = null,
+ val hue1: Float = 0f,
+ val hue2: Float = 0f,
+ val tracks: List = emptyList(),
+ ) {
+ fun toOffline() = OfflineSet(key, title, cover, hue1 to hue2, tracks)
+ }
+
+ companion object {
+ const val LIKED = "liked"
+
+ fun albumKey(id: Long) = "$ALBUM$id"
+
+ fun playlistKey(key: String) = "$PLAYLIST$key"
+
+ private const val TAG = "Musyx"
+ private val JSON = Json { ignoreUnknownKeys = true }
+
+ /** A track id as a file name; ids of uploaded tracks can hold anything. */
+ internal fun fileName(id: String): String =
+ if (id.all { it.isLetterOrDigit() || it == '-' || it == '_' }) id else "u" + sha1(id).take(16)
+
+ internal fun coverName(url: String): String = sha1(url).take(24) + ".img"
+
+ private fun sha1(s: String): String =
+ MessageDigest.getInstance("SHA-1").digest(s.toByteArray()).joinToString("") { "%02x".format(it) }
+ }
+}
diff --git a/core/src/main/java/it/panov/musyx/player/ExoEngine.kt b/core/src/main/java/it/panov/musyx/player/ExoEngine.kt
index bdbc038..60282a5 100644
--- a/core/src/main/java/it/panov/musyx/player/ExoEngine.kt
+++ b/core/src/main/java/it/panov/musyx/player/ExoEngine.kt
@@ -18,6 +18,7 @@ import androidx.media3.common.util.UnstableApi
import androidx.media3.database.StandaloneDatabaseProvider
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSpec
+import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.datasource.ResolvingDataSource
import androidx.media3.datasource.cache.CacheDataSource
@@ -105,7 +106,8 @@ class ExoEngine(
} else {
null
}
- val source: DataSource.Factory = cached ?: identified
+ // Downloaded files are read straight from disk; links go through the cache when there is one.
+ val source: DataSource.Factory = DefaultDataSource.Factory(context, cached ?: identified)
val decrypting = AesCtrDataSource.Factory(source) { uri: Uri -> keys[uri.toString()] }
val loadControl = DefaultLoadControl.Builder()
.setBufferDurationsMs(buffering.minMs, buffering.maxMs, buffering.startMs, buffering.resumeMs)
@@ -165,7 +167,8 @@ class ExoEngine(
override fun preload(stream: Stream) {
if (cached == null) return
cancelPreload()
- upcoming = stream.urls.firstOrNull()
+ // A downloaded file needs no fetching ahead.
+ upcoming = stream.urls.firstOrNull()?.takeUnless { it.startsWith("file:") }
if (ready && !exo.isLoading) startPreload()
}
diff --git a/core/src/main/java/it/panov/musyx/player/PlaybackController.kt b/core/src/main/java/it/panov/musyx/player/PlaybackController.kt
index 83820be..7fac32c 100644
--- a/core/src/main/java/it/panov/musyx/player/PlaybackController.kt
+++ b/core/src/main/java/it/panov/musyx/player/PlaybackController.kt
@@ -16,6 +16,7 @@ import it.panov.musyx.api.Stream
import it.panov.musyx.api.Track
import it.panov.musyx.api.WaveSettings
import it.panov.musyx.api.YmClient
+import it.panov.musyx.api.YmError
import it.panov.musyx.data.Quality
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@@ -50,6 +51,8 @@ class PlaybackController(
private val waveSettings: () -> WaveSettings?,
private val token: () -> String?,
private val onSignedOut: () -> Unit,
+ /** A downloaded track's file as a stream, or null. */
+ private val local: (trackId: String) -> Stream?,
buffering: Buffering,
) : EngineEvents {
private val core = PlayerCore()
@@ -151,17 +154,14 @@ class PlaybackController(
val api = client()
for (effect in effects) when (effect) {
Effect.SignedOut -> onSignedOut()
- is Effect.Fetch -> api?.let { c ->
- scope.launch {
- val result = runCatching { resolve(c, effect.trackId) }
- update { core.fetched(effect.generation, result) }
- }
+ // Downloaded tracks play without a session, so these go ahead offline too.
+ is Effect.Fetch -> scope.launch {
+ val result = runCatching { resolve(api, effect.trackId) }
+ update { core.fetched(effect.generation, result) }
}
- is Effect.Prefetch -> api?.let { c ->
- scope.launch {
- val result = runCatching { resolve(c, effect.trackId) }
- core.prefetched(effect.trackId, result)
- }
+ is Effect.Prefetch -> scope.launch {
+ val result = runCatching { resolve(api, effect.trackId) }
+ core.prefetched(effect.trackId, result)
}
is Effect.WaveFetch -> api?.let { c ->
// My Wave's settings ride along as seeds when a session starts.
@@ -189,12 +189,15 @@ class PlaybackController(
}
}
- private suspend fun resolve(c: YmClient, trackId: String): Stream {
- val q = quality()
- return if (q == Quality.Lossless) c.losslessStream(trackId) else c.stream(trackId, q.maxKbps)
- }
+ /** A downloaded file when there is one, else a link from Yandex. */
+ private suspend fun resolve(c: YmClient?, trackId: String): Stream =
+ local(trackId) ?: resolveStream(c ?: throw YmError.Network("offline"), trackId, quality())
private companion object {
const val TAG = "Musyx"
}
}
+
+/** A link to `trackId`'s audio at `quality`. */
+suspend fun resolveStream(c: YmClient, trackId: String, quality: Quality): Stream =
+ if (quality == Quality.Lossless) c.losslessStream(trackId) else c.stream(trackId, quality.maxKbps)
diff --git a/core/src/main/java/it/panov/musyx/state/AppState.kt b/core/src/main/java/it/panov/musyx/state/AppState.kt
index 9337489..404498e 100644
--- a/core/src/main/java/it/panov/musyx/state/AppState.kt
+++ b/core/src/main/java/it/panov/musyx/state/AppState.kt
@@ -34,9 +34,12 @@ import it.panov.musyx.api.Track
import it.panov.musyx.api.WaveSettings
import it.panov.musyx.api.YmClient
import it.panov.musyx.api.YmError
+import it.panov.musyx.api.huesFor
import it.panov.musyx.data.Appearance
import it.panov.musyx.data.FontSize
import it.panov.musyx.data.CredentialStore
+import it.panov.musyx.data.Downloads
+import it.panov.musyx.data.OfflineSet
import it.panov.musyx.data.Locale
import it.panov.musyx.data.Quality
import it.panov.musyx.data.Settings
@@ -49,6 +52,9 @@ import kotlinx.coroutines.launch
/** Tracks in Home's "Recently played". */
const val RECENT = 10
+/** The size a downloaded album's or playlist's cover is kept at. */
+const val SET_COVER = 400
+
/** Where sign-in stands. Everything but [SignedIn] takes the whole screen. */
sealed interface Session {
/** Reading the stored credentials and checking the token. */
@@ -80,6 +86,8 @@ class AppState(
private val clearCovers: suspend () -> Unit,
/** How far ahead playback loads; the phone loads further than the TV. */
buffering: Buffering = Buffering.Default,
+ /** Cover sizes the interface shows, kept with downloads so they appear offline. */
+ coverSizes: List = emptyList(),
) {
var session: Session by mutableStateOf(Session.Restoring)
private set
@@ -140,6 +148,8 @@ class AppState(
val search = SearchState(scope, ::client, ::failed)
+ val downloads = Downloads(context, scope, ::client, { settings.quality }, coverSizes)
+
val playback = PlaybackController(
context = context,
scope = scope,
@@ -148,6 +158,7 @@ class AppState(
waveSettings = { waveShown },
token = { credentials?.accessToken },
onSignedOut = ::signOut,
+ local = downloads::stream,
buffering = buffering,
)
@@ -198,6 +209,8 @@ class AppState(
// Credentials stay for a retry when Yandex is only unreachable.
if (err.isRetryable) {
credentials = creds
+ // Downloads are what's left to play; the phone shows them.
+ nav.reset(Route.Downloads())
session = Session.Unreachable
} else {
forget(err)
@@ -246,6 +259,7 @@ class AppState(
credentials = creds
nav.reset(Route.Home)
session = Session.SignedIn(client, account)
+ downloads.attach(account.uid)
// Liked tracks drive the hearts; playlists feed "Add to playlist"; Home is the first page.
loadLiked()
loadLikedIds()
@@ -357,7 +371,7 @@ class AppState(
loadTab(CollectionTab.Albums)
}
is Route.Album, is Route.Artist, is Route.Playlist -> loadPage(route)
- Route.NowPlaying -> {}
+ Route.NowPlaying, is Route.Downloads -> {}
}
}
@@ -373,7 +387,10 @@ class AppState(
else -> error("not a page: $route")
}
},
- ) { pages[route] = it }
+ ) {
+ pages[route] = it
+ it.get()?.let(::syncDownload)
+ }
}
// ---- Loading ----
@@ -436,6 +453,7 @@ class AppState(
is Loadable.Failed -> Liked.Failed(r.error)
else -> Liked.NotLoaded
}
+ syncLiked()
}
}
@@ -529,6 +547,77 @@ class AppState(
}
}
+ // ---- Downloads ----
+
+ fun downloadTrack(track: Track) {
+ sheet = null
+ downloads.addTrack(track)
+ toast(UiText.Res(R.string.toast_downloading, track.fullTitle))
+ }
+
+ /** Removes a track's file, whichever album or playlist brought it. */
+ fun removeDownload(track: Track) {
+ sheet = null
+ downloads.removeTrack(track.id)
+ toast(UiText.Res(R.string.toast_download_removed, track.fullTitle))
+ }
+
+ fun downloadAlbum(info: AlbumPage) {
+ val a = info.album
+ downloadSet(Downloads.albumKey(a.id), a.fullTitle, a.coverUrl(SET_COVER), a.hues, info.tracks)
+ }
+
+ fun downloadPlaylist(info: PlaylistPage) {
+ val p = info.playlist
+ downloadSet(Downloads.playlistKey(p.id.key), p.title, p.coverUrl(SET_COVER), p.hues, info.tracks)
+ }
+
+ /** Liked tracks, kept in step with every like and unlike from then on. */
+ fun downloadLiked() {
+ val tracks = liked.tracks() ?: return
+ downloads.addSet(Downloads.LIKED, "", null, huesFor((account?.uid ?: 0).toULong()), tracks)
+ toast(UiText.Res(R.string.toast_downloading_liked))
+ }
+
+ private fun downloadSet(key: String, title: String, cover: String?, hues: Pair, tracks: List) {
+ downloads.addSet(key, title, cover, hues, tracks)
+ toast(UiText.Res(R.string.toast_downloading, title))
+ }
+
+ fun removeDownloadSet(key: String) {
+ val set = downloads.set(key) ?: return
+ downloads.removeSet(key)
+ if (nav.current == Route.Downloads(key)) back()
+ toast(
+ if (set.kind == OfflineSet.Kind.Liked) UiText.Res(R.string.toast_liked_download_removed)
+ else UiText.Res(R.string.toast_download_removed, set.title),
+ )
+ }
+
+ fun clearDownloads() {
+ downloads.clear()
+ toast(UiText.Res(R.string.toast_downloads_cleared))
+ }
+
+ /** A connection came back: reconnect if Yandex was out of reach, and carry on downloading. */
+ fun onNetworkAvailable() {
+ if (session == Session.Unreachable) restore()
+ downloads.kick()
+ }
+
+ /** A downloaded album or playlist follows the page as it is now. */
+ private fun syncDownload(page: Page) {
+ when (page) {
+ is Page.OfAlbum -> downloads.sync(Downloads.albumKey(page.info.album.id), page.info.tracks)
+ is Page.OfPlaylist -> downloads.sync(Downloads.playlistKey(page.info.playlist.id.key), page.info.tracks)
+ is Page.OfArtist -> {}
+ }
+ }
+
+ private fun syncLiked() {
+ liked.tracks()?.let { downloads.sync(Downloads.LIKED, it) }
+ }
+
// ---- My Wave ----
fun setWaveSettings(next: WaveSettings) {
@@ -548,7 +637,13 @@ class AppState(
/** Lyrics for `track`, fetched once while the lyrics tab shows it: Yandex's, else LRCLIB's. */
fun wantLyrics(track: Track) {
- if (lyrics.containsKey(track.id)) return
+ // A failure is asked again the next time they're wanted, e.g. once back online.
+ if (lyrics[track.id]?.needsLoad == false) return
+ if (client == null) {
+ // Offline there's nobody to ask; waiting would never end.
+ lyrics[track.id] = Loadable.Failed(YmError.Network("offline"))
+ return
+ }
lyrics[track.id] = Loadable.Loading
load({ it.lyrics(track.id) ?: Lrclib.lyrics(track) }) { lyrics[track.id] = it }
}
@@ -654,6 +749,7 @@ class AppState(
fun likeTrack(track: Track, on: Boolean) {
liked = liked.with(track, on)
+ syncLiked()
if (on) likes = likes.copy(dislikedTracks = likes.dislikedTracks - track.id)
edit(UiText.Res(if (on) R.string.toast_liked else R.string.toast_unliked), likeFailed) {
it.setTrackLiked(track.fullId, on)
diff --git a/core/src/main/java/it/panov/musyx/state/Route.kt b/core/src/main/java/it/panov/musyx/state/Route.kt
index 93d3961..8542531 100644
--- a/core/src/main/java/it/panov/musyx/state/Route.kt
+++ b/core/src/main/java/it/panov/musyx/state/Route.kt
@@ -21,6 +21,8 @@ sealed interface Route {
data class Playlist(val id: PlaylistId) : Route
/** Index into the app's flattened genre list. */
data class Genre(val index: Int) : Route
+ /** What's on the device: everything, or one downloaded set by its key. */
+ data class Downloads(val set: String? = null) : Route
companion object {
/** Navigation drawer order. */
diff --git a/core/src/main/res/values-ru/strings.xml b/core/src/main/res/values-ru/strings.xml
index 6b36eac..71cbb6f 100644
--- a/core/src/main/res/values-ru/strings.xml
+++ b/core/src/main/res/values-ru/strings.xml
@@ -52,6 +52,11 @@
Качество звука: %1$s. Применится со следующего трека.
Кеш обложек очищен
Не удалось очистить кеш обложек.
+ «%1$s» скачивается для прослушивания офлайн
+ «Мне нравится» скачивается для прослушивания офлайн
+ «%1$s» удалено с устройства
+ «Мне нравится» удалено с устройства
+ Все загрузки удалены
- Играем %1$d трек в духе «%2$s»
- Играем %1$d трека в духе «%2$s»
diff --git a/core/src/main/res/values/strings.xml b/core/src/main/res/values/strings.xml
index 1462d4c..75b4033 100644
--- a/core/src/main/res/values/strings.xml
+++ b/core/src/main/res/values/strings.xml
@@ -52,6 +52,11 @@
Streaming quality: %1$s. Applies from the next track.
Cover cache cleared
Couldn\'t clear the cover cache.
+ Downloading “%1$s” for offline listening
+ Downloading Liked tracks for offline listening
+ Removed “%1$s” from the device
+ Removed Liked tracks from the device
+ All downloads removed
- Playing %1$d track like “%2$s”
- Playing %1$d tracks like “%2$s”
diff --git a/core/src/test/java/it/panov/musyx/api/ApiTest.kt b/core/src/test/java/it/panov/musyx/api/ApiTest.kt
index 514da12..e11cbf3 100644
--- a/core/src/test/java/it/panov/musyx/api/ApiTest.kt
+++ b/core/src/test/java/it/panov/musyx/api/ApiTest.kt
@@ -37,6 +37,23 @@ class ApiTest {
assertEquals("12345:77", t.fullId)
}
+ @Test
+ fun trackSurvivesItsOwnJson() {
+ // Downloads keep tracks on disk this way; reading one back must give the same track.
+ val t = Track.from(
+ json(
+ """{"id":"9","title":"Song","version":"Live","durationMs":1000,"explicit":true,"available":false,
+ "artists":[{"id":1,"name":"A","cover":{"uri":"avatars.yandex.net/a/%%"}},{"name":"B"}],
+ "albums":[{"id":77,"title":"Album","year":1988}],"coverUri":"avatars.yandex.net/x/%%",
+ "lyricsInfo":{"hasAvailableTextLyrics":true},"type":"podcast-episode"}""",
+ ),
+ )!!
+ assertEquals(t, Track.from(t.toJson()))
+ assertEquals("https://avatars.yandex.net/a/50x50", Track.from(t.toJson())!!.artists[0].coverUrl(50))
+ val bare = Track.bare("u-1")
+ assertEquals(bare, Track.from(bare.toJson()))
+ }
+
@Test
fun trackCarriesAlbumYearAndArtistPhotos() {
val t = Track.from(
diff --git a/mobile/src/main/AndroidManifest.xml b/mobile/src/main/AndroidManifest.xml
index 04605f1..ae5f029 100644
--- a/mobile/src/main/AndroidManifest.xml
+++ b/mobile/src/main/AndroidManifest.xml
@@ -6,6 +6,9 @@
+
+
+
+
+
+
= Build.VERSION_CODES.Q) ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC else 0
+ ServiceCompat.startForeground(this, NOTIFICATION, notification(this, progress), type)
+ return START_NOT_STICKY
+ }
+
+ /** Android 15 caps data sync at six hours a day; what's left carries on next time. */
+ override fun onTimeout(startId: Int, fgsType: Int) {
+ stopSelf()
+ }
+
+ override fun onDestroy() {
+ running = false
+ super.onDestroy()
+ }
+
+ companion object {
+ private const val CHANNEL = "downloads"
+ private const val NOTIFICATION = 2
+ private var running = false
+ private var latest: DownloadProgress? = null
+
+ /** Shows `progress`, starting the service for it; null stops it. */
+ fun update(context: Context, progress: DownloadProgress?) {
+ latest = progress
+ val intent = Intent(context, DownloadService::class.java)
+ if (progress == null) {
+ context.stopService(intent)
+ return
+ }
+ if (running) {
+ // Without the permission the service still runs; there's just nothing to update.
+ val allowed = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
+ ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
+ if (allowed) NotificationManagerCompat.from(context).notify(NOTIFICATION, notification(context, progress))
+ return
+ }
+ try {
+ ContextCompat.startForegroundService(context, intent)
+ } catch (e: IllegalStateException) {
+ // From the background (a connection coming back) Android may refuse; the
+ // downloads go on while the app lives, and the service starts next time.
+ Log.w("Musyx", "download service: $e")
+ }
+ }
+
+ private fun notification(context: Context, p: DownloadProgress): android.app.Notification {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val channel = NotificationChannel(CHANNEL, context.getString(R.string.notify_downloads_channel), NotificationManager.IMPORTANCE_LOW)
+ context.getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
+ }
+ val open = PendingIntent.getActivity(
+ context,
+ 0,
+ Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ return NotificationCompat.Builder(context, CHANNEL)
+ .setSmallIcon(R.drawable.ic_download)
+ .setContentTitle(context.getString(R.string.notify_downloading))
+ .setContentText(context.getString(R.string.notify_progress, p.done + 1, p.total, p.title.orEmpty()))
+ .setProgress(p.total, p.done, false)
+ .setContentIntent(open)
+ .setOngoing(true)
+ .setOnlyAlertOnce(true)
+ .setSilent(true)
+ .build()
+ }
+ }
+}
diff --git a/mobile/src/main/java/it/panov/musyx/mobile/Musyx.kt b/mobile/src/main/java/it/panov/musyx/mobile/Musyx.kt
index f1502a8..aa2fc48 100644
--- a/mobile/src/main/java/it/panov/musyx/mobile/Musyx.kt
+++ b/mobile/src/main/java/it/panov/musyx/mobile/Musyx.kt
@@ -4,23 +4,33 @@ package it.panov.musyx.mobile
import android.app.Application
import android.content.Context
import android.content.res.Resources
+import android.net.ConnectivityManager
+import android.net.Network
+import android.net.NetworkCapabilities
+import android.net.NetworkRequest
import androidx.core.os.ConfigurationCompat
import coil3.ImageLoader
import coil3.PlatformContext
import coil3.SingletonImageLoader
import coil3.disk.DiskCache
import coil3.disk.directory
+import coil3.intercept.Interceptor
import coil3.memory.MemoryCache
import coil3.network.okhttp.OkHttpNetworkFetcherFactory
+import coil3.request.ImageResult
import coil3.request.crossfade
import it.panov.musyx.api.Lrclib
import it.panov.musyx.data.CredentialStore
+import it.panov.musyx.data.Downloads
import it.panov.musyx.data.SettingsStore
+import it.panov.musyx.mobile.ui.components.COVER_LARGE
+import it.panov.musyx.mobile.ui.components.COVER_SMALL
import it.panov.musyx.player.Buffering
import it.panov.musyx.state.AppState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class Musyx : Application(), SingletonImageLoader.Factory {
@@ -30,6 +40,21 @@ class Musyx : Application(), SingletonImageLoader.Factory {
override fun onCreate() {
super.onCreate()
Lrclib.agent = "Musyx/${BuildConfig.VERSION_NAME} (https://git.panov.it/panov/musyz-mobile)"
+ state.downloads.onProgress = { DownloadService.update(this, it) }
+ watchNetwork()
+ }
+
+ /** A connection coming back reconnects an offline session and resumes downloads. */
+ private fun watchNetwork() {
+ val request = NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build()
+ getSystemService(ConnectivityManager::class.java).registerNetworkCallback(
+ request,
+ object : ConnectivityManager.NetworkCallback() {
+ override fun onAvailable(network: Network) {
+ scope.launch { state.onNetworkAvailable() }
+ }
+ },
+ )
}
val state: AppState by lazy {
@@ -44,12 +69,16 @@ class Musyx : Application(), SingletonImageLoader.Factory {
},
// Mobile data slows and drops out: buffer whole tracks and preload the next one.
buffering = Buffering.Mobile,
+ coverSizes = listOf(COVER_SMALL, COVER_LARGE),
)
}
/** Covers: kept in memory and on disk so rows of cards open instantly the second time. */
override fun newImageLoader(context: PlatformContext): ImageLoader = ImageLoader.Builder(context)
- .components { add(OkHttpNetworkFetcherFactory()) }
+ .components {
+ add(OfflineCovers { state.downloads })
+ add(OkHttpNetworkFetcherFactory())
+ }
.memoryCache { MemoryCache.Builder().maxSizePercent(context, 0.2).build() }
.diskCache {
DiskCache.Builder().directory(cacheDir.resolve("covers")).maxSizeBytes(COVER_CACHE_BYTES).build()
@@ -57,6 +86,15 @@ class Musyx : Application(), SingletonImageLoader.Factory {
.crossfade(true)
.build()
+ /** Downloaded music's covers come from the copies kept with it, so they show offline too. */
+ private class OfflineCovers(private val downloads: () -> Downloads) : Interceptor {
+ override suspend fun intercept(chain: Interceptor.Chain): ImageResult {
+ val url = chain.request.data as? String ?: return chain.proceed()
+ val file = downloads().coverFile(url) ?: return chain.proceed()
+ return chain.withRequest(chain.request.newBuilder().data(file).build()).proceed()
+ }
+ }
+
companion object {
private const val COVER_CACHE_BYTES = 200L * 1024 * 1024
diff --git a/mobile/src/main/java/it/panov/musyx/mobile/ui/MusyxApp.kt b/mobile/src/main/java/it/panov/musyx/mobile/ui/MusyxApp.kt
index d239235..5f4ed47 100644
--- a/mobile/src/main/java/it/panov/musyx/mobile/ui/MusyxApp.kt
+++ b/mobile/src/main/java/it/panov/musyx/mobile/ui/MusyxApp.kt
@@ -9,6 +9,7 @@ import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
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
@@ -16,6 +17,7 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
@@ -28,6 +30,7 @@ import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.ui.Alignment
@@ -39,6 +42,7 @@ import it.panov.musyx.mobile.ui.components.MusyxIcon
import it.panov.musyx.mobile.ui.screens.AlbumScreen
import it.panov.musyx.mobile.ui.screens.ArtistScreen
import it.panov.musyx.mobile.ui.screens.ChartScreen
+import it.panov.musyx.mobile.ui.screens.DownloadsScreen
import it.panov.musyx.mobile.ui.screens.CollectionScreen
import it.panov.musyx.mobile.ui.screens.GenreScreen
import it.panov.musyx.mobile.ui.screens.HoldingScreen
@@ -67,11 +71,14 @@ fun MusyxApp(state: AppState, onExit: () -> Unit) {
when (val s = state.session) {
Session.Restoring -> HoldingScreen(stringResource(R.string.session_checking))
is Session.Connecting -> HoldingScreen(stringResource(R.string.session_signing_in))
- Session.Unreachable -> UnreachableScreen(state)
+ // Out of reach with music on the device: carry on with that.
+ Session.Unreachable -> if (state.downloads.hasAny) Shell(state, onExit, offline = true) else UnreachableScreen(state)
is Session.SignedOut -> SignInScreen(s.signIn)
is Session.SignedIn -> Shell(state, onExit)
}
- if (state.session !is Session.SignedIn) ToastHost(state, Modifier.systemBarsPadding())
+ if (state.session !is Session.SignedIn && !(state.session == Session.Unreachable && state.downloads.hasAny)) {
+ ToastHost(state, Modifier.systemBarsPadding())
+ }
}
}
@@ -86,24 +93,27 @@ private val NAV = listOf(
NavItem(Route.Podcasts, R.string.nav_podcasts, R.drawable.ic_podcast),
)
+/** The signed-in app; `offline`, only Downloads and the player, while Yandex is out of reach. */
@Composable
-private fun Shell(state: AppState, onExit: () -> Unit) {
+private fun Shell(state: AppState, onExit: () -> Unit, offline: Boolean = false) {
val route = state.nav.current
val pages = rememberSaveableStateHolder()
BackHandler { if (!state.back()) onExit() }
Scaffold(
containerColor = MusyxTheme.colors.bg,
- topBar = { TopBar(state, route) },
+ topBar = { TopBar(state, route, offline) },
bottomBar = {
- Column {
+ // The navigation bar keeps clear of the system's; offline, without it, the column does.
+ Column(if (offline) Modifier.navigationBarsPadding() else Modifier) {
if (state.playback.state.hasTrack) MiniPlayer(state)
- NavBar(state.nav.section, state::navigate)
+ if (!offline) NavBar(state.nav.section, state::navigate)
}
},
) { padding ->
Box(Modifier.fillMaxSize().padding(padding)) {
- pages.SaveableStateProvider(route.toString()) { Page(state, route) }
+ val page = if (offline && route !is Route.Downloads) Route.Downloads() else route
+ pages.SaveableStateProvider(page.toString()) { Page(state, page) }
ToastHost(state)
}
}
@@ -137,12 +147,16 @@ private fun Page(state: AppState, route: Route) {
is Route.Album -> AlbumScreen(state, route)
is Route.Artist -> ArtistScreen(state, route)
is Route.Playlist -> PlaylistScreen(state, route)
+ is Route.Downloads -> DownloadsScreen(state, route)
}
}
-/** Back on pages under a section, the wordmark on the sections themselves; Settings on the right. */
+/**
+ * Back on pages under a section, the wordmark on the sections themselves; Settings on the right,
+ * or offline, a note saying so and a way to reconnect.
+ */
@Composable
-private fun TopBar(state: AppState, route: Route) {
+private fun TopBar(state: AppState, route: Route, offline: Boolean) {
Row(
Modifier.fillMaxWidth().statusBarsPadding().height(56.dp).padding(horizontal = 4.dp),
verticalAlignment = Alignment.CenterVertically,
@@ -153,7 +167,14 @@ private fun TopBar(state: AppState, route: Route) {
IconButton(onClick = { state.back() }) { MusyxIcon(R.drawable.ic_chevron_left) }
}
Spacer(Modifier.weight(1f))
- if (route != Route.Settings) {
+ if (offline) {
+ val c = MusyxTheme.colors
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ MusyxIcon(R.drawable.ic_wifi_off, tint = c.muted, size = 18.dp)
+ Text(stringResource(R.string.offline_badge), style = MusyxTheme.type.meta, color = c.muted)
+ }
+ TextButton(onClick = state::restore) { Text(stringResource(R.string.action_try_again)) }
+ } else if (route != Route.Settings) {
IconButton(onClick = { state.navigate(Route.Settings) }) { MusyxIcon(R.drawable.ic_settings, tint = MusyxTheme.colors.muted) }
}
}
diff --git a/mobile/src/main/java/it/panov/musyx/mobile/ui/components/Tracks.kt b/mobile/src/main/java/it/panov/musyx/mobile/ui/components/Tracks.kt
index 5ac92d2..1ced122 100644
--- a/mobile/src/main/java/it/panov/musyx/mobile/ui/components/Tracks.kt
+++ b/mobile/src/main/java/it/panov/musyx/mobile/ui/components/Tracks.kt
@@ -66,6 +66,7 @@ fun LazyListScope.trackItems(
track = track,
playing = state.playback.state.track?.id == track.id,
liked = state.liked.contains(track.id),
+ downloaded = state.downloads.isDone(track.id),
columns = columns,
shift = shifts?.getOrNull(i),
onPlay = { state.playTracks(tracks, i) },
@@ -85,6 +86,8 @@ fun TrackRow(
track: Track,
playing: Boolean,
liked: Boolean,
+ /** On the device, so it plays offline. */
+ downloaded: Boolean,
columns: Columns,
shift: Int?,
onPlay: () -> Unit,
@@ -124,7 +127,10 @@ fun TrackRow(
(if (columns.artist) track.artistsOrUnknown() else track.album?.title).takeIf { !it.isNullOrEmpty() },
clock(track.durationMs),
).joinToString(" · ")
- Text(subtitle, style = MusyxTheme.type.meta, color = c.muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ if (downloaded) MusyxIcon(R.drawable.ic_download, tint = c.accent, size = 13.dp)
+ Text(subtitle, style = MusyxTheme.type.meta, color = c.muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
}
if (onLike != null) {
IconButton(onClick = onLike) {
diff --git a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Detail.kt b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Detail.kt
index 606e59f..441e3ff 100644
--- a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Detail.kt
+++ b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Detail.kt
@@ -31,6 +31,7 @@ import it.panov.musyx.api.ArtistPage
import it.panov.musyx.api.PlaylistPage
import it.panov.musyx.api.PlaylistSummary
import it.panov.musyx.api.YmError
+import it.panov.musyx.data.Downloads
import it.panov.musyx.mobile.R
import it.panov.musyx.mobile.ui.components.COVER_LARGE
import it.panov.musyx.mobile.ui.components.Columns
@@ -123,7 +124,10 @@ private fun LazyListScope.albumPage(state: AppState, info: AlbumPage) {
}
item(key = "play") {
val liked = a.id in state.likes.albums
- PlayBar(state, info.tracks) { LikeButton(liked) { state.likeAlbum(a.id, !liked) } }
+ PlayBar(state, info.tracks) {
+ LikeButton(liked) { state.likeAlbum(a.id, !liked) }
+ DownloadButton(state, Downloads.albumKey(a.id), a.fullTitle) { state.downloadAlbum(info) }
+ }
}
trackItems(state, info.tracks, Columns.ALBUM_PAGE, keyPrefix = "album")
}
@@ -220,6 +224,7 @@ private fun LazyListScope.playlistPage(state: AppState, info: PlaylistPage) {
val liked = p.id in state.likes.playlists
LikeButton(liked) { state.likePlaylist(p.id, !liked) }
}
+ DownloadButton(state, Downloads.playlistKey(p.id.key), p.title) { state.downloadPlaylist(info) }
}
}
trackItems(state, info.tracks, playlist = if (own) p.id else null, positions = info.positions, keyPrefix = "pl")
diff --git a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Downloads.kt b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Downloads.kt
new file mode 100644
index 0000000..b4ff96c
--- /dev/null
+++ b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Downloads.kt
@@ -0,0 +1,249 @@
+// What's on the device: downloaded albums, playlists and tracks, how far the downloads have
+// got, and the button pages use to download or remove themselves. Offline, it's the app.
+package it.panov.musyx.mobile.ui.screens
+
+import android.text.format.Formatter
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.lazy.LazyListScope
+import androidx.compose.foundation.lazy.items
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.LinearProgressIndicator
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.pluralStringResource
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import it.panov.musyx.data.OfflineSet
+import it.panov.musyx.mobile.R
+import it.panov.musyx.mobile.ui.components.MusyxIcon
+import it.panov.musyx.mobile.ui.components.Note
+import it.panov.musyx.mobile.ui.components.PlayBar
+import it.panov.musyx.mobile.ui.components.ScreenTitle
+import it.panov.musyx.mobile.ui.components.SectionTitle
+import it.panov.musyx.mobile.ui.components.Thumb
+import it.panov.musyx.mobile.ui.components.trackItems
+import it.panov.musyx.mobile.ui.durationWords
+import it.panov.musyx.mobile.ui.theme.MusyxTheme
+import it.panov.musyx.mobile.ui.tracksWord
+import it.panov.musyx.state.AppState
+import it.panov.musyx.state.Route
+import it.panov.musyx.state.Session
+
+@Composable
+fun DownloadsScreen(state: AppState, route: Route.Downloads) {
+ val key = route.set
+ if (key == null) AllDownloads(state) else DownloadedSet(state, key)
+}
+
+@Composable
+private fun AllDownloads(state: AppState) {
+ val d = state.downloads
+ val space = MusyxTheme.space
+ PageColumn {
+ item(key = "title") { ScreenTitle(stringResource(R.string.downloads_title)) }
+ if (state.session == Session.Unreachable) item(key = "offline") { Note(stringResource(R.string.offline_note)) }
+ if (!d.hasAny) {
+ item(key = "empty") { Note(stringResource(R.string.downloads_empty)) }
+ return@PageColumn
+ }
+ status(state)
+ if (d.sets.isNotEmpty()) {
+ item(key = "sets-title") { SectionTitle(stringResource(R.string.downloads_sets), Modifier.padding(horizontal = space.gutter)) }
+ items(d.sets.asReversed(), key = { "set:${it.key}" }) { set -> SetRow(state, set) }
+ gap("tracks-gap")
+ }
+ val tracks = d.doneTracks
+ if (tracks.isNotEmpty()) {
+ item(key = "tracks-title") { SectionTitle(stringResource(R.string.downloads_tracks), Modifier.padding(horizontal = space.gutter)) }
+ item(key = "play") {
+ val size = Formatter.formatShortFileSize(LocalContext.current, d.bytes)
+ PlayBar(state, tracks, summary = "${tracksWord(tracks.size)} · ${durationWords(tracks.sumOf { it.durationMs })} · $size")
+ }
+ trackItems(state, tracks, keyPrefix = "dl", hearts = state.client != null)
+ }
+ }
+}
+
+/** How the downloads are getting on: the track on its way, what's left, what failed. */
+private fun LazyListScope.status(state: AppState) {
+ val d = state.downloads
+ val queued = d.queued
+ val failed = d.failed.size
+ if (queued == 0 && failed == 0) return
+ item(key = "status") {
+ val c = MusyxTheme.colors
+ Column(
+ Modifier.fillMaxWidth().padding(horizontal = MusyxTheme.space.gutter),
+ verticalArrangement = Arrangement.spacedBy(MusyxTheme.space.s),
+ ) {
+ val current = d.current
+ if (queued > 0) {
+ Text(
+ if (current != null) pluralStringResource(R.plurals.downloads_left, queued, queued) else stringResource(R.string.downloads_waiting),
+ style = MusyxTheme.type.meta,
+ color = c.muted,
+ )
+ if (current != null) {
+ LinearProgressIndicator(
+ progress = { current.second },
+ modifier = Modifier.fillMaxWidth(),
+ color = c.accent,
+ trackColor = c.raised,
+ )
+ }
+ }
+ if (failed > 0) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(pluralStringResource(R.plurals.downloads_failed, failed, failed), style = MusyxTheme.type.meta, color = c.like, modifier = Modifier.weight(1f))
+ if (state.client != null) TextButton(onClick = d::retry) { Text(stringResource(R.string.action_try_again)) }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun SetRow(state: AppState, set: OfflineSet) {
+ val c = MusyxTheme.colors
+ val (done, total) = state.downloads.progressOf(set)
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .clickable { state.navigate(Route.Downloads(set.key)) }
+ .padding(horizontal = MusyxTheme.space.gutter, vertical = 6.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ Thumb(set.cover, set.hues, 56.dp)
+ Column(Modifier.weight(1f)) {
+ Text(setTitle(set), style = MusyxTheme.type.bodyMedium, color = c.fg, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ val count = if (done < total) stringResource(R.string.downloads_set_progress, done, total) else tracksWord(total)
+ Text("${setKind(set)} · $count", style = MusyxTheme.type.meta, color = c.muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ SetMark(done, total)
+ }
+}
+
+@Composable
+private fun DownloadedSet(state: AppState, key: String) {
+ val d = state.downloads
+ val set = d.set(key)
+ PageColumn {
+ if (set == null) {
+ item(key = "gone") { Note(stringResource(R.string.downloads_gone)) }
+ return@PageColumn
+ }
+ val all = d.tracksOf(set)
+ // Offline only what's on the device plays; online the rest streams.
+ val tracks = if (state.session is Session.SignedIn) all else all.filter { d.isDone(it.id) }
+ item(key = "head") {
+ val c = MusyxTheme.colors
+ Row(
+ Modifier.fillMaxWidth().padding(horizontal = MusyxTheme.space.gutter),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(16.dp),
+ ) {
+ Thumb(set.cover, set.hues, 112.dp)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(setKind(set), style = MusyxTheme.type.meta, color = c.muted, maxLines = 1)
+ Text(setTitle(set), style = MusyxTheme.type.displayS, color = c.fg, maxLines = 3, overflow = TextOverflow.Ellipsis)
+ val (done, total) = d.progressOf(set)
+ if (done < total) Text(stringResource(R.string.downloads_set_progress, done, total), style = MusyxTheme.type.meta, color = c.muted)
+ }
+ }
+ }
+ item(key = "play") {
+ PlayBar(state, tracks, summary = "${tracksWord(tracks.size)} · ${durationWords(tracks.sumOf { it.durationMs })}") {
+ DownloadButton(state, set.key, setTitle(set)) {}
+ }
+ }
+ trackItems(state, all, keyPrefix = "dls", hearts = state.client != null)
+ }
+}
+
+/**
+ * Downloads a page's tracks, shows how far that has got, and removes them again after asking.
+ * `download` is only called when nothing is downloaded yet.
+ */
+@Composable
+fun DownloadButton(state: AppState, key: String, title: String, download: () -> Unit) {
+ val set = state.downloads.set(key)
+ var confirm by remember { mutableStateOf(false) }
+ val label = stringResource(if (set == null) R.string.action_download else R.string.action_downloaded)
+ IconButton(
+ onClick = { if (set == null) download() else confirm = true },
+ modifier = Modifier.size(44.dp).semantics { contentDescription = label },
+ ) {
+ if (set == null) {
+ MusyxIcon(R.drawable.ic_download)
+ } else {
+ val (done, total) = state.downloads.progressOf(set)
+ SetMark(done, total)
+ }
+ }
+ if (confirm) {
+ AlertDialog(
+ onDismissRequest = { confirm = false },
+ title = { Text(stringResource(R.string.download_remove_title, title)) },
+ text = { Text(stringResource(R.string.download_remove_body)) },
+ confirmButton = {
+ TextButton(onClick = { confirm = false; state.removeDownloadSet(key) }) {
+ Text(stringResource(R.string.action_remove), color = MusyxTheme.colors.like)
+ }
+ },
+ dismissButton = { TextButton(onClick = { confirm = false }) { Text(stringResource(R.string.action_cancel)) } },
+ containerColor = MusyxTheme.colors.panel,
+ )
+ }
+}
+
+/** A ring filling up while a set downloads, then a tick. */
+@Composable
+private fun SetMark(done: Int, total: Int) {
+ val c = MusyxTheme.colors
+ Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) {
+ if (done < total) {
+ CircularProgressIndicator(
+ progress = { done.toFloat() / total },
+ modifier = Modifier.size(20.dp),
+ color = c.accent,
+ trackColor = c.raised,
+ strokeWidth = 2.5.dp,
+ )
+ } else {
+ MusyxIcon(R.drawable.ic_circle_check, tint = c.accent)
+ }
+ }
+}
+
+@Composable
+private fun setTitle(set: OfflineSet): String =
+ if (set.kind == OfflineSet.Kind.Liked) stringResource(R.string.tab_liked_tracks) else set.title
+
+@Composable
+private fun setKind(set: OfflineSet): String = stringResource(
+ when (set.kind) {
+ OfflineSet.Kind.Album -> R.string.kind_album
+ OfflineSet.Kind.Playlist, OfflineSet.Kind.Liked -> R.string.downloads_kind_playlist
+ },
+)
diff --git a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Library.kt b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Library.kt
index 9f91c32..fbea662 100644
--- a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Library.kt
+++ b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Library.kt
@@ -18,6 +18,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
+import it.panov.musyx.data.Downloads
import it.panov.musyx.mobile.R
import it.panov.musyx.mobile.ui.components.CardGrid
import it.panov.musyx.mobile.ui.components.Failure
@@ -48,6 +49,17 @@ private fun tabLabel(tab: CollectionTab) = when (tab) {
fun CollectionScreen(state: AppState) {
PageColumn {
item(key = "title") { ScreenTitle(stringResource(R.string.nav_collection)) }
+ item(key = "downloads") {
+ val count = state.downloads.doneTracks.size
+ val label = stringResource(R.string.downloads_title)
+ Box(Modifier.padding(horizontal = MusyxTheme.space.gutter)) {
+ AssistChip(
+ onClick = { state.navigate(Route.Downloads()) },
+ label = { Text(if (count > 0) "$label $count" else label) },
+ leadingIcon = { MusyxIcon(R.drawable.ic_download, size = 18.dp) },
+ )
+ }
+ }
item(key = "tabs") {
val tabs = CollectionTab.entries
PrimaryScrollableTabRow(selectedTabIndex = tabs.indexOf(state.collectionTab), edgePadding = MusyxTheme.space.gutter) {
@@ -76,7 +88,9 @@ fun CollectionScreen(state: AppState) {
item(key = "empty") { Note(stringResource(R.string.empty_liked)) }
} else {
item(key = "play") {
- PlayBar(state, liked.tracks, summary = "${tracksWord(liked.tracks.size)} · ${durationWords(liked.tracks.sumOf { it.durationMs })}")
+ PlayBar(state, liked.tracks, summary = "${tracksWord(liked.tracks.size)} · ${durationWords(liked.tracks.sumOf { it.durationMs })}") {
+ DownloadButton(state, Downloads.LIKED, stringResource(R.string.tab_liked_tracks), state::downloadLiked)
+ }
}
trackItems(state, liked.tracks, keyPrefix = "liked", hearts = false)
}
diff --git a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Player.kt b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Player.kt
index 9399232..47ca5eb 100644
--- a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Player.kt
+++ b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Player.kt
@@ -198,8 +198,11 @@ private fun TrackInfo(state: AppState, p: PlaybackState, track: Track) {
Text(noticeText(notice), style = MusyxTheme.type.meta, color = c.like, maxLines = 2)
}
}
- IconButton(onClick = { state.likeTrack(track, !liked) }) {
- MusyxIcon(if (liked) R.drawable.ic_heart_fill else R.drawable.ic_heart, tint = if (liked) c.like else c.fg)
+ // Offline there's no collection to change.
+ if (state.client != null) {
+ IconButton(onClick = { state.likeTrack(track, !liked) }) {
+ MusyxIcon(if (liked) R.drawable.ic_heart_fill else R.drawable.ic_heart, tint = if (liked) c.like else c.fg)
+ }
}
IconButton(onClick = { state.openSheet(Sheet.TrackMenu(track)) }) { MusyxIcon(R.drawable.ic_ellipsis) }
}
diff --git a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Settings.kt b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Settings.kt
index abe8299..52d6f43 100644
--- a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Settings.kt
+++ b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Settings.kt
@@ -1,6 +1,7 @@
// Settings: account, streaming quality, appearance, font size, language, storage.
package it.panov.musyx.mobile.ui.screens
+import android.text.format.Formatter
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -13,12 +14,19 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.AlertDialog
import androidx.compose.material3.FilterChip
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import it.panov.musyx.data.Appearance
@@ -110,6 +118,7 @@ fun SettingsScreen(state: AppState) {
MusyxIcon(R.drawable.ic_trash_2, size = 18.dp)
Text(stringResource(R.string.action_clear_covers), modifier = Modifier.padding(start = 8.dp))
}
+ Downloads(state)
}
}
item(key = "version") {
@@ -123,6 +132,39 @@ fun SettingsScreen(state: AppState) {
}
}
+/** What downloads take, and a way to remove them all after asking. */
+@Composable
+private fun Downloads(state: AppState) {
+ val d = state.downloads
+ var confirm by remember { mutableStateOf(false) }
+ val size = Formatter.formatShortFileSize(LocalContext.current, d.bytes)
+ Text(
+ if (d.hasAny) stringResource(R.string.settings_downloads, size) else stringResource(R.string.settings_downloads_none),
+ style = MusyxTheme.type.meta,
+ color = MusyxTheme.colors.muted,
+ )
+ if (d.hasAny) {
+ OutlinedButton(onClick = { confirm = true }) {
+ MusyxIcon(R.drawable.ic_trash_2, size = 18.dp)
+ Text(stringResource(R.string.action_clear_downloads), modifier = Modifier.padding(start = 8.dp))
+ }
+ }
+ if (confirm) {
+ AlertDialog(
+ onDismissRequest = { confirm = false },
+ title = { Text(stringResource(R.string.clear_downloads_title)) },
+ text = { Text(stringResource(R.string.clear_downloads_body)) },
+ confirmButton = {
+ TextButton(onClick = { confirm = false; state.clearDownloads() }) {
+ Text(stringResource(R.string.action_remove), color = MusyxTheme.colors.like)
+ }
+ },
+ dismissButton = { TextButton(onClick = { confirm = false }) { Text(stringResource(R.string.action_cancel)) } },
+ containerColor = MusyxTheme.colors.panel,
+ )
+ }
+}
+
@Composable
private fun Section(title: String, content: @Composable () -> Unit) {
val space = MusyxTheme.space
diff --git a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Sheets.kt b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Sheets.kt
index 8a0f6e4..5b26a0a 100644
--- a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Sheets.kt
+++ b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Sheets.kt
@@ -126,6 +126,8 @@ private fun TrackMenu(state: AppState, sheet: Sheet.TrackMenu) {
val disliked = track.id in state.likes.dislikedTracks
// Where the menu was opened: no "go to" for the page already showing.
val here = state.nav.current
+ // Offline, only the queue and downloads work.
+ val online = state.client != null
Head(track.fullTitle, track.artistsOrUnknown().ifEmpty { null }) { Thumb(track.coverUrl(COVER_SMALL), track.hues, 48.dp) }
HorizontalDivider(color = MusyxTheme.colors.line)
Actions {
@@ -134,6 +136,12 @@ private fun TrackMenu(state: AppState, sheet: Sheet.TrackMenu) {
else Item(R.drawable.ic_skip_forward, stringResource(R.string.menu_play_next)) { state.playNext(track) }
}
item { Item(R.drawable.ic_list_music, stringResource(R.string.menu_add_to_queue)) { state.addToQueue(track) } }
+ if (state.downloads.isWanted(track.id)) {
+ item { Item(R.drawable.ic_trash_2, stringResource(R.string.menu_remove_download)) { state.removeDownload(track) } }
+ } else if (track.available && online) {
+ item { Item(R.drawable.ic_download, stringResource(R.string.menu_download)) { state.downloadTrack(track) } }
+ }
+ if (!online) return@Actions
item {
Item(if (liked) R.drawable.ic_heart_fill else R.drawable.ic_heart, stringResource(if (liked) R.string.menu_unlike else R.string.menu_like)) {
state.closeSheet()
diff --git a/mobile/src/main/res/drawable/ic_circle_check.xml b/mobile/src/main/res/drawable/ic_circle_check.xml
new file mode 100644
index 0000000..55b7452
--- /dev/null
+++ b/mobile/src/main/res/drawable/ic_circle_check.xml
@@ -0,0 +1,20 @@
+
+
+
+
+
+
diff --git a/mobile/src/main/res/drawable/ic_download.xml b/mobile/src/main/res/drawable/ic_download.xml
new file mode 100644
index 0000000..56c8dce
--- /dev/null
+++ b/mobile/src/main/res/drawable/ic_download.xml
@@ -0,0 +1,26 @@
+
+
+
+
+
+
+
diff --git a/mobile/src/main/res/drawable/ic_wifi_off.xml b/mobile/src/main/res/drawable/ic_wifi_off.xml
new file mode 100644
index 0000000..6d10d64
--- /dev/null
+++ b/mobile/src/main/res/drawable/ic_wifi_off.xml
@@ -0,0 +1,50 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/mobile/src/main/res/values-ru/strings_phone.xml b/mobile/src/main/res/values-ru/strings_phone.xml
index 7d9abc0..287ff04 100644
--- a/mobile/src/main/res/values-ru/strings_phone.xml
+++ b/mobile/src/main/res/values-ru/strings_phone.xml
@@ -4,4 +4,42 @@
Открыть страницу входа Яндекса
Код копируется, когда открывается страница. Вставьте его там, подтвердите вход и вернитесь сюда — дальше всё произойдёт само.
Войдите в Musyx, чтобы ваша музыка появилась здесь.
+
+ Загрузки
+ Здесь пока пусто. Скачайте альбом, плейлист или «Мне нравится» кнопкой загрузки на их странице, а трек — через его меню, и они будут играть без интернета.
+ Альбомы и плейлисты
+ Треки
+ Остальное скачается, когда появится интернет
+ Это больше не скачано.
+ Скачано %1$d из %2$d
+ Плейлист
+
+ - Скачивается, остался %1$d трек
+ - Скачивается, осталось %1$d трека
+ - Скачивается, осталось %1$d треков
+ - Скачивается, осталось %1$d трека
+
+
+ - Не удалось скачать %1$d трек
+ - Не удалось скачать %1$d трека
+ - Не удалось скачать %1$d треков
+ - Не удалось скачать %1$d трека
+
+ Скачать
+ Скачано
+ Удалить
+ Скачать
+ Удалить загрузку
+ Удалить «%1$s» с устройства?
+ Чтобы снова послушать, понадобится интернет.
+ Офлайн
+ Яндекс Музыка недоступна, поэтому играют только загрузки. Попробуйте ещё раз, когда появится интернет.
+ Загрузки занимают %1$s на устройстве.
+ Ничего не скачано.
+ Удалить все загрузки
+ Удалить все загрузки?
+ Все скачанные треки будут удалены с устройства. Ваша музыка в Яндексе останется как есть.
+ Загрузки
+ Скачивание для прослушивания офлайн
+ %1$d из %2$d · %3$s
diff --git a/mobile/src/main/res/values/strings_phone.xml b/mobile/src/main/res/values/strings_phone.xml
index c07949c..f1ee941 100644
--- a/mobile/src/main/res/values/strings_phone.xml
+++ b/mobile/src/main/res/values/strings_phone.xml
@@ -6,4 +6,38 @@
Opening the page copies the code. Paste it there, confirm, and come back: sign-in finishes on its own.
Sign in to Musyx to see your music here.
+
+ Downloads
+ Nothing downloaded yet. Use the download button on an album, a playlist or Liked tracks, or Download in a track\'s menu, and it plays without a connection.
+ Albums and playlists
+ Tracks
+ Waiting for a connection to download the rest
+ This isn\'t downloaded any more.
+ Downloaded: %1$d of %2$d
+ Playlist
+
+ - Downloading, %1$d track to go
+ - Downloading, %1$d tracks to go
+
+
+ - %1$d track couldn\'t be downloaded
+ - %1$d tracks couldn\'t be downloaded
+
+ Download
+ Downloaded
+ Remove
+ Download
+ Remove download
+ Remove “%1$s” from the device?
+ It will need a connection to play again.
+ Offline
+ Yandex Music can\'t be reached, so only downloads play. Try again once you\'re connected.
+ Downloads take %1$s on this device.
+ Nothing is downloaded.
+ Remove all downloads
+ Remove all downloads?
+ Every downloaded track is deleted from this device. Your music on Yandex stays as it is.
+ Downloads
+ Downloading for offline listening
+ %1$d of %2$d · %3$s
diff --git a/tv/src/main/java/it/panov/musyx/tv/ui/MusyxApp.kt b/tv/src/main/java/it/panov/musyx/tv/ui/MusyxApp.kt
index 8fd265b..9bd1f48 100644
--- a/tv/src/main/java/it/panov/musyx/tv/ui/MusyxApp.kt
+++ b/tv/src/main/java/it/panov/musyx/tv/ui/MusyxApp.kt
@@ -162,6 +162,8 @@ private fun Page(state: AppState, route: Route, entry: FocusEntry) {
is Route.Album -> AlbumScreen(state, route, entry)
is Route.Artist -> ArtistScreen(state, route, entry)
is Route.Playlist -> PlaylistScreen(state, route, entry)
+ // Downloading is the phone's; while Yandex is out of reach the TV shows its own screen.
+ is Route.Downloads -> {}
}
}