Add offline listening to the phone app

Albums, playlists and Liked tracks get a download button beside the heart,
and every track's menu offers Download or Remove download. Files are fetched
one at a time at the streaming quality, stored decrypted with their covers,
and play from the device even online. A downloaded album, playlist or Liked
tracks follows later changes to it. What's wanted is saved before it's
fetched, so a download cut short resumes when the connection returns or the
app next starts; a foreground service with a progress notification keeps it
going with the screen off.

Collection links to a Downloads page listing what's on the device, with
progress, failures and a retry. When Yandex can't be reached at launch and
something is downloaded, the app opens on that page with the player instead
of the "can't reach" screen, and reconnects by itself when the network
returns. Offline, menus and Now Playing hide what needs a connection, and
lyrics say they can't load instead of waiting forever. Settings shows the
space downloads take and can remove them all.

Another account signing in clears the previous one's downloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Yuriy PanovandClaude Opus 5.5 committed 2026-10-23 14:12:34 +06:00
1 parent c13a4053ac
commit d3b3e139b5
31 files changed
+1451 -35

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
<!-- @license lucide-static v0.460.0 - ISC -->
<svg
class="lucide lucide-circle-check"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="10" />
<path d="m9 12 2 2 4-4" />
</svg>

After

Width:  |  Height:  |  Size: 357 B

+17
View File
@@ -0,0 +1,17 @@
<!-- @license lucide-static v0.460.0 - ISC -->
<svg
class="lucide lucide-download"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="7 10 12 15 17 10" />
<line x1="12" x2="12" y1="15" y2="3" />
</svg>

After

Width:  |  Height:  |  Size: 428 B

+21
View File
@@ -0,0 +1,21 @@
<!-- @license lucide-static v0.460.0 - ISC -->
<svg
class="lucide lucide-wifi-off"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 20h.01" />
<path d="M8.5 16.429a5 5 0 0 1 7 0" />
<path d="M5 12.859a10 10 0 0 1 5.17-2.69" />
<path d="M19 12.859a10 10 0 0 0-2.007-1.523" />
<path d="M2 8.82a15 15 0 0 1 4.177-2.643" />
<path d="M22 8.82a15 15 0 0 0-11.288-3.764" />
<path d="m2 2 20 20" />
</svg>

After

Width:  |  Height:  |  Size: 574 B

