Split the shared code into a core module
The Yandex Music client, the player, the app state and the stores move from the TV app to :core (it.panov.musyx.*), so a phone app can build on them. The TV app becomes :tv with the same application id. CoverHues, SessionPlayer and the strings the state layer shows move with them; LRCLIB's user agent is set by each app. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
90ac73facc
commit
4c978efa80
121 files changed
+464
-397
No files matched your search
@@ -0,0 +1,110 @@
|
||||
// Yandex OAuth device flow: show a code, the user confirms it on Yandex's page (or scans
|
||||
// the QR), poll until a token arrives. Uses the official Android app's public client id,
|
||||
// because third parties can't register an app for the music API.
|
||||
package it.panov.musyx.api
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import okhttp3.FormBody
|
||||
import okhttp3.Request
|
||||
import java.io.IOException
|
||||
|
||||
private const val OAUTH = "https://oauth.yandex.ru"
|
||||
private const val CLIENT_ID = "23cabbbdc6cd418abb4b39c32c41195d"
|
||||
private const val CLIENT_SECRET = "53bc75238f0c4d08a118e51fe9203300"
|
||||
/** Shown on Yandex's list of signed-in devices. */
|
||||
private const val DEVICE_NAME = "Musyx TV"
|
||||
/** Yandex rate-limits polling; faster than this turns a pending login into a rejected one. */
|
||||
private const val MIN_POLL_SEC = 3L
|
||||
|
||||
/** A pending sign-in: what to show the user and what to poll with. */
|
||||
class DeviceCode(
|
||||
val userCode: String,
|
||||
val verificationUrl: String,
|
||||
val expiresInSec: Long,
|
||||
val intervalSec: Long,
|
||||
internal val deviceCode: String,
|
||||
) {
|
||||
override fun toString() = "DeviceCode($userCode, $verificationUrl)"
|
||||
}
|
||||
|
||||
sealed interface Poll {
|
||||
/** The user hasn't confirmed yet. Keep polling at [DeviceCode.intervalSec]. */
|
||||
data object Pending : Poll
|
||||
data class Granted(val credentials: Credentials) : Poll
|
||||
}
|
||||
|
||||
object Auth {
|
||||
suspend fun requestCode(): DeviceCode {
|
||||
val deviceId = (1..10).map { ALPHANUMERIC.random() }.joinToString("")
|
||||
val v = post("/device/code", "client_id" to CLIENT_ID, "device_id" to deviceId, "device_name" to DEVICE_NAME)
|
||||
return DeviceCode(
|
||||
deviceCode = v.str("device_code") ?: throw YmError.Api("device code response carried no device code"),
|
||||
userCode = v.str("user_code") ?: throw YmError.Api("device code response carried no user code"),
|
||||
verificationUrl = v.str("verification_url") ?: "https://ya.ru/device",
|
||||
expiresInSec = v.long("expires_in") ?: 300,
|
||||
intervalSec = (v.long("interval") ?: 5).coerceAtLeast(MIN_POLL_SEC),
|
||||
)
|
||||
}
|
||||
|
||||
/** Poll once. [Poll.Pending] is the normal answer until the user confirms. */
|
||||
suspend fun poll(code: DeviceCode): Poll = try {
|
||||
val v = post(
|
||||
"/token",
|
||||
"grant_type" to "device_code", "code" to code.deviceCode,
|
||||
"client_id" to CLIENT_ID, "client_secret" to CLIENT_SECRET,
|
||||
)
|
||||
Poll.Granted(credentials(v))
|
||||
} catch (e: OAuthRejected) {
|
||||
if ("authorization_pending" in e.text) Poll.Pending else throw YmError.fromOAuth(e.text)
|
||||
}
|
||||
|
||||
/** Swap a refresh token for a new pair. Store the result: Yandex rotates the refresh token. */
|
||||
suspend fun refresh(old: Credentials): Credentials {
|
||||
val refresh = old.refreshToken ?: throw YmError.Unauthorized("no refresh token")
|
||||
val v = try {
|
||||
post(
|
||||
"/token",
|
||||
"grant_type" to "refresh_token", "refresh_token" to refresh,
|
||||
"client_id" to CLIENT_ID, "client_secret" to CLIENT_SECRET,
|
||||
)
|
||||
} catch (e: OAuthRejected) {
|
||||
throw YmError.fromOAuth(e.text)
|
||||
}
|
||||
val fresh = credentials(v)
|
||||
// Keep the old refresh token if Yandex didn't rotate it.
|
||||
return if (fresh.refreshToken == null) Credentials(fresh.accessToken, old.refreshToken, fresh.expiresAt) else fresh
|
||||
}
|
||||
|
||||
private fun credentials(v: JsonElement): Credentials {
|
||||
val access = v.str("access_token") ?: throw YmError.Api("token response carried no access token")
|
||||
val now = System.currentTimeMillis() / 1000
|
||||
return Credentials(access, v.str("refresh_token"), v.long("expires_in")?.let { now + it })
|
||||
}
|
||||
|
||||
/** A 400 from the OAuth server: its text decides between pending and a real failure. */
|
||||
private class OAuthRejected(val text: String) : Exception(text)
|
||||
|
||||
private suspend fun post(path: String, vararg fields: Pair<String, String>): JsonElement = withContext(Dispatchers.IO) {
|
||||
val body = FormBody.Builder().apply { fields.forEach { (k, v) -> add(k, v) } }.build()
|
||||
val request = Request.Builder().url(OAUTH + path)
|
||||
.header("X-Yandex-Music-Client", CLIENT_HEADER)
|
||||
.post(body)
|
||||
.build()
|
||||
try {
|
||||
Http.api.newCall(request).execute().use { response ->
|
||||
val json = parseJson(response.body.string())
|
||||
when {
|
||||
response.isSuccessful -> json
|
||||
response.code == 400 -> throw OAuthRejected(errorMessage(json, 400))
|
||||
else -> throw statusError(response.code, json, path)
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
throw YmError.Network(e.message ?: "io")
|
||||
}
|
||||
}
|
||||
|
||||
private val ALPHANUMERIC = ('A'..'Z') + ('a'..'z') + ('0'..'9')
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Placeholder art seeds: every item without a cover gets two stable hues, as on the desktop.
|
||||
package it.panov.musyx.api
|
||||
|
||||
/** Two stable hues for placeholder art; equal seeds give equal art. Port of ym-api `hues_for`. */
|
||||
fun huesFor(seed: ULong): Pair<Float, Float> =
|
||||
(seed * 47uL % 360uL).toFloat() to ((seed * 131uL + 90uL) % 360uL).toFloat()
|
||||
|
||||
/** Seeds per item kind, as in ym-api, so an item gets the same art as on the desktop. */
|
||||
object CoverHues {
|
||||
fun album(id: Long) = huesFor(id.toULong())
|
||||
fun artist(id: Long) = huesFor(id.toULong() xor 0x5bd1_e995uL)
|
||||
fun playlist(owner: Long, kind: Long) = huesFor(owner.toULong() * 1_000_003uL xor kind.toULong())
|
||||
fun clip(id: Long) = huesFor(id.toULong() xor 0x2c1b_3c6duL)
|
||||
|
||||
/** A track borrows its album's art, or hashes its own (string) id. */
|
||||
fun track(id: String, albumId: Long?): Pair<Float, Float> = huesFor(
|
||||
albumId?.toULong() ?: id.encodeToByteArray().fold(7uL) { h, b -> h * 31uL + b.toUByte().toULong() },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// What the credential store keeps. `toString` never prints the tokens.
|
||||
package it.panov.musyx.api
|
||||
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
|
||||
/** Refresh once less than this much lifetime is left. */
|
||||
private const val REFRESH_MARGIN_SEC = 7L * 24 * 3600
|
||||
|
||||
class Credentials(
|
||||
val accessToken: String,
|
||||
val refreshToken: String? = null,
|
||||
/** Unix seconds; null when Yandex didn't say (pasted tokens). */
|
||||
val expiresAt: Long? = null,
|
||||
) {
|
||||
/** True when the token expires within a week and can be refreshed. */
|
||||
fun needsRefresh(nowSec: Long = System.currentTimeMillis() / 1000): Boolean {
|
||||
if (refreshToken == null || expiresAt == null) return false
|
||||
return expiresAt - nowSec < REFRESH_MARGIN_SEC
|
||||
}
|
||||
|
||||
fun toJson(): String = JsonObject(
|
||||
buildMap {
|
||||
put("access_token", JsonPrimitive(accessToken))
|
||||
refreshToken?.let { put("refresh_token", JsonPrimitive(it)) }
|
||||
expiresAt?.let { put("expires_at", JsonPrimitive(it)) }
|
||||
},
|
||||
).toString()
|
||||
|
||||
override fun toString() = "Credentials(<redacted>, refresh=${refreshToken != null}, expiresAt=$expiresAt)"
|
||||
|
||||
override fun equals(other: Any?) = other is Credentials && other.accessToken == accessToken &&
|
||||
other.refreshToken == refreshToken && other.expiresAt == expiresAt
|
||||
|
||||
override fun hashCode() = accessToken.hashCode()
|
||||
|
||||
companion object {
|
||||
/** A token the user pasted. Its lifetime is unknown, so it is never refreshed. */
|
||||
fun fromToken(token: String) = Credentials(token.trim())
|
||||
|
||||
fun fromJson(json: String): Credentials {
|
||||
val v = parseJson(json)
|
||||
return Credentials(v.str("access_token") ?: error("no access token"), v.str("refresh_token"), v.long("expires_at"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// Tolerant readers over kotlinx JSON trees. The API sends ids as numbers or strings and
|
||||
// drops fields freely, so every model is read field by field instead of through a schema.
|
||||
package it.panov.musyx.api
|
||||
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
import kotlinx.serialization.json.longOrNull
|
||||
|
||||
internal val JsonParser = Json { ignoreUnknownKeys = true; isLenient = true }
|
||||
|
||||
internal fun parseJson(text: String): JsonElement =
|
||||
runCatching { JsonParser.parseToJsonElement(text) }.getOrDefault(JsonNull)
|
||||
|
||||
internal val JsonElement?.obj: JsonObject? get() = this as? JsonObject
|
||||
internal val JsonElement?.arr: JsonArray? get() = this as? JsonArray
|
||||
|
||||
internal operator fun JsonElement?.get(key: String): JsonElement? = (this as? JsonObject)?.get(key)
|
||||
|
||||
/** A string field; numbers are given as their text. Blank strings count as missing. */
|
||||
internal fun JsonElement?.str(key: String): String? = this[key].asString()
|
||||
|
||||
internal fun JsonElement?.asString(): String? {
|
||||
val p = this as? JsonPrimitive ?: return null
|
||||
if (p is JsonNull) return null
|
||||
return p.content.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
/** A whole number from a number or a numeric string. */
|
||||
internal fun JsonElement?.long(key: String): Long? = this[key].asLong()
|
||||
|
||||
internal fun JsonElement?.asLong(): Long? {
|
||||
val p = this as? JsonPrimitive ?: return null
|
||||
if (p is JsonNull) return null
|
||||
return p.longOrNull ?: p.doubleOrNull?.toLong() ?: p.content.trim().toLongOrNull()
|
||||
}
|
||||
|
||||
internal fun JsonElement?.double(key: String): Double? {
|
||||
val p = this[key] as? JsonPrimitive ?: return null
|
||||
if (p is JsonNull) return null
|
||||
return p.doubleOrNull ?: p.content.toDoubleOrNull()
|
||||
}
|
||||
|
||||
internal fun JsonElement?.bool(key: String): Boolean? {
|
||||
val p = this[key] as? JsonPrimitive ?: return null
|
||||
if (p is JsonNull) return null
|
||||
return p.booleanOrNull ?: when (p.content) {
|
||||
"1" -> true
|
||||
"0" -> false
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/** The elements of an array field; missing or not an array is empty. */
|
||||
internal fun JsonElement?.list(key: String): List<JsonElement> = this[key].arr.orEmpty()
|
||||
|
||||
internal fun JsonElement?.strings(key: String): List<String> = list(key).mapNotNull { it.asString() }
|
||||
|
||||
/** The API wraps payloads as `{"result": …}`; this unwraps when it does. */
|
||||
internal fun JsonElement.result(): JsonElement = this["result"] ?: this
|
||||
@@ -0,0 +1,129 @@
|
||||
// LRCLIB (lrclib.net): an open lyrics database, asked when Yandex has no lyrics for a track.
|
||||
// No key; it asks clients to name themselves in the User-Agent.
|
||||
package it.panov.musyx.api
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.Request
|
||||
import java.io.IOException
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToLong
|
||||
|
||||
private const val LRCLIB_BASE = "https://lrclib.net/api"
|
||||
|
||||
object Lrclib {
|
||||
/** How this app names itself to LRCLIB; each app sets its own name and version at startup. */
|
||||
var agent = "Musyx (https://git.panov.it/panov/musyz-mobile)"
|
||||
|
||||
/** How far a search result's length may be from the track's and still be the same recording. */
|
||||
internal const val DURATION_SLACK_S = 3.0
|
||||
|
||||
/**
|
||||
* Lyrics for `track`: the exact match by title, artist, album and length first, then the
|
||||
* closest search result. Null for speech, instrumentals and tracks LRCLIB doesn't know.
|
||||
*/
|
||||
suspend fun lyrics(track: Track): Lyrics? {
|
||||
if (track.spoken) return null
|
||||
val artist = track.artists.firstOrNull()?.name ?: return null
|
||||
val seconds = (track.durationMs / 1000.0).takeIf { it > 0 }
|
||||
if (seconds != null) {
|
||||
val exact = try {
|
||||
get(
|
||||
"/get",
|
||||
Params().add("track_name", track.title).add("artist_name", artist)
|
||||
.add("album_name", track.album?.title?.takeIf { it.isNotBlank() })
|
||||
.add("duration", seconds.roundToLong()),
|
||||
)
|
||||
} catch (e: YmError) {
|
||||
// `/get` answers 503 "ServerOverloaded" now and then; search still works then.
|
||||
if (e is YmError.NotFound || e.isRetryable) null else throw e
|
||||
}
|
||||
if (exact != null) {
|
||||
val l = fromRecord(exact)
|
||||
// The exact match is often a plain-text copy of a recording that has a synced one.
|
||||
if (l == null || l.synced) return l
|
||||
val found = try {
|
||||
get("/search", Params().add("track_name", track.title).add("artist_name", artist))
|
||||
} catch (e: YmError) {
|
||||
return l
|
||||
}
|
||||
return better(l, pick(found.arr.orEmpty(), seconds)?.let(::fromRecord))
|
||||
}
|
||||
}
|
||||
val found = get("/search", Params().add("track_name", track.title).add("artist_name", artist))
|
||||
return pick(found.arr.orEmpty(), seconds)?.let(::fromRecord)
|
||||
}
|
||||
|
||||
/** The exact match's plain lyrics, unless search found the same recording synced. */
|
||||
internal fun better(exact: Lyrics, searched: Lyrics?): Lyrics = if (searched?.synced == true) searched else exact
|
||||
|
||||
/** A record's lyrics, synced when it has them; null for instrumentals and empty records. */
|
||||
internal fun fromRecord(r: JsonElement): Lyrics? {
|
||||
if (r.bool("instrumental") == true) return null
|
||||
r.str("syncedLyrics")?.takeIf { it.isNotBlank() }?.let { lrc ->
|
||||
Lyrics.fromLrc(lrc, emptyList(), LyricsSource.Lrclib).takeIf { it.lines.isNotEmpty() }?.let { return it }
|
||||
}
|
||||
return r.str("plainLyrics")?.takeIf { it.isNotBlank() }
|
||||
?.let { Lyrics.fromText(it.trim(), emptyList(), LyricsSource.Lrclib) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The search result for a track `seconds` long: lengths within the slack only (any length
|
||||
* when it's unknown), synced over plain, then the closest. An instrumental closest match
|
||||
* means there are no lyrics, not that a further one should stand in.
|
||||
*/
|
||||
internal fun pick(results: List<JsonElement>, seconds: Double?): JsonElement? {
|
||||
fun off(r: JsonElement): Double {
|
||||
val d = r.double("duration") ?: return Double.MAX_VALUE
|
||||
return if (seconds == null) 0.0 else abs(d - seconds)
|
||||
}
|
||||
val near = results.filter { off(it) <= DURATION_SLACK_S }.sortedBy(::off)
|
||||
if (near.firstOrNull()?.bool("instrumental") == true) return null
|
||||
val withLyrics = near.filter { fromRecord(it) != null }
|
||||
return withLyrics.firstOrNull { !it.str("syncedLyrics").isNullOrBlank() } ?: withLyrics.firstOrNull()
|
||||
}
|
||||
|
||||
/** A GET, tried again twice when LRCLIB says it's busy (429, 503), as its error asks. */
|
||||
private suspend fun get(path: String, params: Params): JsonElement {
|
||||
val url = (LRCLIB_BASE + path).toHttpUrl().newBuilder().apply {
|
||||
params.pairs.forEach { (k, v) -> addQueryParameter(k, v) }
|
||||
}.build()
|
||||
val request = Request.Builder().url(url).header("User-Agent", agent).get().build()
|
||||
var attempt = 0
|
||||
while (true) {
|
||||
val (status, retryAfter, body) = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
Http.api.newCall(request).execute().use { r -> Triple(r.code, r.header("Retry-After"), r.body.string()) }
|
||||
} catch (e: IOException) {
|
||||
throw YmError.Network(e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
if (status in 200..299) return parseJson(body)
|
||||
if ((status == 429 || status == 503) && attempt < 2) {
|
||||
delay(retryDelayMs(retryAfter, attempt))
|
||||
attempt += 1
|
||||
continue
|
||||
}
|
||||
throw lrclibError(status, path)
|
||||
}
|
||||
}
|
||||
|
||||
/** `Retry-After` seconds when given, else 1 s then 2 s; never more than 3 s on a TV that's waiting. */
|
||||
internal fun retryDelayMs(retryAfter: String?, attempt: Int): Long {
|
||||
val asked = retryAfter?.trim()?.toLongOrNull()?.let { it * 1000 }
|
||||
return (asked ?: (1000L shl attempt)).coerceIn(0, 3000)
|
||||
}
|
||||
|
||||
/** Never `Unauthorized`: that signs the user out of Yandex, and LRCLIB has no accounts. */
|
||||
internal fun lrclibError(status: Int, path: String): YmError {
|
||||
val message = "lrclib $path: http $status"
|
||||
return when {
|
||||
status == 404 -> YmError.NotFound(message)
|
||||
status == 429 || status >= 500 -> YmError.Network(message)
|
||||
else -> YmError.Api(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Lyrics: synced (LRC) or plain text. Port of ym-api edit.rs.
|
||||
package it.panov.musyx.api
|
||||
|
||||
/** One line of lyrics; synced lyrics carry the moment it's sung. */
|
||||
data class LyricLine(val atMs: Long?, val text: String)
|
||||
|
||||
/** Where lyrics came from; anything but Yandex is credited under them. */
|
||||
enum class LyricsSource { Yandex, Lrclib }
|
||||
|
||||
data class Lyrics(
|
||||
val lines: List<LyricLine>,
|
||||
val synced: Boolean,
|
||||
val writers: List<String>,
|
||||
val source: LyricsSource = LyricsSource.Yandex,
|
||||
) {
|
||||
/** The line being sung at `positionMs`: the last line that has started. */
|
||||
fun current(positionMs: Long): Int? {
|
||||
if (!synced) return null
|
||||
return lines.indexOfLast { it.atMs != null && it.atMs <= positionMs }.takeIf { it >= 0 }
|
||||
}
|
||||
|
||||
/**
|
||||
* The few lines a glance from the sofa shows at `positionMs`: synced, the line being sung
|
||||
* between its neighbours (before the first, just the first, to come); plain, the line as far
|
||||
* through the words as the song is through its `durationMs`. Null when there's nothing to show.
|
||||
*/
|
||||
fun glance(positionMs: Long, durationMs: Long): Glance? {
|
||||
if (synced) {
|
||||
if (lines.isEmpty()) return null
|
||||
val i = current(positionMs) ?: return Glance(null, null, lines.first().text)
|
||||
return Glance(lines.getOrNull(i - 1)?.text, lines[i].text, lines.getOrNull(i + 1)?.text)
|
||||
}
|
||||
val words = lines.map { it.text }.filter { it.isNotBlank() }
|
||||
if (words.isEmpty() || durationMs <= 0) return null
|
||||
val i = (positionMs.coerceIn(0, durationMs) * words.size / durationMs).toInt().coerceAtMost(words.size - 1)
|
||||
return Glance(words.getOrNull(i - 1), words[i], words.getOrNull(i + 1))
|
||||
}
|
||||
|
||||
/** Three lines around now; an empty line is a break in the singing. */
|
||||
data class Glance(val previous: String?, val current: String?, val next: String?)
|
||||
|
||||
companion object {
|
||||
/** Plain text: one line per line, blank lines kept as paragraph breaks. */
|
||||
fun fromText(text: String, writers: List<String>, source: LyricsSource = LyricsSource.Yandex) =
|
||||
Lyrics(text.lines().map { LyricLine(null, it.trimEnd()) }, synced = false, writers = writers, source = source)
|
||||
|
||||
/** LRC: `[mm:ss.xx] words`. Lines with several stamps repeat; metadata tags are dropped. */
|
||||
fun fromLrc(lrc: String, writers: List<String>, source: LyricsSource = LyricsSource.Yandex): Lyrics {
|
||||
val lines = mutableListOf<LyricLine>()
|
||||
for (raw in lrc.lines()) {
|
||||
var rest = raw.trim()
|
||||
val stamps = mutableListOf<Long>()
|
||||
while (rest.startsWith('[')) {
|
||||
val end = rest.indexOf(']')
|
||||
if (end < 0) break
|
||||
val at = parseStamp(rest.substring(1, end))
|
||||
if (at == null) {
|
||||
// `[ar:Artist]` and friends: not a lyric line.
|
||||
stamps.clear()
|
||||
rest = ""
|
||||
break
|
||||
}
|
||||
stamps += at
|
||||
rest = rest.substring(end + 1).trimStart()
|
||||
}
|
||||
for (at in stamps) lines += LyricLine(at, rest)
|
||||
}
|
||||
return Lyrics(lines.sortedBy { it.atMs }, synced = true, writers = writers, source = source)
|
||||
}
|
||||
|
||||
/** `mm:ss`, `mm:ss.x`, `mm:ss.xx` or `mm:ss.xxx`. */
|
||||
internal fun parseStamp(s: String): Long? {
|
||||
val colon = s.indexOf(':')
|
||||
if (colon < 0) return null
|
||||
val min = s.substring(0, colon).trim().toLongOrNull() ?: return null
|
||||
val sec = s.substring(colon + 1)
|
||||
val whole = sec.substringBefore('.').toLongOrNull() ?: return null
|
||||
val frac = if ('.' in sec) sec.substringAfter('.') else ""
|
||||
if (whole >= 60 || frac.length > 3 || !frac.all { it.isDigit() }) return null
|
||||
val millis = if (frac.isEmpty()) 0 else frac.toLong() * pow10(3 - frac.length)
|
||||
return (min * 60 + whole) * 1000 + millis
|
||||
}
|
||||
|
||||
private fun pow10(n: Int): Long = (0 until n).fold(1L) { acc, _ -> acc * 10 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
// The app-facing shapes of API objects, keeping only what the UI uses and resolving every
|
||||
// missing field once, here. Port of ym-api's models.rs, library.rs, discover.rs and clips.rs.
|
||||
package it.panov.musyx.api
|
||||
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
|
||||
/** Absolute URL for a `%%`-templated image uri at `size`×`size` pixels. */
|
||||
fun coverUrl(uri: String?, size: Int): String? {
|
||||
if (uri.isNullOrEmpty()) return null
|
||||
val sized = uri.replace("%%", "${size}x$size")
|
||||
return when {
|
||||
sized.startsWith("//") -> "https:$sized"
|
||||
sized.startsWith("http://") || sized.startsWith("https://") -> sized
|
||||
else -> "https://$sized"
|
||||
}
|
||||
}
|
||||
|
||||
/** "Artist A, Artist B", or null when there are none (the UI says "Unknown artist"). */
|
||||
fun joinNames(artists: List<ArtistRef>): String? =
|
||||
artists.takeIf { it.isNotEmpty() }?.joinToString(", ") { it.name }
|
||||
|
||||
data class ArtistRef(val id: Long?, val name: String, private val coverUri: String? = null) {
|
||||
fun coverUrl(size: Int): String? = coverUrl(coverUri, size)
|
||||
}
|
||||
|
||||
data class AlbumRef(val id: Long, val title: String, val year: Int? = null)
|
||||
|
||||
data class Track(
|
||||
/** Numeric track id as a string; user-uploaded tracks use non-numeric ids. */
|
||||
val id: String,
|
||||
val title: String,
|
||||
/** "Remastered 2011", "Live" and the like. */
|
||||
val version: String?,
|
||||
val artists: List<ArtistRef>,
|
||||
val album: AlbumRef?,
|
||||
val durationMs: Long,
|
||||
private val coverUri: String?,
|
||||
/** False for tracks removed from the catalogue or blocked in the region. */
|
||||
val available: Boolean,
|
||||
val explicit: Boolean,
|
||||
val lyricsAvailable: Boolean,
|
||||
/** A podcast episode or a chapter of an audiobook, not a song. */
|
||||
val spoken: Boolean = false,
|
||||
) {
|
||||
/** `trackId:albumId`, the form station feedback and queues use. */
|
||||
val fullId: String
|
||||
get() = if (album != null && ':' !in id) "$id:${album.id}" else id
|
||||
|
||||
val artistLine: String? get() = joinNames(artists)
|
||||
|
||||
/** Title with its version: "Song (Live)". */
|
||||
val fullTitle: String get() = if (version != null) "$title ($version)" else title
|
||||
|
||||
fun coverUrl(size: Int): String? = coverUrl(coverUri, size)
|
||||
|
||||
val hues: Pair<Float, Float> get() = CoverHues.track(id, album?.id)
|
||||
|
||||
companion object {
|
||||
fun from(t: JsonElement?): Track? {
|
||||
val id = t.str("id") ?: return null
|
||||
val firstAlbum = t.list("albums").firstOrNull()
|
||||
val albumKind = AlbumKind.from(firstAlbum.str("metaType"), firstAlbum.str("type"))
|
||||
val album = t.list("albums").firstNotNullOfOrNull { a ->
|
||||
a.long("id")?.let { AlbumRef(it, a.str("title").orEmpty(), a.long("year")?.toInt()) }
|
||||
}
|
||||
val info = t["lyricsInfo"]
|
||||
return Track(
|
||||
id = id,
|
||||
title = t.str("title") ?: "Untitled",
|
||||
version = t.str("version")?.takeIf { it.isNotBlank() },
|
||||
artists = artistRefs(t.list("artists")),
|
||||
album = album,
|
||||
durationMs = (t.long("durationMs") ?: 0).coerceAtLeast(0),
|
||||
coverUri = t.str("coverUri") ?: t.str("ogImage"),
|
||||
available = t.bool("available") ?: true,
|
||||
explicit = t.bool("explicit") == true || t.str("contentWarning") == "explicit",
|
||||
// `lyricsInfo` is the current, per-account answer; the old flag can say yes
|
||||
// when the lyrics endpoint then says no.
|
||||
lyricsAvailable = if (info != null) {
|
||||
info.bool("hasAvailableSyncLyrics") == true || info.bool("hasAvailableTextLyrics") == true
|
||||
} else {
|
||||
t.bool("lyricsAvailable") == true
|
||||
},
|
||||
spoken = t.str("type") in SPOKEN_TYPES || albumKind == AlbumKind.Podcast || albumKind == AlbumKind.Audiobook,
|
||||
)
|
||||
}
|
||||
|
||||
/** Track `type`s that are speech rather than music. */
|
||||
private val SPOKEN_TYPES = setOf("podcast-episode", "audiobook")
|
||||
|
||||
/** A bare track for tests and previews. */
|
||||
fun bare(id: String, title: String = "T$id", durationMs: Long = 100_000) =
|
||||
Track(id, title, null, emptyList(), null, durationMs, null, true, false, false)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun artistRefs(list: List<JsonElement>): List<ArtistRef> =
|
||||
list.mapNotNull { a -> a.str("name")?.let { ArtistRef(a.long("id"), it, a["cover"].str("uri") ?: a.str("ogImage")) } }
|
||||
|
||||
/** An artist's photo uris from `brief-info`: the gallery, and the artist's main photo. */
|
||||
internal fun artistPhotoUris(b: JsonElement?): List<String> =
|
||||
(b.list("allCovers").mapNotNull { it.str("uri") } + listOfNotNull(b["artist"]["cover"].str("uri"))).distinct()
|
||||
|
||||
enum class AlbumKind {
|
||||
Album, Single, Compilation, Podcast, Audiobook;
|
||||
|
||||
companion object {
|
||||
fun from(metaType: String?, type: String?): AlbumKind = when {
|
||||
// Books come as metaType "podcast" with type "audiobook": the type decides.
|
||||
type == "audiobook" || metaType == "audiobook" -> Audiobook
|
||||
metaType == "podcast" || type == "podcast" -> Podcast
|
||||
type == "single" -> Single
|
||||
type == "compilation" -> Compilation
|
||||
else -> Album
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class AlbumSummary(
|
||||
val id: Long,
|
||||
val title: String,
|
||||
val version: String?,
|
||||
val artists: List<ArtistRef>,
|
||||
val year: Int?,
|
||||
val trackCount: Int,
|
||||
val kind: AlbumKind,
|
||||
private val coverUri: String?,
|
||||
) {
|
||||
val fullTitle: String get() = if (version != null) "$title ($version)" else title
|
||||
val artistLine: String? get() = joinNames(artists)
|
||||
fun coverUrl(size: Int): String? = coverUrl(coverUri, size)
|
||||
val hues: Pair<Float, Float> get() = CoverHues.album(id)
|
||||
|
||||
val isPodcast: Boolean get() = kind == AlbumKind.Podcast || kind == AlbumKind.Audiobook
|
||||
|
||||
companion object {
|
||||
fun from(a: JsonElement?): AlbumSummary? {
|
||||
val id = a.long("id") ?: return null
|
||||
return AlbumSummary(
|
||||
id = id,
|
||||
title = a.str("title") ?: "Untitled",
|
||||
version = a.str("version")?.takeIf { it.isNotBlank() },
|
||||
artists = artistRefs(a.list("artists")),
|
||||
year = a.long("year")?.toInt(),
|
||||
trackCount = (a.long("trackCount") ?: 0).coerceAtLeast(0).toInt(),
|
||||
kind = AlbumKind.from(a.str("metaType"), a.str("type")),
|
||||
coverUri = a.str("coverUri") ?: a["cover"].str("uri"),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class ArtistSummary(
|
||||
val id: Long,
|
||||
val name: String,
|
||||
val genres: List<String>,
|
||||
val likes: Long?,
|
||||
private val coverUri: String?,
|
||||
) {
|
||||
fun coverUrl(size: Int): String? = coverUrl(coverUri, size)
|
||||
val hues: Pair<Float, Float> get() = CoverHues.artist(id)
|
||||
|
||||
companion object {
|
||||
fun from(a: JsonElement?): ArtistSummary? {
|
||||
val id = a.long("id") ?: return null
|
||||
return ArtistSummary(
|
||||
id = id,
|
||||
name = a.str("name") ?: "Unknown artist",
|
||||
genres = a.strings("genres"),
|
||||
likes = a.long("likesCount"),
|
||||
coverUri = a["cover"].str("uri") ?: a.str("ogImage"),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A playlist is addressed by its owner and a per-owner number ("kind"). */
|
||||
data class PlaylistId(val owner: Long, val kind: Long) {
|
||||
val key: String get() = "$owner:$kind"
|
||||
}
|
||||
|
||||
data class PlaylistSummary(
|
||||
val id: PlaylistId,
|
||||
val title: String,
|
||||
val ownerName: String,
|
||||
val trackCount: Int,
|
||||
val durationMs: Long,
|
||||
val public: Boolean,
|
||||
private val coverUri: String?,
|
||||
) {
|
||||
fun coverUrl(size: Int): String? = coverUrl(coverUri, size)
|
||||
val hues: Pair<Float, Float> get() = CoverHues.playlist(id.owner, id.kind)
|
||||
|
||||
companion object {
|
||||
fun from(p: JsonElement?): PlaylistSummary? {
|
||||
val owner = p["owner"]
|
||||
val uid = p.long("uid") ?: owner.long("uid") ?: return null
|
||||
val kind = p.long("kind") ?: return null
|
||||
val cover = p["cover"]
|
||||
return PlaylistSummary(
|
||||
id = PlaylistId(uid, kind),
|
||||
title = p.str("title") ?: "Untitled playlist",
|
||||
ownerName = owner.str("name") ?: owner.str("login") ?: "",
|
||||
trackCount = (p.long("trackCount") ?: 0).coerceAtLeast(0).toInt(),
|
||||
durationMs = (p.long("durationMs") ?: 0).coerceAtLeast(0),
|
||||
public = p.str("visibility") == "public",
|
||||
coverUri = cover.str("uri") ?: cover.strings("itemsUri").firstOrNull() ?: p.str("ogImage"),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The user's playlists for Collection and the "Add to playlist" list. */
|
||||
data class LibraryPlaylists(val own: List<PlaylistSummary>, val liked: List<PlaylistSummary>)
|
||||
|
||||
data class AlbumPage(
|
||||
val album: AlbumSummary,
|
||||
val tracks: List<Track>,
|
||||
val releaseDate: String?,
|
||||
val label: String?,
|
||||
val likes: Long?,
|
||||
) {
|
||||
companion object {
|
||||
fun from(a: JsonElement?): AlbumPage? {
|
||||
val album = AlbumSummary.from(a) ?: return null
|
||||
val tracks = a.list("volumes").flatMap { it.arr.orEmpty() }.mapNotNull { Track.from(it) }
|
||||
val label = a.list("labels").firstNotNullOfOrNull { it.asString() ?: it.str("name") }
|
||||
return AlbumPage(album, tracks, a.str("releaseDate"), label, a.long("likesCount"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class ArtistPage(
|
||||
val artist: ArtistSummary,
|
||||
val popular: List<Track>,
|
||||
val albums: List<AlbumSummary>,
|
||||
/** Compilations and features the artist appears on. */
|
||||
val alsoAlbums: List<AlbumSummary>,
|
||||
val similar: List<ArtistSummary>,
|
||||
val monthlyListeners: Long?,
|
||||
/** Music videos; filled by a second request. */
|
||||
val clips: List<Clip> = emptyList(),
|
||||
) {
|
||||
companion object {
|
||||
fun from(b: JsonElement?): ArtistPage? {
|
||||
val artist = ArtistSummary.from(b["artist"]) ?: return null
|
||||
return ArtistPage(
|
||||
artist = artist,
|
||||
popular = b.list("popularTracks").mapNotNull { Track.from(it) },
|
||||
albums = b.list("albums").mapNotNull { AlbumSummary.from(it) },
|
||||
alsoAlbums = b.list("alsoAlbums").mapNotNull { AlbumSummary.from(it) },
|
||||
similar = b.list("similarArtists").mapNotNull { ArtistSummary.from(it) },
|
||||
monthlyListeners = b["stats"].long("lastMonthListeners"),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class PlaylistPage(
|
||||
val playlist: PlaylistSummary,
|
||||
val description: String?,
|
||||
val tracks: List<Track>,
|
||||
/**
|
||||
* Each track's index in the playlist on the server. Tracks that couldn't be resolved
|
||||
* are left out of [tracks], so edits must use these rather than row numbers.
|
||||
*/
|
||||
val positions: List<Int> = tracks.indices.toList(),
|
||||
)
|
||||
|
||||
/** A music video. Clips play on the Yandex Music website; the app lists them. */
|
||||
data class Clip(
|
||||
val id: Long,
|
||||
val title: String,
|
||||
val artists: List<ArtistRef>,
|
||||
val durationSec: Long,
|
||||
val explicit: Boolean,
|
||||
private val coverUri: String?,
|
||||
) {
|
||||
/** Where the clip plays: the Yandex Music web player. */
|
||||
val url: String get() = "https://music.yandex.ru/video?ids=$id"
|
||||
val artistLine: String? get() = joinNames(artists)
|
||||
fun coverUrl(size: Int): String? = coverUrl(coverUri, size)
|
||||
val hues: Pair<Float, Float> get() = CoverHues.clip(id)
|
||||
|
||||
companion object {
|
||||
/** A clip object from any endpoint. `artists` stand in when the clip lists none. */
|
||||
fun from(v: JsonElement?, artists: JsonElement? = null): Clip? {
|
||||
val id = v.long("clipId") ?: v.long("id") ?: return null
|
||||
var people = artistRefs(v.list("artists"))
|
||||
if (people.isEmpty()) people = artistRefs(artists.arr.orEmpty())
|
||||
return Clip(
|
||||
id = id,
|
||||
title = v.str("title") ?: "Untitled clip",
|
||||
artists = people,
|
||||
durationSec = v.long("duration") ?: 0,
|
||||
explicit = v.bool("explicit") == true,
|
||||
coverUri = v.str("thumbnail") ?: v["cover"].str("uri"),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Search and discovery ----
|
||||
|
||||
enum class SearchKind(val apiType: String) {
|
||||
All("all"), Tracks("track"), Albums("album"), Artists("artist"), Playlists("playlist"), Podcasts("podcast"),
|
||||
}
|
||||
|
||||
sealed interface BestMatch {
|
||||
data class OfTrack(val track: Track) : BestMatch
|
||||
data class OfAlbum(val album: AlbumSummary) : BestMatch
|
||||
data class OfArtist(val artist: ArtistSummary) : BestMatch
|
||||
data class OfPlaylist(val playlist: PlaylistSummary) : BestMatch
|
||||
}
|
||||
|
||||
data class Totals(
|
||||
val tracks: Int = 0,
|
||||
val albums: Int = 0,
|
||||
val artists: Int = 0,
|
||||
val playlists: Int = 0,
|
||||
val podcasts: Int = 0,
|
||||
) {
|
||||
operator fun get(kind: SearchKind): Int? = when (kind) {
|
||||
SearchKind.All -> null
|
||||
SearchKind.Tracks -> tracks
|
||||
SearchKind.Albums -> albums
|
||||
SearchKind.Artists -> artists
|
||||
SearchKind.Playlists -> playlists
|
||||
SearchKind.Podcasts -> podcasts
|
||||
}
|
||||
}
|
||||
|
||||
data class SearchResults(
|
||||
/** The query Yandex actually searched, when it corrected a typo. */
|
||||
val corrected: String? = null,
|
||||
val best: BestMatch? = null,
|
||||
val tracks: List<Track> = emptyList(),
|
||||
val albums: List<AlbumSummary> = emptyList(),
|
||||
val artists: List<ArtistSummary> = emptyList(),
|
||||
val playlists: List<PlaylistSummary> = emptyList(),
|
||||
val podcasts: List<AlbumSummary> = emptyList(),
|
||||
/** Total matches per kind, beyond the page returned. */
|
||||
val totals: Totals = Totals(),
|
||||
) {
|
||||
val isEmpty: Boolean
|
||||
get() = best == null && tracks.isEmpty() && albums.isEmpty() && artists.isEmpty() &&
|
||||
playlists.isEmpty() && podcasts.isEmpty()
|
||||
|
||||
/** This page followed by `more`, for "Show more". */
|
||||
fun plus(more: SearchResults) = copy(
|
||||
tracks = tracks + more.tracks,
|
||||
albums = albums + more.albums,
|
||||
artists = artists + more.artists,
|
||||
playlists = playlists + more.playlists,
|
||||
podcasts = podcasts + more.podcasts,
|
||||
)
|
||||
|
||||
companion object {
|
||||
fun from(s: JsonElement?): SearchResults {
|
||||
fun total(key: String) = (s[key].long("total") ?: 0).toInt()
|
||||
fun results(key: String) = s[key].list("results")
|
||||
val b = s["best"]
|
||||
val best: BestMatch? = when (b.str("type")) {
|
||||
"track" -> Track.from(b["result"])?.let { BestMatch.OfTrack(it) }
|
||||
"album", "podcast" -> AlbumSummary.from(b["result"])?.let { BestMatch.OfAlbum(it) }
|
||||
"artist" -> ArtistSummary.from(b["result"])?.let { BestMatch.OfArtist(it) }
|
||||
"playlist" -> PlaylistSummary.from(b["result"])?.let { BestMatch.OfPlaylist(it) }
|
||||
else -> null
|
||||
}
|
||||
return SearchResults(
|
||||
corrected = s.str("misspellResult").takeIf { s.bool("misspellCorrected") == true },
|
||||
best = best,
|
||||
tracks = results("tracks").mapNotNull { Track.from(it) },
|
||||
albums = results("albums").mapNotNull { AlbumSummary.from(it) },
|
||||
artists = results("artists").mapNotNull { ArtistSummary.from(it) },
|
||||
playlists = results("playlists").mapNotNull { PlaylistSummary.from(it) },
|
||||
podcasts = results("podcasts").mapNotNull { AlbumSummary.from(it) },
|
||||
totals = Totals(total("tracks"), total("albums"), total("artists"), total("playlists"), total("podcasts")),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class ChartEntry(
|
||||
val position: Int,
|
||||
/** Places moved since the last chart: positive is up. */
|
||||
val shift: Int,
|
||||
val track: Track,
|
||||
) {
|
||||
companion object {
|
||||
/** From a chart track entry: `{"track": {…}, "chart": {"position", "shift"}}`. */
|
||||
fun from(e: JsonElement?): ChartEntry? {
|
||||
val track = Track.from(e["track"]) ?: return null
|
||||
val chart = e["chart"]
|
||||
return ChartEntry((chart.long("position") ?: 0).toInt().coerceAtLeast(0), (chart.long("shift") ?: 0).toInt(), track)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A personal playlist ("Playlist of the Day", "Déjà Vu"…) with its blurb. */
|
||||
data class Personal(val playlist: PlaylistSummary, val description: String?)
|
||||
|
||||
data class Home(
|
||||
val personal: List<Personal> = emptyList(),
|
||||
val chart: List<ChartEntry> = emptyList(),
|
||||
val newReleases: List<AlbumSummary> = emptyList(),
|
||||
val newPlaylists: List<PlaylistSummary> = emptyList(),
|
||||
)
|
||||
|
||||
data class Genre(
|
||||
val id: String,
|
||||
val title: String,
|
||||
/** `#rrggbb` from Yandex, used to tint the genre tile. */
|
||||
val color: String?,
|
||||
val subGenres: List<Genre>,
|
||||
) {
|
||||
companion object {
|
||||
fun from(g: JsonElement?): Genre? {
|
||||
val titles = g["titles"]
|
||||
val title = g.str("title") ?: titles["en"].str("title") ?: titles["ru"].str("title") ?: return null
|
||||
return Genre(
|
||||
id = g.str("id") ?: return null,
|
||||
title = title,
|
||||
color = g.str("color")?.takeIf { it.startsWith('#') },
|
||||
subGenres = g.list("subGenres").mapNotNull { from(it) },
|
||||
)
|
||||
}
|
||||
|
||||
/** Top-level genres first, then every sub-genre, each once. */
|
||||
fun flatten(genres: List<Genre>): List<Genre> {
|
||||
val flat = genres.toMutableList()
|
||||
for (g in genres) for (sub in g.subGenres) if (flat.none { it.id == sub.id }) flat += sub
|
||||
return flat
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Account ----
|
||||
|
||||
/** The signed-in user as the UI needs them. */
|
||||
data class Account(
|
||||
val uid: Long,
|
||||
val login: String,
|
||||
/** Best human-readable name: display name, then full name, then login. */
|
||||
val name: String,
|
||||
/** Yandex Plus unlocks full-length tracks; without it the API serves 30-second previews. */
|
||||
val hasPlus: Boolean,
|
||||
/** When the current subscription ends, as Yandex formats it (ISO 8601). */
|
||||
val subscriptionEnd: String?,
|
||||
) {
|
||||
/** One letter for the avatar. */
|
||||
val initial: String
|
||||
get() = name.firstOrNull { it.isLetterOrDigit() }?.uppercase() ?: "?"
|
||||
|
||||
companion object {
|
||||
/** From `/account/status`; null when it describes no signed-in user. */
|
||||
fun from(status: JsonElement?): Account? {
|
||||
val account = status["account"]
|
||||
val uid = account.long("uid") ?: return null
|
||||
val login = account.str("login").orEmpty()
|
||||
val name = account.str("displayName")?.takeIf { it.isNotBlank() }
|
||||
?: account.str("fullName")?.takeIf { it.isNotBlank() }
|
||||
?: login
|
||||
val sub = status["subscription"]
|
||||
return Account(
|
||||
uid = uid,
|
||||
login = login,
|
||||
name = name,
|
||||
hasPlus = status["plus"].bool("hasPlus") == true,
|
||||
subscriptionEnd = sub.str("end") ?: sub.list("autoRenewable").firstNotNullOfOrNull { it.str("expires") },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What the user has liked or disliked, by id, for drawing hearts and bans. */
|
||||
data class LikedIds(
|
||||
val albums: Set<Long> = emptySet(),
|
||||
val artists: Set<Long> = emptySet(),
|
||||
val playlists: Set<PlaylistId> = emptySet(),
|
||||
val dislikedTracks: Set<String> = emptySet(),
|
||||
val clips: Set<Long> = emptySet(),
|
||||
)
|
||||
|
||||
/** Where a track's audio comes from. Signed URLs and the key never go to logs. */
|
||||
class Stream(
|
||||
/** Mirrors of the same file; any one works. */
|
||||
val urls: List<String>,
|
||||
/** "mp3", "aac", "flac" or "flac-mp4". */
|
||||
val codec: String,
|
||||
/** 0 when Yandex doesn't say (lossless). */
|
||||
val bitrateKbps: Int,
|
||||
/** True when only a 30-second preview is available (no Plus). */
|
||||
val preview: Boolean,
|
||||
/** Hex AES-CTR key for an encrypted (`encraw`) file. */
|
||||
val key: String?,
|
||||
) {
|
||||
val lossless: Boolean get() = codec == "flac" || codec == "flac-mp4"
|
||||
|
||||
/** "MP3 320" or "FLAC", shown on Now Playing. */
|
||||
val label: String
|
||||
get() {
|
||||
val name = codec.removeSuffix("-mp4").uppercase()
|
||||
return if (lossless || bitrateKbps == 0) name else "$name $bitrateKbps"
|
||||
}
|
||||
|
||||
/** The file format: "flac-mp4" is FLAC inside an MP4 container. */
|
||||
val container: String get() = if (codec.endsWith("-mp4")) "mp4" else codec
|
||||
|
||||
override fun toString() = "Stream($codec, $bitrateKbps kbps, preview=$preview, mirrors=${urls.size}, encrypted=${key != null})"
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Request signatures the API checks: the MP3 link, `/get-file-info` and lyrics.
|
||||
package it.panov.musyx.api
|
||||
|
||||
import java.security.MessageDigest
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
import kotlin.io.encoding.Base64
|
||||
|
||||
internal object Signing {
|
||||
private const val MP3_SALT = "XGRlBW9FXlekgbPrRHuSiA"
|
||||
private const val HMAC_KEY = "p93jhgh689SBReK6ghtw62"
|
||||
const val CODECS = "flac,flac-mp4,mp3,aac,he-aac,aac-mp4,he-aac-mp4"
|
||||
const val TRANSPORT = "encraw"
|
||||
|
||||
/** The direct MP3 link from a download-info XML, or null when a part is missing. */
|
||||
fun mp3Link(xml: String): String? {
|
||||
fun tag(name: String): String? {
|
||||
val start = xml.indexOf("<$name>").takeIf { it >= 0 } ?: return null
|
||||
val from = start + name.length + 2
|
||||
val end = xml.indexOf("</$name>", from).takeIf { it >= 0 } ?: return null
|
||||
return xml.substring(from, end)
|
||||
}
|
||||
val host = tag("host") ?: return null
|
||||
val path = tag("path") ?: return null
|
||||
val ts = tag("ts") ?: return null
|
||||
val s = tag("s") ?: return null
|
||||
val sign = md5Hex(MP3_SALT + path.removePrefix("/") + s)
|
||||
return "https://$host/get-mp3/$sign/$ts$path"
|
||||
}
|
||||
|
||||
/** `sign` for `/get-file-info`: commas removed, base64 with its last character dropped. */
|
||||
fun fileInfo(ts: Long, trackId: Long, quality: String): String {
|
||||
val message = "$ts$trackId$quality$CODECS$TRANSPORT".replace(",", "")
|
||||
return hmacBase64(message).dropLast(1)
|
||||
}
|
||||
|
||||
/** `sign` for `/tracks/{id}/lyrics`, padding kept. */
|
||||
fun lyrics(trackId: Long, ts: Long): String = hmacBase64("$trackId$ts")
|
||||
|
||||
private fun hmacBase64(message: String): String {
|
||||
val mac = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(HMAC_KEY.encodeToByteArray(), "HmacSHA256")) }
|
||||
return Base64.encode(mac.doFinal(message.encodeToByteArray()))
|
||||
}
|
||||
|
||||
fun md5Hex(text: String): String =
|
||||
MessageDigest.getInstance("MD5").digest(text.encodeToByteArray()).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// The HTTP layer: identity headers, the `result` envelope, error mapping and retries.
|
||||
package it.panov.musyx.api
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import okhttp3.FormBody
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.random.Random
|
||||
|
||||
const val API_BASE = "https://api.music.yandex.net"
|
||||
const val CLIENT_HEADER = "YandexMusicAndroid/24023621"
|
||||
private const val USER_AGENT = "Musyx-TV/0.1.0"
|
||||
|
||||
/** The language Yandex writes its own titles in: genres, Home blocks, stations. */
|
||||
enum class ContentLanguage(val wire: String) { Russian("ru"), English("en") }
|
||||
|
||||
/** Query or form parameters, in order; a list repeats its key. */
|
||||
class Params {
|
||||
internal val pairs = mutableListOf<Pair<String, String>>()
|
||||
|
||||
fun add(key: String, value: Any?): Params {
|
||||
if (value != null) pairs += key to value.toString()
|
||||
return this
|
||||
}
|
||||
|
||||
fun addAll(key: String, values: Iterable<Any>): Params {
|
||||
values.forEach { pairs += key to it.toString() }
|
||||
return this
|
||||
}
|
||||
}
|
||||
|
||||
internal object Http {
|
||||
/** One client for the whole app: API calls, downloads and ExoPlayer share its pool. */
|
||||
val client: OkHttpClient = OkHttpClient.Builder()
|
||||
.connectTimeout(10, TimeUnit.SECONDS)
|
||||
.readTimeout(30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
/** The API answers JSON calls quickly; a slow one is a dead connection. */
|
||||
val api: OkHttpClient = client.newBuilder().callTimeout(15, TimeUnit.SECONDS).build()
|
||||
}
|
||||
|
||||
/** Whether `host` is Yandex's own, so it may see the token. */
|
||||
internal fun isYandexHost(host: String): Boolean =
|
||||
host == "yandex.net" || host.endsWith(".yandex.net") || host == "yandex.ru" || host.endsWith(".yandex.ru")
|
||||
|
||||
internal class Transport(private val token: String?, val language: ContentLanguage) {
|
||||
|
||||
private fun Request.Builder.identity(url: String): Request.Builder {
|
||||
header("X-Yandex-Music-Client", CLIENT_HEADER)
|
||||
header("User-Agent", USER_AGENT)
|
||||
header("Accept-Language", language.wire)
|
||||
if (token != null && isYandexHost(url.toHttpUrl().host)) header("Authorization", "OAuth $token")
|
||||
return this
|
||||
}
|
||||
|
||||
/** A JSON GET, retried twice on network trouble. Returns the unwrapped `result`. */
|
||||
suspend fun get(path: String, params: Params = Params()): JsonElement {
|
||||
val url = (API_BASE + path).toHttpUrl().newBuilder().apply {
|
||||
params.pairs.forEach { (k, v) -> addQueryParameter(k, v) }
|
||||
}.build().toString()
|
||||
var attempt = 0
|
||||
while (true) {
|
||||
try {
|
||||
return send(Request.Builder().url(url).identity(url).get().build())
|
||||
} catch (e: YmError) {
|
||||
if (!e.isRetryable || attempt >= 2) throw e
|
||||
delay(Random.nextLong(0, minOf(4_000L, 300L shl attempt) + 1))
|
||||
attempt += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun postForm(path: String, params: Params = Params()): JsonElement {
|
||||
val url = API_BASE + path
|
||||
val body = FormBody.Builder().apply { params.pairs.forEach { (k, v) -> add(k, v) } }.build()
|
||||
return send(Request.Builder().url(url).identity(url).post(body).build())
|
||||
}
|
||||
|
||||
suspend fun postJson(path: String, body: JsonElement): JsonElement {
|
||||
if (token == null) throw YmError.Unauthorized("not signed in")
|
||||
val url = API_BASE + path
|
||||
val request = Request.Builder().url(url).identity(url)
|
||||
.post(body.toString().toRequestBody("application/json".toMediaType()))
|
||||
.build()
|
||||
return send(request)
|
||||
}
|
||||
|
||||
/** A plain-text fetch (download-info XML, lyrics files). No retry. */
|
||||
suspend fun text(url: String): String = withContext(Dispatchers.IO) {
|
||||
val request = Request.Builder().url(url).identity(url).get().build()
|
||||
try {
|
||||
Http.client.newCall(request).execute().use { response ->
|
||||
val text = response.body.string()
|
||||
if (!response.isSuccessful) throw statusError(response.code, parseJson(text), url)
|
||||
text
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
throw YmError.Network(e.message ?: "io")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun send(request: Request): JsonElement = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
Http.api.newCall(request).execute().use { response ->
|
||||
val text = response.body.string()
|
||||
val json = if (text.isBlank()) JsonNull else parseJson(text)
|
||||
if (!response.isSuccessful) throw statusError(response.code, json, request.url.encodedPath)
|
||||
if (json is JsonObject && "result" in json) json["result"]!! else json
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
throw YmError.Network(e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The message Yandex put in an error body, in any of its shapes. */
|
||||
internal fun errorMessage(body: JsonElement, status: Int): String {
|
||||
fun named(v: JsonElement?): String? {
|
||||
val o = v.obj ?: return null
|
||||
val name = o.str("name").orEmpty()
|
||||
val message = o.str("message").orEmpty()
|
||||
return listOf(name, message).filter { it.isNotEmpty() }.joinToString(": ").takeIf { it.isNotEmpty() }
|
||||
}
|
||||
named(body["result"])?.let { return it }
|
||||
named(body)?.let { return it }
|
||||
named(body["error"])?.let { return it }
|
||||
val error = (body["error"] as? JsonPrimitive)?.content
|
||||
if (error != null) {
|
||||
val description = body.str("errorDescription") ?: body.str("error_description")
|
||||
return listOfNotNull(error, description).joinToString(" ")
|
||||
}
|
||||
return "http $status"
|
||||
}
|
||||
|
||||
internal fun statusError(status: Int, body: JsonElement, what: String): YmError {
|
||||
val message = "$what: ${errorMessage(body, status)}"
|
||||
return when {
|
||||
status == 401 || status == 403 -> YmError.Unauthorized(message)
|
||||
status == 404 -> YmError.NotFound(message)
|
||||
status == 429 || status == 502 -> YmError.Network(message)
|
||||
status >= 500 -> YmError.Server(message)
|
||||
else -> YmError.Api(message)
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a mutation's answer says it went through. */
|
||||
internal fun acknowledged(result: JsonElement, loosely: Boolean = false): Boolean = when {
|
||||
result is JsonPrimitive && result.content == "ok" -> true
|
||||
result is JsonObject && ("revision" in result || result.str("status") == "ok") -> true
|
||||
loosely && result is JsonObject -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
internal fun requireAck(result: JsonElement, what: String, loosely: Boolean = false) {
|
||||
if (!acknowledged(result, loosely)) throw YmError.Api("$what was not acknowledged: $result")
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// My Wave and other radio stations ("rotor"), plus listening reports. Port of ym-api wave.rs.
|
||||
package it.panov.musyx.api
|
||||
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.TimeZone
|
||||
|
||||
/** The personal station behind "My Wave". */
|
||||
const val MY_WAVE = "user:onyourwave"
|
||||
|
||||
enum class Mood(val api: String?) {
|
||||
Any(null), Energetic("active"), Cheerful("fun"), Calm("calm"), Sad("sad");
|
||||
|
||||
companion object {
|
||||
fun from(s: String?) = entries.firstOrNull { it.api != null && it.api == s } ?: Any
|
||||
}
|
||||
}
|
||||
|
||||
enum class Character(val api: String?) {
|
||||
Default(null), Favourite("favorite"), Unfamiliar("discover"), Popular("popular");
|
||||
|
||||
companion object {
|
||||
fun from(s: String?) = entries.firstOrNull { it.api != null && it.api == s } ?: Default
|
||||
}
|
||||
}
|
||||
|
||||
enum class Language(val api: String?) {
|
||||
Any(null), Russian("russian"), Foreign("not-russian");
|
||||
|
||||
companion object {
|
||||
fun from(s: String?) = entries.firstOrNull { it.api != null && it.api == s } ?: Any
|
||||
}
|
||||
}
|
||||
|
||||
data class WaveSettings(
|
||||
val mood: Mood = Mood.Any,
|
||||
val character: Character = Character.Default,
|
||||
val language: Language = Language.Any,
|
||||
) {
|
||||
val isDefault: Boolean get() = this == WaveSettings()
|
||||
|
||||
/** Settings as session seeds (`settingMoodEnergy:calm`…); defaults add nothing. */
|
||||
fun seeds(): List<String> = buildList {
|
||||
mood.api?.let { add("settingMoodEnergy:$it") }
|
||||
character.api?.let { add("settingDiversity:$it") }
|
||||
language.api?.let { add("settingLanguage:$it") }
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** From a station's `settings2` (or `settings`): `{moodEnergy, diversity, language}`. */
|
||||
fun from(s: JsonElement?) = WaveSettings(
|
||||
Mood.from(s.str("moodEnergy")),
|
||||
Character.from(s.str("diversity")),
|
||||
Language.from(s.str("language")),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** A station to start: My Wave, a genre, an activity, an era. */
|
||||
data class Station(
|
||||
/** `type:tag`, e.g. `genre:rock`. */
|
||||
val id: String,
|
||||
val name: String,
|
||||
val color: String?,
|
||||
private val iconUri: String?,
|
||||
) {
|
||||
fun iconUrl(size: Int): String? = coverUrl(iconUri, size)
|
||||
|
||||
companion object {
|
||||
fun from(r: JsonElement?): Station? {
|
||||
val s = r["station"] ?: return null
|
||||
val idObj = s["id"]
|
||||
val type = idObj.str("type") ?: return null
|
||||
val tag = idObj.str("tag") ?: return null
|
||||
val icon = s["icon"]
|
||||
return Station(
|
||||
id = "$type:$tag",
|
||||
name = r.str("customName") ?: s.str("name") ?: "Station",
|
||||
color = icon.str("backgroundColor")?.takeIf { it.startsWith('#') },
|
||||
iconUri = icon.str("imageUrl"),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One batch of station tracks. Feedback names the session and the batch. */
|
||||
data class WaveBatch(val sessionId: String?, val tracks: List<Track>, val batchId: String?) {
|
||||
companion object {
|
||||
/** From a `/rotor/session/...` result: `{radioSessionId, batchId, sequence: [{track}]}`. */
|
||||
fun from(v: JsonElement?) = WaveBatch(
|
||||
sessionId = v.str("radioSessionId"),
|
||||
tracks = v.list("sequence").mapNotNull { Track.from(it["track"]) },
|
||||
batchId = v.str("batchId"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Listening events a station learns from. */
|
||||
sealed interface WaveEvent {
|
||||
data object Started : WaveEvent
|
||||
data class TrackStarted(val trackId: String) : WaveEvent
|
||||
data class TrackFinished(val trackId: String, val playedMs: Long) : WaveEvent
|
||||
data class Skipped(val trackId: String, val playedMs: Long) : WaveEvent
|
||||
|
||||
/** The session feedback body's `event` object. */
|
||||
fun toJson(now: String): JsonObject {
|
||||
val (type, track, played) = when (this) {
|
||||
Started -> Triple("radioStarted", null, null)
|
||||
is TrackStarted -> Triple("trackStarted", trackId, null)
|
||||
is TrackFinished -> Triple("trackFinished", trackId, playedMs)
|
||||
is Skipped -> Triple("skip", trackId, playedMs)
|
||||
}
|
||||
val fields = linkedMapOf<String, JsonElement>("type" to JsonPrimitive(type), "timestamp" to JsonPrimitive(now))
|
||||
if (track != null) fields["trackId"] = JsonPrimitive(track)
|
||||
if (played != null) fields["totalPlayedSeconds"] = JsonPrimitive(played / 1000.0)
|
||||
return JsonObject(fields)
|
||||
}
|
||||
}
|
||||
|
||||
/** A finished or abandoned listen, for the user's history and the artists' counts. */
|
||||
data class PlayReport(
|
||||
val trackId: String,
|
||||
val albumId: Long?,
|
||||
val lengthMs: Long,
|
||||
val playedMs: Long,
|
||||
val endPositionMs: Long,
|
||||
/** Where it was played from, e.g. `musyx-wave` or `musyx-tv`. */
|
||||
val from: String,
|
||||
)
|
||||
|
||||
/** `2026-10-15T15:20:01.042Z`, the only format `/play-audio` accepts. */
|
||||
fun isoMillis(epochMs: Long): String =
|
||||
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
|
||||
.apply { timeZone = TimeZone.getTimeZone("UTC") }
|
||||
.format(Date(epochMs))
|
||||
|
||||
/** `"123"` and `"123:456"` both mean track 123; uploads have no numeric id. */
|
||||
fun numericId(id: String): Long? = id.substringBefore(':').toLongOrNull()
|
||||
@@ -0,0 +1,569 @@
|
||||
// An authenticated Yandex Music client. Port of ym-api's client.rs, with yamuse's wire
|
||||
// behaviour inlined.
|
||||
package it.panov.musyx.api
|
||||
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
/** How many featured podcasts to resolve. */
|
||||
const val FEATURED_PODCASTS = 48
|
||||
/** Ids per batched request. */
|
||||
private const val BATCH = 250
|
||||
|
||||
class YmClient private constructor(
|
||||
private val token: String?,
|
||||
val language: ContentLanguage,
|
||||
/** The signed-in user's uid; every `/users/{uid}/…` call needs it. */
|
||||
val uid: Long?,
|
||||
) {
|
||||
private val http = Transport(token, language)
|
||||
|
||||
private fun me(): Long = uid ?: throw YmError.Unauthorized("not signed in")
|
||||
|
||||
/** The same account, with Yandex answering in `language`. */
|
||||
fun inLanguage(language: ContentLanguage) = YmClient(token, language, uid)
|
||||
|
||||
/** Re-reads the account, e.g. after a subscription may have changed. */
|
||||
suspend fun account(): Account =
|
||||
Account.from(http.get("/account/status")) ?: throw YmError.Unauthorized("account status has no user")
|
||||
|
||||
// ---- Tracks ----
|
||||
|
||||
/** Full metadata for `ids` (`"trackId"` or `"trackId:albumId"`), in the given order. */
|
||||
suspend fun tracks(ids: List<String>): List<Track> =
|
||||
ids.chunked(BATCH).flatMap { chunk ->
|
||||
http.postForm("/tracks", Params().add("with-positions", true).addAll("track-ids", chunk))
|
||||
.arr.orEmpty().mapNotNull { Track.from(it) }
|
||||
}
|
||||
|
||||
/** The user's liked tracks, newest like first, with full metadata. */
|
||||
suspend fun likedTracks(): List<Track> {
|
||||
val raw = http.get("/users/${me()}/likes/tracks")
|
||||
val library = raw["library"] ?: raw
|
||||
val ids = library.list("tracks").mapNotNull { short ->
|
||||
val id = short.str("id") ?: return@mapNotNull null
|
||||
val album = short.str("albumId")
|
||||
if (album != null && ':' !in id) "$id:$album" else id
|
||||
}
|
||||
return tracks(ids)
|
||||
}
|
||||
|
||||
/** Tracks Yandex considers similar (about 20), best match first. */
|
||||
suspend fun similarTracks(trackId: String): List<Track> =
|
||||
http.get("/tracks/$trackId/similar").list("similarTracks").mapNotNull { Track.from(it) }
|
||||
|
||||
/** Resolves a signed, short-lived audio URL for a track, at most `maxKbps` when set. */
|
||||
suspend fun stream(trackId: String, maxKbps: Int?): Stream {
|
||||
val variants = http.get("/tracks/$trackId/download-info").arr.orEmpty()
|
||||
val variant = bestVariant(variants, maxKbps) ?: throw YmError.Api("no playable variant for track $trackId")
|
||||
val xml = http.text(variant.str("downloadInfoUrl")!!)
|
||||
val url = Signing.mp3Link(xml) ?: throw YmError.Api("download-info xml is missing host/path/ts/s")
|
||||
return Stream(
|
||||
urls = listOf(url),
|
||||
codec = variant.str("codec").orEmpty(),
|
||||
bitrateKbps = (variant.long("bitrateInKbps") ?: 0).coerceAtLeast(0).toInt(),
|
||||
preview = variant.bool("preview") == true,
|
||||
key = null,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* FLAC when Yandex grants it for this track and account. Otherwise Yandex answers with
|
||||
* the best lossy file it allows (often AAC 192), played as is unless it's HE-AAC; then
|
||||
* the MP3 path, as [stream] with no cap.
|
||||
*/
|
||||
suspend fun losslessStream(trackId: String): Stream {
|
||||
val id = numericId(trackId)
|
||||
if (id != null) {
|
||||
try {
|
||||
val ts = System.currentTimeMillis() / 1000
|
||||
val params = Params()
|
||||
.add("ts", ts)
|
||||
.add("trackId", id)
|
||||
.add("quality", "lossless")
|
||||
.add("codecs", Signing.CODECS)
|
||||
.add("transports", Signing.TRANSPORT)
|
||||
.add("sign", Signing.fileInfo(ts, id, "lossless"))
|
||||
fileInfoStream(http.get("/get-file-info", params)["downloadInfo"])?.let { return it }
|
||||
} catch (e: YmError) {
|
||||
// An API refusal (region, rights) still leaves the MP3 path.
|
||||
// A server error (5xx) is Yandex's trouble with this file, not the connection.
|
||||
if (e is YmError.Unauthorized || e is YmError.Network) throw e
|
||||
}
|
||||
}
|
||||
return stream(trackId, null)
|
||||
}
|
||||
|
||||
// ---- Library ----
|
||||
|
||||
/** Albums the user liked, newest first, with full details. */
|
||||
suspend fun likedAlbums(): List<AlbumSummary> {
|
||||
val ids = likedAlbumIds(http.get("/users/${me()}/likes/albums"))
|
||||
return albums(ids)
|
||||
}
|
||||
|
||||
private fun likedAlbumIds(likes: JsonElement): List<Long> =
|
||||
likes.arr.orEmpty().mapNotNull { it["album"].long("id") ?: it.long("id") }
|
||||
|
||||
private suspend fun albums(ids: List<Long>): List<AlbumSummary> =
|
||||
ids.chunked(BATCH).flatMap { chunk ->
|
||||
http.postForm("/albums", Params().addAll("album-ids", chunk)).arr.orEmpty().mapNotNull { AlbumSummary.from(it) }
|
||||
}
|
||||
|
||||
suspend fun likedArtists(): List<ArtistSummary> =
|
||||
http.get("/users/${me()}/likes/artists").arr.orEmpty().mapNotNull { ArtistSummary.from(it) }
|
||||
|
||||
private fun likedPlaylistIds(likes: JsonElement): List<PlaylistId> =
|
||||
likes.arr.orEmpty().mapNotNull { like ->
|
||||
val p = like["playlist"] ?: return@mapNotNull null
|
||||
val owner = p.long("uid") ?: p["owner"].long("uid") ?: return@mapNotNull null
|
||||
PlaylistId(owner, p.long("kind") ?: return@mapNotNull null)
|
||||
}
|
||||
|
||||
private suspend fun playlists(ids: List<PlaylistId>): List<PlaylistSummary> =
|
||||
ids.chunked(BATCH).flatMap { chunk ->
|
||||
http.postForm("/playlists/list", Params().addAll("playlist-ids", chunk.map { it.key }))
|
||||
.arr.orEmpty().mapNotNull { PlaylistSummary.from(it) }
|
||||
}
|
||||
|
||||
/** Playlists the user owns, and ones they liked. */
|
||||
suspend fun libraryPlaylists(): LibraryPlaylists = coroutineScope {
|
||||
val own = async { http.get("/users/${me()}/playlists/list").arr.orEmpty().mapNotNull { PlaylistSummary.from(it) } }
|
||||
val liked = async { playlists(likedPlaylistIds(http.get("/users/${me()}/likes/playlists"))) }
|
||||
LibraryPlaylists(own.await(), liked.await())
|
||||
}
|
||||
|
||||
suspend fun album(id: Long): AlbumPage =
|
||||
AlbumPage.from(http.get("/albums/$id/with-tracks")) ?: throw YmError.NotFound("album $id has no id")
|
||||
|
||||
suspend fun artist(id: Long): ArtistPage = coroutineScope {
|
||||
val clips = async { runCatching { artistClips(id) } }
|
||||
val page = ArtistPage.from(http.get("/artists/$id/brief-info")) ?: throw YmError.NotFound("artist $id")
|
||||
// The page is still worth showing without its videos.
|
||||
page.copy(clips = clips.await().getOrElse { emptyList() })
|
||||
}
|
||||
|
||||
/** URLs of an artist's photos at `size`×`size`, for the screen saver. */
|
||||
suspend fun artistPhotos(id: Long, size: Int): List<String> =
|
||||
artistPhotoUris(http.get("/artists/$id/brief-info")).mapNotNull { coverUrl(it, size) }
|
||||
|
||||
/** A playlist with all its tracks. Tracks the response didn't embed are looked up. */
|
||||
suspend fun playlist(id: PlaylistId): PlaylistPage {
|
||||
val raw = http.get("/users/${id.owner}/playlists/${id.kind}")
|
||||
val playlist = PlaylistSummary.from(raw) ?: throw YmError.NotFound("playlist ${id.key} incomplete")
|
||||
val slots = raw.list("tracks").map { short -> Track.from(short["track"]) to short.str("id") }
|
||||
val missing = slots.mapIndexedNotNull { i, (track, sid) -> if (track == null && sid != null) i to sid else null }
|
||||
val fetched = if (missing.isEmpty()) emptyMap() else {
|
||||
val found = tracks(missing.map { it.second }).associateBy { it.id }
|
||||
missing.mapNotNull { (i, sid) -> found[sid.substringBefore(':')]?.let { i to it } }.toMap()
|
||||
}
|
||||
val resolved = slots.mapIndexedNotNull { i, (track, _) -> (track ?: fetched[i])?.let { i to it } }
|
||||
return PlaylistPage(
|
||||
playlist,
|
||||
raw.str("description")?.takeIf { it.isNotBlank() },
|
||||
resolved.map { it.second },
|
||||
resolved.map { it.first },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- Search and discovery ----
|
||||
|
||||
/** One page of search results. `page` starts at 0. */
|
||||
suspend fun search(text: String, kind: SearchKind, page: Int): SearchResults =
|
||||
SearchResults.from(
|
||||
http.get(
|
||||
"/search",
|
||||
Params().add("text", text).add("nocorrect", false).add("type", kind.apiType)
|
||||
.add("page", page).add("playlist-in-best", true),
|
||||
),
|
||||
)
|
||||
|
||||
/** Completions for a partial query, best first. */
|
||||
suspend fun suggest(part: String): List<String> =
|
||||
http.get("/search/suggest", Params().add("part", part)).strings("suggestions")
|
||||
|
||||
/** The home page: personal playlists, new releases and playlists, the chart. */
|
||||
suspend fun home(): Home = coroutineScope {
|
||||
val chart = async { runCatching { chart() } }
|
||||
val landing = http.get(
|
||||
"/landing3",
|
||||
Params().addAll("blocks", listOf("personalplaylists", "new-releases", "new-playlists"))
|
||||
.add("eitherUserId", "10254713668400548221"),
|
||||
)
|
||||
val home = homeFromLanding(landing)
|
||||
// The chart block on landing3 holds a handful of items; the chart endpoint has them all.
|
||||
chart.await().getOrNull()?.takeIf { it.isNotEmpty() }?.let { home.copy(chart = it) } ?: home
|
||||
}
|
||||
|
||||
suspend fun chart(): List<ChartEntry> =
|
||||
http.get("/landing3/chart")["chart"].list("tracks").mapNotNull { ChartEntry.from(it) }
|
||||
|
||||
/** The last `limit` different tracks the user played, newest first, on any device. */
|
||||
suspend fun recentlyPlayed(limit: Int): List<Track> =
|
||||
tracks(recentTrackIds(http.get("/music-history", Params().add("fullModelsCount", 0)), limit))
|
||||
|
||||
suspend fun genres(): List<Genre> = http.get("/genres").arr.orEmpty().mapNotNull { Genre.from(it) }
|
||||
|
||||
/** Editorial playlists filed under a genre or mood tag. */
|
||||
suspend fun tagPlaylists(tag: String): List<PlaylistSummary> {
|
||||
val raw = http.get("/tags/$tag/playlist-ids")
|
||||
val ids = tagPlaylistIds(raw)
|
||||
return if (ids.isEmpty()) emptyList() else playlists(ids)
|
||||
}
|
||||
|
||||
/** Podcasts Yandex currently features (the first [FEATURED_PODCASTS]). */
|
||||
suspend fun featuredPodcasts(): List<AlbumSummary> {
|
||||
val ids = http.get("/landing3/podcasts").list("podcasts").mapNotNull { it.asLong() }.take(FEATURED_PODCASTS)
|
||||
return albums(ids)
|
||||
}
|
||||
|
||||
// ---- Stations ----
|
||||
|
||||
/** Stations Yandex suggests to this user. */
|
||||
suspend fun stations(): List<Station> =
|
||||
http.get("/rotor/stations/dashboard").list("stations").mapNotNull { Station.from(it) }
|
||||
|
||||
suspend fun waveSettings(station: String): WaveSettings {
|
||||
val first = http.get("/rotor/station/$station/info").arr?.firstOrNull()
|
||||
return WaveSettings.from(first["settings2"] ?: first["settings"])
|
||||
}
|
||||
|
||||
suspend fun setWaveSettings(station: String, settings: WaveSettings) {
|
||||
val result = http.postForm(
|
||||
"/rotor/station/$station/settings3",
|
||||
Params()
|
||||
.add("moodEnergy", settings.mood.api ?: "all")
|
||||
.add("diversity", settings.character.api ?: "default")
|
||||
.add("type", "rotor")
|
||||
.add("language", settings.language.api ?: "any"),
|
||||
)
|
||||
requireAck(result, "station settings")
|
||||
}
|
||||
|
||||
/** Starts a station session. My Wave's settings travel as extra seeds. */
|
||||
suspend fun waveStart(station: String, settings: WaveSettings?): WaveBatch {
|
||||
val seeds = listOf(station) + settings?.seeds().orEmpty()
|
||||
val body = buildJsonObject {
|
||||
put("seeds", JsonArray(seeds.map { JsonPrimitive(it) }))
|
||||
put("includeTracksInResponse", true)
|
||||
}
|
||||
return WaveBatch.from(http.postJson("/rotor/session/new", body))
|
||||
}
|
||||
|
||||
/** The next batch of a session. `queue` is the recently queued tracks (`fullId`s). */
|
||||
suspend fun waveMore(sessionId: String, queue: List<String>): WaveBatch {
|
||||
val body = buildJsonObject { put("queue", buildJsonArray { queue.forEach { add(JsonPrimitive(it)) } }) }
|
||||
val batch = WaveBatch.from(http.postJson("/rotor/session/$sessionId/tracks", body))
|
||||
return if (batch.sessionId == null) batch.copy(sessionId = sessionId) else batch
|
||||
}
|
||||
|
||||
/** Tells a session what happened, so the next batch fits better. */
|
||||
suspend fun waveFeedback(sessionId: String, event: WaveEvent, batchId: String?) {
|
||||
val now = isoMillis(System.currentTimeMillis())
|
||||
val fields = linkedMapOf<String, JsonElement>("event" to event.toJson(now))
|
||||
if (batchId != null) fields["batchId"] = JsonPrimitive(batchId)
|
||||
if (event is WaveEvent.Started) fields["from"] = JsonPrimitive("musyx-wave")
|
||||
http.postJson("/rotor/session/$sessionId/feedback", JsonObject(fields))
|
||||
}
|
||||
|
||||
/** Records a listen in the user's history. Tracks without numeric ids are skipped. */
|
||||
suspend fun reportPlay(report: PlayReport) {
|
||||
val trackId = numericId(report.trackId) ?: return
|
||||
val now = isoMillis(System.currentTimeMillis())
|
||||
val result = http.postForm(
|
||||
"/play-audio",
|
||||
Params()
|
||||
.add("track-id", trackId)
|
||||
.add("from-cache", false)
|
||||
.add("from", report.from)
|
||||
.add("play-id", "")
|
||||
.add("uid", uid ?: "")
|
||||
.add("timestamp", now)
|
||||
.add("track-length-seconds", report.lengthMs / 1000)
|
||||
.add("total-played-seconds", report.playedMs / 1000)
|
||||
.add("end-position-seconds", report.endPositionMs / 1000)
|
||||
.add("album-id", report.albumId ?: 0)
|
||||
.add("playlist-id", "")
|
||||
.add("client-now", now),
|
||||
)
|
||||
requireAck(result, "play report")
|
||||
}
|
||||
|
||||
// ---- Clips ----
|
||||
|
||||
/** An artist's music videos, newest first. */
|
||||
suspend fun artistClips(artistId: Long): List<Clip> =
|
||||
http.get("/artists/$artistId/blocks/artist-clips").list("items").mapNotNull { item ->
|
||||
val data = item["data"] ?: return@mapNotNull null
|
||||
Clip.from(data["clip"] ?: return@mapNotNull null, data["artists"])
|
||||
}
|
||||
|
||||
/** Every clip the user liked, newest first. Bare references are looked up. */
|
||||
suspend fun likedClips(): List<Clip> {
|
||||
val pageSize = 100
|
||||
val entries = mutableListOf<Any>() // Clip, or a Long id still to look up
|
||||
for (page in 0 until 20) {
|
||||
val raw = http.get("/users/${me()}/likes/clips", Params().add("page", page).add("pageSize", pageSize))
|
||||
for (e in raw.list("clips")) {
|
||||
val entry = e["clip"] ?: e
|
||||
if (entry["title"] != null) Clip.from(entry)?.let { entries += it }
|
||||
else (entry.long("clipId") ?: entry.long("id"))?.let { entries += it }
|
||||
}
|
||||
val pager = raw["pager"]
|
||||
val total = pager.long("total")
|
||||
val per = pager.long("perPage")
|
||||
if (total == null || per == null || per <= 0 || (page + 1) * per >= total) break
|
||||
}
|
||||
val missing = entries.filterIsInstance<Long>()
|
||||
val found = mutableMapOf<Long, Clip>()
|
||||
for (chunk in missing.chunked(pageSize)) {
|
||||
http.get("/clips", Params().add("clipIds", chunk.joinToString(","))).arr.orEmpty()
|
||||
.mapNotNull { Clip.from(it) }.forEach { found[it.id] = it }
|
||||
}
|
||||
return entries.mapNotNull { if (it is Long) found[it] else it as Clip }
|
||||
}
|
||||
|
||||
suspend fun setClipLiked(id: Long, liked: Boolean) {
|
||||
val result = if (liked) {
|
||||
http.postForm("/users/${me()}/likes/clips/add", Params().add("clip-id", id))
|
||||
} else {
|
||||
http.postForm("/users/${me()}/likes/clips/$id/remove")
|
||||
}
|
||||
requireAck(result, "clip like", loosely = true)
|
||||
}
|
||||
|
||||
// ---- Likes ----
|
||||
|
||||
private suspend fun setLiked(kind: String, ids: List<String>, liked: Boolean, dislike: Boolean = false) {
|
||||
val list = if (dislike) "dislikes" else "likes"
|
||||
val action = if (liked) "add-multiple" else "remove"
|
||||
val result = http.postForm("/users/${me()}/$list/${kind}s/$action", Params().addAll("$kind-ids", ids))
|
||||
requireAck(result, "$list $kind")
|
||||
}
|
||||
|
||||
/** Track ids are `fullId`s or plain ids; Yandex accepts both. */
|
||||
suspend fun setTrackLiked(trackId: String, liked: Boolean) = setLiked("track", listOf(trackId), liked)
|
||||
|
||||
/** "Don't recommend": the track stops appearing in waves and mixes. */
|
||||
suspend fun setTrackDisliked(trackId: String, disliked: Boolean) =
|
||||
setLiked("track", listOf(trackId), disliked, dislike = true)
|
||||
|
||||
suspend fun setAlbumLiked(id: Long, liked: Boolean) = setLiked("album", listOf(id.toString()), liked)
|
||||
|
||||
suspend fun setArtistLiked(id: Long, liked: Boolean) = setLiked("artist", listOf(id.toString()), liked)
|
||||
|
||||
suspend fun setPlaylistLiked(id: PlaylistId, liked: Boolean) = setLiked("playlist", listOf(id.key), liked)
|
||||
|
||||
/** Ids only (no details), for drawing like state on every page. */
|
||||
suspend fun likedIds(): LikedIds = coroutineScope {
|
||||
val me = me()
|
||||
val albums = async { likedAlbumIds(http.get("/users/$me/likes/albums")).toSet() }
|
||||
val artists = async { http.get("/users/$me/likes/artists").arr.orEmpty().mapNotNull { it.long("id") }.toSet() }
|
||||
val playlists = async { likedPlaylistIds(http.get("/users/$me/likes/playlists")).toSet() }
|
||||
val disliked = async {
|
||||
val raw = http.get("/users/$me/dislikes/tracks")
|
||||
(raw["library"] ?: raw).list("tracks").mapNotNull { it.str("id")?.substringBefore(':') }.toSet()
|
||||
}
|
||||
// Clips are optional: a failure here shouldn't hide every other heart.
|
||||
val clips = async {
|
||||
try {
|
||||
likedClips().map { it.id }.toSet()
|
||||
} catch (e: YmError) {
|
||||
if (e is YmError.Unauthorized) throw e
|
||||
emptySet()
|
||||
}
|
||||
}
|
||||
LikedIds(albums.await(), artists.await(), playlists.await(), disliked.await(), clips.await())
|
||||
}
|
||||
|
||||
// ---- Playlists ----
|
||||
|
||||
suspend fun createPlaylist(title: String, public: Boolean): PlaylistSummary {
|
||||
val p = http.postForm(
|
||||
"/users/${me()}/playlists/create",
|
||||
Params().add("title", title).add("visibility", if (public) "public" else "private"),
|
||||
)
|
||||
return PlaylistSummary.from(p) ?: throw YmError.Api("created playlist has no id")
|
||||
}
|
||||
|
||||
suspend fun renamePlaylist(id: PlaylistId, title: String) {
|
||||
http.postForm("/users/${me()}/playlists/${id.kind}/name", Params().add("value", title))
|
||||
}
|
||||
|
||||
suspend fun setPlaylistPublic(id: PlaylistId, public: Boolean) {
|
||||
http.postForm(
|
||||
"/users/${me()}/playlists/${id.kind}/visibility",
|
||||
Params().add("value", if (public) "public" else "private"),
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun deletePlaylist(id: PlaylistId) {
|
||||
requireAck(http.postForm("/users/${me()}/playlists/${id.kind}/delete"), "playlist delete")
|
||||
}
|
||||
|
||||
/** The playlist's revision and length, which every edit needs fresh. */
|
||||
private suspend fun revision(id: PlaylistId): Pair<Long, Int> {
|
||||
val p = http.get("/users/${id.owner}/playlists/${id.kind}")
|
||||
val len = p.long("trackCount")?.toInt()?.coerceAtLeast(0) ?: p.list("tracks").size
|
||||
return (p.long("revision") ?: 0) to len
|
||||
}
|
||||
|
||||
private suspend fun change(id: PlaylistId, diff: JsonArray, revision: Long) {
|
||||
http.postForm(
|
||||
"/users/${me()}/playlists/${id.kind}/change",
|
||||
Params().add("kind", id.kind).add("revision", revision).add("diff", diff.toString()),
|
||||
)
|
||||
}
|
||||
|
||||
/** Playlist diffs need numeric track and album ids. */
|
||||
private fun diffTrack(track: Track): JsonObject {
|
||||
val id = numericId(track.id) ?: throw YmError.Api("this track can't go in a playlist")
|
||||
val album = track.album?.id ?: throw YmError.Api("track has no album")
|
||||
return buildJsonObject { put("id", id); put("albumId", album) }
|
||||
}
|
||||
|
||||
private fun insert(at: Int, track: Track) = buildJsonObject {
|
||||
put("op", "insert")
|
||||
put("at", at)
|
||||
put("tracks", JsonArray(listOf(diffTrack(track))))
|
||||
}
|
||||
|
||||
private fun delete(from: Int, to: Int) = buildJsonObject { put("op", "delete"); put("from", from); put("to", to) }
|
||||
|
||||
/** Appends a track to the end of one of the user's playlists. */
|
||||
suspend fun addToPlaylist(id: PlaylistId, track: Track) {
|
||||
diffTrack(track) // fails on unusable ids before any request
|
||||
val (rev, len) = revision(id)
|
||||
change(id, JsonArray(listOf(insert(len, track))), rev)
|
||||
}
|
||||
|
||||
/** Removes the track at `index`. */
|
||||
suspend fun removeFromPlaylist(id: PlaylistId, index: Int) {
|
||||
val (rev, _) = revision(id)
|
||||
change(id, JsonArray(listOf(delete(index, index + 1))), rev)
|
||||
}
|
||||
|
||||
/** Moves the track at `from` so it ends up at `to`. */
|
||||
suspend fun moveInPlaylist(id: PlaylistId, track: Track, from: Int, to: Int) {
|
||||
val add = insert(to, track)
|
||||
val (rev, _) = revision(id)
|
||||
change(id, JsonArray(listOf(delete(from, from + 1), add)), rev)
|
||||
}
|
||||
|
||||
// ---- Lyrics ----
|
||||
|
||||
/** Synced lyrics when Yandex has them, else plain text; null when there are none. */
|
||||
suspend fun lyrics(trackId: String): Lyrics? {
|
||||
val id = numericId(trackId) ?: return null
|
||||
for (format in listOf("LRC", "TEXT")) {
|
||||
val ts = System.currentTimeMillis() / 1000
|
||||
val meta = try {
|
||||
http.get(
|
||||
"/tracks/$id/lyrics",
|
||||
Params().add("format", format).add("timeStamp", ts).add("sign", Signing.lyrics(id, ts)),
|
||||
)
|
||||
} catch (e: YmError.NotFound) {
|
||||
continue
|
||||
}
|
||||
val url = meta.str("downloadUrl") ?: continue
|
||||
val text = http.text(url)
|
||||
if (text.isBlank()) continue
|
||||
val writers = meta.strings("writers")
|
||||
return if (format == "LRC") Lyrics.fromLrc(text, writers) else Lyrics.fromText(text, writers)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Builds a client for `credentials` and loads the account. */
|
||||
suspend fun connect(credentials: Credentials, language: ContentLanguage): Pair<YmClient, Account> {
|
||||
val probe = YmClient(credentials.accessToken, language, null)
|
||||
val account = probe.account()
|
||||
return YmClient(credentials.accessToken, language, account.uid) to account
|
||||
}
|
||||
|
||||
/** A client with no token, for previews and tests. Every account call fails. */
|
||||
fun unauthenticated() = YmClient(null, ContentLanguage.English, null)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the variant to play: full tracks over previews, then the highest bitrate within
|
||||
* `maxKbps` (or the lowest there is, when everything is above it), then MP3 over AAC.
|
||||
*/
|
||||
internal fun bestVariant(variants: List<JsonElement>, maxKbps: Int?): JsonElement? {
|
||||
val cap = maxKbps?.toLong() ?: Long.MAX_VALUE
|
||||
return variants
|
||||
.filter { it.str("downloadInfoUrl") != null && it.str("codec") in setOf("mp3", "aac") }
|
||||
.maxWithOrNull(
|
||||
compareBy<JsonElement> { it.bool("preview") != true }
|
||||
.thenBy { val k = it.long("bitrateInKbps") ?: 0; if (k <= cap) 1 else 0 }
|
||||
.thenBy { val k = it.long("bitrateInKbps") ?: 0; if (k <= cap) k else -k }
|
||||
.thenBy { it.str("codec") == "mp3" },
|
||||
)
|
||||
}
|
||||
|
||||
/** Builds a stream from a `/get-file-info` reply, when it's a codec we decode well. */
|
||||
internal fun fileInfoStream(info: JsonElement?): Stream? {
|
||||
val codec = info.str("codec") ?: return null
|
||||
val urls = (info.strings("urls") + listOfNotNull(info.str("url"))).distinct()
|
||||
if (codec !in setOf("flac", "flac-mp4", "mp3", "aac", "aac-mp4") || urls.isEmpty()) return null
|
||||
return Stream(urls, codec, (info.long("bitrate") ?: 0).coerceAtLeast(0).toInt(), false, info.str("key"))
|
||||
}
|
||||
|
||||
/** Playlist ids from `/tags/{id}/playlist-ids`: `{"ids":[{"uid":1,"kind":2}]}` or `"uid:kind"`. */
|
||||
internal fun tagPlaylistIds(raw: JsonElement): List<PlaylistId> =
|
||||
raw.list("ids").mapNotNull { id ->
|
||||
when (id) {
|
||||
is JsonPrimitive -> id.content.split(':').takeIf { it.size == 2 }?.let { (u, k) ->
|
||||
val uid = u.toLongOrNull() ?: return@let null
|
||||
PlaylistId(uid, k.toLongOrNull() ?: return@let null)
|
||||
}
|
||||
is JsonObject -> PlaylistId(id.long("uid") ?: return@mapNotNull null, id.long("kind") ?: return@mapNotNull null)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/** `trackId:albumId` for the newest `limit` distinct tracks in the history. */
|
||||
internal fun recentTrackIds(history: JsonElement, limit: Int): List<String> {
|
||||
val seen = HashSet<String>()
|
||||
return history.list("historyTabs").asSequence()
|
||||
.flatMap { it.list("items") }
|
||||
.flatMap { it.list("tracks") }
|
||||
.mapNotNull { item ->
|
||||
val id = item["data"]["itemId"]
|
||||
val track = id.str("trackId") ?: return@mapNotNull null
|
||||
val album = id.str("albumId")
|
||||
if (album != null) "$track:$album" else track
|
||||
}
|
||||
.filter { seen.add(it.substringBefore(':')) }
|
||||
.take(limit)
|
||||
.toList()
|
||||
}
|
||||
|
||||
/** Splits `/landing3` blocks by entity type. */
|
||||
internal fun homeFromLanding(landing: JsonElement): Home {
|
||||
val personal = mutableListOf<Personal>()
|
||||
val releases = mutableListOf<AlbumSummary>()
|
||||
val playlists = mutableListOf<PlaylistSummary>()
|
||||
val chart = mutableListOf<ChartEntry>()
|
||||
for (block in landing.list("blocks")) for (entity in block.list("entities")) {
|
||||
val data = entity["data"]
|
||||
when (entity.str("type")) {
|
||||
"personal-playlist" -> PlaylistSummary.from(data["data"])?.let {
|
||||
personal += Personal(it, data.str("previewDescription")?.takeIf { d -> d.isNotBlank() })
|
||||
}
|
||||
"album" -> AlbumSummary.from(data)?.let { releases += it }
|
||||
"playlist" -> PlaylistSummary.from(data)?.let { playlists += it }
|
||||
"chart-item" -> ChartEntry.from(data)?.let { chart += it }
|
||||
}
|
||||
}
|
||||
return Home(personal, chart, releases, playlists)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Errors the app can act on. Messages are for logs, not for display.
|
||||
package it.panov.musyx.api
|
||||
|
||||
sealed class YmError(message: String) : Exception(message) {
|
||||
/** The token is missing, revoked or expired. Sign in again. */
|
||||
class Unauthorized(message: String) : YmError("unauthorized: $message")
|
||||
|
||||
/** The sign-in code ran out before the user confirmed it. */
|
||||
class CodeExpired : YmError("sign-in code expired")
|
||||
|
||||
/** The user declined access on Yandex's page. */
|
||||
class Denied : YmError("sign-in was declined")
|
||||
|
||||
/** No connection, DNS failure, timeout: worth retrying. */
|
||||
class Network(message: String) : YmError("network: $message")
|
||||
|
||||
/** The server failed (5xx other than 502): worth retrying, but the connection works. */
|
||||
class Server(message: String) : YmError("server: $message")
|
||||
|
||||
/** Something isn't there (404). */
|
||||
class NotFound(message: String) : YmError("not found: $message")
|
||||
|
||||
/** Anything else the server rejected. */
|
||||
class Api(message: String) : YmError("api: $message")
|
||||
|
||||
val isRetryable: Boolean get() = this is Network || this is Server
|
||||
|
||||
companion object {
|
||||
/** OAuth rejections arrive as free text carrying the RFC 8628 error code. */
|
||||
fun fromOAuth(message: String): YmError {
|
||||
val m = message.lowercase()
|
||||
return when {
|
||||
"expired" in m || "timed out" in m -> CodeExpired()
|
||||
"denied" in m -> Denied()
|
||||
"invalid_grant" in m || "bad refresh" in m -> Unauthorized(message)
|
||||
else -> Api(message)
|
||||
}
|
||||
}
|
||||
|
||||
/** Any throwable as a [YmError]: I/O failures are network trouble. */
|
||||
fun of(t: Throwable): YmError = when (t) {
|
||||
is YmError -> t
|
||||
is java.io.IOException -> Network(t.message ?: t.javaClass.simpleName)
|
||||
else -> Api(t.message ?: t.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// Keeping the user signed in: credentials are encrypted with a key that lives in the Android
|
||||
// Keystore and never leaves it, and the ciphertext sits in private preferences.
|
||||
package it.panov.musyx.data
|
||||
|
||||
import android.content.Context
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
import androidx.core.content.edit
|
||||
import it.panov.musyx.api.Credentials
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
class CredentialStore(context: Context) {
|
||||
private val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
/** Stored credentials, or null when there are none or they can't be read any more. */
|
||||
fun load(): Credentials? {
|
||||
val sealed = prefs.getString(KEY_BLOB, null) ?: return null
|
||||
// An unreadable entry is treated as absent; the next sign-in overwrites it.
|
||||
return runCatching { Credentials.fromJson(decrypt(sealed)) }.getOrNull()
|
||||
}
|
||||
|
||||
fun save(credentials: Credentials) {
|
||||
prefs.edit { putString(KEY_BLOB, encrypt(credentials.toJson())) }
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
prefs.edit { remove(KEY_BLOB) }
|
||||
}
|
||||
|
||||
private fun key(): SecretKey {
|
||||
val store = KeyStore.getInstance(KEYSTORE).apply { load(null) }
|
||||
(store.getKey(ALIAS, null) as? SecretKey)?.let { return it }
|
||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE)
|
||||
generator.init(
|
||||
KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(256)
|
||||
.build(),
|
||||
)
|
||||
return generator.generateKey()
|
||||
}
|
||||
|
||||
private fun encrypt(plain: String): String {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.ENCRYPT_MODE, key()) }
|
||||
val sealed = cipher.iv + cipher.doFinal(plain.encodeToByteArray())
|
||||
return Base64.encodeToString(sealed, Base64.NO_WRAP)
|
||||
}
|
||||
|
||||
private fun decrypt(sealed: String): String {
|
||||
val bytes = Base64.decode(sealed, Base64.NO_WRAP)
|
||||
val iv = bytes.copyOfRange(0, IV_BYTES)
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION).apply {
|
||||
init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, iv))
|
||||
}
|
||||
return cipher.doFinal(bytes, IV_BYTES, bytes.size - IV_BYTES).decodeToString()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val KEYSTORE = "AndroidKeyStore"
|
||||
const val ALIAS = "musyx-session"
|
||||
const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||
const val IV_BYTES = 12
|
||||
const val KEY_BLOB = "credentials"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Preferences kept between launches. Port of the desktop store.rs.
|
||||
package it.panov.musyx.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.core.content.edit
|
||||
|
||||
/** Streaming quality, as a cap on the bitrate Musyx asks for. */
|
||||
enum class Quality(val key: String, val maxKbps: Int?) {
|
||||
/** FLAC where Yandex grants it, else the best lossy file it allows. */
|
||||
Lossless("lossless", null),
|
||||
/** The best MP3 Yandex offers. */
|
||||
Best("best", null),
|
||||
/** Up to 192 kbps. */
|
||||
Balanced("balanced", 192),
|
||||
/** Up to 128 kbps, for slow or metered connections. */
|
||||
DataSaver("data-saver", 128),
|
||||
}
|
||||
|
||||
enum class Appearance(val key: String) {
|
||||
/** Follow the system's light or dark setting. */
|
||||
System("system"),
|
||||
Light("light"),
|
||||
Dark("dark"),
|
||||
}
|
||||
|
||||
/** Interface text size, as a multiple of the desktop sizes. The original TV size was 1.5. */
|
||||
enum class FontSize(val key: String, val scale: Float) {
|
||||
Small("small", 0.9f),
|
||||
Medium("medium", 1.05f),
|
||||
Large("large", 1.2f),
|
||||
}
|
||||
|
||||
/** The interface language. */
|
||||
enum class Locale(val key: String, val tag: String?) {
|
||||
/** The system's first preferred language, when Musyx has it; else English. */
|
||||
System("system", null),
|
||||
English("english", "en"),
|
||||
Russian("russian", "ru"),
|
||||
}
|
||||
|
||||
data class Settings(
|
||||
val quality: Quality = Quality.Best,
|
||||
val appearance: Appearance = Appearance.System,
|
||||
val fontSize: FontSize = FontSize.Medium,
|
||||
val language: Locale = Locale.System,
|
||||
/** Whether the screen saver shows the playing track's lyrics over the photos. */
|
||||
val saverLyrics: Boolean = false,
|
||||
)
|
||||
|
||||
class SettingsStore(context: Context) {
|
||||
private val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
|
||||
|
||||
/** Saved settings; anything missing or unknown keeps its default. */
|
||||
fun load(): Settings {
|
||||
val d = Settings()
|
||||
return Settings(
|
||||
quality = Quality.entries.firstOrNull { it.key == prefs.getString("quality", null) } ?: d.quality,
|
||||
appearance = Appearance.entries.firstOrNull { it.key == prefs.getString("appearance", null) } ?: d.appearance,
|
||||
fontSize = FontSize.entries.firstOrNull { it.key == prefs.getString("font_size", null) } ?: d.fontSize,
|
||||
language = Locale.entries.firstOrNull { it.key == prefs.getString("language", null) } ?: d.language,
|
||||
saverLyrics = prefs.getBoolean("saver_lyrics", d.saverLyrics),
|
||||
)
|
||||
}
|
||||
|
||||
fun save(settings: Settings) {
|
||||
prefs.edit {
|
||||
putString("quality", settings.quality.key)
|
||||
putString("appearance", settings.appearance.key)
|
||||
putString("font_size", settings.fontSize.key)
|
||||
putString("language", settings.language.key)
|
||||
putBoolean("saver_lyrics", settings.saverLyrics)
|
||||
}
|
||||
}
|
||||
|
||||
/** The language saved, read before anything else so the first frame is in it. */
|
||||
fun language(): Locale = load().language
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// Decrypts `encraw` lossless files as ExoPlayer reads them. AES-CTR is a stream cipher
|
||||
// over a 128-bit big-endian block counter starting at zero, so any byte offset can be
|
||||
// decrypted on its own and seeking keeps working.
|
||||
package it.panov.musyx.player
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.media3.common.C
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.datasource.DataSource
|
||||
import androidx.media3.datasource.DataSpec
|
||||
import androidx.media3.datasource.TransferListener
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/** Passes reads through, decrypting those whose URI has a key. */
|
||||
@OptIn(UnstableApi::class)
|
||||
class AesCtrDataSource(private val upstream: DataSource, private val keyFor: (Uri) -> ByteArray?) : DataSource {
|
||||
private var cipher: Cipher? = null
|
||||
|
||||
override fun addTransferListener(transferListener: TransferListener) = upstream.addTransferListener(transferListener)
|
||||
|
||||
override fun open(dataSpec: DataSpec): Long {
|
||||
val length = upstream.open(dataSpec)
|
||||
cipher = keyFor(dataSpec.uri)?.let { ctrCipher(it, dataSpec.position) }
|
||||
return length
|
||||
}
|
||||
|
||||
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
|
||||
val read = upstream.read(buffer, offset, length)
|
||||
if (read == C.RESULT_END_OF_INPUT || read <= 0) return read
|
||||
// CTR never buffers, so the output is exactly as long as the input.
|
||||
cipher?.update(buffer, offset, read, buffer, offset)
|
||||
return read
|
||||
}
|
||||
|
||||
override fun getUri(): Uri? = upstream.uri
|
||||
|
||||
override fun getResponseHeaders(): Map<String, List<String>> = upstream.responseHeaders
|
||||
|
||||
override fun close() {
|
||||
cipher = null
|
||||
upstream.close()
|
||||
}
|
||||
|
||||
class Factory(private val upstream: DataSource.Factory, private val keyFor: (Uri) -> ByteArray?) : DataSource.Factory {
|
||||
override fun createDataSource(): DataSource = AesCtrDataSource(upstream.createDataSource(), keyFor)
|
||||
}
|
||||
}
|
||||
|
||||
private const val BLOCK = 16
|
||||
|
||||
/** An AES-CTR cipher whose keystream starts at byte `offset` of the file. */
|
||||
fun ctrCipher(key: ByteArray, offset: Long): Cipher {
|
||||
val iv = ByteArray(BLOCK)
|
||||
var n = offset / BLOCK
|
||||
for (i in BLOCK - 1 downTo 0) {
|
||||
iv[i] = (n and 0xFF).toByte()
|
||||
n = n ushr 8
|
||||
}
|
||||
val c = Cipher.getInstance("AES/CTR/NoPadding")
|
||||
c.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(iv))
|
||||
val skip = (offset % BLOCK).toInt()
|
||||
if (skip > 0) c.update(ByteArray(skip))
|
||||
return c
|
||||
}
|
||||
|
||||
/** A hex key as bytes; null when it isn't 16 or 32 bytes of hex. */
|
||||
fun hexKey(hex: String): ByteArray? {
|
||||
val h = hex.trim()
|
||||
if (h.length != 32 && h.length != 64) return null
|
||||
return runCatching { ByteArray(h.length / 2) { i -> h.substring(i * 2, i * 2 + 2).toInt(16).toByte() } }.getOrNull()
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
// The audio engine: one ExoPlayer that plays one track at a time. The queue lives in
|
||||
// PlayerCore; this only loads what it's told and reports back, tagged with the generation
|
||||
// of the load so late events from a previous track are ignored.
|
||||
package it.panov.musyx.player
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.media3.common.AudioAttributes
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.MediaMetadata
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.common.Player
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.datasource.DefaultHttpDataSource
|
||||
import androidx.media3.datasource.ResolvingDataSource
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
|
||||
import it.panov.musyx.api.CLIENT_HEADER
|
||||
import it.panov.musyx.api.Stream
|
||||
import it.panov.musyx.api.Track
|
||||
import it.panov.musyx.api.isYandexHost
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
interface EngineEvents {
|
||||
fun loaded(generation: Long, durationMs: Long?)
|
||||
fun position(generation: Long, positionMs: Long)
|
||||
fun ended(generation: Long)
|
||||
fun failed(generation: Long, reason: String)
|
||||
/** Playback paused or resumed without being asked to (audio focus, headphones). */
|
||||
fun playingChanged(generation: Long, playing: Boolean)
|
||||
}
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
class ExoEngine(context: Context, private val token: () -> String?, private val events: EngineEvents) : Engine {
|
||||
/** Keys for encrypted files, by URL. Read on ExoPlayer's loader threads. */
|
||||
private val keys = ConcurrentHashMap<String, ByteArray>()
|
||||
|
||||
val exo: ExoPlayer
|
||||
|
||||
private var generation = 0L
|
||||
private var ready = false
|
||||
private var mirrors: List<String> = emptyList()
|
||||
private var mirror = 0
|
||||
private var item: MediaItem.Builder? = null
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
private val tick = object : Runnable {
|
||||
override fun run() {
|
||||
if (ready) events.position(generation, exo.currentPosition)
|
||||
handler.postDelayed(this, TICK_MS)
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
val http = DefaultHttpDataSource.Factory()
|
||||
.setUserAgent("Musyx-TV/0.1.0")
|
||||
.setConnectTimeoutMs(15_000)
|
||||
.setReadTimeoutMs(30_000)
|
||||
.setAllowCrossProtocolRedirects(true)
|
||||
// Yandex's CDN gets the same identity as the API; nobody else sees the token.
|
||||
val identified = ResolvingDataSource.Factory(http) { spec ->
|
||||
val host = spec.uri.host.orEmpty()
|
||||
if (!isYandexHost(host)) return@Factory spec
|
||||
val headers = mutableMapOf("X-Yandex-Music-Client" to CLIENT_HEADER)
|
||||
token()?.let { headers["Authorization"] = "OAuth $it" }
|
||||
spec.withAdditionalHeaders(headers)
|
||||
}
|
||||
val decrypting = AesCtrDataSource.Factory(identified) { uri: Uri -> keys[uri.toString()] }
|
||||
exo = ExoPlayer.Builder(context)
|
||||
.setMediaSourceFactory(DefaultMediaSourceFactory(decrypting))
|
||||
.setAudioAttributes(
|
||||
AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build(),
|
||||
/* handleAudioFocus = */ true,
|
||||
)
|
||||
.setHandleAudioBecomingNoisy(true)
|
||||
.setWakeMode(C.WAKE_MODE_NETWORK)
|
||||
.build()
|
||||
exo.addListener(Listener())
|
||||
handler.post(tick)
|
||||
}
|
||||
|
||||
override fun load(generation: Long, track: Track, stream: Stream, play: Boolean) {
|
||||
this.generation = generation
|
||||
ready = false
|
||||
mirrors = stream.urls
|
||||
mirror = 0
|
||||
keys.clear()
|
||||
val key = stream.key?.let { hexKey(it) }
|
||||
if (key != null) stream.urls.forEach { keys[it] = key }
|
||||
val metadata = MediaMetadata.Builder()
|
||||
.setTitle(track.fullTitle)
|
||||
.setArtist(track.artistLine)
|
||||
.setAlbumTitle(track.album?.title)
|
||||
.setArtworkUri(track.coverUrl(400)?.let(Uri::parse))
|
||||
.setIsPlayable(true)
|
||||
.setIsBrowsable(false)
|
||||
.build()
|
||||
item = MediaItem.Builder().setMediaId(track.id).setMediaMetadata(metadata)
|
||||
start(play)
|
||||
}
|
||||
|
||||
private fun start(play: Boolean) {
|
||||
val builder = item ?: return
|
||||
exo.setMediaItem(builder.setUri(mirrors[mirror]).build())
|
||||
exo.prepare()
|
||||
exo.playWhenReady = play
|
||||
}
|
||||
|
||||
override fun play() {
|
||||
if (exo.playbackState == Player.STATE_IDLE) exo.prepare()
|
||||
exo.play()
|
||||
}
|
||||
|
||||
override fun pause() = exo.pause()
|
||||
|
||||
override fun seek(positionMs: Long) = exo.seekTo(positionMs)
|
||||
|
||||
override fun stop() {
|
||||
ready = false
|
||||
exo.stop()
|
||||
exo.clearMediaItems()
|
||||
}
|
||||
|
||||
private inner class Listener : Player.Listener {
|
||||
override fun onPlaybackStateChanged(state: Int) {
|
||||
when (state) {
|
||||
Player.STATE_READY -> if (!ready) {
|
||||
ready = true
|
||||
events.loaded(generation, exo.duration.takeIf { it != C.TIME_UNSET && it > 0 })
|
||||
}
|
||||
Player.STATE_ENDED -> if (ready) {
|
||||
ready = false
|
||||
events.ended(generation)
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPlayerError(error: PlaybackException) {
|
||||
// Another mirror of the same file may still answer.
|
||||
if (!ready && mirror + 1 < mirrors.size) {
|
||||
mirror += 1
|
||||
start(play = true)
|
||||
return
|
||||
}
|
||||
ready = false
|
||||
events.failed(generation, "${error.errorCodeName}: ${error.message}")
|
||||
}
|
||||
|
||||
override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
|
||||
if (reason != Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST) events.playingChanged(generation, playWhenReady)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TICK_MS = 250L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
// Runs PlayerCore on the main thread: forwards engine events and user commands to it,
|
||||
// carries out the effects it asks for against the API, and publishes what the UI shows.
|
||||
package it.panov.musyx.player
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import it.panov.musyx.api.MY_WAVE
|
||||
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.data.Quality
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** What the UI shows about playback; replaced as a whole on every change but the clock. */
|
||||
@Immutable
|
||||
data class PlaybackState(
|
||||
val track: Track? = null,
|
||||
val status: Status = Status.Paused,
|
||||
val durationMs: Long = 0,
|
||||
val shuffle: Boolean = false,
|
||||
val repeat: Repeat = Repeat.Off,
|
||||
/** Tracks after the current one, with their play-order positions for jumping. */
|
||||
val upcoming: List<Pair<Int, Track>> = emptyList(),
|
||||
val stream: Stream? = null,
|
||||
val notice: Notice? = null,
|
||||
val waveStation: String? = null,
|
||||
) {
|
||||
val hasTrack: Boolean get() = track != null
|
||||
|
||||
/** My Wave itself is what's queued. */
|
||||
val isMyWave: Boolean get() = waveStation == MY_WAVE
|
||||
}
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
class PlaybackController(
|
||||
context: Context,
|
||||
private val scope: CoroutineScope,
|
||||
private val client: () -> YmClient?,
|
||||
private val quality: () -> Quality,
|
||||
/** My Wave's settings, sent as seeds when a session starts. */
|
||||
private val waveSettings: () -> WaveSettings?,
|
||||
private val token: () -> String?,
|
||||
private val onSignedOut: () -> Unit,
|
||||
) : EngineEvents {
|
||||
private val core = PlayerCore()
|
||||
private val engine = ExoEngine(context, token, this)
|
||||
|
||||
/** The ExoPlayer, wrapped so the media session's next/previous reach the queue. */
|
||||
val sessionPlayer = SessionPlayer(engine.exo, this)
|
||||
|
||||
var state by mutableStateOf(PlaybackState())
|
||||
private set
|
||||
|
||||
/** Milliseconds into the current track. Kept apart so the clock doesn't redraw everything. */
|
||||
var positionMs by mutableLongStateOf(0L)
|
||||
private set
|
||||
|
||||
init {
|
||||
core.engine = engine
|
||||
}
|
||||
|
||||
// ---- Commands ----
|
||||
|
||||
fun play(tracks: List<Track>, start: Int, shuffle: Boolean = false) =
|
||||
update { core.play(tracks, start, if (shuffle) true else null) }
|
||||
|
||||
fun playNext(track: Track) = update { core.playNext(track) }
|
||||
fun append(track: Track) = update { core.append(track) }
|
||||
fun playWave(station: String) = update { core.playWave(station) }
|
||||
fun waveRestart() = update { core.waveRestart() }
|
||||
fun toggle() = update { core.toggle() }
|
||||
fun next() = update { core.next() }
|
||||
fun previous() = update { core.previous() }
|
||||
fun toggleShuffle() = update { core.toggleShuffle() }
|
||||
fun cycleRepeat() = update { core.cycleRepeat() }
|
||||
fun jumpTo(orderPos: Int) = update { core.jumpTo(orderPos) }
|
||||
|
||||
fun seek(toMs: Long) = update {
|
||||
core.seek(toMs)
|
||||
emptyList()
|
||||
}
|
||||
|
||||
fun seekBy(deltaMs: Long) = seek((core.positionMs + deltaMs).coerceAtLeast(0))
|
||||
|
||||
/** Play or pause as asked, e.g. by the media session or a remote's play key. */
|
||||
fun setPlaying(playing: Boolean) {
|
||||
val now = core.status == Status.Playing || core.status == Status.Loading
|
||||
if (playing != now) toggle()
|
||||
}
|
||||
|
||||
/** Stops playback and forgets the queue (sign-out). */
|
||||
fun reset() {
|
||||
core.reset()
|
||||
publish()
|
||||
}
|
||||
|
||||
private fun update(change: () -> List<Effect>) {
|
||||
run(change())
|
||||
publish()
|
||||
}
|
||||
|
||||
private fun publish() {
|
||||
val q = core.queue
|
||||
state = PlaybackState(
|
||||
track = core.track,
|
||||
status = core.status,
|
||||
durationMs = core.durationMs,
|
||||
shuffle = core.shuffle,
|
||||
repeat = core.repeat,
|
||||
upcoming = q?.upcoming().orEmpty(),
|
||||
stream = core.stream,
|
||||
notice = core.notice,
|
||||
waveStation = core.waveStation,
|
||||
)
|
||||
positionMs = core.positionMs
|
||||
}
|
||||
|
||||
// ---- Engine events ----
|
||||
|
||||
override fun loaded(generation: Long, durationMs: Long?) = update { core.onLoaded(generation, durationMs) }
|
||||
|
||||
override fun position(generation: Long, positionMs: Long) {
|
||||
core.onPosition(generation, positionMs)
|
||||
this.positionMs = core.positionMs
|
||||
}
|
||||
|
||||
override fun ended(generation: Long) = update { core.onEnded(generation) }
|
||||
|
||||
override fun failed(generation: Long, reason: String) = update { core.onFailed(generation, reason) }
|
||||
|
||||
override fun playingChanged(generation: Long, playing: Boolean) {
|
||||
core.onPlayingChanged(generation, playing)
|
||||
publish()
|
||||
}
|
||||
|
||||
// ---- Effects ----
|
||||
|
||||
private fun run(effects: List<Effect>) {
|
||||
if (effects.isEmpty()) return
|
||||
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) }
|
||||
}
|
||||
}
|
||||
is Effect.Prefetch -> api?.let { c ->
|
||||
scope.launch {
|
||||
val result = runCatching { resolve(c, 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.
|
||||
val settings = if (effect.station == MY_WAVE) waveSettings() else null
|
||||
scope.launch {
|
||||
val result = runCatching {
|
||||
val session = effect.sessionId
|
||||
if (session != null) c.waveMore(session, effect.queue) else c.waveStart(effect.station, settings)
|
||||
}
|
||||
update { core.waveBatch(effect.station, effect.epoch, result) }
|
||||
}
|
||||
}
|
||||
// Feedback and reports are fire-and-forget: a lost one only blunts recommendations.
|
||||
is Effect.WaveFeedback -> api?.let { c ->
|
||||
scope.launch {
|
||||
runCatching { c.waveFeedback(effect.sessionId, effect.event, effect.batchId) }
|
||||
.onFailure { Log.w(TAG, "wave feedback ${effect.event}: $it") }
|
||||
}
|
||||
}
|
||||
is Effect.Report -> api?.let { c ->
|
||||
scope.launch {
|
||||
runCatching { c.reportPlay(effect.report) }.onFailure { Log.w(TAG, "play report: $it") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "Musyx"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
// Playback state: the queue, what's loaded, and the rules for moving between tracks.
|
||||
// Network work is described as [Effect]s for the app to run, so this class stays free of
|
||||
// the API client and can be tested on its own. Port of the desktop `player/mod.rs`.
|
||||
package it.panov.musyx.player
|
||||
|
||||
import it.panov.musyx.api.PlayReport
|
||||
import it.panov.musyx.api.Stream
|
||||
import it.panov.musyx.api.Track
|
||||
import it.panov.musyx.api.WaveBatch
|
||||
import it.panov.musyx.api.WaveEvent
|
||||
import it.panov.musyx.api.YmError
|
||||
import kotlin.random.Random
|
||||
|
||||
/** Give up after this many unplayable tracks in a row instead of skipping forever. */
|
||||
private const val MAX_SKIPS = 3
|
||||
/** "Previous" restarts the current track once it has played this long. */
|
||||
private const val RESTART_AFTER_MS = 3_000L
|
||||
/** Ask a station for more once this few tracks are left. */
|
||||
private const val WAVE_LOW_WATER = 2
|
||||
/** Recent tracks sent with a request for more, so the station knows the context. */
|
||||
private const val WAVE_CONTEXT = 5
|
||||
|
||||
const val FROM_LIST = "musyx-tv"
|
||||
const val FROM_WAVE = "musyx-wave"
|
||||
|
||||
enum class Status {
|
||||
Loading,
|
||||
Playing,
|
||||
Paused,
|
||||
/** The queue ran out with repeat off. Play starts the last track again. */
|
||||
Ended,
|
||||
}
|
||||
|
||||
/** One line for Now Playing when something went wrong. */
|
||||
sealed interface Notice {
|
||||
data object StationDry : Notice
|
||||
data object TooManyFailures : Notice
|
||||
data class Skipped(val title: String) : Notice
|
||||
}
|
||||
|
||||
/** Work the app has to do on the player's behalf. */
|
||||
sealed interface Effect {
|
||||
data class Fetch(val generation: Long, val trackId: String) : Effect
|
||||
data class Prefetch(val trackId: String) : Effect
|
||||
/** The token stopped working mid-session. */
|
||||
data object SignedOut : Effect
|
||||
/** Start a session (`sessionId == null`) or continue one; `queue` is recent `fullId`s. */
|
||||
data class WaveFetch(val station: String, val sessionId: String?, val queue: List<String>, val epoch: Int) : Effect
|
||||
data class WaveFeedback(val sessionId: String, val event: WaveEvent, val batchId: String?) : Effect
|
||||
data class Report(val report: PlayReport) : Effect
|
||||
}
|
||||
|
||||
/** What the engine (ExoPlayer) is told to do. */
|
||||
interface Engine {
|
||||
fun load(generation: Long, track: Track, stream: Stream, play: Boolean)
|
||||
fun play()
|
||||
fun pause()
|
||||
fun seek(positionMs: Long)
|
||||
fun stop()
|
||||
}
|
||||
|
||||
/** A station being played, endlessly topped up. */
|
||||
private class Wave(
|
||||
val station: String,
|
||||
/** Bumped when settings restart the session, so batches asked for before are dropped. */
|
||||
var epoch: Int,
|
||||
/** Set by the first batch; feedback can't be sent before it. */
|
||||
var sessionId: String? = null,
|
||||
/** The batch each queued track came in; feedback must name the track's own batch. */
|
||||
val batches: MutableMap<String, String> = mutableMapOf(),
|
||||
var fetching: Boolean = true,
|
||||
/** The queue ran out before the next batch came; advance when it does. */
|
||||
var waiting: Boolean = true,
|
||||
)
|
||||
|
||||
class PlayerCore(private val random: Random = Random.Default) {
|
||||
var engine: Engine? = null
|
||||
|
||||
var queue: Queue<Track>? = null
|
||||
private set
|
||||
var repeat: Repeat = Repeat.Off
|
||||
private set
|
||||
var shuffle: Boolean = false
|
||||
private set
|
||||
var generation: Long = 0
|
||||
private set
|
||||
var status: Status = Status.Paused
|
||||
private set
|
||||
var positionMs: Long = 0
|
||||
private set
|
||||
var durationMs: Long = 0
|
||||
private set
|
||||
/** The stream playing now. */
|
||||
var stream: Stream? = null
|
||||
private set
|
||||
private var currentTrackId: String? = null
|
||||
private var prefetched: Pair<String, Stream>? = null
|
||||
internal var skips: Int = 0
|
||||
private set
|
||||
var notice: Notice? = null
|
||||
private set
|
||||
private var wave: Wave? = null
|
||||
/** The track that started playing and hasn't been reported yet. */
|
||||
private var started: String? = null
|
||||
/** Paused while the next track was still loading: it loads but doesn't start. */
|
||||
private var holdPaused = false
|
||||
private var waveEpoch = 0
|
||||
|
||||
val track: Track? get() = queue?.current
|
||||
|
||||
/** The station playing, if the queue is a wave. */
|
||||
val waveStation: String? get() = wave?.station
|
||||
|
||||
/** Stops playback and forgets the queue (sign-out). */
|
||||
fun reset() {
|
||||
// No reports: the session they'd go to is ending.
|
||||
engine?.stop()
|
||||
queue = null
|
||||
repeat = Repeat.Off
|
||||
shuffle = false
|
||||
status = Status.Paused
|
||||
positionMs = 0
|
||||
durationMs = 0
|
||||
stream = null
|
||||
currentTrackId = null
|
||||
prefetched = null
|
||||
skips = 0
|
||||
notice = null
|
||||
wave = null
|
||||
started = null
|
||||
holdPaused = false
|
||||
}
|
||||
|
||||
/** Replace the queue. `shuffle` sets shuffle first; with it on, `start` is ignored. */
|
||||
fun play(tracks: List<Track>, start: Int, shuffle: Boolean? = null): List<Effect> {
|
||||
if (shuffle != null) this.shuffle = shuffle
|
||||
val first = if (shuffle == true && tracks.isNotEmpty()) random.nextInt(tracks.size) else start
|
||||
val effects = leave(false).toMutableList()
|
||||
wave = null
|
||||
queue = Queue.of(tracks, first, this.shuffle, random)
|
||||
skips = 0
|
||||
notice = null
|
||||
effects += loadCurrent()
|
||||
return effects
|
||||
}
|
||||
|
||||
/** Queue a track right after the current one (or play it if nothing is queued). */
|
||||
fun playNext(track: Track): List<Effect> {
|
||||
val q = queue ?: return play(listOf(track), 0)
|
||||
return if (q.insertNext(track) { a, b -> a.id == b.id }) prefetchNext() else emptyList()
|
||||
}
|
||||
|
||||
/** Queue a track at the end. */
|
||||
fun append(track: Track): List<Effect> {
|
||||
val q = queue ?: return play(listOf(track), 0)
|
||||
q.extend(listOf(track))
|
||||
return prefetchNext()
|
||||
}
|
||||
|
||||
/** Start a station (`type:tag`). */
|
||||
fun playWave(station: String): List<Effect> {
|
||||
val effects = leave(false).toMutableList()
|
||||
queue = null
|
||||
stream = null
|
||||
currentTrackId = null
|
||||
skips = 0
|
||||
notice = null
|
||||
status = Status.Loading
|
||||
engine?.stop()
|
||||
waveEpoch += 1
|
||||
wave = Wave(station, waveEpoch)
|
||||
effects += Effect.WaveFetch(station, null, emptyList(), waveEpoch)
|
||||
return effects
|
||||
}
|
||||
|
||||
/** The station's settings changed: replace what's queued after the current track. */
|
||||
fun waveRestart(): List<Effect> {
|
||||
// Settings are seeds of a session, so new settings mean a new session.
|
||||
val recent = listOfNotNull(track?.fullId)
|
||||
val w = wave ?: return emptyList()
|
||||
queue?.clearUpcoming()
|
||||
prefetched = null
|
||||
w.sessionId = null
|
||||
w.fetching = true
|
||||
waveEpoch += 1
|
||||
w.epoch = waveEpoch
|
||||
return listOf(Effect.WaveFetch(w.station, null, recent, w.epoch))
|
||||
}
|
||||
|
||||
fun toggle(): List<Effect> {
|
||||
when (status) {
|
||||
Status.Playing -> {
|
||||
engine?.pause()
|
||||
status = Status.Paused
|
||||
}
|
||||
Status.Paused -> when {
|
||||
// The track is still on its way: let it start when it lands.
|
||||
holdPaused && stream == null -> {
|
||||
holdPaused = false
|
||||
status = Status.Loading
|
||||
}
|
||||
stream != null -> {
|
||||
holdPaused = false
|
||||
engine?.play()
|
||||
status = Status.Playing
|
||||
}
|
||||
queue != null -> return loadCurrent()
|
||||
// A station whose first batch never came: ask again.
|
||||
else -> wave?.let { return playWave(it.station) }
|
||||
}
|
||||
Status.Ended -> return loadCurrent()
|
||||
Status.Loading -> {
|
||||
holdPaused = true
|
||||
engine?.pause()
|
||||
status = Status.Paused
|
||||
}
|
||||
}
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
fun next(): List<Effect> = step(user = true, finished = false)
|
||||
|
||||
fun previous(): List<Effect> {
|
||||
if (positionMs >= RESTART_AFTER_MS || !canGoBack()) {
|
||||
seek(0)
|
||||
return emptyList()
|
||||
}
|
||||
val effects = leave(false).toMutableList()
|
||||
val q = queue ?: return effects
|
||||
q.back(repeat)
|
||||
effects += loadCurrent()
|
||||
return effects
|
||||
}
|
||||
|
||||
fun toggleShuffle(): List<Effect> {
|
||||
// A station decides its own order.
|
||||
if (wave != null) return emptyList()
|
||||
shuffle = !shuffle
|
||||
queue?.setShuffle(shuffle)
|
||||
return prefetchNext()
|
||||
}
|
||||
|
||||
fun cycleRepeat(): List<Effect> {
|
||||
repeat = repeat.next()
|
||||
return prefetchNext()
|
||||
}
|
||||
|
||||
fun jumpTo(orderPos: Int): List<Effect> {
|
||||
val effects = leave(false).toMutableList()
|
||||
val q = queue ?: return effects
|
||||
q.jump(orderPos)
|
||||
effects += loadCurrent()
|
||||
return effects
|
||||
}
|
||||
|
||||
fun seek(toMs: Long) {
|
||||
val to = toMs.coerceIn(0, durationMs.coerceAtLeast(0))
|
||||
positionMs = to
|
||||
if (status == Status.Ended) {
|
||||
// The player is empty after the end; reload and play from `to`.
|
||||
val s = stream ?: return
|
||||
loadStream(s, play = true)
|
||||
engine?.seek(to)
|
||||
} else {
|
||||
engine?.seek(to)
|
||||
}
|
||||
}
|
||||
|
||||
fun fetched(generation: Long, result: Result<Stream>): List<Effect> {
|
||||
if (generation != this.generation) return emptyList()
|
||||
result.fold(
|
||||
onSuccess = { loadStream(it, play = !holdPaused) },
|
||||
onFailure = { e ->
|
||||
if (e is YmError.Unauthorized) return listOf(Effect.SignedOut)
|
||||
android.util.Log.w("Musyx", "fetch: $e")
|
||||
return skipUnplayable()
|
||||
},
|
||||
)
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
fun prefetched(trackId: String, result: Result<Stream>) {
|
||||
result.onSuccess { prefetched = trackId to it }
|
||||
.onFailure { android.util.Log.w("Musyx", "prefetch $trackId: $it") }
|
||||
}
|
||||
|
||||
// ---- Engine events ----
|
||||
|
||||
fun onLoaded(generation: Long, durationMs: Long?): List<Effect> {
|
||||
if (generation != this.generation) return emptyList()
|
||||
if (durationMs != null && durationMs > 0) this.durationMs = durationMs
|
||||
status = if (holdPaused) Status.Paused else Status.Playing
|
||||
skips = 0
|
||||
val effects = mutableListOf<Effect>()
|
||||
val t = track
|
||||
if (t != null) {
|
||||
val w = wave
|
||||
val session = w?.sessionId
|
||||
if (w != null && session != null) {
|
||||
effects += Effect.WaveFeedback(session, WaveEvent.TrackStarted(t.fullId), w.batches[t.id])
|
||||
}
|
||||
started = t.id
|
||||
}
|
||||
effects += prefetchNext()
|
||||
effects += topUp()
|
||||
return effects
|
||||
}
|
||||
|
||||
fun onPosition(generation: Long, positionMs: Long) {
|
||||
if (generation == this.generation) this.positionMs = positionMs
|
||||
}
|
||||
|
||||
/** The engine paused or resumed by itself (audio focus, a headset unplugged). */
|
||||
fun onPlayingChanged(generation: Long, playing: Boolean) {
|
||||
if (generation != this.generation) return
|
||||
if (status == Status.Playing && !playing) status = Status.Paused
|
||||
else if (status == Status.Paused && playing && stream != null) status = Status.Playing
|
||||
}
|
||||
|
||||
fun onEnded(generation: Long): List<Effect> =
|
||||
if (generation == this.generation) step(user = false, finished = true) else emptyList()
|
||||
|
||||
fun onFailed(generation: Long, reason: String): List<Effect> {
|
||||
if (generation != this.generation) return emptyList()
|
||||
android.util.Log.w("Musyx", "decode: $reason")
|
||||
return skipUnplayable()
|
||||
}
|
||||
|
||||
// ---- Internals ----
|
||||
|
||||
private fun canGoBack(): Boolean = (queue?.size ?: 0) > 1
|
||||
|
||||
/**
|
||||
* Next track. `finished` distinguishes a natural end (repeat-one replays) from a skip;
|
||||
* `user` skips always move on.
|
||||
*/
|
||||
private fun step(user: Boolean, finished: Boolean): List<Effect> {
|
||||
val effects = leave(finished && !user).toMutableList()
|
||||
val q = queue ?: return effects
|
||||
val w = wave
|
||||
if (q.advance(repeat, finished && !user)) {
|
||||
effects += loadCurrent()
|
||||
} else if (w != null) {
|
||||
// The batch ran dry; carry on as soon as the next one lands.
|
||||
w.waiting = true
|
||||
status = Status.Loading
|
||||
effects += topUp()
|
||||
} else {
|
||||
status = Status.Ended
|
||||
positionMs = durationMs
|
||||
}
|
||||
return effects
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports the track being left: to the listening history always, and to the station
|
||||
* when it's a wave. `finished` means it played to the end.
|
||||
*/
|
||||
private fun leave(finished: Boolean): List<Effect> {
|
||||
val id = started ?: return emptyList()
|
||||
started = null
|
||||
val t = track?.takeIf { it.id == id } ?: return emptyList()
|
||||
val played = if (finished) durationMs else positionMs.coerceAtMost(durationMs)
|
||||
val w = wave
|
||||
val effects = mutableListOf<Effect>(
|
||||
Effect.Report(PlayReport(id, t.album?.id, durationMs, played, played, if (w != null) FROM_WAVE else FROM_LIST)),
|
||||
)
|
||||
val session = w?.sessionId
|
||||
if (w != null && session != null) {
|
||||
val event = if (finished) WaveEvent.TrackFinished(t.fullId, played) else WaveEvent.Skipped(t.fullId, played)
|
||||
effects += Effect.WaveFeedback(session, event, w.batches[id])
|
||||
}
|
||||
return effects
|
||||
}
|
||||
|
||||
/** Asks the station for more when the queue runs low. */
|
||||
private fun topUp(): List<Effect> {
|
||||
val w = wave ?: return emptyList()
|
||||
val q = queue ?: return emptyList()
|
||||
if (w.fetching || q.upcomingCount >= WAVE_LOW_WATER) return emptyList()
|
||||
w.fetching = true
|
||||
return listOf(Effect.WaveFetch(w.station, w.sessionId, q.tail(WAVE_CONTEXT).map { it.fullId }, w.epoch))
|
||||
}
|
||||
|
||||
fun waveBatch(station: String, epoch: Int, result: Result<WaveBatch>): List<Effect> {
|
||||
// A batch for another station, or from before new settings, is stale.
|
||||
val w = wave?.takeIf { it.station == station && it.epoch == epoch } ?: return emptyList()
|
||||
w.fetching = false
|
||||
val batch = result.getOrNull()?.takeIf { it.tracks.isNotEmpty() }
|
||||
if (batch == null) {
|
||||
val e = result.exceptionOrNull()
|
||||
if (e is YmError.Unauthorized) return listOf(Effect.SignedOut)
|
||||
if (e != null) android.util.Log.w("Musyx", "wave batch: $e")
|
||||
if (w.waiting) {
|
||||
w.waiting = false
|
||||
status = if (queue != null) Status.Ended else Status.Paused
|
||||
notice = Notice.StationDry
|
||||
}
|
||||
return emptyList()
|
||||
}
|
||||
batch.batchId?.let { b -> batch.tracks.forEach { w.batches[it.id] = b } }
|
||||
// The first batch of a session opens it: tell the station the radio started.
|
||||
val effects = mutableListOf<Effect>()
|
||||
val session = batch.sessionId
|
||||
if (w.sessionId == null && session != null) {
|
||||
w.sessionId = session
|
||||
effects += Effect.WaveFeedback(session, WaveEvent.Started, batch.batchId)
|
||||
}
|
||||
val waiting = w.waiting
|
||||
w.waiting = false
|
||||
val q = queue
|
||||
effects += if (q == null) {
|
||||
queue = Queue.of(batch.tracks, 0, false, random)
|
||||
loadCurrent()
|
||||
} else {
|
||||
q.extend(batch.tracks)
|
||||
if (waiting && q.advance(Repeat.Off, false)) loadCurrent() else prefetchNext()
|
||||
}
|
||||
return effects
|
||||
}
|
||||
|
||||
private fun loadCurrent(): List<Effect> {
|
||||
val t = track ?: return emptyList()
|
||||
holdPaused = false
|
||||
generation += 1
|
||||
positionMs = 0
|
||||
durationMs = t.durationMs
|
||||
|
||||
// Replaying the same track (repeat one, play after the end) reuses its stream.
|
||||
val ready = prefetched
|
||||
val reuse = when {
|
||||
ready != null && ready.first == t.id -> ready.second.also { prefetched = null }
|
||||
currentTrackId == t.id -> stream
|
||||
else -> null
|
||||
}
|
||||
if (reuse != null) {
|
||||
loadStream(reuse, play = true)
|
||||
return emptyList()
|
||||
}
|
||||
// The previous track mustn't keep playing while this one is fetched.
|
||||
engine?.pause()
|
||||
status = Status.Loading
|
||||
stream = null
|
||||
return listOf(Effect.Fetch(generation, t.id))
|
||||
}
|
||||
|
||||
private fun loadStream(s: Stream, play: Boolean) {
|
||||
val t = track ?: return
|
||||
currentTrackId = t.id
|
||||
status = if (play) Status.Loading else Status.Paused
|
||||
engine?.load(generation, t, s, play)
|
||||
stream = s
|
||||
}
|
||||
|
||||
private fun prefetchNext(): List<Effect> {
|
||||
val q = queue ?: return emptyList()
|
||||
val next = q.peekNext(repeat) ?: return emptyList()
|
||||
if (currentTrackId == next.id) return emptyList()
|
||||
if (prefetched?.first == next.id) return emptyList()
|
||||
prefetched = null
|
||||
return listOf(Effect.Prefetch(next.id))
|
||||
}
|
||||
|
||||
private fun skipUnplayable(): List<Effect> {
|
||||
val title = track?.fullTitle.orEmpty()
|
||||
skips += 1
|
||||
stream = null
|
||||
currentTrackId = null
|
||||
if (skips >= MAX_SKIPS) {
|
||||
engine?.pause()
|
||||
status = Status.Paused
|
||||
notice = Notice.TooManyFailures
|
||||
return emptyList()
|
||||
}
|
||||
notice = Notice.Skipped(title)
|
||||
return step(user = true, finished = false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// Play order over a fixed list of items: shuffle, repeat, next/previous. Port of the
|
||||
// desktop `player/queue.rs`; generic so the rules can be tested with plain numbers.
|
||||
package it.panov.musyx.player
|
||||
|
||||
import kotlin.random.Random
|
||||
|
||||
enum class Repeat {
|
||||
Off, All, One;
|
||||
|
||||
fun next(): Repeat = when (this) {
|
||||
Off -> All
|
||||
All -> One
|
||||
One -> Off
|
||||
}
|
||||
}
|
||||
|
||||
class Queue<T> private constructor(
|
||||
private val items: MutableList<T>,
|
||||
/** Indices into [items] in play order. */
|
||||
private var order: MutableList<Int>,
|
||||
/** Position in [order] of the current item. */
|
||||
private var pos: Int,
|
||||
private val random: Random,
|
||||
) {
|
||||
private var shuffle = false
|
||||
|
||||
val current: T get() = items[order[pos]]
|
||||
|
||||
val size: Int get() = items.size
|
||||
|
||||
/**
|
||||
* Moves on after a track. `finished` is true when it played to the end, in which case
|
||||
* [Repeat.One] replays it; a skip always advances. Returns false at the end of the
|
||||
* queue with repeat off.
|
||||
*/
|
||||
fun advance(repeat: Repeat, finished: Boolean): Boolean {
|
||||
if (finished && repeat == Repeat.One) return true
|
||||
return when {
|
||||
pos + 1 < order.size -> { pos += 1; true }
|
||||
repeat != Repeat.Off -> { pos = 0; true }
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
/** Steps back one item, wrapping when repeat is on. Returns false at the start. */
|
||||
fun back(repeat: Repeat): Boolean = when {
|
||||
pos > 0 -> { pos -= 1; true }
|
||||
repeat != Repeat.Off -> { pos = order.size - 1; true }
|
||||
else -> false
|
||||
}
|
||||
|
||||
/** The item that `advance(repeat, true)` would move to, without moving. */
|
||||
fun peekNext(repeat: Repeat): T? = when {
|
||||
repeat == Repeat.One -> current
|
||||
pos + 1 < order.size -> items[order[pos + 1]]
|
||||
repeat == Repeat.All -> items[order[0]]
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** Items after the current one, in play order (no wrap-around), with their positions. */
|
||||
fun upcoming(): List<Pair<Int, T>> =
|
||||
(pos + 1 until order.size).map { it to items[order[it]] }
|
||||
|
||||
val upcomingCount: Int get() = order.size - pos - 1
|
||||
|
||||
/** Jumps to a play-order position from [upcoming]. */
|
||||
fun jump(orderPos: Int) {
|
||||
if (orderPos in order.indices) pos = orderPos
|
||||
}
|
||||
|
||||
/**
|
||||
* Turning shuffle on keeps the current item and shuffles everything after it;
|
||||
* turning it off restores list order at the current item.
|
||||
*/
|
||||
fun setShuffle(on: Boolean) {
|
||||
if (on == shuffle) return
|
||||
val cur = order[pos]
|
||||
if (on) {
|
||||
val rest = items.indices.filter { it != cur }.shuffled(random)
|
||||
order = (listOf(cur) + rest).toMutableList()
|
||||
pos = 0
|
||||
} else {
|
||||
order = items.indices.toMutableList()
|
||||
pos = cur
|
||||
}
|
||||
shuffle = on
|
||||
}
|
||||
|
||||
/** The last `n` items of the play order, oldest first. */
|
||||
fun tail(n: Int): List<T> = order.takeLast(n).map { items[it] }
|
||||
|
||||
/** Adds items to the end of the play order (radio batches arriving). */
|
||||
fun extend(more: Iterable<T>) {
|
||||
for (item in more) {
|
||||
order.add(items.size)
|
||||
items.add(item)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts an item right after the current one. If it's already coming up it moves there
|
||||
* instead of being duplicated; if it *is* the current item nothing changes. Returns
|
||||
* whether the queue changed.
|
||||
*/
|
||||
fun insertNext(item: T, same: (T, T) -> Boolean): Boolean {
|
||||
if (same(current, item)) return false
|
||||
val later = (pos + 1 until order.size).firstOrNull { same(items[order[it]], item) }
|
||||
if (later != null) {
|
||||
val index = order.removeAt(later)
|
||||
order.add(pos + 1, index)
|
||||
} else {
|
||||
items.add(item)
|
||||
order.add(pos + 1, items.size - 1)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** Drops everything after the current item, e.g. when a station's settings change. */
|
||||
fun clearUpcoming() {
|
||||
val keep = order.subList(0, pos + 1).map { items[it] }
|
||||
items.clear()
|
||||
items.addAll(keep)
|
||||
order = items.indices.toMutableList()
|
||||
}
|
||||
|
||||
/** Play-order index of an item position, for tests. */
|
||||
internal fun orderAt(i: Int): Int = order[i]
|
||||
|
||||
companion object {
|
||||
/** A queue over `items` starting at `start`; null for an empty list. */
|
||||
fun <T> of(items: List<T>, start: Int, shuffle: Boolean, random: Random = Random.Default): Queue<T>? {
|
||||
if (items.isEmpty()) return null
|
||||
val q = Queue(items.toMutableList(), items.indices.toMutableList(), start.coerceIn(0, items.size - 1), random)
|
||||
if (shuffle) q.setShuffle(true)
|
||||
return q
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// The player that each app's media session wraps.
|
||||
package it.panov.musyx.player
|
||||
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.ForwardingSimpleBasePlayer
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import com.google.common.util.concurrent.Futures
|
||||
import com.google.common.util.concurrent.ListenableFuture
|
||||
|
||||
/**
|
||||
* The ExoPlayer as the media session sees it. ExoPlayer only ever holds the current
|
||||
* track, so next and previous are added here and routed to the queue, as are play,
|
||||
* pause and seeks, so PlayerCore stays the one source of truth.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
class SessionPlayer(player: Player, private val controller: PlaybackController) :
|
||||
ForwardingSimpleBasePlayer(player) {
|
||||
|
||||
override fun getState(): State {
|
||||
val state = super.getState()
|
||||
val commands = state.availableCommands.buildUpon()
|
||||
.addAll(
|
||||
Player.COMMAND_PLAY_PAUSE,
|
||||
Player.COMMAND_SEEK_TO_NEXT,
|
||||
Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM,
|
||||
Player.COMMAND_SEEK_TO_PREVIOUS,
|
||||
Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM,
|
||||
)
|
||||
.build()
|
||||
return state.buildUpon().setAvailableCommands(commands).build()
|
||||
}
|
||||
|
||||
override fun handleSetPlayWhenReady(playWhenReady: Boolean): ListenableFuture<*> {
|
||||
controller.setPlaying(playWhenReady)
|
||||
return Futures.immediateVoidFuture()
|
||||
}
|
||||
|
||||
/** A stop from the system or the Assistant pauses, so the queue stays as it is. */
|
||||
override fun handleStop(): ListenableFuture<*> {
|
||||
controller.setPlaying(false)
|
||||
return Futures.immediateVoidFuture()
|
||||
}
|
||||
|
||||
/** The queue prepares tracks itself; play after a stop goes through [handleSetPlayWhenReady]. */
|
||||
override fun handlePrepare(): ListenableFuture<*> = Futures.immediateVoidFuture()
|
||||
|
||||
override fun handleSeek(mediaItemIndex: Int, positionMs: Long, seekCommand: Int): ListenableFuture<*> {
|
||||
when (seekCommand) {
|
||||
Player.COMMAND_SEEK_TO_NEXT, Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM -> controller.next()
|
||||
Player.COMMAND_SEEK_TO_PREVIOUS, Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM -> controller.previous()
|
||||
else -> controller.seek(positionMs.coerceAtLeast(0))
|
||||
}
|
||||
return Futures.immediateVoidFuture()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,798 @@
|
||||
// Application state and everything that changes it. Port of the desktop app.rs and
|
||||
// app/edit.rs: screens read these fields and call these methods; all of it runs on the
|
||||
// main thread, with network calls in coroutines that write their results back.
|
||||
package it.panov.musyx.state
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import it.panov.musyx.R
|
||||
import it.panov.musyx.api.Account
|
||||
import it.panov.musyx.api.AlbumPage
|
||||
import it.panov.musyx.api.AlbumSummary
|
||||
import it.panov.musyx.api.ArtistPage
|
||||
import it.panov.musyx.api.ArtistSummary
|
||||
import it.panov.musyx.api.Auth
|
||||
import it.panov.musyx.api.Clip
|
||||
import it.panov.musyx.api.ContentLanguage
|
||||
import it.panov.musyx.api.Credentials
|
||||
import it.panov.musyx.api.Genre
|
||||
import it.panov.musyx.api.Home
|
||||
import it.panov.musyx.api.LibraryPlaylists
|
||||
import it.panov.musyx.api.LikedIds
|
||||
import it.panov.musyx.api.Lrclib
|
||||
import it.panov.musyx.api.Lyrics
|
||||
import it.panov.musyx.api.MY_WAVE
|
||||
import it.panov.musyx.api.PlaylistId
|
||||
import it.panov.musyx.api.PlaylistPage
|
||||
import it.panov.musyx.api.PlaylistSummary
|
||||
import it.panov.musyx.api.Station
|
||||
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.Appearance
|
||||
import it.panov.musyx.data.FontSize
|
||||
import it.panov.musyx.data.CredentialStore
|
||||
import it.panov.musyx.data.Locale
|
||||
import it.panov.musyx.data.Quality
|
||||
import it.panov.musyx.data.Settings
|
||||
import it.panov.musyx.data.SettingsStore
|
||||
import it.panov.musyx.player.PlaybackController
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Tracks in Home's "Recently played". */
|
||||
const val RECENT = 10
|
||||
|
||||
/** Where sign-in stands. Everything but [SignedIn] takes the whole screen. */
|
||||
sealed interface Session {
|
||||
/** Reading the stored credentials and checking the token. */
|
||||
data object Restoring : Session
|
||||
data class SignedOut(val signIn: SignInState) : Session
|
||||
/** Fresh credentials are being checked. `pasted` picks the error wording if they fail. */
|
||||
data class Connecting(val pasted: Boolean) : Session
|
||||
data object Unreachable : Session
|
||||
data class SignedIn(val client: YmClient, val account: Account) : Session
|
||||
}
|
||||
|
||||
enum class CollectionTab { Tracks, Albums, Artists, Playlists, Clips }
|
||||
|
||||
/** A loaded detail page. */
|
||||
sealed interface Page {
|
||||
data class OfAlbum(val info: AlbumPage) : Page
|
||||
data class OfArtist(val info: ArtistPage) : Page
|
||||
data class OfPlaylist(val info: PlaylistPage) : Page
|
||||
}
|
||||
|
||||
class AppState(
|
||||
context: Context,
|
||||
private val scope: CoroutineScope,
|
||||
private val credentialStore: CredentialStore,
|
||||
private val settingsStore: SettingsStore,
|
||||
/** The device language, for [Locale.System]. */
|
||||
private val systemLanguage: () -> String,
|
||||
/** Coil's disk cache, cleared from Settings. */
|
||||
private val clearCovers: suspend () -> Unit,
|
||||
) {
|
||||
var session: Session by mutableStateOf(Session.Restoring)
|
||||
private set
|
||||
val nav = Navigator()
|
||||
var settings: Settings by mutableStateOf(settingsStore.load())
|
||||
private set
|
||||
private var credentials: Credentials? = null
|
||||
|
||||
// Library
|
||||
var collectionTab by mutableStateOf(CollectionTab.Tracks)
|
||||
private set
|
||||
var liked: Liked by mutableStateOf(Liked.NotLoaded)
|
||||
private set
|
||||
var albums: Loadable<List<AlbumSummary>> by mutableStateOf(Loadable.NotLoaded)
|
||||
private set
|
||||
var artists: Loadable<List<ArtistSummary>> by mutableStateOf(Loadable.NotLoaded)
|
||||
private set
|
||||
var playlists: Loadable<LibraryPlaylists> by mutableStateOf(Loadable.NotLoaded)
|
||||
private set
|
||||
var clips: Loadable<List<Clip>> by mutableStateOf(Loadable.NotLoaded)
|
||||
private set
|
||||
/** Albums, artists, playlists and clips liked, and tracks disliked, by id. */
|
||||
var likes by mutableStateOf(LikedIds())
|
||||
private set
|
||||
|
||||
// Discovery
|
||||
var home: Loadable<Home> by mutableStateOf(Loadable.NotLoaded)
|
||||
private set
|
||||
/** The last tracks played on any device. Reloaded on every visit to Home. */
|
||||
var recent: Loadable<List<Track>> by mutableStateOf(Loadable.NotLoaded)
|
||||
private set
|
||||
/** Top-level genres followed by their sub-genres, so a `Route.Genre` index finds either. */
|
||||
var genres: Loadable<List<Genre>> by mutableStateOf(Loadable.NotLoaded)
|
||||
private set
|
||||
var podcasts: Loadable<List<AlbumSummary>> by mutableStateOf(Loadable.NotLoaded)
|
||||
private set
|
||||
val genrePlaylists = mutableStateMapOf<Int, Loadable<List<PlaylistSummary>>>()
|
||||
|
||||
// My Wave
|
||||
var waveSettings: Loadable<WaveSettings> by mutableStateOf(Loadable.NotLoaded)
|
||||
private set
|
||||
var stations: Loadable<List<Station>> by mutableStateOf(Loadable.NotLoaded)
|
||||
private set
|
||||
/** Settings picked but not yet confirmed by Yandex. */
|
||||
var waveSaving: WaveSettings? by mutableStateOf(null)
|
||||
private set
|
||||
|
||||
/** Album, artist and playlist pages visited this session. */
|
||||
val pages = mutableStateMapOf<Route, Loadable<Page>>()
|
||||
/** Lyrics per track id, fetched while the lyrics tab is open. */
|
||||
val lyrics = mutableStateMapOf<String, Loadable<Lyrics?>>()
|
||||
|
||||
var sheet: Sheet? by mutableStateOf(null)
|
||||
private set
|
||||
var toast: Toast? by mutableStateOf(null)
|
||||
private set
|
||||
private var toastSerial = 0L
|
||||
|
||||
val search = SearchState(scope, ::client, ::failed)
|
||||
|
||||
val playback = PlaybackController(
|
||||
context = context,
|
||||
scope = scope,
|
||||
client = ::client,
|
||||
quality = { settings.quality },
|
||||
waveSettings = { waveShown },
|
||||
token = { credentials?.accessToken },
|
||||
onSignedOut = ::signOut,
|
||||
)
|
||||
|
||||
val client: YmClient? get() = (session as? Session.SignedIn)?.client
|
||||
val account: Account? get() = (session as? Session.SignedIn)?.account
|
||||
|
||||
/** The wave settings to show: the pending choice while saving. */
|
||||
val waveShown: WaveSettings? get() = waveSaving ?: waveSettings.get()
|
||||
|
||||
/** What Yandex should write its own titles in. */
|
||||
private val contentLanguage: ContentLanguage
|
||||
get() = if (resolvedLanguage == "ru") ContentLanguage.Russian else ContentLanguage.English
|
||||
|
||||
/** `en` or `ru`: the language the interface is in. */
|
||||
val resolvedLanguage: String
|
||||
get() = settings.language.tag ?: if (systemLanguage().startsWith("ru")) "ru" else "en"
|
||||
|
||||
// ---- Session ----
|
||||
|
||||
fun start() {
|
||||
if (session == Session.Restoring) restore()
|
||||
}
|
||||
|
||||
fun restore() {
|
||||
session = Session.Restoring
|
||||
scope.launch {
|
||||
val stored = credentialStore.load()
|
||||
if (stored == null) {
|
||||
session = signedOut()
|
||||
return@launch
|
||||
}
|
||||
var creds = stored
|
||||
if (creds.needsRefresh()) creds = refresh(creds) ?: creds
|
||||
try {
|
||||
val (client, account) = YmClient.connect(creds, contentLanguage)
|
||||
signedIn(creds, client, account)
|
||||
} catch (e: YmError.Unauthorized) {
|
||||
val fresh = refresh(creds)
|
||||
if (fresh == null) return@launch forget(e)
|
||||
try {
|
||||
val (client, account) = YmClient.connect(fresh, contentLanguage)
|
||||
signedIn(fresh, client, account)
|
||||
} catch (e2: Throwable) {
|
||||
forget(YmError.of(e2))
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
val err = YmError.of(e)
|
||||
// Credentials stay for a retry when Yandex is only unreachable.
|
||||
if (err.isRetryable) {
|
||||
credentials = creds
|
||||
session = Session.Unreachable
|
||||
} else {
|
||||
forget(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Refresh and persist; null when there is nothing to refresh with or Yandex said no. */
|
||||
private suspend fun refresh(old: Credentials): Credentials? {
|
||||
if (old.refreshToken == null) return null
|
||||
return runCatching { Auth.refresh(old) }.getOrNull()?.also { credentialStore.save(it) }
|
||||
}
|
||||
|
||||
private fun forget(reason: YmError) {
|
||||
Log.w(TAG, "stored sign-in rejected: $reason")
|
||||
credentialStore.clear()
|
||||
session = signedOut()
|
||||
}
|
||||
|
||||
private fun signedOut(): Session.SignedOut = Session.SignedOut(SignInState(scope, ::granted))
|
||||
|
||||
/** Save first so a restart right after sign-in doesn't lose it, then check the token. */
|
||||
private fun granted(creds: Credentials) {
|
||||
val pasted = creds.refreshToken == null
|
||||
session = Session.Connecting(pasted)
|
||||
credentialStore.save(creds)
|
||||
scope.launch {
|
||||
try {
|
||||
val (client, account) = YmClient.connect(creds, contentLanguage)
|
||||
signedIn(creds, client, account)
|
||||
} catch (e: Throwable) {
|
||||
val err = YmError.of(e)
|
||||
Log.w(TAG, "sign-in: $err")
|
||||
// Don't keep credentials that just failed.
|
||||
credentialStore.clear()
|
||||
session = Session.SignedOut(
|
||||
if (err is YmError.Unauthorized && pasted) SignInState.rejectedToken(scope, ::granted)
|
||||
else SignInState.withError(scope, err, ::granted),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun signedIn(creds: Credentials, client: YmClient, account: Account) {
|
||||
credentials = creds
|
||||
nav.reset(Route.Home)
|
||||
session = Session.SignedIn(client, account)
|
||||
// Liked tracks drive the hearts; playlists feed "Add to playlist"; Home is the first page.
|
||||
loadLiked()
|
||||
loadLikedIds()
|
||||
forceLoadTab(CollectionTab.Playlists)
|
||||
onEnter(Route.Home)
|
||||
}
|
||||
|
||||
fun signOut() {
|
||||
(session as? Session.SignedOut)?.signIn?.dispose()
|
||||
credentialStore.clear()
|
||||
credentials = null
|
||||
playback.reset()
|
||||
nav.reset(Route.Home)
|
||||
liked = Liked.NotLoaded
|
||||
albums = Loadable.NotLoaded
|
||||
artists = Loadable.NotLoaded
|
||||
playlists = Loadable.NotLoaded
|
||||
clips = Loadable.NotLoaded
|
||||
collectionTab = CollectionTab.Tracks
|
||||
likes = LikedIds()
|
||||
clearDiscovery()
|
||||
pages.clear()
|
||||
lyrics.clear()
|
||||
search.clear()
|
||||
sheet = null
|
||||
session = signedOut()
|
||||
}
|
||||
|
||||
private fun clearDiscovery() {
|
||||
home = Loadable.NotLoaded
|
||||
recent = Loadable.NotLoaded
|
||||
genres = Loadable.NotLoaded
|
||||
podcasts = Loadable.NotLoaded
|
||||
genrePlaylists.clear()
|
||||
waveSettings = Loadable.NotLoaded
|
||||
stations = Loadable.NotLoaded
|
||||
waveSaving = null
|
||||
}
|
||||
|
||||
/** A rejected token ends the session; anything else is logged and shown by the caller. */
|
||||
private fun failed(e: YmError): Boolean {
|
||||
Log.w(TAG, "request failed: $e")
|
||||
if (e is YmError.Unauthorized) {
|
||||
signOut()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Runs `block`, then hands its result to `done` unless the token turned out to be dead. */
|
||||
private fun <T> load(block: suspend (YmClient) -> T, done: (Loadable<T>) -> Unit) {
|
||||
val c = client ?: return
|
||||
scope.launch {
|
||||
val result = runCatching { block(c) }
|
||||
// Results for a session that has since ended, or for a client in the language
|
||||
// before a switch, are dropped; even a 401 from them says nothing about now.
|
||||
if (client !== c) return@launch
|
||||
val error = result.exceptionOrNull()?.let(YmError::of)
|
||||
if (error != null && failed(error)) return@launch
|
||||
done(Loadable.of(result))
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Navigation ----
|
||||
|
||||
fun navigate(route: Route) {
|
||||
sheet = null
|
||||
nav.go(route)
|
||||
onEnter(route)
|
||||
}
|
||||
|
||||
/** Back: closes a dialog first, then walks the history. False when there's nowhere left. */
|
||||
fun back(): Boolean {
|
||||
if (sheet != null) {
|
||||
sheet = null
|
||||
return true
|
||||
}
|
||||
if (!nav.back()) return false
|
||||
onEnter(nav.current)
|
||||
return true
|
||||
}
|
||||
|
||||
/** Loads what a route shows on first visit, and retries after a failure. */
|
||||
fun onEnter(route: Route) {
|
||||
when (route) {
|
||||
Route.Collection -> {
|
||||
if (liked is Liked.Failed) loadLiked()
|
||||
loadTab(collectionTab)
|
||||
}
|
||||
// Settings shows the subscription, which can change outside the app.
|
||||
Route.Settings -> load({ it.account() }) { r ->
|
||||
val fresh = r.get() ?: return@load
|
||||
(session as? Session.SignedIn)?.let { session = it.copy(account = fresh) }
|
||||
}
|
||||
Route.Home -> {
|
||||
if (home.needsLoad) loadHome()
|
||||
// History changes with every listen, so it's re-read on each visit.
|
||||
if (recent != Loadable.Loading) loadRecent()
|
||||
if (genres.needsLoad) loadGenres()
|
||||
loadWave()
|
||||
}
|
||||
Route.Wave -> loadWave()
|
||||
Route.Search -> if (genres.needsLoad) loadGenres()
|
||||
Route.Chart -> if (home.needsLoad) loadHome()
|
||||
is Route.Genre -> if (genres.needsLoad) loadGenres() else loadGenre(route.index)
|
||||
Route.Podcasts -> {
|
||||
if (podcasts.needsLoad) loadPodcasts()
|
||||
// "Yours" comes from liked albums.
|
||||
loadTab(CollectionTab.Albums)
|
||||
}
|
||||
is Route.Album, is Route.Artist, is Route.Playlist -> loadPage(route)
|
||||
Route.NowPlaying -> {}
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadPage(route: Route, force: Boolean = false) {
|
||||
if (!force && pages[route]?.needsLoad == false) return
|
||||
if (pages[route] == null || pages[route]?.needsLoad == true) pages[route] = Loadable.Loading
|
||||
load<Page>(
|
||||
{
|
||||
when (route) {
|
||||
is Route.Album -> Page.OfAlbum(it.album(route.id))
|
||||
is Route.Artist -> Page.OfArtist(it.artist(route.id))
|
||||
is Route.Playlist -> Page.OfPlaylist(it.playlist(route.id))
|
||||
else -> error("not a page: $route")
|
||||
}
|
||||
},
|
||||
) { pages[route] = it }
|
||||
}
|
||||
|
||||
// ---- Loading ----
|
||||
|
||||
fun loadHome() {
|
||||
home = Loadable.Loading
|
||||
load({ it.home() }) { home = it }
|
||||
}
|
||||
|
||||
fun loadRecent() {
|
||||
// A reload keeps showing the previous list until the new one arrives.
|
||||
if (recent !is Loadable.Loaded) recent = Loadable.Loading
|
||||
load({ it.recentlyPlayed(RECENT) }) { r ->
|
||||
// Keep an older list rather than dropping the section.
|
||||
if (r is Loadable.Loaded || recent !is Loadable.Loaded) recent = r
|
||||
}
|
||||
}
|
||||
|
||||
fun loadGenres() {
|
||||
if (client == null) return
|
||||
genres = Loadable.Loading
|
||||
load({ Genre.flatten(it.genres()) }) {
|
||||
genres = it
|
||||
// A genre page opened before the list arrived (after a language switch) loads now.
|
||||
(nav.current as? Route.Genre)?.let { g -> loadGenre(g.index) }
|
||||
}
|
||||
}
|
||||
|
||||
fun loadGenre(index: Int, force: Boolean = false) {
|
||||
if (!force && genrePlaylists[index]?.needsLoad == false) return
|
||||
val genre = genres.get()?.getOrNull(index) ?: return
|
||||
genrePlaylists[index] = Loadable.Loading
|
||||
load({ it.tagPlaylists(genre.id) }) { genrePlaylists[index] = it }
|
||||
}
|
||||
|
||||
fun loadPodcasts() {
|
||||
podcasts = Loadable.Loading
|
||||
load({ it.featuredPodcasts() }) { podcasts = it }
|
||||
}
|
||||
|
||||
fun loadWave() {
|
||||
if (waveSettings.needsLoad) {
|
||||
waveSettings = Loadable.Loading
|
||||
load({ it.waveSettings(MY_WAVE) }) { waveSettings = it }
|
||||
}
|
||||
if (stations.needsLoad) {
|
||||
stations = Loadable.Loading
|
||||
load({ it.stations() }) { stations = it }
|
||||
}
|
||||
}
|
||||
|
||||
fun retryPage(route: Route) = loadPage(route, force = true)
|
||||
|
||||
fun loadLiked() {
|
||||
if (client == null || liked == Liked.Loading) return
|
||||
liked = Liked.Loading
|
||||
load({ it.likedTracks() }) { r ->
|
||||
liked = when (r) {
|
||||
is Loadable.Loaded -> Liked.Loaded(r.value)
|
||||
is Loadable.Failed -> Liked.Failed(r.error)
|
||||
else -> Liked.NotLoaded
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadLikedIds() {
|
||||
load({ it.likedIds() }) { r -> r.get()?.let { likes = it } }
|
||||
}
|
||||
|
||||
fun selectTab(tab: CollectionTab) {
|
||||
collectionTab = tab
|
||||
loadTab(tab)
|
||||
}
|
||||
|
||||
private fun loadTab(tab: CollectionTab) {
|
||||
val needed = when (tab) {
|
||||
CollectionTab.Tracks -> liked == Liked.NotLoaded
|
||||
CollectionTab.Albums -> albums.needsLoad
|
||||
CollectionTab.Artists -> artists.needsLoad
|
||||
CollectionTab.Playlists -> playlists.needsLoad
|
||||
CollectionTab.Clips -> clips.needsLoad
|
||||
}
|
||||
if (needed) forceLoadTab(tab)
|
||||
}
|
||||
|
||||
fun forceLoadTab(tab: CollectionTab) {
|
||||
when (tab) {
|
||||
CollectionTab.Tracks -> loadLiked()
|
||||
CollectionTab.Albums -> {
|
||||
albums = Loadable.Loading
|
||||
load({ it.likedAlbums() }) { albums = it }
|
||||
}
|
||||
CollectionTab.Artists -> {
|
||||
artists = Loadable.Loading
|
||||
load({ it.likedArtists() }) { artists = it }
|
||||
}
|
||||
CollectionTab.Playlists -> {
|
||||
playlists = Loadable.Loading
|
||||
load({ it.libraryPlaylists() }) { playlists = it }
|
||||
}
|
||||
CollectionTab.Clips -> {
|
||||
clips = Loadable.Loading
|
||||
load({ it.likedClips() }) { clips = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Playback ----
|
||||
|
||||
fun playTracks(tracks: List<Track>, start: Int, shuffle: Boolean = false) {
|
||||
if (tracks.isEmpty()) return
|
||||
playback.play(tracks, start, shuffle)
|
||||
}
|
||||
|
||||
fun playWave(station: String) = playback.playWave(station)
|
||||
|
||||
fun playNext(track: Track) {
|
||||
sheet = null
|
||||
if (playback.state.track?.id == track.id) {
|
||||
toast(UiText.Res(R.string.toast_already_playing, track.fullTitle))
|
||||
return
|
||||
}
|
||||
toast(UiText.Res(R.string.toast_plays_next, track.fullTitle))
|
||||
playback.playNext(track)
|
||||
}
|
||||
|
||||
/** "Next track" in the menu of the track playing now. */
|
||||
fun skipFromMenu() {
|
||||
sheet = null
|
||||
playback.next()
|
||||
}
|
||||
|
||||
fun addToQueue(track: Track) {
|
||||
sheet = null
|
||||
toast(UiText.Res(R.string.toast_added_to_queue, track.fullTitle))
|
||||
playback.append(track)
|
||||
}
|
||||
|
||||
/** Plays the tracks Yandex finds similar to this one. */
|
||||
fun playSimilar(track: Track) {
|
||||
sheet = null
|
||||
toast(UiText.Res(R.string.toast_finding_similar, track.fullTitle))
|
||||
load({ it.similarTracks(track.id) }) { r ->
|
||||
when (r) {
|
||||
is Loadable.Loaded -> if (r.value.isEmpty()) {
|
||||
toast(UiText.Res(R.string.toast_no_similar, track.fullTitle))
|
||||
} else {
|
||||
toast(UiText.Plural(R.plurals.toast_playing_similar, r.value.size, r.value.size, track.fullTitle))
|
||||
playTracks(r.value, 0)
|
||||
}
|
||||
else -> toast(UiText.Res(R.string.toast_similar_failed))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- My Wave ----
|
||||
|
||||
fun setWaveSettings(next: WaveSettings) {
|
||||
if (waveSaving != null) return
|
||||
waveSaving = next
|
||||
load({ it.setWaveSettings(MY_WAVE, next) }) { r ->
|
||||
waveSaving = null
|
||||
if (r is Loadable.Loaded) {
|
||||
waveSettings = Loadable.Loaded(next)
|
||||
// A playing My Wave picks the new settings up from the next track.
|
||||
if (playback.state.isMyWave) playback.waveRestart()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Lyrics ----
|
||||
|
||||
/** 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
|
||||
lyrics[track.id] = Loadable.Loading
|
||||
load({ it.lyrics(track.id) ?: Lrclib.lyrics(track) }) { lyrics[track.id] = it }
|
||||
}
|
||||
|
||||
fun retryLyrics(track: Track) {
|
||||
lyrics.remove(track.id)
|
||||
wantLyrics(track)
|
||||
}
|
||||
|
||||
// ---- Dialogs and toasts ----
|
||||
|
||||
fun openSheet(next: Sheet) {
|
||||
sheet = next
|
||||
}
|
||||
|
||||
fun closeSheet() {
|
||||
sheet = null
|
||||
}
|
||||
|
||||
fun toast(text: UiText) {
|
||||
toastSerial += 1
|
||||
toast = Toast(text, toastSerial)
|
||||
}
|
||||
|
||||
fun dismissToast(serial: Long) {
|
||||
if (toast?.serial == serial) toast = null
|
||||
}
|
||||
|
||||
// ---- Settings ----
|
||||
|
||||
fun setQuality(quality: Quality) {
|
||||
updateSettings(settings.copy(quality = quality))
|
||||
toast(UiText.Res(R.string.toast_quality, UiText.Res(qualityLabel(quality))))
|
||||
}
|
||||
|
||||
fun setAppearance(appearance: Appearance) = updateSettings(settings.copy(appearance = appearance))
|
||||
|
||||
fun setFontSize(fontSize: FontSize) = updateSettings(settings.copy(fontSize = fontSize))
|
||||
|
||||
fun setSaverLyrics(on: Boolean) = updateSettings(settings.copy(saverLyrics = on))
|
||||
|
||||
/** The activity recreates itself in the new language; Yandex's own titles follow. */
|
||||
fun setLanguage(language: Locale) {
|
||||
val before = contentLanguage
|
||||
updateSettings(settings.copy(language = language))
|
||||
if (contentLanguage == before) return
|
||||
val s = session as? Session.SignedIn ?: return
|
||||
session = s.copy(client = s.client.inLanguage(contentLanguage))
|
||||
clearDiscovery()
|
||||
// Requests still out belong to the old client and will be dropped: ask again.
|
||||
pages.keys.filter { pages[it] == Loadable.Loading }.forEach { pages.remove(it) }
|
||||
lyrics.keys.filter { lyrics[it] == Loadable.Loading }.forEach { lyrics.remove(it) }
|
||||
if (liked == Liked.Loading) {
|
||||
liked = Liked.NotLoaded
|
||||
loadLiked()
|
||||
}
|
||||
if (albums == Loadable.Loading) forceLoadTab(CollectionTab.Albums)
|
||||
if (artists == Loadable.Loading) forceLoadTab(CollectionTab.Artists)
|
||||
if (playlists == Loadable.Loading) forceLoadTab(CollectionTab.Playlists)
|
||||
if (clips == Loadable.Loading) forceLoadTab(CollectionTab.Clips)
|
||||
loadLikedIds()
|
||||
onEnter(nav.current)
|
||||
}
|
||||
|
||||
private fun updateSettings(next: Settings) {
|
||||
settings = next
|
||||
settingsStore.save(next)
|
||||
}
|
||||
|
||||
fun clearCoverCache() {
|
||||
scope.launch {
|
||||
runCatching { clearCovers() }
|
||||
.onSuccess { toast(UiText.Res(R.string.toast_covers_cleared)) }
|
||||
.onFailure { toast(UiText.Res(R.string.toast_covers_failed)) }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Edits: shown at once, undone by a reload if Yandex refuses ----
|
||||
|
||||
/** Sends a change, then reports and refreshes. */
|
||||
private fun edit(done: UiText, failedText: UiText, refresh: () -> Unit = {}, change: suspend (YmClient) -> Unit) {
|
||||
val c = client ?: return
|
||||
scope.launch {
|
||||
val result = runCatching { change(c) }
|
||||
// The account signed out (or changed) meanwhile: nothing here to report or fix.
|
||||
if (client?.uid != c.uid) return@launch
|
||||
val error = result.exceptionOrNull()?.let(YmError::of)
|
||||
if (error == null) {
|
||||
toast(done)
|
||||
refresh()
|
||||
return@launch
|
||||
}
|
||||
if (failed(error)) return@launch
|
||||
toast(failedText)
|
||||
// The optimistic change may be wrong now; re-read the truth.
|
||||
liked = Liked.NotLoaded
|
||||
loadLiked()
|
||||
loadLikedIds()
|
||||
}
|
||||
}
|
||||
|
||||
private val likeFailed = UiText.Res(R.string.toast_like_failed)
|
||||
|
||||
fun likeTrack(track: Track, on: Boolean) {
|
||||
liked = liked.with(track, on)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
fun dislikeTrack(track: Track, on: Boolean) {
|
||||
sheet = null
|
||||
likes = likes.copy(dislikedTracks = if (on) likes.dislikedTracks + track.id else likes.dislikedTracks - track.id)
|
||||
if (on) liked = liked.with(track, false)
|
||||
// Not hearing it again starts now.
|
||||
if (on && playback.state.track?.id == track.id) playback.next()
|
||||
edit(
|
||||
UiText.Res(if (on) R.string.toast_disliked else R.string.toast_undisliked),
|
||||
UiText.Res(R.string.toast_change_failed),
|
||||
) { it.setTrackDisliked(track.fullId, on) }
|
||||
}
|
||||
|
||||
fun likeAlbum(id: Long, on: Boolean) {
|
||||
likes = likes.copy(albums = if (on) likes.albums + id else likes.albums - id)
|
||||
albums = Loadable.NotLoaded
|
||||
edit(
|
||||
UiText.Res(if (on) R.string.toast_album_liked else R.string.toast_album_unliked),
|
||||
likeFailed,
|
||||
refresh = ::loadLikedIds,
|
||||
) { it.setAlbumLiked(id, on) }
|
||||
}
|
||||
|
||||
fun likeArtist(id: Long, on: Boolean) {
|
||||
likes = likes.copy(artists = if (on) likes.artists + id else likes.artists - id)
|
||||
artists = Loadable.NotLoaded
|
||||
edit(
|
||||
UiText.Res(if (on) R.string.toast_artist_liked else R.string.toast_artist_unliked),
|
||||
likeFailed,
|
||||
refresh = ::loadLikedIds,
|
||||
) { it.setArtistLiked(id, on) }
|
||||
}
|
||||
|
||||
fun likePlaylist(id: PlaylistId, on: Boolean) {
|
||||
likes = likes.copy(playlists = if (on) likes.playlists + id else likes.playlists - id)
|
||||
edit(
|
||||
UiText.Res(if (on) R.string.toast_playlist_liked else R.string.toast_playlist_unliked),
|
||||
likeFailed,
|
||||
refresh = { forceLoadTab(CollectionTab.Playlists); loadLikedIds() },
|
||||
) { it.setPlaylistLiked(id, on) }
|
||||
}
|
||||
|
||||
fun likeClip(clip: Clip, on: Boolean) {
|
||||
likes = likes.copy(clips = if (on) likes.clips + clip.id else likes.clips - clip.id)
|
||||
clips.get()?.let { list ->
|
||||
val rest = list.filter { it.id != clip.id }
|
||||
clips = Loadable.Loaded(if (on) listOf(clip) + rest else rest)
|
||||
}
|
||||
edit(UiText.Res(if (on) R.string.toast_clip_liked else R.string.toast_clip_unliked), likeFailed) {
|
||||
it.setClipLiked(clip.id, on)
|
||||
}
|
||||
}
|
||||
|
||||
private fun playlistTitle(id: PlaylistId): String? =
|
||||
playlists.get()?.let { (it.own + it.liked).firstOrNull { p -> p.id == id }?.title }
|
||||
|
||||
private fun refreshPlaylist(id: PlaylistId) {
|
||||
val route = Route.Playlist(id)
|
||||
if (nav.current == route) loadPage(route, force = true) else pages.remove(route)
|
||||
}
|
||||
|
||||
fun addToPlaylist(id: PlaylistId, track: Track) {
|
||||
sheet = null
|
||||
val title = playlistTitle(id)
|
||||
edit(
|
||||
title?.let { UiText.Res(R.string.toast_added_to, it) } ?: UiText.Res(R.string.toast_added_to_playlist),
|
||||
title?.let { UiText.Res(R.string.toast_add_failed, it) } ?: UiText.Res(R.string.toast_add_failed_playlist),
|
||||
refresh = { refreshPlaylist(id); forceLoadTab(CollectionTab.Playlists) },
|
||||
) { it.addToPlaylist(id, track) }
|
||||
}
|
||||
|
||||
fun createPlaylist(name: String, add: Track?) {
|
||||
val title = name.trim()
|
||||
if (title.isEmpty()) return
|
||||
sheet = null
|
||||
edit(
|
||||
UiText.Res(if (add != null) R.string.toast_created_with_track else R.string.toast_created, title),
|
||||
UiText.Res(R.string.toast_create_failed),
|
||||
refresh = { forceLoadTab(CollectionTab.Playlists) },
|
||||
) {
|
||||
val created = it.createPlaylist(title, public = false)
|
||||
if (add != null) it.addToPlaylist(created.id, add)
|
||||
}
|
||||
}
|
||||
|
||||
fun renamePlaylist(id: PlaylistId, name: String) {
|
||||
val title = name.trim()
|
||||
if (title.isEmpty()) return
|
||||
sheet = null
|
||||
edit(
|
||||
UiText.Res(R.string.toast_renamed, title),
|
||||
UiText.Res(R.string.toast_rename_failed),
|
||||
refresh = { refreshPlaylist(id); forceLoadTab(CollectionTab.Playlists) },
|
||||
) { it.renamePlaylist(id, title) }
|
||||
}
|
||||
|
||||
fun setPlaylistPublic(id: PlaylistId, public: Boolean) = edit(
|
||||
UiText.Res(if (public) R.string.toast_now_public else R.string.toast_now_private),
|
||||
UiText.Res(R.string.toast_visibility_failed),
|
||||
refresh = { refreshPlaylist(id); forceLoadTab(CollectionTab.Playlists) },
|
||||
) { it.setPlaylistPublic(id, public) }
|
||||
|
||||
fun deletePlaylist(id: PlaylistId) {
|
||||
sheet = null
|
||||
val title = playlistTitle(id).orEmpty()
|
||||
nav.leave(Route.Playlist(id))
|
||||
pages.remove(Route.Playlist(id))
|
||||
edit(
|
||||
UiText.Res(R.string.toast_deleted, title),
|
||||
UiText.Res(R.string.toast_delete_failed, title),
|
||||
refresh = { forceLoadTab(CollectionTab.Playlists) },
|
||||
) { it.deletePlaylist(id) }
|
||||
}
|
||||
|
||||
fun removeFromPlaylist(id: PlaylistId, index: Int) {
|
||||
sheet = null
|
||||
edit(
|
||||
UiText.Res(R.string.toast_removed),
|
||||
UiText.Res(R.string.toast_remove_failed),
|
||||
refresh = { refreshPlaylist(id); forceLoadTab(CollectionTab.Playlists) },
|
||||
) { it.removeFromPlaylist(id, index) }
|
||||
}
|
||||
|
||||
fun movePlaylistTrack(id: PlaylistId, track: Track, from: Int, to: Int) {
|
||||
sheet = null
|
||||
edit(UiText.Res(R.string.toast_moved), UiText.Res(R.string.toast_move_failed), refresh = { refreshPlaylist(id) }) {
|
||||
it.moveInPlaylist(id, track, from, to)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "Musyx"
|
||||
}
|
||||
}
|
||||
|
||||
fun qualityLabel(q: Quality): Int = when (q) {
|
||||
Quality.Lossless -> R.string.quality_lossless
|
||||
Quality.Best -> R.string.quality_best
|
||||
Quality.Balanced -> R.string.quality_balanced
|
||||
Quality.DataSaver -> R.string.quality_data_saver
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// Small state types shared by every screen.
|
||||
package it.panov.musyx.state
|
||||
|
||||
import androidx.annotation.PluralsRes
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.runtime.Immutable
|
||||
import it.panov.musyx.api.PlaylistId
|
||||
import it.panov.musyx.api.Track
|
||||
import it.panov.musyx.api.YmError
|
||||
|
||||
/** Something fetched from the API: not asked for yet, on its way, here, or failed. */
|
||||
sealed interface Loadable<out T> {
|
||||
data object NotLoaded : Loadable<Nothing>
|
||||
data object Loading : Loadable<Nothing>
|
||||
data class Loaded<T>(val value: T) : Loadable<T>
|
||||
data class Failed(val error: YmError) : Loadable<Nothing>
|
||||
|
||||
/** Not loaded yet, or failed: worth (re)requesting. */
|
||||
val needsLoad: Boolean get() = this is NotLoaded || this is Failed
|
||||
|
||||
fun get(): T? = (this as? Loaded<T>)?.value
|
||||
|
||||
companion object {
|
||||
fun <T> of(result: Result<T>): Loadable<T> =
|
||||
result.fold({ Loaded(it) }, { Failed(YmError.of(it)) })
|
||||
}
|
||||
}
|
||||
|
||||
/** Text for the UI decided outside it: a string resource and its arguments. */
|
||||
@Immutable
|
||||
sealed interface UiText {
|
||||
class Res(@param:StringRes val id: Int, vararg val args: Any) : UiText
|
||||
class Plural(@param:PluralsRes val id: Int, val count: Int, vararg val args: Any) : UiText
|
||||
class Raw(val text: String) : UiText
|
||||
}
|
||||
|
||||
/** A short status message floating over the screen. */
|
||||
@Immutable
|
||||
data class Toast(val text: UiText, val serial: Long)
|
||||
|
||||
/** The liked-tracks list as the app holds it. Also answers "is this track liked?". */
|
||||
sealed interface Liked {
|
||||
data object NotLoaded : Liked
|
||||
data object Loading : Liked
|
||||
data class Loaded(val tracks: List<Track>) : Liked {
|
||||
val ids: Set<String> = tracks.mapTo(HashSet()) { it.id }
|
||||
}
|
||||
data class Failed(val error: YmError) : Liked
|
||||
|
||||
fun contains(trackId: String): Boolean = this is Loaded && trackId in ids
|
||||
|
||||
fun tracks(): List<Track>? = (this as? Loaded)?.tracks
|
||||
|
||||
/** A copy with `track` liked (at the top, like Yandex lists it) or unliked. */
|
||||
fun with(track: Track, liked: Boolean): Liked {
|
||||
if (this !is Loaded) return this
|
||||
if (contains(track.id) == liked) return this
|
||||
return Loaded(if (liked) listOf(track) + tracks else tracks.filter { it.id != track.id })
|
||||
}
|
||||
}
|
||||
|
||||
/** Dialogs over the screen: track actions, new/rename playlist, delete confirmation. */
|
||||
sealed interface Sheet {
|
||||
data class TrackMenu(
|
||||
val track: Track,
|
||||
/** Set when opened from one of the user's own playlists: its id, the row, its length. */
|
||||
val playlist: PlaylistSlot? = null,
|
||||
/** Showing the "Add to playlist" list instead of the actions. */
|
||||
val choosing: Boolean = false,
|
||||
) : Sheet
|
||||
|
||||
data class NewPlaylist(val add: Track?) : Sheet
|
||||
data class Rename(val id: PlaylistId, val name: String) : Sheet
|
||||
data class ConfirmDelete(val id: PlaylistId, val title: String) : Sheet
|
||||
}
|
||||
|
||||
/** A row of one of the user's playlists: its server index, and its neighbours' for moving. */
|
||||
data class PlaylistSlot(val id: PlaylistId, val index: Int, val up: Int?, val down: Int?)
|
||||
@@ -0,0 +1,78 @@
|
||||
// Every place the content area can show, and the back stack between them.
|
||||
package it.panov.musyx.state
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import it.panov.musyx.api.PlaylistId
|
||||
|
||||
sealed interface Route {
|
||||
data object Home : Route
|
||||
data object Wave : Route
|
||||
data object Search : Route
|
||||
data object Collection : Route
|
||||
data object Podcasts : Route
|
||||
data object Settings : Route
|
||||
/** The full-screen player with the queue and lyrics. */
|
||||
data object NowPlaying : Route
|
||||
data object Chart : Route
|
||||
data class Album(val id: Long) : Route
|
||||
data class Artist(val id: Long) : Route
|
||||
data class Playlist(val id: PlaylistId) : Route
|
||||
/** Index into the app's flattened genre list. */
|
||||
data class Genre(val index: Int) : Route
|
||||
|
||||
companion object {
|
||||
/** Navigation drawer order. */
|
||||
val NAV: List<Route> = listOf(Home, Wave, Search, Collection, Podcasts)
|
||||
|
||||
/** The drawer destinations, Settings included. */
|
||||
val SECTIONS: Set<Route> = (NAV + Settings).toSet()
|
||||
}
|
||||
}
|
||||
|
||||
/** Back-stack navigation: the drawer and links push, Back pops. */
|
||||
class Navigator(start: Route = Route.Home) {
|
||||
var current: Route by mutableStateOf(start)
|
||||
private set
|
||||
private var history: List<Route> by mutableStateOf(emptyList())
|
||||
|
||||
val canGoBack: Boolean get() = history.isNotEmpty()
|
||||
|
||||
/**
|
||||
* The drawer destination the current page belongs to: the last one visited on the way
|
||||
* here, so a podcast opened from Podcasts lights Podcasts and Now Playing keeps its place.
|
||||
*/
|
||||
val section: Route get() = (history + current).lastOrNull { it in Route.SECTIONS } ?: Route.Home
|
||||
|
||||
fun go(route: Route) {
|
||||
if (route == current) return
|
||||
history = (history + current).takeLast(MAX_HISTORY)
|
||||
current = route
|
||||
}
|
||||
|
||||
/** Returns false when there was nowhere to go back to. */
|
||||
fun back(): Boolean {
|
||||
val previous = history.lastOrNull() ?: return false
|
||||
history = history.dropLast(1)
|
||||
current = previous
|
||||
return true
|
||||
}
|
||||
|
||||
/** Leaves `route` if it's showing, e.g. a deleted playlist. */
|
||||
fun leave(route: Route) {
|
||||
if (current == route && !back()) current = Route.Home
|
||||
history = history.filter { it != route }
|
||||
}
|
||||
|
||||
fun reset(start: Route = Route.Home) {
|
||||
history = emptyList()
|
||||
current = start
|
||||
}
|
||||
|
||||
internal val depth: Int get() = history.size
|
||||
|
||||
private companion object {
|
||||
const val MAX_HISTORY = 50
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// Search: suggestions while typing, results by kind, more pages on request.
|
||||
package it.panov.musyx.state
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import it.panov.musyx.api.SearchKind
|
||||
import it.panov.musyx.api.SearchResults
|
||||
import it.panov.musyx.api.YmClient
|
||||
import it.panov.musyx.api.YmError
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Wait this long after the last keystroke before asking for suggestions. */
|
||||
private const val DEBOUNCE_MS = 250L
|
||||
/** Tracks shown in the "All" tab before "Show all". */
|
||||
const val ALL_TAB_TRACKS = 5
|
||||
|
||||
data class Results(val data: SearchResults, val page: Int, val loadingMore: Boolean = false)
|
||||
|
||||
class SearchState(private val scope: CoroutineScope, private val client: () -> YmClient?, private val failed: (YmError) -> Boolean) {
|
||||
var text by mutableStateOf("")
|
||||
private set
|
||||
/** The query the results are for; `text` may have moved on since. */
|
||||
var query by mutableStateOf("")
|
||||
private set
|
||||
var kind by mutableStateOf(SearchKind.All)
|
||||
private set
|
||||
var results: Loadable<Results> by mutableStateOf(Loadable.NotLoaded)
|
||||
private set
|
||||
var suggestions: List<String> by mutableStateOf(emptyList())
|
||||
private set
|
||||
|
||||
private var suggestJob: Job? = null
|
||||
|
||||
fun change(value: String) {
|
||||
text = value
|
||||
suggestJob?.cancel()
|
||||
if (value.isBlank()) {
|
||||
suggestions = emptyList()
|
||||
return
|
||||
}
|
||||
val c = client() ?: return
|
||||
suggestJob = scope.launch {
|
||||
delay(DEBOUNCE_MS)
|
||||
runCatching { c.suggest(value.trim()) }
|
||||
.onSuccess { if (value == text) suggestions = it.take(8) }
|
||||
}
|
||||
}
|
||||
|
||||
fun pick(suggestion: String) {
|
||||
text = suggestion
|
||||
submit()
|
||||
}
|
||||
|
||||
fun submit() {
|
||||
suggestJob?.cancel()
|
||||
suggestions = emptyList()
|
||||
val q = text.trim()
|
||||
if (q.isEmpty()) return
|
||||
if (q != query || results.needsLoad) {
|
||||
query = q
|
||||
fetch(0)
|
||||
}
|
||||
}
|
||||
|
||||
fun tab(next: SearchKind) {
|
||||
if (next == kind) return
|
||||
kind = next
|
||||
if (query.isNotEmpty()) fetch(0)
|
||||
}
|
||||
|
||||
fun more() {
|
||||
val current = results.get() ?: return
|
||||
if (current.loadingMore) return
|
||||
results = Loadable.Loaded(current.copy(loadingMore = true))
|
||||
fetch(current.page + 1)
|
||||
}
|
||||
|
||||
fun retry() {
|
||||
if (query.isNotEmpty()) fetch(0)
|
||||
}
|
||||
|
||||
fun hasMore(r: Results): Boolean {
|
||||
val total = r.data.totals[kind] ?: return false
|
||||
val shown = when (kind) {
|
||||
SearchKind.All -> return false
|
||||
SearchKind.Tracks -> r.data.tracks.size
|
||||
SearchKind.Albums -> r.data.albums.size
|
||||
SearchKind.Artists -> r.data.artists.size
|
||||
SearchKind.Playlists -> r.data.playlists.size
|
||||
SearchKind.Podcasts -> r.data.podcasts.size
|
||||
}
|
||||
return shown < total
|
||||
}
|
||||
|
||||
private fun fetch(page: Int) {
|
||||
val c = client() ?: return
|
||||
if (page == 0) results = Loadable.Loading
|
||||
val (q, k) = query to kind
|
||||
scope.launch {
|
||||
val result = runCatching { c.search(q, k, page) }
|
||||
// Results for an older query or another tab are dropped.
|
||||
if (q != query || k != kind) return@launch
|
||||
val current = results.get()
|
||||
result.fold(
|
||||
onSuccess = { data ->
|
||||
results = Loadable.Loaded(
|
||||
if (page > 0 && current != null) Results(current.data.plus(data), page) else Results(data, page),
|
||||
)
|
||||
},
|
||||
onFailure = { e ->
|
||||
val err = YmError.of(e)
|
||||
if (failed(err)) return@fold
|
||||
results = if (page > 0 && current != null) Loadable.Loaded(current.copy(loadingMore = false)) else Loadable.Failed(err)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
suggestJob?.cancel()
|
||||
text = ""
|
||||
query = ""
|
||||
kind = SearchKind.All
|
||||
results = Loadable.NotLoaded
|
||||
suggestions = emptyList()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// Device-code sign-in: get a code, the user confirms it on Yandex's page (or scans the
|
||||
// QR with their phone), we poll until a token arrives. A pasted token is the fallback.
|
||||
package it.panov.musyx.state
|
||||
|
||||
import android.os.SystemClock
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import it.panov.musyx.R
|
||||
import it.panov.musyx.api.Auth
|
||||
import it.panov.musyx.api.Credentials
|
||||
import it.panov.musyx.api.DeviceCode
|
||||
import it.panov.musyx.api.Poll
|
||||
import it.panov.musyx.api.YmError
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class SignInState(private val scope: CoroutineScope, private val onGranted: (Credentials) -> Unit) {
|
||||
sealed interface Stage {
|
||||
data object Idle : Stage
|
||||
data object Requesting : Stage
|
||||
/** A code is on screen until `deadline` ([SystemClock.elapsedRealtime] millis). */
|
||||
data class Waiting(val code: DeviceCode, val deadline: Long) : Stage
|
||||
}
|
||||
|
||||
var stage: Stage by mutableStateOf(Stage.Idle)
|
||||
private set
|
||||
var error: UiText? by mutableStateOf(null)
|
||||
private set
|
||||
var tokenOpen by mutableStateOf(false)
|
||||
private set
|
||||
var token by mutableStateOf("")
|
||||
|
||||
private var job: Job? = null
|
||||
|
||||
fun getCode() {
|
||||
job?.cancel()
|
||||
error = null
|
||||
stage = Stage.Requesting
|
||||
job = scope.launch {
|
||||
try {
|
||||
val code = Auth.requestCode()
|
||||
val deadline = SystemClock.elapsedRealtime() + code.expiresInSec * 1000
|
||||
stage = Stage.Waiting(code, deadline)
|
||||
poll(code, deadline)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
fail(YmError.of(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun poll(code: DeviceCode, deadline: Long) {
|
||||
while (true) {
|
||||
delay(code.intervalSec * 1000)
|
||||
if (SystemClock.elapsedRealtime() >= deadline) return fail(YmError.CodeExpired())
|
||||
val result = try {
|
||||
Auth.poll(code)
|
||||
} catch (e: YmError) {
|
||||
// A dropped poll isn't fatal: try again next interval.
|
||||
if (e.isRetryable) continue
|
||||
return fail(e)
|
||||
}
|
||||
if (result is Poll.Granted) {
|
||||
stage = Stage.Idle
|
||||
onGranted(result.credentials)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
job?.cancel()
|
||||
stage = Stage.Idle
|
||||
error = null
|
||||
}
|
||||
|
||||
fun toggleToken() {
|
||||
tokenOpen = !tokenOpen
|
||||
}
|
||||
|
||||
fun useToken() {
|
||||
val credentials = Credentials.fromToken(token)
|
||||
if (credentials.accessToken.isEmpty()) return
|
||||
token = ""
|
||||
job?.cancel()
|
||||
stage = Stage.Idle
|
||||
onGranted(credentials)
|
||||
}
|
||||
|
||||
private fun fail(e: YmError) {
|
||||
stage = Stage.Idle
|
||||
error = describe(e)
|
||||
}
|
||||
|
||||
/** Stops polling, e.g. when the screen goes away. */
|
||||
fun dispose() {
|
||||
job?.cancel()
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Shown after a pasted token turned out to be invalid. */
|
||||
fun rejectedToken(scope: CoroutineScope, onGranted: (Credentials) -> Unit) = SignInState(scope, onGranted).apply {
|
||||
error = UiText.Res(R.string.signin_token_rejected)
|
||||
tokenOpen = true
|
||||
}
|
||||
|
||||
/** Shown when connecting with fresh credentials failed. */
|
||||
fun withError(scope: CoroutineScope, e: YmError, onGranted: (Credentials) -> Unit) =
|
||||
SignInState(scope, onGranted).apply { error = describe(e) }
|
||||
|
||||
/** The user's next step for each failure. Never shows the raw error. */
|
||||
fun describe(e: YmError): UiText = UiText.Res(
|
||||
when (e) {
|
||||
is YmError.CodeExpired -> R.string.signin_error_expired
|
||||
is YmError.Denied -> R.string.signin_error_denied
|
||||
is YmError.Network -> R.string.signin_error_network
|
||||
is YmError.Unauthorized -> R.string.signin_error_unauthorized
|
||||
else -> R.string.signin_error_unexpected
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Strings the shared state layer shows: toasts, sign-in errors, quality names. -->
|
||||
<resources>
|
||||
<string name="signin_token_rejected">Яндекс не принял этот токен. Проверьте его и вставьте ещё раз.</string>
|
||||
<string name="signin_error_expired">Срок действия кода истёк до подтверждения. Получите новый код и попробуйте снова.</string>
|
||||
<string name="signin_error_denied">Доступ отклонён на странице Яндекса. Если это ошибка, получите новый код.</string>
|
||||
<string name="signin_error_network">Яндекс недоступен. Проверьте подключение и попробуйте ещё раз.</string>
|
||||
<string name="signin_error_unauthorized">Яндекс не принял вход. Получите новый код и попробуйте снова.</string>
|
||||
<string name="signin_error_unexpected">Яндекс прислал неожиданный ответ. Попробуйте чуть позже.</string>
|
||||
<string name="quality_lossless">Без потерь</string>
|
||||
<string name="quality_best">Лучшее</string>
|
||||
<string name="quality_balanced">Оптимальное</string>
|
||||
<string name="quality_data_saver">Экономия трафика</string>
|
||||
<string name="toast_already_playing">«%1$s» уже играет</string>
|
||||
<string name="toast_plays_next">«%1$s» зазвучит следующим</string>
|
||||
<string name="toast_added_to_queue">«%1$s» добавлен в очередь</string>
|
||||
<string name="toast_finding_similar">Ищем треки в духе «%1$s»…</string>
|
||||
<string name="toast_no_similar">У Яндекса нет похожих треков для «%1$s»</string>
|
||||
<string name="toast_similar_failed">Не удалось найти похожие треки. Попробуйте ещё раз.</string>
|
||||
<string name="toast_liked">Добавлено в «Мне нравится»</string>
|
||||
<string name="toast_unliked">Убрано из «Мне нравится»</string>
|
||||
<string name="toast_like_failed">Не удалось изменить отметку. Попробуйте ещё раз.</string>
|
||||
<string name="toast_disliked">Этот трек больше не будет попадаться в рекомендациях</string>
|
||||
<string name="toast_undisliked">Трек снова может попадаться в рекомендациях</string>
|
||||
<string name="toast_change_failed">Не удалось это изменить. Попробуйте ещё раз.</string>
|
||||
<string name="toast_album_liked">Альбом добавлен в коллекцию</string>
|
||||
<string name="toast_album_unliked">Альбом убран из коллекции</string>
|
||||
<string name="toast_artist_liked">Исполнитель добавлен в коллекцию</string>
|
||||
<string name="toast_artist_unliked">Исполнитель убран из коллекции</string>
|
||||
<string name="toast_playlist_liked">Плейлист добавлен в коллекцию</string>
|
||||
<string name="toast_playlist_unliked">Плейлист убран из коллекции</string>
|
||||
<string name="toast_clip_liked">Клип добавлен в коллекцию</string>
|
||||
<string name="toast_clip_unliked">Клип убран из коллекции</string>
|
||||
<string name="toast_added_to">Добавлено в «%1$s»</string>
|
||||
<string name="toast_added_to_playlist">Добавлено в плейлист</string>
|
||||
<string name="toast_add_failed">Не удалось добавить в «%1$s». Попробуйте ещё раз.</string>
|
||||
<string name="toast_add_failed_playlist">Не удалось добавить в плейлист. Попробуйте ещё раз.</string>
|
||||
<string name="toast_created">Плейлист «%1$s» создан</string>
|
||||
<string name="toast_created_with_track">Плейлист «%1$s» создан, трек добавлен</string>
|
||||
<string name="toast_create_failed">Не удалось создать плейлист. Попробуйте ещё раз.</string>
|
||||
<string name="toast_renamed">Плейлист переименован в «%1$s»</string>
|
||||
<string name="toast_rename_failed">Не удалось переименовать плейлист. Попробуйте ещё раз.</string>
|
||||
<string name="toast_now_public">Теперь плейлист видят все, у кого есть ссылка</string>
|
||||
<string name="toast_now_private">Теперь плейлист видите только вы</string>
|
||||
<string name="toast_visibility_failed">Не удалось изменить доступ. Попробуйте ещё раз.</string>
|
||||
<string name="toast_deleted">Плейлист «%1$s» удалён</string>
|
||||
<string name="toast_delete_failed">Не удалось удалить «%1$s». Попробуйте ещё раз.</string>
|
||||
<string name="toast_removed">Удалено из плейлиста</string>
|
||||
<string name="toast_remove_failed">Не удалось удалить трек. Попробуйте ещё раз.</string>
|
||||
<string name="toast_moved">Перемещено</string>
|
||||
<string name="toast_move_failed">Не удалось переместить трек. Попробуйте ещё раз.</string>
|
||||
<string name="toast_quality">Качество звука: %1$s. Применится со следующего трека.</string>
|
||||
<string name="toast_covers_cleared">Кеш обложек очищен</string>
|
||||
<string name="toast_covers_failed">Не удалось очистить кеш обложек.</string>
|
||||
<plurals name="toast_playing_similar">
|
||||
<item quantity="one">Играем %1$d трек в духе «%2$s»</item>
|
||||
<item quantity="few">Играем %1$d трека в духе «%2$s»</item>
|
||||
<item quantity="many">Играем %1$d треков в духе «%2$s»</item>
|
||||
<item quantity="other">Играем %1$d трека в духе «%2$s»</item>
|
||||
</plurals>
|
||||
</resources>
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Strings the shared state layer shows: toasts, sign-in errors, quality names. -->
|
||||
<resources>
|
||||
<string name="signin_token_rejected">Yandex didn\'t accept that token. Check it and paste it again.</string>
|
||||
<string name="signin_error_expired">The code expired before it was confirmed. Get a new code to try again.</string>
|
||||
<string name="signin_error_denied">Access was declined on Yandex\'s page. Get a new code if that was a mistake.</string>
|
||||
<string name="signin_error_network">Can\'t reach Yandex. Check your connection and try again.</string>
|
||||
<string name="signin_error_unauthorized">Yandex didn\'t accept the sign-in. Get a new code to try again.</string>
|
||||
<string name="signin_error_unexpected">Yandex sent an unexpected answer. Try again in a moment.</string>
|
||||
<string name="quality_lossless">Lossless</string>
|
||||
<string name="quality_best">Best</string>
|
||||
<string name="quality_balanced">Balanced</string>
|
||||
<string name="quality_data_saver">Data saver</string>
|
||||
<string name="toast_already_playing">“%1$s” is already playing</string>
|
||||
<string name="toast_plays_next">“%1$s” plays next</string>
|
||||
<string name="toast_added_to_queue">Added “%1$s” to the queue</string>
|
||||
<string name="toast_finding_similar">Finding tracks like “%1$s”…</string>
|
||||
<string name="toast_no_similar">Yandex has no similar tracks for “%1$s”</string>
|
||||
<string name="toast_similar_failed">Couldn\'t find similar tracks. Try again.</string>
|
||||
<string name="toast_liked">Added to Liked tracks</string>
|
||||
<string name="toast_unliked">Removed from Liked tracks</string>
|
||||
<string name="toast_like_failed">Couldn\'t change the like. Try again.</string>
|
||||
<string name="toast_disliked">You won\'t be recommended this track</string>
|
||||
<string name="toast_undisliked">Recommendations for this track restored</string>
|
||||
<string name="toast_change_failed">Couldn\'t change that. Try again.</string>
|
||||
<string name="toast_album_liked">Album added to your collection</string>
|
||||
<string name="toast_album_unliked">Album removed from your collection</string>
|
||||
<string name="toast_artist_liked">Artist added to your collection</string>
|
||||
<string name="toast_artist_unliked">Artist removed from your collection</string>
|
||||
<string name="toast_playlist_liked">Playlist added to your collection</string>
|
||||
<string name="toast_playlist_unliked">Playlist removed from your collection</string>
|
||||
<string name="toast_clip_liked">Clip added to your collection</string>
|
||||
<string name="toast_clip_unliked">Clip removed from your collection</string>
|
||||
<string name="toast_added_to">Added to “%1$s”</string>
|
||||
<string name="toast_added_to_playlist">Added to the playlist</string>
|
||||
<string name="toast_add_failed">Couldn\'t add to “%1$s”. Try again.</string>
|
||||
<string name="toast_add_failed_playlist">Couldn\'t add to the playlist. Try again.</string>
|
||||
<string name="toast_created">Created “%1$s”</string>
|
||||
<string name="toast_created_with_track">Created “%1$s” with the track</string>
|
||||
<string name="toast_create_failed">Couldn\'t create the playlist. Try again.</string>
|
||||
<string name="toast_renamed">Renamed to “%1$s”</string>
|
||||
<string name="toast_rename_failed">Couldn\'t rename the playlist. Try again.</string>
|
||||
<string name="toast_now_public">Anyone with the link can now see this playlist</string>
|
||||
<string name="toast_now_private">Only you can see this playlist now</string>
|
||||
<string name="toast_visibility_failed">Couldn\'t change who can see it. Try again.</string>
|
||||
<string name="toast_deleted">Deleted “%1$s”</string>
|
||||
<string name="toast_delete_failed">Couldn\'t delete “%1$s”. Try again.</string>
|
||||
<string name="toast_removed">Removed from the playlist</string>
|
||||
<string name="toast_remove_failed">Couldn\'t remove the track. Try again.</string>
|
||||
<string name="toast_moved">Moved</string>
|
||||
<string name="toast_move_failed">Couldn\'t move the track. Try again.</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_failed">Couldn\'t clear the cover cache.</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>
|
||||
</plurals>
|
||||
</resources>
|
||||
@@ -0,0 +1,560 @@
|
||||
package it.panov.musyx.api
|
||||
|
||||
import it.panov.musyx.player.ctrCipher
|
||||
import it.panov.musyx.player.hexKey
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/** Ports the ym-api unit tests, plus yamuse's signing vectors. */
|
||||
class ApiTest {
|
||||
private fun json(s: String) = parseJson(s)
|
||||
|
||||
// ---- Models ----
|
||||
|
||||
@Test
|
||||
fun trackConvertsWithArtistsAlbumAndCover() {
|
||||
val t = Track.from(
|
||||
json(
|
||||
"""{"id":"12345","title":"Звезда по имени Солнце","durationMs":225000,
|
||||
"artists":[{"id":1,"name":"Кино"}],"albums":[{"id":77,"title":"Звезда по имени Солнце"}],
|
||||
"coverUri":"avatars.yandex.net/get-music-content/x/%%","lyricsAvailable":true}""",
|
||||
),
|
||||
)!!
|
||||
assertEquals("12345", t.id)
|
||||
assertEquals("Кино", t.artistLine)
|
||||
assertEquals(77L, t.album!!.id)
|
||||
assertEquals(225_000L, t.durationMs)
|
||||
assertEquals("https://avatars.yandex.net/get-music-content/x/200x200", t.coverUrl(200))
|
||||
assertTrue(t.available && t.lyricsAvailable && !t.explicit)
|
||||
assertEquals("12345:77", t.fullId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun trackCarriesAlbumYearAndArtistPhotos() {
|
||||
val t = Track.from(
|
||||
json(
|
||||
"""{"id":1,"artists":[{"id":1,"name":"Кино","cover":{"uri":"k/%%"}},{"id":2,"name":"B"}],
|
||||
"albums":[{"id":77,"title":"Группа крови","year":1988}]}""",
|
||||
),
|
||||
)!!
|
||||
assertEquals(1988, t.album!!.year)
|
||||
assertEquals("https://k/1000x1000", t.artists[0].coverUrl(1000))
|
||||
assertNull(t.artists[1].coverUrl(1000))
|
||||
val photos = artistPhotoUris(json("""{"artist":{"cover":{"uri":"a/%%"}},"allCovers":[{"uri":"b/%%"},{"uri":"a/%%"}]}"""))
|
||||
assertEquals(listOf("b/%%", "a/%%"), photos)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun numericIdsAndVersions() {
|
||||
val t = Track.from(json("""{"id":42,"title":"Song","version":"Live","artists":[]}"""))!!
|
||||
assertEquals("42", t.id)
|
||||
assertEquals("Song (Live)", t.fullTitle)
|
||||
assertNull(t.artistLine)
|
||||
assertNull(Track.from(json("""{"title":"no id"}""")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lyricsInfoWinsOverTheOldFlag() {
|
||||
val t = Track.from(json("""{"id":1,"lyricsAvailable":true,"lyricsInfo":{"hasAvailableSyncLyrics":false}}"""))!!
|
||||
assertFalse(t.lyricsAvailable)
|
||||
assertTrue(Track.from(json("""{"id":1,"contentWarning":"explicit"}"""))!!.explicit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun coverUrlsNormalise() {
|
||||
assertEquals("https://a/100x100", coverUrl("a/%%", 100))
|
||||
assertEquals("https://x.y/%z", coverUrl("https://x.y/%z", 100))
|
||||
assertNull(coverUrl("", 100))
|
||||
assertEquals("https://host/x/50x50", coverUrl("//host/x/%%", 50))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun albumPageFlattensVolumes() {
|
||||
val page = AlbumPage.from(
|
||||
json(
|
||||
"""{"id":5,"title":"Группа крови","year":1988,"type":"","artists":[{"id":1,"name":"Кино"}],
|
||||
"coverUri":"a/%%","labels":[{"name":"Мелодия"}],
|
||||
"volumes":[[{"id":1,"title":"A","durationMs":1000}],[{"id":2,"title":"B","durationMs":2000}]]}""",
|
||||
),
|
||||
)!!
|
||||
assertEquals(2, page.tracks.size)
|
||||
assertEquals(3_000L, page.tracks.sumOf { it.durationMs })
|
||||
assertEquals(AlbumKind.Album, page.album.kind)
|
||||
assertEquals("Мелодия", page.label)
|
||||
assertEquals("https://a/100x100", page.album.coverUrl(100))
|
||||
assertEquals("Мелодия", AlbumPage.from(json("""{"id":5,"labels":["Мелодия"]}"""))!!.label)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun albumKinds() {
|
||||
assertEquals(AlbumKind.Single, AlbumKind.from(null, "single"))
|
||||
assertEquals(AlbumKind.Podcast, AlbumKind.from("podcast", null))
|
||||
assertEquals(AlbumKind.Audiobook, AlbumKind.from(null, "audiobook"))
|
||||
assertEquals(AlbumKind.Album, AlbumKind.from("music", null))
|
||||
// Books arrive as podcasts by metaType; the type says what they are.
|
||||
assertEquals(AlbumKind.Audiobook, AlbumKind.from("podcast", "audiobook"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun episodesAndChaptersAreSpoken() {
|
||||
assertTrue(Track.from(json("""{"id":1,"type":"podcast-episode"}"""))!!.spoken)
|
||||
assertTrue(Track.from(json("""{"id":1,"albums":[{"id":2,"metaType":"podcast","type":"audiobook"}]}"""))!!.spoken)
|
||||
assertFalse(Track.from(json("""{"id":1,"type":"music","albums":[{"id":2,"type":"single"}]}"""))!!.spoken)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun playlistNeedsOwnerAndKindAndUsesMosaicCover() {
|
||||
val s = PlaylistSummary.from(
|
||||
json(
|
||||
"""{"owner":{"uid":9,"name":"Юрий"},"kind":1003,"title":"Дорога","trackCount":14,
|
||||
"visibility":"private","cover":{"type":"mosaic","itemsUri":["m/%%"]}}""",
|
||||
),
|
||||
)!!
|
||||
assertEquals(PlaylistId(9, 1003), s.id)
|
||||
assertFalse(s.public)
|
||||
assertEquals(14, s.trackCount)
|
||||
assertEquals("https://m/200x200", s.coverUrl(200))
|
||||
assertNull(PlaylistSummary.from(json("""{"title":"x"}""")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun artistPageFromBriefInfo() {
|
||||
val page = ArtistPage.from(
|
||||
json(
|
||||
"""{"artist":{"id":3,"name":"Земфира","genres":["rock"],"cover":{"uri":"z/%%"}},
|
||||
"popularTracks":[{"id":10,"title":"Хочешь?"}],"albums":[{"id":20,"title":"Вендетта","year":2005}],
|
||||
"similarArtists":[{"id":4,"name":"Сплин"}],"stats":{"lastMonthListeners":4100000}}""",
|
||||
),
|
||||
)!!
|
||||
assertEquals("Земфира", page.artist.name)
|
||||
assertEquals(1, page.popular.size)
|
||||
assertEquals(2005, page.albums[0].year)
|
||||
assertEquals("Сплин", page.similar[0].name)
|
||||
assertEquals(4_100_000L, page.monthlyListeners)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clipsFromBothShapes() {
|
||||
val raw = json(
|
||||
"""{"items":[{"type":"clip","data":{"artists":[{"id":41075,"name":"КИНО"}],
|
||||
"clip":{"id":578780,"title":"Звезда","duration":263,"cover":{"uri":"https://avatars.yandex.net/c/%%"}}}}]}""",
|
||||
)
|
||||
val c = raw.list("items").mapNotNull { Clip.from(it["data"]["clip"], it["data"]["artists"]) }.single()
|
||||
assertEquals(578780L, c.id)
|
||||
assertEquals("КИНО", c.artistLine)
|
||||
assertEquals("https://avatars.yandex.net/c/200x200", c.coverUrl(200))
|
||||
assertEquals("https://music.yandex.ru/video?ids=578780", c.url)
|
||||
val d = Clip.from(json("""{"clipId":7,"title":"T","thumbnail":"a/%%","explicit":true,"artists":[{"id":"3","name":"A"}]}"""))!!
|
||||
assertEquals(7L, d.id)
|
||||
assertTrue(d.explicit)
|
||||
assertEquals(listOf(ArtistRef(3, "A")), d.artists)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun searchResultsConvertWithBestMatchAndTotals() {
|
||||
val r = SearchResults.from(
|
||||
json(
|
||||
"""{"best":{"type":"artist","result":{"id":3,"name":"Земфира"}},
|
||||
"tracks":{"total":120,"results":[{"id":1,"title":"Хочешь?"}]},
|
||||
"albums":{"total":40,"results":[{"id":5,"title":"Вендетта"}]},
|
||||
"misspellCorrected":true,"misspellResult":"земфира"}""",
|
||||
),
|
||||
)
|
||||
assertEquals("Земфира", (r.best as BestMatch.OfArtist).artist.name)
|
||||
assertEquals(1, r.tracks.size)
|
||||
assertEquals(120, r.totals[SearchKind.Tracks])
|
||||
assertEquals(40, r.totals[SearchKind.Albums])
|
||||
assertEquals("земфира", r.corrected)
|
||||
assertFalse(r.isEmpty)
|
||||
assertTrue(SearchResults.from(json("{}")).isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun landingBlocksSplitByEntityType() {
|
||||
val home = homeFromLanding(
|
||||
json(
|
||||
"""{"blocks":[
|
||||
{"type":"personal-playlists","entities":[{"type":"personal-playlist","data":{
|
||||
"data":{"uid":1,"kind":3,"title":"Плейлист дня","owner":{"uid":1}},"previewDescription":"Updated every day"}}]},
|
||||
{"type":"new-releases","entities":[{"type":"album","data":{"id":9,"title":"New"}}]},
|
||||
{"type":"chart","entities":[{"type":"chart-item","data":{"track":{"id":7,"title":"Top"},"chart":{"position":1,"shift":0}}}]}
|
||||
]}""",
|
||||
),
|
||||
)
|
||||
assertEquals("Плейлист дня", home.personal[0].playlist.title)
|
||||
assertEquals("Updated every day", home.personal[0].description)
|
||||
assertEquals(9L, home.newReleases[0].id)
|
||||
assertEquals(1, home.chart[0].position)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun chartEntryReadsPositionAndShift() {
|
||||
val e = ChartEntry.from(json("""{"id":1,"track":{"id":1,"title":"Хит"},"chart":{"position":3,"shift":-2}}"""))!!
|
||||
assertEquals(3 to -2, e.position to e.shift)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun genreTitleFallsBackAndFlattens() {
|
||||
val g = Genre.from(json("""{"id":"rock","titles":{"en":{"title":"Rock"}},"color":"#ff0000","subGenres":[{"id":"punk","title":"Punk"}]}"""))!!
|
||||
assertEquals("Rock", g.title)
|
||||
assertEquals("punk", g.subGenres[0].id)
|
||||
assertEquals("#ff0000", g.color)
|
||||
fun genre(id: String, vararg subs: String) = Genre(id, id, null, subs.map { Genre(it, it, null, emptyList()) })
|
||||
val flat = Genre.flatten(listOf(genre("rock", "punk", "metal"), genre("metal", "doom"), genre("pop", "punk")))
|
||||
assertEquals(listOf("rock", "metal", "pop", "punk", "doom"), flat.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun accountPrefersDisplayNameAndReadsPlus() {
|
||||
val a = Account.from(
|
||||
json(
|
||||
"""{"account":{"uid":42,"login":"yuriy.panov","displayName":"Юрий","fullName":"Юрий Панов"},
|
||||
"plus":{"hasPlus":true},"subscription":{"end":"2027-01-01T00:00:00+03:00"}}""",
|
||||
),
|
||||
)!!
|
||||
assertEquals(42L, a.uid)
|
||||
assertEquals("Юрий", a.name)
|
||||
assertEquals("Ю", a.initial)
|
||||
assertTrue(a.hasPlus)
|
||||
assertEquals("2027-01-01T00:00:00+03:00", a.subscriptionEnd)
|
||||
val b = Account.from(json("""{"account":{"uid":7,"login":"listener","displayName":" "}}"""))!!
|
||||
assertEquals("listener", b.name)
|
||||
assertFalse(b.hasPlus)
|
||||
assertNull(Account.from(json("""{"account":{"now":"2026-10-15"}}""")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tagIdsAcceptObjectsAndStrings() {
|
||||
assertEquals(
|
||||
listOf(PlaylistId(1, 2), PlaylistId(3, 4)),
|
||||
tagPlaylistIds(json("""{"ids":[{"uid":1,"kind":2},"3:4",null,{"uid":5}]}""")),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recentIdsWalkDaysAndSkipRepeats() {
|
||||
val history = json(
|
||||
"""{"historyTabs":[
|
||||
{"date":"2026-10-15","items":[{"context":{"type":"wave"},"tracks":[
|
||||
{"type":"track","data":{"itemId":{"trackId":"1","albumId":"10"}}},
|
||||
{"type":"track","data":{"itemId":{"trackId":"2"}}}]}]},
|
||||
{"date":"2026-10-14","items":[{"tracks":[
|
||||
{"type":"track","data":{"itemId":{"trackId":"1","albumId":"10"}}},
|
||||
{"type":"track","data":{}},
|
||||
{"type":"track","data":{"itemId":{"trackId":"3","albumId":"30"}}},
|
||||
{"type":"track","data":{"itemId":{"trackId":"4","albumId":"40"}}}]}]}]}""",
|
||||
)
|
||||
assertEquals(listOf("1:10", "2", "3:30"), recentTrackIds(history, 3))
|
||||
assertEquals(4, recentTrackIds(history, 10).size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bestVariantPrefersFullMp3AtTopBitrate() {
|
||||
val v = json(
|
||||
"""[{"codec":"aac","bitrateInKbps":256,"downloadInfoUrl":"a"},
|
||||
{"codec":"mp3","bitrateInKbps":192,"downloadInfoUrl":"b"},
|
||||
{"codec":"mp3","bitrateInKbps":320,"downloadInfoUrl":"c"},
|
||||
{"codec":"mp3","bitrateInKbps":320,"downloadInfoUrl":"p","preview":true},
|
||||
{"codec":"flac","bitrateInKbps":900,"downloadInfoUrl":"f"}]""",
|
||||
).arr!!
|
||||
assertEquals("c", bestVariant(v, null).str("downloadInfoUrl"))
|
||||
assertEquals("b", bestVariant(v, 192).str("downloadInfoUrl"))
|
||||
assertEquals("nothing fits: take the smallest", "b", bestVariant(v, 64).str("downloadInfoUrl"))
|
||||
val previews = json("""[{"codec":"mp3","bitrateInKbps":128,"downloadInfoUrl":"p","preview":true}]""").arr!!
|
||||
assertEquals(true, bestVariant(previews, null).bool("preview"))
|
||||
assertNull(bestVariant(emptyList(), null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fileInfoRepliesBecomeStreamsExceptHeAac() {
|
||||
val flac = fileInfoStream(json("""{"codec":"flac-mp4","bitrate":0,"transport":"encraw","key":"00ff","urls":["https://a","https://b"]}"""))!!
|
||||
assertEquals(listOf("https://a", "https://b"), flac.urls)
|
||||
assertEquals("FLAC" to "mp4", flac.label to flac.container)
|
||||
assertEquals("00ff", flac.key)
|
||||
assertFalse("key leaked into toString", "00ff" in flac.toString())
|
||||
assertTrue(flac.lossless)
|
||||
val aac = fileInfoStream(json("""{"codec":"aac-mp4","bitrate":192,"key":"00ff","urls":["https://a"]}"""))!!
|
||||
assertEquals(Triple("AAC 192", "mp4", false), Triple(aac.label, aac.container, aac.lossless))
|
||||
assertNull(fileInfoStream(json("""{"codec":"he-aac-mp4","bitrate":64,"urls":["https://a"]}""")))
|
||||
assertNull(fileInfoStream(json("""{"codec":"flac","urls":[]}""")))
|
||||
val mp3 = Stream(emptyList(), "mp3", 320, false, null)
|
||||
assertEquals("MP3 320" to "mp3", mp3.label to mp3.container)
|
||||
}
|
||||
|
||||
// ---- Waves ----
|
||||
|
||||
@Test
|
||||
fun settingsRoundTripAndBecomeSeeds() {
|
||||
val s = WaveSettings.from(json("""{"moodEnergy":"calm","diversity":"discover","language":"not-russian"}"""))
|
||||
assertEquals(WaveSettings(Mood.Calm, Character.Unfamiliar, Language.Foreign), s)
|
||||
assertEquals(WaveSettings(), WaveSettings.from(json("{}")))
|
||||
assertTrue(WaveSettings().seeds().isEmpty())
|
||||
assertEquals(
|
||||
listOf("settingMoodEnergy:calm", "settingDiversity:discover", "settingLanguage:russian"),
|
||||
WaveSettings(Mood.Calm, Character.Unfamiliar, Language.Russian).seeds(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun feedbackEventsSerialiseLikeTheOfficialClients() {
|
||||
val skip = WaveEvent.Skipped("1:2", 1500).toJson("T")
|
||||
assertEquals("skip", skip.str("type"))
|
||||
assertEquals("1:2", skip.str("trackId"))
|
||||
assertEquals(JsonPrimitive(1.5), skip["totalPlayedSeconds"])
|
||||
assertEquals(setOf("type", "timestamp"), WaveEvent.Started.toJson("T").keys)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sessionBatchAndStationParse() {
|
||||
val b = WaveBatch.from(json("""{"radioSessionId":"s1","batchId":"b1","sequence":[{"type":"track","track":{"id":"7","title":"A"}},{"type":"ad"}]}"""))
|
||||
assertEquals(Triple("s1", "b1", 1), Triple(b.sessionId, b.batchId, b.tracks.size))
|
||||
val s = Station.from(
|
||||
json("""{"station":{"id":{"type":"genre","tag":"rock"},"name":"Рок","icon":{"backgroundColor":"#ff4444","imageUrl":"avatars.yandex.net/x/%%"}}}"""),
|
||||
)!!
|
||||
assertEquals("genre:rock", s.id)
|
||||
assertEquals("#ff4444", s.color)
|
||||
assertEquals("https://avatars.yandex.net/x/200x200", s.iconUrl(200))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun isoMillisAlwaysHasThreeFractionDigits() {
|
||||
assertEquals("1970-01-01T00:00:00.000Z", isoMillis(0))
|
||||
assertEquals("2026-10-15T15:40:01.042Z", isoMillis(1_792_078_801_042))
|
||||
assertEquals("2000-02-29T00:00:00.000Z", isoMillis(951_782_400_000))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun numericIds() {
|
||||
assertEquals(123L, numericId("123"))
|
||||
assertEquals(123L, numericId("123:456"))
|
||||
assertNull(numericId("abc-upload"))
|
||||
}
|
||||
|
||||
// ---- Lyrics ----
|
||||
|
||||
@Test
|
||||
fun lrcParsesStampsAndDropsTags() {
|
||||
val l = Lyrics.fromLrc("[ar:Кино]\n[00:12.50] Первая\n[00:20.1]Вторая\n[01:02.345][00:05.00] Повтор\n\nбез метки", emptyList())
|
||||
assertEquals(
|
||||
listOf(5_000L to "Повтор", 12_500L to "Первая", 20_100L to "Вторая", 62_345L to "Повтор"),
|
||||
l.lines.map { it.atMs!! to it.text },
|
||||
)
|
||||
assertTrue(l.synced)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun currentLineFollowsPosition() {
|
||||
val l = Lyrics.fromLrc("[00:10.00]a\n[00:20.00]b", emptyList())
|
||||
assertNull(l.current(5_000))
|
||||
assertEquals(0, l.current(10_000))
|
||||
assertEquals(1, l.current(25_000))
|
||||
assertNull(Lyrics.fromText("a\nb", emptyList()).current(25_000))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun badStampsAreNotLyrics() {
|
||||
assertEquals(62_000L, Lyrics.parseStamp("01:02"))
|
||||
assertNull(Lyrics.parseStamp("1:75"))
|
||||
assertNull(Lyrics.parseStamp("ti"))
|
||||
assertNull(Lyrics.parseStamp("00:01.1234"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun syncedGlanceIsTheSungLineBetweenItsNeighbours() {
|
||||
val l = Lyrics.fromLrc("[00:10.00]one\n[00:20.00]\n[00:30.00]three", emptyList())
|
||||
assertEquals(Lyrics.Glance(null, null, "one"), l.glance(5_000, 60_000))
|
||||
assertEquals(Lyrics.Glance(null, "one", ""), l.glance(10_000, 60_000))
|
||||
assertEquals(Lyrics.Glance("one", "", "three"), l.glance(25_000, 60_000))
|
||||
assertEquals(Lyrics.Glance("", "three", null), l.glance(59_000, 60_000))
|
||||
assertNull(Lyrics(emptyList(), synced = true, writers = emptyList()).glance(0, 60_000))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun plainGlanceFollowsTheSongsShareOfTheWords() {
|
||||
val l = Lyrics.fromText("a\n\nb\nc\nd", emptyList())
|
||||
assertEquals(Lyrics.Glance(null, "a", "b"), l.glance(0, 100_000))
|
||||
assertEquals(Lyrics.Glance("a", "b", "c"), l.glance(25_000, 100_000))
|
||||
assertEquals(Lyrics.Glance("c", "d", null), l.glance(99_000, 100_000))
|
||||
// Past the end, or with the length unknown, it doesn't guess.
|
||||
assertEquals(Lyrics.Glance("c", "d", null), l.glance(150_000, 100_000))
|
||||
assertNull(l.glance(10_000, 0))
|
||||
assertNull(Lyrics.fromText(" \n", emptyList()).glance(0, 100_000))
|
||||
}
|
||||
|
||||
// ---- LRCLIB ----
|
||||
|
||||
private fun record(duration: Double, synced: String? = null, plain: String? = null, instrumental: Boolean = false) =
|
||||
json(
|
||||
buildString {
|
||||
append("""{"duration":$duration,"instrumental":$instrumental""")
|
||||
append(""","syncedLyrics":${synced?.let { JsonPrimitive(it) } ?: "null"}""")
|
||||
append(""","plainLyrics":${plain?.let { JsonPrimitive(it) } ?: "null"}}""")
|
||||
},
|
||||
)
|
||||
|
||||
@Test
|
||||
fun lrclibRecordPrefersSyncedAndIsCredited() {
|
||||
val l = Lrclib.fromRecord(record(280.0, synced = "[00:01.00]Тёплое место", plain = "Тёплое место"))!!
|
||||
assertTrue(l.synced)
|
||||
assertEquals(LyricsSource.Lrclib, l.source)
|
||||
assertEquals(listOf(1_000L to "Тёплое место"), l.lines.map { it.atMs!! to it.text })
|
||||
|
||||
val plain = Lrclib.fromRecord(record(280.0, plain = "a\nb\n"))!!
|
||||
assertFalse(plain.synced)
|
||||
assertEquals(listOf("a", "b"), plain.lines.map { it.text })
|
||||
assertEquals(LyricsSource.Lrclib, plain.source)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lrclibInstrumentalsAndEmptyRecordsHaveNoLyrics() {
|
||||
assertNull(Lrclib.fromRecord(record(200.0, plain = "la", instrumental = true)))
|
||||
assertNull(Lrclib.fromRecord(record(200.0)))
|
||||
assertNull(Lrclib.fromRecord(record(200.0, synced = "[ar:Someone]", plain = " ")))
|
||||
// Synced text with no stamped lines falls back to the plain text.
|
||||
assertFalse(Lrclib.fromRecord(record(200.0, synced = "[ar:Someone]", plain = "words"))!!.synced)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lrclibPicksTheSameRecordingSyncedFirst() {
|
||||
val live = record(246.0, synced = "[00:01.00]live")
|
||||
val plainNear = record(280.0, plain = "studio")
|
||||
val syncedNear = record(282.5, synced = "[00:01.00]studio")
|
||||
val results = listOf(live, plainNear, syncedNear)
|
||||
assertEquals(syncedNear, Lrclib.pick(results, 280.0))
|
||||
// Nothing within the slack: a different recording's words are worse than none.
|
||||
assertNull(Lrclib.pick(listOf(live), 280.0))
|
||||
// Length unknown: any record with lyrics will do, synced first.
|
||||
assertEquals(live, Lrclib.pick(listOf(plainNear, live), null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lrclibClosestInstrumentalMeansNoLyrics() {
|
||||
val results = listOf(record(281.0, synced = "[00:01.00]cover"), record(280.0, instrumental = true))
|
||||
assertNull(Lrclib.pick(results, 280.0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lrclibSyncedSearchResultBeatsAPlainExactMatch() {
|
||||
val plain = Lrclib.fromRecord(record(173.0, plain = "words"))!!
|
||||
val synced = Lrclib.fromRecord(record(172.0, synced = "[00:01.00]words"))!!
|
||||
assertEquals(synced, Lrclib.better(plain, synced))
|
||||
assertEquals(plain, Lrclib.better(plain, Lrclib.fromRecord(record(172.0, plain = "other"))))
|
||||
assertEquals(plain, Lrclib.better(plain, null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lrclibBusyRetriesWaitBriefly() {
|
||||
assertEquals(1000L, Lrclib.retryDelayMs(null, 0))
|
||||
assertEquals(2000L, Lrclib.retryDelayMs(null, 1))
|
||||
assertEquals(2000L, Lrclib.retryDelayMs(" 2 ", 0))
|
||||
assertEquals(3000L, Lrclib.retryDelayMs("120", 0))
|
||||
// An HTTP date isn't worth parsing for a few seconds' wait.
|
||||
assertEquals(1000L, Lrclib.retryDelayMs("Wed, 21 Oct 2026 07:28:00 GMT", 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lrclibErrorsNeverSignTheUserOut() {
|
||||
assertTrue(Lrclib.lrclibError(404, "/get") is YmError.NotFound)
|
||||
assertTrue(Lrclib.lrclibError(403, "/get") is YmError.Api)
|
||||
assertTrue(Lrclib.lrclibError(401, "/get") is YmError.Api)
|
||||
assertTrue(Lrclib.lrclibError(429, "/get").isRetryable)
|
||||
assertTrue(Lrclib.lrclibError(503, "/get").isRetryable)
|
||||
}
|
||||
|
||||
// ---- Auth, errors, signing ----
|
||||
|
||||
@Test
|
||||
fun credentialsRoundTripAndRefreshNearExpiry() {
|
||||
val week = 7L * 24 * 3600
|
||||
val c = Credentials("a", "r", 10 * week)
|
||||
assertEquals(c, Credentials.fromJson(c.toJson()))
|
||||
assertFalse("secret" in Credentials("secret-access", "secret-refresh", 1).toString())
|
||||
assertFalse(c.needsRefresh(8 * week))
|
||||
assertTrue(c.needsRefresh(9 * week + 1))
|
||||
val pasted = Credentials.fromToken(" a \n")
|
||||
assertEquals("a", pasted.accessToken)
|
||||
assertFalse(pasted.needsRefresh(Long.MAX_VALUE / 2))
|
||||
assertEquals(Credentials.fromToken("a"), Credentials.fromJson("""{"access_token":"a"}"""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun oauthCodesMapToActionableErrors() {
|
||||
assertTrue(YmError.fromOAuth("expired_token: code expired") is YmError.CodeExpired)
|
||||
assertTrue(YmError.fromOAuth("device authorization timed out") is YmError.CodeExpired)
|
||||
assertTrue(YmError.fromOAuth("access_denied") is YmError.Denied)
|
||||
assertTrue(YmError.fromOAuth("invalid_grant") is YmError.Unauthorized)
|
||||
assertTrue(YmError.fromOAuth("something new") is YmError.Api)
|
||||
assertTrue(YmError.Network("dns").isRetryable)
|
||||
assertFalse(YmError.Unauthorized("").isRetryable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun errorBodiesAndStatuses() {
|
||||
assertEquals("validate: bad", errorMessage(json("""{"error":{"name":"validate","message":"bad"}}"""), 400))
|
||||
assertEquals("authorization_pending wait", errorMessage(json("""{"error":"authorization_pending","error_description":"wait"}"""), 400))
|
||||
assertEquals("http 418", errorMessage(json("nope"), 418))
|
||||
assertTrue(statusError(401, json("{}"), "x") is YmError.Unauthorized)
|
||||
assertTrue(statusError(404, json("{}"), "x") is YmError.NotFound)
|
||||
assertTrue(statusError(502, json("{}"), "x") is YmError.Network)
|
||||
assertTrue(statusError(429, json("{}"), "x") is YmError.Network)
|
||||
val server = statusError(503, json("{}"), "x")
|
||||
assertTrue("other 5xx aren't the connection, so lossless falls back to MP3", server is YmError.Server)
|
||||
assertTrue(server.isRetryable)
|
||||
assertTrue(statusError(400, json("{}"), "x") is YmError.Api)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun acknowledgements() {
|
||||
assertTrue(acknowledged(JsonPrimitive("ok")))
|
||||
assertTrue(acknowledged(json("""{"revision":3}""")))
|
||||
assertFalse(acknowledged(json("{}")))
|
||||
assertTrue(acknowledged(json("{}"), loosely = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun signingMatchesYamuseVectors() {
|
||||
assertEquals("5Xma89MBvxVhn4bCHIDRA/W8OGjHoibkEZj5b0DbRp8", Signing.fileInfo(1_700_000_000, 42, "lossless"))
|
||||
assertEquals("xbCyTDmnI1xqeQil9/hP1qB2FtKWwefJgL9dAJueaYs=", Signing.lyrics(42, 1_700_000_000))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mp3LinkFromDownloadInfo() {
|
||||
val xml = "<download-info><host>s1.yandex.net</host><path>/a/b.mp3</path><ts>0061</ts><region>-1</region><s>xyz</s></download-info>"
|
||||
val sign = Signing.md5Hex("XGRlBW9FXlekgbPrRHuSiA" + "a/b.mp3" + "xyz")
|
||||
assertEquals("https://s1.yandex.net/get-mp3/$sign/0061/a/b.mp3", Signing.mp3Link(xml))
|
||||
assertNull(Signing.mp3Link("<download-info><host>h</host></download-info>"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun yandexHostsSeeTheToken() {
|
||||
assertTrue(isYandexHost("api.music.yandex.net"))
|
||||
assertTrue(isYandexHost("oauth.yandex.ru"))
|
||||
assertFalse(isYandexHost("evil-yandex.net"))
|
||||
assertFalse(isYandexHost("example.com"))
|
||||
}
|
||||
|
||||
// ---- encraw decryption ----
|
||||
|
||||
@Test
|
||||
fun ctrDecryptsFromAnyOffset() {
|
||||
val key = hexKey("00112233445566778899aabbccddeeff")!!
|
||||
val plain = ByteArray(100) { it.toByte() }
|
||||
val whole = Cipher.getInstance("AES/CTR/NoPadding").apply {
|
||||
init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(ByteArray(16)))
|
||||
}.doFinal(plain)
|
||||
for (offset in listOf(0L, 1L, 15L, 16L, 37L, 64L)) {
|
||||
val part = ctrCipher(key, offset).update(whole, offset.toInt(), whole.size - offset.toInt())
|
||||
assertArrayEquals("offset $offset", plain.copyOfRange(offset.toInt(), plain.size), part)
|
||||
}
|
||||
assertNull(hexKey("abc"))
|
||||
assertEquals(32, hexKey("0".repeat(64))!!.size)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package it.panov.musyx.api
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
/** Parity with the desktop's placeholder hues. */
|
||||
class CoverHuesTest {
|
||||
// Expected values come from ym-api's `hues_for` and its per-kind seeds (u64 wrapping maths).
|
||||
@Test
|
||||
fun huesMatchTheDesktop() {
|
||||
assertEquals(47f to 221f, CoverHues.album(1))
|
||||
assertEquals(329f to 335f, CoverHues.album(-1))
|
||||
assertEquals(233f to 119f, CoverHues.artist(42))
|
||||
assertEquals(2f to 356f, CoverHues.playlist(owner = 503_646_255, kind = 3))
|
||||
assertEquals(295f to 85f, CoverHues.track("12345:678", albumId = null))
|
||||
assertEquals(CoverHues.album(7), CoverHues.track("12345:678", albumId = 7))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
package it.panov.musyx.player
|
||||
|
||||
import it.panov.musyx.api.Stream
|
||||
import it.panov.musyx.api.Track
|
||||
import it.panov.musyx.api.WaveBatch
|
||||
import it.panov.musyx.api.WaveEvent
|
||||
import it.panov.musyx.api.YmError
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/** Ports the desktop player/mod.rs tests. */
|
||||
class PlayerCoreTest {
|
||||
private fun track(id: String, secs: Long = 100) = Track.bare(id, durationMs = secs * 1000)
|
||||
|
||||
private fun stream() = Stream(listOf("u"), "mp3", 320, false, null)
|
||||
|
||||
private fun List<Effect>.fetchGeneration(): Long? = filterIsInstance<Effect.Fetch>().firstOrNull()?.generation
|
||||
|
||||
private fun playing(n: Int, start: Int): PlayerCore {
|
||||
val p = PlayerCore()
|
||||
val gen = p.play((0 until n).map { track("$it") }, start).fetchGeneration()!!
|
||||
p.fetched(gen, Result.success(stream()))
|
||||
p.onLoaded(gen, null)
|
||||
return p
|
||||
}
|
||||
|
||||
private fun PlayerCore.upcomingIds() = queue!!.upcoming().map { it.second.id }
|
||||
|
||||
@Test
|
||||
fun playFetchesThenPlaysAndPrefetchesNext() {
|
||||
val p = PlayerCore()
|
||||
val effects = p.play(listOf(track("a", 10), track("b", 20)), 0)
|
||||
assertEquals(listOf(Effect.Fetch(1, "a")), effects.filterIsInstance<Effect.Fetch>())
|
||||
assertEquals(Status.Loading, p.status)
|
||||
assertTrue(p.fetched(1, Result.success(stream())).isEmpty())
|
||||
val loaded = p.onLoaded(1, null)
|
||||
assertEquals(Status.Playing, p.status)
|
||||
assertEquals(10_000L, p.durationMs)
|
||||
assertEquals(listOf<Effect>(Effect.Prefetch("b")), loaded)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun prefetchedStreamIsUsedWithoutAnotherFetch() {
|
||||
val p = playing(3, 0)
|
||||
p.prefetched("1", Result.success(stream()))
|
||||
val effects = p.onEnded(p.generation)
|
||||
assertTrue(effects.none { it is Effect.Fetch })
|
||||
assertEquals("1", p.track!!.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staleEventsAreIgnored() {
|
||||
val p = playing(3, 0)
|
||||
val old = p.generation
|
||||
p.next()
|
||||
p.onPosition(old, 50_000)
|
||||
assertEquals(0L, p.positionMs)
|
||||
assertTrue(p.fetched(old, Result.success(stream())).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun endOfQueueStopsAndPlayRestartsLastTrack() {
|
||||
val p = playing(1, 0)
|
||||
val effects = p.onEnded(p.generation)
|
||||
val report = (effects.single() as Effect.Report).report
|
||||
assertEquals(100_000L, report.playedMs)
|
||||
assertEquals(FROM_LIST, report.from)
|
||||
assertEquals(Status.Ended, p.status)
|
||||
val again = p.toggle()
|
||||
assertNull("replay reuses the stream", again.fetchGeneration())
|
||||
assertEquals(Status.Loading, p.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun repeatOneReplaysWithoutFetching() {
|
||||
val p = playing(3, 1)
|
||||
p.cycleRepeat()
|
||||
p.cycleRepeat()
|
||||
assertEquals(Repeat.One, p.repeat)
|
||||
val effects = p.onEnded(p.generation)
|
||||
assertTrue(effects.none { it is Effect.Fetch })
|
||||
assertEquals("1", p.track!!.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun previousRestartsAfterThreeSeconds() {
|
||||
val p = playing(3, 1)
|
||||
p.onPosition(p.generation, 10_000)
|
||||
p.previous()
|
||||
assertEquals("1", p.track!!.id)
|
||||
assertEquals(0L, p.positionMs)
|
||||
p.previous()
|
||||
assertEquals("0", p.track!!.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unplayableTracksAreSkippedThenGivenUpOn() {
|
||||
val p = playing(5, 0)
|
||||
for (expected in 1 until 3) {
|
||||
p.next()
|
||||
p.fetched(p.generation, Result.failure(YmError.Api("gone")))
|
||||
assertEquals(expected, p.skips)
|
||||
assertTrue(p.notice is Notice.Skipped)
|
||||
}
|
||||
val effects = p.fetched(p.generation, Result.failure(YmError.Api("gone")))
|
||||
assertTrue(effects.isEmpty())
|
||||
assertEquals(Notice.TooManyFailures, p.notice)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun expiredTokenSignsOut() {
|
||||
val p = PlayerCore()
|
||||
p.play(listOf(track("a", 10)), 0)
|
||||
assertEquals(listOf<Effect>(Effect.SignedOut), p.fetched(1, Result.failure(YmError.Unauthorized("401"))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shufflePlayTurnsShuffleOn() {
|
||||
val p = PlayerCore()
|
||||
p.play((0 until 20).map { track("$it", 10) }, 0, shuffle = true)
|
||||
assertTrue(p.shuffle)
|
||||
assertEquals(19, p.queue!!.upcomingCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resetDropsTheQueue() {
|
||||
val p = playing(3, 0)
|
||||
p.reset()
|
||||
assertNull(p.track)
|
||||
}
|
||||
|
||||
private fun waveWith(n: Int): PlayerCore {
|
||||
val p = PlayerCore()
|
||||
val start = p.playWave("user:onyourwave")
|
||||
assertEquals(listOf<Effect>(Effect.WaveFetch("user:onyourwave", null, emptyList(), 1)), start)
|
||||
val batch = WaveBatch("s1", (0 until n).map { track("w$it") }, "b1")
|
||||
val effects = p.waveBatch("user:onyourwave", 1, Result.success(batch))
|
||||
assertEquals(Effect.WaveFeedback("s1", WaveEvent.Started, "b1"), effects[0])
|
||||
val fetch = effects[1] as Effect.Fetch
|
||||
p.fetched(fetch.generation, Result.success(stream()))
|
||||
return p
|
||||
}
|
||||
|
||||
private fun PlayerCore.loaded() = onLoaded(generation, null)
|
||||
|
||||
@Test
|
||||
fun waveReportsStartAndTopsUpWhenLow() {
|
||||
val p = waveWith(3)
|
||||
val effects = p.loaded()
|
||||
assertTrue(effects.contains(Effect.WaveFeedback("s1", WaveEvent.TrackStarted("w0"), "b1")))
|
||||
assertTrue("two still queued", effects.none { it is Effect.WaveFetch })
|
||||
|
||||
p.onPosition(p.generation, 20_000)
|
||||
val skip = p.next()
|
||||
assertTrue(skip.contains(Effect.WaveFeedback("s1", WaveEvent.Skipped("w0", 20_000), "b1")))
|
||||
assertTrue(skip.any { it is Effect.Report && it.report.from == FROM_WAVE })
|
||||
|
||||
p.fetched(p.generation, Result.success(stream()))
|
||||
val more = p.loaded().filterIsInstance<Effect.WaveFetch>().single()
|
||||
assertEquals("s1", more.sessionId)
|
||||
assertEquals("w2", more.queue.last())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun feedbackNamesEachTracksOwnBatch() {
|
||||
val p = waveWith(2)
|
||||
p.loaded()
|
||||
p.waveBatch("user:onyourwave", 1, Result.success(WaveBatch("s1", listOf(track("n0", 10)), "b2")))
|
||||
val effects = p.next()
|
||||
assertTrue(effects.any { it is Effect.WaveFeedback && it.event is WaveEvent.Skipped && it.batchId == "b1" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun waveWaitsForTheNextBatchWhenDry() {
|
||||
val p = waveWith(1)
|
||||
p.loaded()
|
||||
val effects = p.onEnded(p.generation)
|
||||
assertTrue(effects.any { it is Effect.WaveFeedback && it.event is WaveEvent.TrackFinished })
|
||||
assertEquals("a wave doesn't end", Status.Loading, p.status)
|
||||
val next = p.waveBatch("user:onyourwave", 1, Result.success(WaveBatch("s1", listOf(track("w9", 50)), "b2")))
|
||||
assertEquals("w9", (next.first() as Effect.Fetch).trackId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun newSettingsStartANewSession() {
|
||||
val p = waveWith(3)
|
||||
p.loaded()
|
||||
assertEquals(listOf<Effect>(Effect.WaveFetch("user:onyourwave", null, listOf("w0"), 2)), p.waveRestart())
|
||||
assertEquals(0, p.queue!!.upcomingCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun playAfterAFailedStartAsksTheStationAgain() {
|
||||
val p = PlayerCore()
|
||||
p.playWave("user:onyourwave")
|
||||
assertTrue(p.waveBatch("user:onyourwave", 1, Result.failure(YmError.Network("down"))).isEmpty())
|
||||
assertEquals(Status.Paused, p.status)
|
||||
assertEquals(Notice.StationDry, p.notice)
|
||||
assertEquals(listOf<Effect>(Effect.WaveFetch("user:onyourwave", null, emptyList(), 2)), p.toggle())
|
||||
assertEquals(Status.Loading, p.status)
|
||||
assertNull(p.notice)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun batchesForAnotherStationAreIgnored() {
|
||||
val p = waveWith(2)
|
||||
assertTrue(p.waveBatch("genre:rock", 1, Result.success(WaveBatch(null, listOf(track("x", 10)), null))).isEmpty())
|
||||
assertEquals(2, p.queue!!.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun playingAListLeavesWaveModeAndShuffleIsIgnoredInWaves() {
|
||||
val p = waveWith(2)
|
||||
p.toggleShuffle()
|
||||
assertTrue(!p.shuffle)
|
||||
p.play(listOf(track("a", 10)), 0)
|
||||
assertNull(p.waveStation)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun playNextAndAppend() {
|
||||
val p = playing(3, 0)
|
||||
p.playNext(track("n", 5))
|
||||
p.append(track("z", 5))
|
||||
assertEquals(listOf("n", "1", "2", "z"), p.upcomingIds())
|
||||
val empty = PlayerCore()
|
||||
assertTrue(empty.append(track("solo", 5)).any { it is Effect.Fetch && it.trackId == "solo" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun playNextWinsOverAnAlreadyPrefetchedTrack() {
|
||||
val p = playing(3, 0)
|
||||
p.prefetched("1", Result.success(stream()))
|
||||
assertTrue(p.playNext(track("n", 5)).contains(Effect.Prefetch("n")))
|
||||
p.onEnded(p.generation)
|
||||
assertEquals("n", p.track!!.id)
|
||||
// A late prefetch for the old next track must not be played instead.
|
||||
p.prefetched("1", Result.success(stream()))
|
||||
assertEquals("n", p.track!!.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun playNextOnThePlayingTrackChangesNothing() {
|
||||
val p = playing(3, 0)
|
||||
assertTrue(p.playNext(track("0")).isEmpty())
|
||||
p.next()
|
||||
assertEquals("skip moves on instead of replaying", "1", p.track!!.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun playNextInAWave() {
|
||||
val p = waveWith(3)
|
||||
p.loaded()
|
||||
p.playNext(track("n", 5))
|
||||
p.next()
|
||||
assertEquals("n", p.track!!.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pausingWhileLoadingStopsTheOldTrackAndHoldsTheNewOne() {
|
||||
val engine = FakeEngine()
|
||||
val p = PlayerCore().also { it.engine = engine }
|
||||
val gen = p.play(listOf(track("a"), track("b")), 0).fetchGeneration()!!
|
||||
p.fetched(gen, Result.success(stream()))
|
||||
p.onLoaded(gen, null)
|
||||
engine.calls.clear()
|
||||
p.next()
|
||||
assertTrue("the old track stops while the next is fetched", "pause" in engine.calls)
|
||||
assertEquals(Status.Loading, p.status)
|
||||
p.toggle()
|
||||
assertEquals(Status.Paused, p.status)
|
||||
p.fetched(p.generation, Result.success(stream()))
|
||||
assertEquals("load:false", engine.calls.last())
|
||||
p.onLoaded(p.generation, null)
|
||||
assertEquals("it stays paused once loaded", Status.Paused, p.status)
|
||||
p.toggle()
|
||||
assertEquals(Status.Playing, p.status)
|
||||
assertEquals("play", engine.calls.last())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resumingWhileStillFetchingLetsItStart() {
|
||||
val engine = FakeEngine()
|
||||
val p = PlayerCore().also { it.engine = engine }
|
||||
p.play(listOf(track("a")), 0)
|
||||
p.toggle()
|
||||
p.toggle()
|
||||
assertEquals(Status.Loading, p.status)
|
||||
p.fetched(p.generation, Result.success(stream()))
|
||||
assertEquals("load:true", engine.calls.last())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun batchesAskedForBeforeASettingsChangeAreDropped() {
|
||||
val p = waveWith(2)
|
||||
p.loaded()
|
||||
val restart = p.waveRestart().single() as Effect.WaveFetch
|
||||
// A top-up from the old session lands after the restart.
|
||||
assertTrue(p.waveBatch("user:onyourwave", 1, Result.success(WaveBatch("s1", listOf(track("old")), "b9"))).isEmpty())
|
||||
assertEquals(0, p.queue!!.upcomingCount)
|
||||
val fresh = p.waveBatch("user:onyourwave", restart.epoch, Result.success(WaveBatch("s2", listOf(track("new")), "c1")))
|
||||
assertTrue(fresh.contains(Effect.WaveFeedback("s2", WaveEvent.Started, "c1")))
|
||||
assertEquals("new", p.queue!!.upcoming().single().second.id)
|
||||
}
|
||||
|
||||
private class FakeEngine : Engine {
|
||||
val calls = mutableListOf<String>()
|
||||
override fun load(generation: Long, track: Track, stream: Stream, play: Boolean) { calls += "load:$play" }
|
||||
override fun play() { calls += "play" }
|
||||
override fun pause() { calls += "pause" }
|
||||
override fun seek(positionMs: Long) { calls += "seek" }
|
||||
override fun stop() { calls += "stop" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package it.panov.musyx.player
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/** Ports the desktop queue.rs tests. */
|
||||
class QueueTest {
|
||||
private fun q(n: Int, start: Int) = Queue.of((0 until n).toList(), start, shuffle = false)!!
|
||||
|
||||
private fun Queue<Int>.next() = upcoming().map { it.second }
|
||||
|
||||
@Test
|
||||
fun emptyListHasNoQueue() = assertNull(Queue.of(emptyList<Int>(), 0, false))
|
||||
|
||||
@Test
|
||||
fun startIsClamped() = assertEquals(2, q(3, 99).current)
|
||||
|
||||
@Test
|
||||
fun advanceStopsAtEndWithoutRepeat() {
|
||||
val q = q(2, 0)
|
||||
assertTrue(q.advance(Repeat.Off, true))
|
||||
assertEquals(1, q.current)
|
||||
assertFalse(q.advance(Repeat.Off, true))
|
||||
assertEquals(1, q.current)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun repeatAllWrapsBothWays() {
|
||||
val q = q(3, 2)
|
||||
assertTrue(q.advance(Repeat.All, true))
|
||||
assertEquals(0, q.current)
|
||||
assertTrue(q.back(Repeat.All))
|
||||
assertEquals(2, q.current)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun repeatOneReplaysOnFinishButSkipMovesOn() {
|
||||
val q = q(3, 1)
|
||||
assertTrue(q.advance(Repeat.One, true))
|
||||
assertEquals(1, q.current)
|
||||
assertTrue(q.advance(Repeat.One, false))
|
||||
assertEquals(2, q.current)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backStopsAtStartWithoutRepeat() {
|
||||
val q = q(3, 0)
|
||||
assertFalse(q.back(Repeat.Off))
|
||||
assertEquals(0, q.current)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun peekMatchesAdvance() {
|
||||
for (repeat in Repeat.entries) for (start in 0 until 3) {
|
||||
val q = q(3, start)
|
||||
val peeked = q.peekNext(repeat)
|
||||
val moved = q.advance(repeat, true)
|
||||
assertEquals("$repeat from $start", peeked, if (moved) q.current else null)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shuffleKeepsCurrentAndCoversEverything() {
|
||||
val q = q(50, 17)
|
||||
q.setShuffle(true)
|
||||
assertEquals(17, q.current)
|
||||
assertEquals((0 until 50).toList(), (listOf(17) + q.next()).sorted())
|
||||
q.advance(Repeat.Off, false)
|
||||
val now = q.current
|
||||
q.setShuffle(false)
|
||||
assertEquals("unshuffling keeps the current item", now, q.current)
|
||||
assertEquals(49 - now, q.upcomingCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun extendAppendsAfterEverything() {
|
||||
val q = q(2, 1)
|
||||
assertFalse(q.advance(Repeat.Off, true))
|
||||
q.extend(listOf(10, 11))
|
||||
assertTrue(q.advance(Repeat.Off, true))
|
||||
assertEquals(10, q.current)
|
||||
assertEquals(listOf(11), q.next())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clearUpcomingKeepsHistoryAndCurrent() {
|
||||
val q = q(5, 0)
|
||||
q.setShuffle(true)
|
||||
q.advance(Repeat.Off, false)
|
||||
val first = q.tail(5).first()
|
||||
val now = q.current
|
||||
q.clearUpcoming()
|
||||
assertEquals(2, q.size)
|
||||
assertEquals(now, q.current)
|
||||
assertEquals(0, q.upcomingCount)
|
||||
assertTrue(q.back(Repeat.Off))
|
||||
assertEquals(first, q.current)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun insertNextPlaysAfterCurrentEvenWhenShuffled() {
|
||||
val q = q(4, 1)
|
||||
q.setShuffle(true)
|
||||
assertTrue(q.insertNext(99) { a, b -> a == b })
|
||||
assertEquals(99, q.next().first())
|
||||
assertEquals(1, q.current)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun insertNextMovesInsteadOfDuplicatingAndIgnoresCurrent() {
|
||||
val q = q(5, 1)
|
||||
assertFalse("the current item stays put", q.insertNext(1) { a, b -> a == b })
|
||||
assertEquals(listOf(2, 3, 4), q.next())
|
||||
assertTrue(q.insertNext(4) { a, b -> a == b })
|
||||
assertEquals(listOf(4, 2, 3), q.next())
|
||||
assertEquals("moved, not added", 5, q.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun jumpMovesToUpcomingPosition() {
|
||||
val q = q(5, 0)
|
||||
val (pos, item) = q.upcoming()[2]
|
||||
q.jump(pos)
|
||||
assertEquals(item, q.current)
|
||||
q.jump(99)
|
||||
assertEquals(item, q.current)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package it.panov.musyx.state
|
||||
|
||||
import it.panov.musyx.api.PlaylistId
|
||||
import it.panov.musyx.api.Track
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/** Ports the desktop route.rs and collection.rs tests. */
|
||||
class StateTest {
|
||||
@Test
|
||||
fun backReturnsToPreviousRoute() {
|
||||
val nav = Navigator(Route.Home)
|
||||
nav.go(Route.Search)
|
||||
nav.go(Route.Collection)
|
||||
assertTrue(nav.back())
|
||||
assertEquals(Route.Search, nav.current)
|
||||
nav.back()
|
||||
assertEquals(Route.Home, nav.current)
|
||||
assertFalse(nav.canGoBack)
|
||||
assertFalse(nav.back())
|
||||
assertEquals(Route.Home, nav.current)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sectionIsWherePagesWereReachedFrom() {
|
||||
val nav = Navigator(Route.Home)
|
||||
assertEquals(Route.Home, nav.section)
|
||||
nav.go(Route.Podcasts)
|
||||
nav.go(Route.Album(7))
|
||||
assertEquals(Route.Podcasts, nav.section)
|
||||
nav.go(Route.NowPlaying)
|
||||
assertEquals(Route.Podcasts, nav.section)
|
||||
nav.go(Route.Search)
|
||||
nav.go(Route.Genre(0))
|
||||
assertEquals(Route.Search, nav.section)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun revisitingTheCurrentRouteDoesNotGrowHistory() {
|
||||
val nav = Navigator(Route.Home)
|
||||
nav.go(Route.Home)
|
||||
assertFalse(nav.canGoBack)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun historyIsBounded() {
|
||||
val nav = Navigator(Route.Home)
|
||||
repeat(200) { nav.go(if (it % 2 == 0) Route.Search else Route.Home) }
|
||||
assertEquals(50, nav.depth)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun leavingADeletedPageGoesBackAndForgetsIt() {
|
||||
val nav = Navigator(Route.Home)
|
||||
val gone = Route.Playlist(PlaylistId(1, 2))
|
||||
nav.go(gone)
|
||||
nav.go(Route.Search)
|
||||
nav.go(gone)
|
||||
nav.leave(gone)
|
||||
assertEquals(Route.Search, nav.current)
|
||||
nav.back()
|
||||
assertEquals(Route.Home, nav.current)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun likedAddsOnTopAndRemoves() {
|
||||
val base = Liked.Loaded(listOf(Track.bare("1"), Track.bare("2")))
|
||||
assertTrue(base.contains("2") && !base.contains("3"))
|
||||
val added = base.with(Track.bare("3"), true)
|
||||
assertEquals("3", added.tracks()!![0].id)
|
||||
val removed = added.with(Track.bare("1"), false)
|
||||
assertTrue(!removed.contains("1") && removed.contains("2"))
|
||||
assertSame("a no-op keeps the list", removed, removed.with(Track.bare("2"), true))
|
||||
assertSame(Liked.NotLoaded, Liked.NotLoaded.with(Track.bare("9"), true))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user