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

@@ -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<ArtistRef>): 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<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 {
fun from(t: JsonElement?): Track? {
val id = t.str("id") ?: return null
@@ -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 <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) {
try {
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.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 <T> file(url: String, read: (InputStream, contentLength: Long) -> T): T = http.file(url, read)
// ---- Library ----
/** 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.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()
}
@@ -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)
@@ -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<Int> = 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<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 ----
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)
@@ -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. */
+5
View File
@@ -52,6 +52,11 @@
<string name="toast_quality">Качество звука: %1$s. Применится со следующего трека.</string>
<string name="toast_covers_cleared">Кеш обложек очищен</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">
<item quantity="one">Играем %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_covers_cleared">Cover cache cleared</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">
<item quantity="one">Playing %1$d track 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)
}
@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(