@@ -3,6 +3,11 @@
package it.panov.musyx.api package it.panov.musyx.api
import kotlinx.serialization.json.JsonElement 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. */ /** Absolute URL for a `%%`-templated image uri at `size`×`size` pixels. */
fun coverUrl(uri: String?, size: Int): String? { fun coverUrl(uri: String?, size: Int): String? {
@@ -21,6 +26,12 @@ fun joinNames(artists: List<ArtistRef>): String? =
data class ArtistRef(val id: Long?, val name: String, private val coverUri: String? = null) { data class ArtistRef(val id: Long?, val name: String, private val coverUri: String? = null) {
fun coverUrl(size: Int): String? = coverUrl(coverUri, size) 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) data class AlbumRef(val id: Long, val title: String, val year: Int? = null)
@@ -55,6 +66,29 @@ data class Track(
val hues: Pair<Float, Float> get() = CoverHues.track(id, album?.id) val hues: Pair<Float, Float> 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 { companion object {
fun from(t: JsonElement?): Track? { fun from(t: JsonElement?): Track? {
val id = t.str("id") ?: return null val id = t.str("id") ?: return null
@@ -15,6 +15,7 @@ import okhttp3.OkHttpClient
import okhttp3.Request import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException import java.io.IOException
import java.io.InputStream
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import kotlin.random.Random 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 <T> 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) { private suspend fun send(request: Request): JsonElement = withContext(Dispatchers.IO) {
try { try {
Http.api.newCall(request).execute().use { response -> Http.api.newCall(request).execute().use { response ->
@@ -11,6 +11,7 @@ import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put import kotlinx.serialization.json.put
import java.io.InputStream
/** How many featured podcasts to resolve. */ /** How many featured podcasts to resolve. */
const val FEATURED_PODCASTS = 48 const val FEATURED_PODCASTS = 48
@@ -101,6 +102,9 @@ class YmClient private constructor(
return stream(trackId, null) return stream(trackId, null)
} }
/** Reads the file at `url`, a link from [stream] or [losslessStream], as its host sends it. */
suspend fun <T> file(url: String, read: (InputStream, contentLength: Long) -> T): T = http.file(url, read)
// ---- Library ---- // ---- Library ----
/** Albums the user liked, newest first, with full details. */ /** Albums the user liked, newest first, with full details. */
@@ -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<Float, Float>,
val trackIds: List<String>,
) {
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<Int> = 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<String, OfflineTrack> by mutableStateOf(emptyMap())
private set
/** Tracks downloaded on their own, not as part of a set. */
var singles: List<String> by mutableStateOf(emptyList())
private set
var sets: List<OfflineSet> by mutableStateOf(emptyList())
private set
/** The track being fetched and how far along it is, 0 to 1. */
var current: Pair<String, Float>? by mutableStateOf(null)
private set
/** Tracks that couldn't be fetched this run; tried again on [retry] or the next launch. */
var failed: Set<String> 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<Track> 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<Track> = 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<Int, Int> = 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<Float, Float>, list: List<Track>) {
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<Track>) {
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<Track>) {
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<String>) {
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<String> = coverSizes.mapNotNull { coverUrl(it) }
/** Every cover a wanted track or set uses. */
private fun coverUrls(): List<String> =
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<String, Saved> = emptyMap(),
val singles: List<String> = emptyList(),
val sets: List<SavedSet> = 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<String> = 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) }
}
}
@@ -18,6 +18,7 @@ import androidx.media3.common.util.UnstableApi
import androidx.media3.database.StandaloneDatabaseProvider import androidx.media3.database.StandaloneDatabaseProvider
import androidx.media3.datasource.DataSource import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSpec import androidx.media3.datasource.DataSpec
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.DefaultHttpDataSource import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.datasource.ResolvingDataSource import androidx.media3.datasource.ResolvingDataSource
import androidx.media3.datasource.cache.CacheDataSource import androidx.media3.datasource.cache.CacheDataSource
@@ -105,7 +106,8 @@ class ExoEngine(
} else { } else {
null 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 decrypting = AesCtrDataSource.Factory(source) { uri: Uri -> keys[uri.toString()] }
val loadControl = DefaultLoadControl.Builder() val loadControl = DefaultLoadControl.Builder()
.setBufferDurationsMs(buffering.minMs, buffering.maxMs, buffering.startMs, buffering.resumeMs) .setBufferDurationsMs(buffering.minMs, buffering.maxMs, buffering.startMs, buffering.resumeMs)
@@ -165,7 +167,8 @@ class ExoEngine(
override fun preload(stream: Stream) { override fun preload(stream: Stream) {
if (cached == null) return if (cached == null) return
cancelPreload() 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() if (ready && !exo.isLoading) startPreload()
} }
@@ -16,6 +16,7 @@ import it.panov.musyx.api.Stream
import it.panov.musyx.api.Track import it.panov.musyx.api.Track
import it.panov.musyx.api.WaveSettings import it.panov.musyx.api.WaveSettings
import it.panov.musyx.api.YmClient import it.panov.musyx.api.YmClient
import it.panov.musyx.api.YmError
import it.panov.musyx.data.Quality import it.panov.musyx.data.Quality
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@@ -50,6 +51,8 @@ class PlaybackController(
private val waveSettings: () -> WaveSettings?, private val waveSettings: () -> WaveSettings?,
private val token: () -> String?, private val token: () -> String?,
private val onSignedOut: () -> Unit, private val onSignedOut: () -> Unit,
/** A downloaded track's file as a stream, or null. */
private val local: (trackId: String) -> Stream?,
buffering: Buffering, buffering: Buffering,
) : EngineEvents { ) : EngineEvents {
private val core = PlayerCore() private val core = PlayerCore()
@@ -151,17 +154,14 @@ class PlaybackController(
val api = client() val api = client()
for (effect in effects) when (effect) { for (effect in effects) when (effect) {
Effect.SignedOut -> onSignedOut() Effect.SignedOut -> onSignedOut()
is Effect.Fetch -> api?.let { c -> // Downloaded tracks play without a session, so these go ahead offline too.
scope.launch { is Effect.Fetch -> scope.launch {
val result = runCatching { resolve(c, effect.trackId) } val result = runCatching { resolve(api, effect.trackId) }
update { core.fetched(effect.generation, result) } update { core.fetched(effect.generation, result) }
}
} }
is Effect.Prefetch -> api?.let { c -> is Effect.Prefetch -> scope.launch {
scope.launch { val result = runCatching { resolve(api, effect.trackId) }
val result = runCatching { resolve(c, effect.trackId) } core.prefetched(effect.trackId, result)
core.prefetched(effect.trackId, result)
}
} }
is Effect.WaveFetch -> api?.let { c -> is Effect.WaveFetch -> api?.let { c ->
// My Wave's settings ride along as seeds when a session starts. // 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 { /** A downloaded file when there is one, else a link from Yandex. */
val q = quality() private suspend fun resolve(c: YmClient?, trackId: String): Stream =
return if (q == Quality.Lossless) c.losslessStream(trackId) else c.stream(trackId, q.maxKbps) local(trackId) ?: resolveStream(c ?: throw YmError.Network("offline"), trackId, quality())
}
private companion object { private companion object {
const val TAG = "Musyx" 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)
@@ -34,9 +34,12 @@ import it.panov.musyx.api.Track
import it.panov.musyx.api.WaveSettings import it.panov.musyx.api.WaveSettings
import it.panov.musyx.api.YmClient import it.panov.musyx.api.YmClient
import it.panov.musyx.api.YmError import it.panov.musyx.api.YmError
import it.panov.musyx.api.huesFor
import it.panov.musyx.data.Appearance import it.panov.musyx.data.Appearance
import it.panov.musyx.data.FontSize import it.panov.musyx.data.FontSize
import it.panov.musyx.data.CredentialStore 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.Locale
import it.panov.musyx.data.Quality import it.panov.musyx.data.Quality
import it.panov.musyx.data.Settings import it.panov.musyx.data.Settings
@@ -49,6 +52,9 @@ import kotlinx.coroutines.launch
/** Tracks in Home's "Recently played". */ /** Tracks in Home's "Recently played". */
const val RECENT = 10 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. */ /** Where sign-in stands. Everything but [SignedIn] takes the whole screen. */
sealed interface Session { sealed interface Session {
/** Reading the stored credentials and checking the token. */ /** Reading the stored credentials and checking the token. */
@@ -80,6 +86,8 @@ class AppState(
private val clearCovers: suspend () -> Unit, private val clearCovers: suspend () -> Unit,
/** How far ahead playback loads; the phone loads further than the TV. */ /** How far ahead playback loads; the phone loads further than the TV. */
buffering: Buffering = Buffering.Default, buffering: Buffering = Buffering.Default,
/** Cover sizes the interface shows, kept with downloads so they appear offline. */
coverSizes: List<Int> = emptyList(),
) { ) {
var session: Session by mutableStateOf(Session.Restoring) var session: Session by mutableStateOf(Session.Restoring)
private set private set
@@ -140,6 +148,8 @@ class AppState(
val search = SearchState(scope, ::client, ::failed) val search = SearchState(scope, ::client, ::failed)
val downloads = Downloads(context, scope, ::client, { settings.quality }, coverSizes)
val playback = PlaybackController( val playback = PlaybackController(
context = context, context = context,
scope = scope, scope = scope,
@@ -148,6 +158,7 @@ class AppState(
waveSettings = { waveShown }, waveSettings = { waveShown },
token = { credentials?.accessToken }, token = { credentials?.accessToken },
onSignedOut = ::signOut, onSignedOut = ::signOut,
local = downloads::stream,
buffering = buffering, buffering = buffering,
) )
@@ -198,6 +209,8 @@ class AppState(
// Credentials stay for a retry when Yandex is only unreachable. // Credentials stay for a retry when Yandex is only unreachable.
if (err.isRetryable) { if (err.isRetryable) {
credentials = creds credentials = creds
// Downloads are what's left to play; the phone shows them.
nav.reset(Route.Downloads())
session = Session.Unreachable session = Session.Unreachable
} else { } else {
forget(err) forget(err)
@@ -246,6 +259,7 @@ class AppState(
credentials = creds credentials = creds
nav.reset(Route.Home) nav.reset(Route.Home)
session = Session.SignedIn(client, account) session = Session.SignedIn(client, account)
downloads.attach(account.uid)
// Liked tracks drive the hearts; playlists feed "Add to playlist"; Home is the first page. // Liked tracks drive the hearts; playlists feed "Add to playlist"; Home is the first page.
loadLiked() loadLiked()
loadLikedIds() loadLikedIds()
@@ -357,7 +371,7 @@ class AppState(
loadTab(CollectionTab.Albums) loadTab(CollectionTab.Albums)
} }
is Route.Album, is Route.Artist, is Route.Playlist -> loadPage(route) 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") else -> error("not a page: $route")
} }
}, },
) { pages[route] = it } ) {
pages[route] = it
it.get()?.let(::syncDownload)
}
} }
// ---- Loading ---- // ---- Loading ----
@@ -436,6 +453,7 @@ class AppState(
is Loadable.Failed -> Liked.Failed(r.error) is Loadable.Failed -> Liked.Failed(r.error)
else -> Liked.NotLoaded 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<Float, Float>, tracks: List<Track>) {
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 ---- // ---- My Wave ----
fun setWaveSettings(next: WaveSettings) { 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. */ /** Lyrics for `track`, fetched once while the lyrics tab shows it: Yandex's, else LRCLIB's. */
fun wantLyrics(track: Track) { 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 lyrics[track.id] = Loadable.Loading
load({ it.lyrics(track.id) ?: Lrclib.lyrics(track) }) { lyrics[track.id] = it } load({ it.lyrics(track.id) ?: Lrclib.lyrics(track) }) { lyrics[track.id] = it }
} }
@@ -654,6 +749,7 @@ class AppState(
fun likeTrack(track: Track, on: Boolean) { fun likeTrack(track: Track, on: Boolean) {
liked = liked.with(track, on) liked = liked.with(track, on)
syncLiked()
if (on) likes = likes.copy(dislikedTracks = likes.dislikedTracks - track.id) 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) { edit(UiText.Res(if (on) R.string.toast_liked else R.string.toast_unliked), likeFailed) {
it.setTrackLiked(track.fullId, on) it.setTrackLiked(track.fullId, on)
@@ -21,6 +21,8 @@ sealed interface Route {
data class Playlist(val id: PlaylistId) : Route data class Playlist(val id: PlaylistId) : Route
/** Index into the app's flattened genre list. */ /** Index into the app's flattened genre list. */
data class Genre(val index: Int) : Route 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 { companion object {
/** Navigation drawer order. */ /** Navigation drawer order. */
+5
View File
@@ -52,6 +52,11 @@
<string name="toast_quality">Качество звука: %1$s. Применится со следующего трека.</string> <string name="toast_quality">Качество звука: %1$s. Применится со следующего трека.</string>
<string name="toast_covers_cleared">Кеш обложек очищен</string> <string name="toast_covers_cleared">Кеш обложек очищен</string>
<string name="toast_covers_failed">Не удалось очистить кеш обложек.</string> <string name="toast_covers_failed">Не удалось очистить кеш обложек.</string>
<string name="toast_downloading">«%1$s» скачивается для прослушивания офлайн</string>
<string name="toast_downloading_liked">«Мне нравится» скачивается для прослушивания офлайн</string>
<string name="toast_download_removed">«%1$s» удалено с устройства</string>
<string name="toast_liked_download_removed">«Мне нравится» удалено с устройства</string>
<string name="toast_downloads_cleared">Все загрузки удалены</string>
<plurals name="toast_playing_similar"> <plurals name="toast_playing_similar">
<item quantity="one">Играем %1$d трек в духе «%2$s»</item> <item quantity="one">Играем %1$d трек в духе «%2$s»</item>
<item quantity="few">Играем %1$d трека в духе «%2$s»</item> <item quantity="few">Играем %1$d трека в духе «%2$s»</item>
+5
View File
@@ -52,6 +52,11 @@
<string name="toast_quality">Streaming quality: %1$s. Applies from the next track.</string> <string name="toast_quality">Streaming quality: %1$s. Applies from the next track.</string>
<string name="toast_covers_cleared">Cover cache cleared</string> <string name="toast_covers_cleared">Cover cache cleared</string>
<string name="toast_covers_failed">Couldn\'t clear the cover cache.</string> <string name="toast_covers_failed">Couldn\'t clear the cover cache.</string>
<string name="toast_downloading">Downloading “%1$s” for offline listening</string>
<string name="toast_downloading_liked">Downloading Liked tracks for offline listening</string>
<string name="toast_download_removed">Removed “%1$s” from the device</string>
<string name="toast_liked_download_removed">Removed Liked tracks from the device</string>
<string name="toast_downloads_cleared">All downloads removed</string>
<plurals name="toast_playing_similar"> <plurals name="toast_playing_similar">
<item quantity="one">Playing %1$d track like “%2$s”</item> <item quantity="one">Playing %1$d track like “%2$s”</item>
<item quantity="other">Playing %1$d tracks like “%2$s”</item> <item quantity="other">Playing %1$d tracks like “%2$s”</item>
@@ -37,6 +37,23 @@ class ApiTest {
assertEquals("12345:77", t.fullId) 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 @Test
fun trackCarriesAlbumYearAndArtistPhotos() { fun trackCarriesAlbumYearAndArtistPhotos() {
val t = Track.from( val t = Track.from(
+9
View File
@@ -6,6 +6,9 @@
<uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<!-- To carry on downloading, or reconnect from offline, when a connection comes back. -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application <application
@@ -52,6 +55,12 @@
</intent-filter> </intent-filter>
</service> </service>
<!-- Holds the app up while tracks download for offline listening. -->
<service
android:name=".DownloadService"
android:exported="false"
android:foregroundServiceType="dataSync" />
<!-- Covers for Android Auto, which can't load https itself. Read-only, Yandex hosts only. --> <!-- Covers for Android Auto, which can't load https itself. Read-only, Yandex hosts only. -->
<provider <provider
android:name=".ArtworkProvider" android:name=".ArtworkProvider"
@@ -0,0 +1,106 @@
// Keeps the app running while downloads are under way, with a notification counting them off.
// The downloading itself happens in the app's Downloads; this only holds the process up and
// shows how far it has got, so a long playlist finishes with the screen off.
package it.panov.musyx.mobile
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
import it.panov.musyx.data.DownloadProgress
class DownloadService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
running = true
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val progress = latest
if (progress == null) {
stopSelf()
return START_NOT_STICKY
}
val type = if (Build.VERSION.SDK_INT >= 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()
}
}
}
@@ -4,23 +4,33 @@ package it.panov.musyx.mobile
import android.app.Application import android.app.Application
import android.content.Context import android.content.Context
import android.content.res.Resources 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 androidx.core.os.ConfigurationCompat
import coil3.ImageLoader import coil3.ImageLoader
import coil3.PlatformContext import coil3.PlatformContext
import coil3.SingletonImageLoader import coil3.SingletonImageLoader
import coil3.disk.DiskCache import coil3.disk.DiskCache
import coil3.disk.directory import coil3.disk.directory
import coil3.intercept.Interceptor
import coil3.memory.MemoryCache import coil3.memory.MemoryCache
import coil3.network.okhttp.OkHttpNetworkFetcherFactory import coil3.network.okhttp.OkHttpNetworkFetcherFactory
import coil3.request.ImageResult
import coil3.request.crossfade import coil3.request.crossfade
import it.panov.musyx.api.Lrclib import it.panov.musyx.api.Lrclib
import it.panov.musyx.data.CredentialStore import it.panov.musyx.data.CredentialStore
import it.panov.musyx.data.Downloads
import it.panov.musyx.data.SettingsStore 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.player.Buffering
import it.panov.musyx.state.AppState import it.panov.musyx.state.AppState
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
class Musyx : Application(), SingletonImageLoader.Factory { class Musyx : Application(), SingletonImageLoader.Factory {
@@ -30,6 +40,21 @@ class Musyx : Application(), SingletonImageLoader.Factory {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
Lrclib.agent = "Musyx/${BuildConfig.VERSION_NAME} (https://git.panov.it/panov/musyz-mobile)" 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 { 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. // Mobile data slows and drops out: buffer whole tracks and preload the next one.
buffering = Buffering.Mobile, 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. */ /** 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) 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() } .memoryCache { MemoryCache.Builder().maxSizePercent(context, 0.2).build() }
.diskCache { .diskCache {
DiskCache.Builder().directory(cacheDir.resolve("covers")).maxSizeBytes(COVER_CACHE_BYTES).build() DiskCache.Builder().directory(cacheDir.resolve("covers")).maxSizeBytes(COVER_CACHE_BYTES).build()
@@ -57,6 +86,15 @@ class Musyx : Application(), SingletonImageLoader.Factory {
.crossfade(true) .crossfade(true)
.build() .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 { companion object {
private const val COVER_CACHE_BYTES = 200L * 1024 * 1024 private const val COVER_CACHE_BYTES = 200L * 1024 * 1024
@@ -9,6 +9,7 @@ import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row 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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.layout.statusBarsPadding
@@ -28,6 +30,7 @@ import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.ui.Alignment 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.AlbumScreen
import it.panov.musyx.mobile.ui.screens.ArtistScreen import it.panov.musyx.mobile.ui.screens.ArtistScreen
import it.panov.musyx.mobile.ui.screens.ChartScreen 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.CollectionScreen
import it.panov.musyx.mobile.ui.screens.GenreScreen import it.panov.musyx.mobile.ui.screens.GenreScreen
import it.panov.musyx.mobile.ui.screens.HoldingScreen import it.panov.musyx.mobile.ui.screens.HoldingScreen
@@ -67,11 +71,14 @@ fun MusyxApp(state: AppState, onExit: () -> Unit) {
when (val s = state.session) { when (val s = state.session) {
Session.Restoring -> HoldingScreen(stringResource(R.string.session_checking)) Session.Restoring -> HoldingScreen(stringResource(R.string.session_checking))
is Session.Connecting -> HoldingScreen(stringResource(R.string.session_signing_in)) 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.SignedOut -> SignInScreen(s.signIn)
is Session.SignedIn -> Shell(state, onExit) 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), 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 @Composable
private fun Shell(state: AppState, onExit: () -> Unit) { private fun Shell(state: AppState, onExit: () -> Unit, offline: Boolean = false) {
val route = state.nav.current val route = state.nav.current
val pages = rememberSaveableStateHolder() val pages = rememberSaveableStateHolder()
BackHandler { if (!state.back()) onExit() } BackHandler { if (!state.back()) onExit() }
Scaffold( Scaffold(
containerColor = MusyxTheme.colors.bg, containerColor = MusyxTheme.colors.bg,
topBar = { TopBar(state, route) }, topBar = { TopBar(state, route, offline) },
bottomBar = { 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) if (state.playback.state.hasTrack) MiniPlayer(state)
NavBar(state.nav.section, state::navigate) if (!offline) NavBar(state.nav.section, state::navigate)
} }
}, },
) { padding -> ) { padding ->
Box(Modifier.fillMaxSize().padding(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) ToastHost(state)
} }
} }
@@ -137,12 +147,16 @@ private fun Page(state: AppState, route: Route) {
is Route.Album -> AlbumScreen(state, route) is Route.Album -> AlbumScreen(state, route)
is Route.Artist -> ArtistScreen(state, route) is Route.Artist -> ArtistScreen(state, route)
is Route.Playlist -> PlaylistScreen(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 @Composable
private fun TopBar(state: AppState, route: Route) { private fun TopBar(state: AppState, route: Route, offline: Boolean) {
Row( Row(
Modifier.fillMaxWidth().statusBarsPadding().height(56.dp).padding(horizontal = 4.dp), Modifier.fillMaxWidth().statusBarsPadding().height(56.dp).padding(horizontal = 4.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
@@ -153,7 +167,14 @@ private fun TopBar(state: AppState, route: Route) {
IconButton(onClick = { state.back() }) { MusyxIcon(R.drawable.ic_chevron_left) } IconButton(onClick = { state.back() }) { MusyxIcon(R.drawable.ic_chevron_left) }
} }
Spacer(Modifier.weight(1f)) 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) } IconButton(onClick = { state.navigate(Route.Settings) }) { MusyxIcon(R.drawable.ic_settings, tint = MusyxTheme.colors.muted) }
} }
} }
@@ -66,6 +66,7 @@ fun LazyListScope.trackItems(
track = track, track = track,
playing = state.playback.state.track?.id == track.id, playing = state.playback.state.track?.id == track.id,
liked = state.liked.contains(track.id), liked = state.liked.contains(track.id),
downloaded = state.downloads.isDone(track.id),
columns = columns, columns = columns,
shift = shifts?.getOrNull(i), shift = shifts?.getOrNull(i),
onPlay = { state.playTracks(tracks, i) }, onPlay = { state.playTracks(tracks, i) },
@@ -85,6 +86,8 @@ fun TrackRow(
track: Track, track: Track,
playing: Boolean, playing: Boolean,
liked: Boolean, liked: Boolean,
/** On the device, so it plays offline. */
downloaded: Boolean,
columns: Columns, columns: Columns,
shift: Int?, shift: Int?,
onPlay: () -> Unit, onPlay: () -> Unit,
@@ -124,7 +127,10 @@ fun TrackRow(
(if (columns.artist) track.artistsOrUnknown() else track.album?.title).takeIf { !it.isNullOrEmpty() }, (if (columns.artist) track.artistsOrUnknown() else track.album?.title).takeIf { !it.isNullOrEmpty() },
clock(track.durationMs), clock(track.durationMs),
).joinToString(" · ") ).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) { if (onLike != null) {
IconButton(onClick = onLike) { IconButton(onClick = onLike) {
@@ -31,6 +31,7 @@ import it.panov.musyx.api.ArtistPage
import it.panov.musyx.api.PlaylistPage import it.panov.musyx.api.PlaylistPage
import it.panov.musyx.api.PlaylistSummary import it.panov.musyx.api.PlaylistSummary
import it.panov.musyx.api.YmError import it.panov.musyx.api.YmError
import it.panov.musyx.data.Downloads
import it.panov.musyx.mobile.R import it.panov.musyx.mobile.R
import it.panov.musyx.mobile.ui.components.COVER_LARGE import it.panov.musyx.mobile.ui.components.COVER_LARGE
import it.panov.musyx.mobile.ui.components.Columns import it.panov.musyx.mobile.ui.components.Columns
@@ -123,7 +124,10 @@ private fun LazyListScope.albumPage(state: AppState, info: AlbumPage) {
} }
item(key = "play") { item(key = "play") {
val liked = a.id in state.likes.albums 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") 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 val liked = p.id in state.likes.playlists
LikeButton(liked) { state.likePlaylist(p.id, !liked) } 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") trackItems(state, info.tracks, playlist = if (own) p.id else null, positions = info.positions, keyPrefix = "pl")
@@ -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
},
)
@@ -18,6 +18,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import it.panov.musyx.data.Downloads
import it.panov.musyx.mobile.R import it.panov.musyx.mobile.R
import it.panov.musyx.mobile.ui.components.CardGrid import it.panov.musyx.mobile.ui.components.CardGrid
import it.panov.musyx.mobile.ui.components.Failure import it.panov.musyx.mobile.ui.components.Failure
@@ -48,6 +49,17 @@ private fun tabLabel(tab: CollectionTab) = when (tab) {
fun CollectionScreen(state: AppState) { fun CollectionScreen(state: AppState) {
PageColumn { PageColumn {
item(key = "title") { ScreenTitle(stringResource(R.string.nav_collection)) } 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") { item(key = "tabs") {
val tabs = CollectionTab.entries val tabs = CollectionTab.entries
PrimaryScrollableTabRow(selectedTabIndex = tabs.indexOf(state.collectionTab), edgePadding = MusyxTheme.space.gutter) { 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)) } item(key = "empty") { Note(stringResource(R.string.empty_liked)) }
} else { } else {
item(key = "play") { 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) trackItems(state, liked.tracks, keyPrefix = "liked", hearts = false)
} }
@@ -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) Text(noticeText(notice), style = MusyxTheme.type.meta, color = c.like, maxLines = 2)
} }
} }
IconButton(onClick = { state.likeTrack(track, !liked) }) { // Offline there's no collection to change.
MusyxIcon(if (liked) R.drawable.ic_heart_fill else R.drawable.ic_heart, tint = if (liked) c.like else c.fg) 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) } IconButton(onClick = { state.openSheet(Sheet.TrackMenu(track)) }) { MusyxIcon(R.drawable.ic_ellipsis) }
} }
@@ -1,6 +1,7 @@
// Settings: account, streaming quality, appearance, font size, language, storage. // Settings: account, streaming quality, appearance, font size, language, storage.
package it.panov.musyx.mobile.ui.screens package it.panov.musyx.mobile.ui.screens
import android.text.format.Formatter
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box 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.layout.size
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChip
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable 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.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import it.panov.musyx.data.Appearance import it.panov.musyx.data.Appearance
@@ -110,6 +118,7 @@ fun SettingsScreen(state: AppState) {
MusyxIcon(R.drawable.ic_trash_2, size = 18.dp) MusyxIcon(R.drawable.ic_trash_2, size = 18.dp)
Text(stringResource(R.string.action_clear_covers), modifier = Modifier.padding(start = 8.dp)) Text(stringResource(R.string.action_clear_covers), modifier = Modifier.padding(start = 8.dp))
} }
Downloads(state)
} }
} }
item(key = "version") { 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 @Composable
private fun Section(title: String, content: @Composable () -> Unit) { private fun Section(title: String, content: @Composable () -> Unit) {
val space = MusyxTheme.space val space = MusyxTheme.space
@@ -126,6 +126,8 @@ private fun TrackMenu(state: AppState, sheet: Sheet.TrackMenu) {
val disliked = track.id in state.likes.dislikedTracks val disliked = track.id in state.likes.dislikedTracks
// Where the menu was opened: no "go to" for the page already showing. // Where the menu was opened: no "go to" for the page already showing.
val here = state.nav.current 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) } Head(track.fullTitle, track.artistsOrUnknown().ifEmpty { null }) { Thumb(track.coverUrl(COVER_SMALL), track.hues, 48.dp) }
HorizontalDivider(color = MusyxTheme.colors.line) HorizontalDivider(color = MusyxTheme.colors.line)
Actions { 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) } 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) } } 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 {
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)) { 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() state.closeSheet()
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide circle-check (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 2 12 a 10 10 0 1 0 20 0 a 10 10 0 1 0 -20 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="m 9 12 2 2 4 -4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide download (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 21 15 v 4 a 2 2 0 0 1 -2 2 H 5 a 2 2 0 0 1 -2 -2 v -4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 7 10 L 12 15 L 17 10"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 12 15 L 12 3"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide wifi-off (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 12 20 h 0.01"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 8.5 16.429 a 5 5 0 0 1 7 0"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 5 12.859 a 10 10 0 0 1 5.17 -2.69"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 19 12.859 a 10 10 0 0 0 -2.007 -1.523"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 2 8.82 a 15 15 0 0 1 4.177 -2.643"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 22 8.82 a 15 15 0 0 0 -11.288 -3.764"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="m 2 2 20 20"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -4,4 +4,42 @@
<string name="signin_open_page">Открыть страницу входа Яндекса</string> <string name="signin_open_page">Открыть страницу входа Яндекса</string>
<string name="signin_phone_hint">Код копируется, когда открывается страница. Вставьте его там, подтвердите вход и вернитесь сюда — дальше всё произойдёт само.</string> <string name="signin_phone_hint">Код копируется, когда открывается страница. Вставьте его там, подтвердите вход и вернитесь сюда — дальше всё произойдёт само.</string>
<string name="auto_sign_in">Войдите в Musyx, чтобы ваша музыка появилась здесь.</string> <string name="auto_sign_in">Войдите в Musyx, чтобы ваша музыка появилась здесь.</string>
<!-- Офлайн. -->
<string name="downloads_title">Загрузки</string>
<string name="downloads_empty">Здесь пока пусто. Скачайте альбом, плейлист или «Мне нравится» кнопкой загрузки на их странице, а трек — через его меню, и они будут играть без интернета.</string>
<string name="downloads_sets">Альбомы и плейлисты</string>
<string name="downloads_tracks">Треки</string>
<string name="downloads_waiting">Остальное скачается, когда появится интернет</string>
<string name="downloads_gone">Это больше не скачано.</string>
<string name="downloads_set_progress">Скачано %1$d из %2$d</string>
<string name="downloads_kind_playlist">Плейлист</string>
<plurals name="downloads_left">
<item quantity="one">Скачивается, остался %1$d трек</item>
<item quantity="few">Скачивается, осталось %1$d трека</item>
<item quantity="many">Скачивается, осталось %1$d треков</item>
<item quantity="other">Скачивается, осталось %1$d трека</item>
</plurals>
<plurals name="downloads_failed">
<item quantity="one">Не удалось скачать %1$d трек</item>
<item quantity="few">Не удалось скачать %1$d трека</item>
<item quantity="many">Не удалось скачать %1$d треков</item>
<item quantity="other">Не удалось скачать %1$d трека</item>
</plurals>
<string name="action_download">Скачать</string>
<string name="action_downloaded">Скачано</string>
<string name="action_remove">Удалить</string>
<string name="menu_download">Скачать</string>
<string name="menu_remove_download">Удалить загрузку</string>
<string name="download_remove_title">Удалить «%1$s» с устройства?</string>
<string name="download_remove_body">Чтобы снова послушать, понадобится интернет.</string>
<string name="offline_badge">Офлайн</string>
<string name="offline_note">Яндекс Музыка недоступна, поэтому играют только загрузки. Попробуйте ещё раз, когда появится интернет.</string>
<string name="settings_downloads">Загрузки занимают %1$s на устройстве.</string>
<string name="settings_downloads_none">Ничего не скачано.</string>
<string name="action_clear_downloads">Удалить все загрузки</string>
<string name="clear_downloads_title">Удалить все загрузки?</string>
<string name="clear_downloads_body">Все скачанные треки будут удалены с устройства. Ваша музыка в Яндексе останется как есть.</string>
<string name="notify_downloads_channel">Загрузки</string>
<string name="notify_downloading">Скачивание для прослушивания офлайн</string>
<string name="notify_progress">%1$d из %2$d · %3$s</string>
</resources> </resources>
@@ -6,4 +6,38 @@
<string name="signin_phone_hint">Opening the page copies the code. Paste it there, confirm, and come back: sign-in finishes on its own.</string> <string name="signin_phone_hint">Opening the page copies the code. Paste it there, confirm, and come back: sign-in finishes on its own.</string>
<!-- Shown in the car (Android Auto or Automotive) when nobody is signed in. --> <!-- Shown in the car (Android Auto or Automotive) when nobody is signed in. -->
<string name="auto_sign_in">Sign in to Musyx to see your music here.</string> <string name="auto_sign_in">Sign in to Musyx to see your music here.</string>
<!-- Offline listening. -->
<string name="downloads_title">Downloads</string>
<string name="downloads_empty">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.</string>
<string name="downloads_sets">Albums and playlists</string>
<string name="downloads_tracks">Tracks</string>
<string name="downloads_waiting">Waiting for a connection to download the rest</string>
<string name="downloads_gone">This isn\'t downloaded any more.</string>
<string name="downloads_set_progress">Downloaded: %1$d of %2$d</string>
<string name="downloads_kind_playlist">Playlist</string>
<plurals name="downloads_left">
<item quantity="one">Downloading, %1$d track to go</item>
<item quantity="other">Downloading, %1$d tracks to go</item>
</plurals>
<plurals name="downloads_failed">
<item quantity="one">%1$d track couldn\'t be downloaded</item>
<item quantity="other">%1$d tracks couldn\'t be downloaded</item>
</plurals>
<string name="action_download">Download</string>
<string name="action_downloaded">Downloaded</string>
<string name="action_remove">Remove</string>
<string name="menu_download">Download</string>
<string name="menu_remove_download">Remove download</string>
<string name="download_remove_title">Remove “%1$s” from the device?</string>
<string name="download_remove_body">It will need a connection to play again.</string>
<string name="offline_badge">Offline</string>
<string name="offline_note">Yandex Music can\'t be reached, so only downloads play. Try again once you\'re connected.</string>
<string name="settings_downloads">Downloads take %1$s on this device.</string>
<string name="settings_downloads_none">Nothing is downloaded.</string>
<string name="action_clear_downloads">Remove all downloads</string>
<string name="clear_downloads_title">Remove all downloads?</string>
<string name="clear_downloads_body">Every downloaded track is deleted from this device. Your music on Yandex stays as it is.</string>
<string name="notify_downloads_channel">Downloads</string>
<string name="notify_downloading">Downloading for offline listening</string>
<string name="notify_progress">%1$d of %2$d · %3$s</string>
</resources> </resources>
@@ -162,6 +162,8 @@ private fun Page(state: AppState, route: Route, entry: FocusEntry) {
is Route.Album -> AlbumScreen(state, route, entry) is Route.Album -> AlbumScreen(state, route, entry)
is Route.Artist -> ArtistScreen(state, route, entry) is Route.Artist -> ArtistScreen(state, route, entry)
is Route.Playlist -> PlaylistScreen(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 -> {}
} }
} }