Musyx Mobile: Android TV player for Yandex Music

Kotlin, Compose for TV and Media3 port of the desktop Musyx, with
device-code sign-in, Home, My Wave, search, collection, detail pages,
Now Playing with queue and lyrics, and settings for streaming quality,
appearance, font size (small, medium, large) and language.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yuriy.pandClaude Opus 5.5 committed 2026-10-16 22:14:54 +06:00
commit 46610d95fa
217 files changed
+26144

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
.DS_Store
.env
# Gradle and Android Studio
.gradle/
build/
local.properties
.idea/
*.iml
captures/
.externalNativeBuild/
.cxx/
.kotlin/
# Signing
*.jks
*.keystore
keystore.properties
+64
View File
@@ -0,0 +1,64 @@
# Musyx design system
The approved mockup is [`design/mockup.html`](design/mockup.html) (published at
https://claude.ai/artifact/2gmswtceJM61fcE2F5uYYM). This file records its tokens. They map
1:1 to the Compose theme (`app/src/main/java/it/panov/musyx/tv/ui/theme/Theme.kt`) and to the desktop app's
`crates/musyx/src/ui/theme.rs` in the [musyx](../musyx) repo, so change all of them together.
## Direction
The ground is aubergine graphite, with one amber accent taken from a tape deck's VU needle.
The app is dark-first, and the light theme follows the system setting. Everything stays quiet
except the My Wave hero, which is the one animated, accent-heavy surface.
## Colour
| Token | Dark | Light | Used for |
|--------------|-----------|-----------|----------|
| `bg` | `#1C1A22` | `#F3F1F6` | Window and content background |
| `panel` | `#23202B` | `#FFFFFF` | Sidebar, player bar, drawer, cards that need separation |
| `raised` | `#2D2937` | `#EAE6F0` | Hover and selected rows, chip fills, progress track |
| `line` | `#3A3546` | `#DCD6E4` | 1px dividers and outlines |
| `fg` | `#EEEAF3` | `#1F1B27` | Primary text, the play/pause disc |
| `muted` | `#A39CB0` | `#686178` | Secondary text, idle icons |
| `accent` | `#F0B23E` | `#A86C05` | Current track, progress fill, primary buttons, active nav icon |
| `accent_ink` | `#2A1D04` | `#FFF7E6` | Text and icons on `accent` |
| `like` | `#F27286` | `#D2405A` | Filled heart, falling chart position |
| `ok` | `#7FCB9B` | `#2E8A55` | Subscription status, rising chart position |
Covers that have no artwork yet get a placeholder made of two hues (`h1`, `h2`) derived from
the item id, painted as a diagonal gradient between them.
## Type
| Role | Face | Size / weight | Where |
|---------|----------------------|--------------------|-------|
| Display | Unbounded SemiBold | 46 / 40 / 34 / 30 | My Wave hero, detail page titles, sign-in headline, screen titles |
| Wordmark| Unbounded SemiBold | 20 | `musyx` + amber dot |
| Section | Onest SemiBold | 19 | Section headings ("Made for you") |
| Body | Onest Regular/Medium | 14 (rows 14, meta 13, small 12.5) | Everything else |
The fonts are bundled from `assets/fonts` and licensed under OFL. Durations and
counts use tabular figures.
## Space and shape
- Spacing steps: 2 · 4 · 6 · 8 · 10 · 12 · 14 · 18 · 22 · 28 · 34. Content gutter is 28,
and the gap between sections is 34.
- Radii: cover 10 · control 8 · small cover 6 · pill/round 999 · hero 16 · window cards 14.
- Shell: sidebar 232 · player bar 80 · drawer 320 · track row 52 tall.
- Icons: Lucide 0.460 (ISC), 18px and tinted via `currentColor`. The `-fill` variants are for
liked, play and pause.
## Components
- **Sidebar**: wordmark, five nav items (Home, My Wave, Search, Collection, Podcasts), a
playlist list, and an account chip with sign-out. The active item sits on a `raised` fill
and has an amber icon.
- **Player bar**: shows cover, title/artist, like and dislike on the left. The centre has
transport (shuffle, previous, play disc, next, repeat) over a progress bar with times. On
the right are a quality badge, lyrics, queue and a volume bar.
- **Track row**: index (or an equaliser when playing), cover, title/artist, album, like,
duration and a "more" button that appears on hover. The playing row is amber.
- **Cards**: a cover with a hover play button, the title, and one muted subtitle line.
- **Drawer**: Queue | Lyrics tabs, sliding in from the right over the content edge.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Yuriy Panov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+107
View File
@@ -0,0 +1,107 @@
# Musyx Mobile
An Android TV player for Yandex Music, written in Kotlin with Jetpack Compose for TV and
Media3. It is the TV companion to the desktop [Musyx](../musyx) (Rust, iced), and follows the
same design.
Musyx is an unofficial client. It talks to the same undocumented API the official apps use,
and it isn't affiliated with or endorsed by Yandex.
## What it does
Everything the desktop app does, laid out for a remote: device-code sign-in with a QR for
your phone (or a pasted token), Home (My Wave, recently played, personal playlists, the
chart, new releases, genres), My Wave with its mood, character and language settings and
other stations, search with suggestions and paged results, Collection (liked tracks,
albums, artists, playlists, clips), album, artist, playlist, genre and podcast pages, and a
Now Playing screen with the queue and synced lyrics. Tracks can be liked, disliked, queued
next or last, added to playlists, and used to start similar tracks; your own playlists can
be created, renamed, made public or private, reordered and deleted. Playback runs in a media
session, so it keeps going in the background and answers the remote's media keys. Streaming
quality goes up to FLAC (decrypted on the fly), and the interface is in English or Russian.
Hold select on a track row or a clip for its menu; the heart and the "more" button sit to
the right of each row.
## Stack
- Kotlin, Jetpack Compose with `androidx.tv:tv-material` for the D-pad UI.
- Media3 (ExoPlayer and `MediaSessionService`) for playback, background audio, the Now
Playing card and remote controls.
- OkHttp and kotlinx.serialization for the Yandex Music API.
- Android Keystore for the OAuth token.
- Coil for covers (memory and disk cache) and ZXing for the sign-in QR.
## Build and run
You need JDK 17 or newer (Android Studio's bundled JBR works) and the Android SDK with
platform 37. Point Gradle at the SDK with `sdk.dir` in `local.properties` (Android Studio
writes it) or `ANDROID_HOME`. The Gradle wrapper fetches everything else.
```bash
./gradlew assembleDebug
```
The APK lands in `app/build/outputs/apk/debug/app-debug.apk`. `./gradlew testDebugUnitTest`
runs the JVM tests (the queue and player rules, API parsing and request signing, lyrics,
decryption and theme parity, mostly ported from the desktop tests), and `./gradlew lint` runs Android
Lint, with the report in `app/build/reports/lint-results-debug.html`.
To run it, start an Android TV or Google TV emulator (Device Manager in Android Studio, TV
category) or connect a TV with ADB debugging on, then:
```bash
./gradlew installDebug
```
```bash
adb shell am start -n it.panov.musyx.tv/.MainActivity
```
The app shows up in the TV launcher under its banner. It also installs on phones and
tablets, since neither Leanback nor a touchscreen is required.
### Generated resources
The icons, banner and fonts in `app/src/main/res` come from `assets/`. Regenerate them after
changing the sources:
- `python3 tool/svg_to_vector.py` turns `assets/icons/*.svg` into `res/drawable/ic_<name>.xml`.
The drawables are white masks; code tints them with theme tokens.
- `python3 tool/make_tv_assets.py` draws the 320×180 TV banner (`drawable-xhdpi/banner.png`)
and scales `assets/icon/musyx.png` into the launcher mipmaps. It needs Pillow.
- `python3 tool/make_icon.py assets/icon/musyx.png` redraws the icon itself.
- The fonts are copied by hand from `assets/fonts` to `res/font` (lower-case names).
## Layout
- `app/`: the Android TV app (`it.panov.musyx.tv`), under `app/src/main/java/it/panov/musyx/tv`:
- `api/`: the Yandex Music client, ported from `reference/ym-api` with the `yamuse` wire
details inlined (`Transport.kt` headers and errors, `Auth.kt` device flow, `Signing.kt`).
- `player/`: `PlayerCore` (queue, repeat, waves, reports; a pure port of the desktop
player), `ExoEngine` (one ExoPlayer, with `AesCtrDataSource` for encrypted FLAC),
`PlaybackController` (runs the core's effects) and `PlaybackService` (the media session).
- `state/`: `AppState`, the port of the desktop `app.rs` and `app/edit.rs`, plus search,
sign-in and navigation state.
- `data/`: settings and the Keystore-encrypted credentials.
- `ui/`: the shell (drawer, mini player, dialogs, toasts), `screens/` and `components/`.
The theme is `ui/theme/Theme.kt`, a 1:1 port of `DESIGN.md`.
- `gradle/libs.versions.toml`: dependency versions.
- `DESIGN.md`: design tokens (colour, type, space, components), shared with the desktop app.
- `design/mockup.html`: the approved desktop mockup.
- `assets/fonts`: Onest and Unbounded (OFL). They go to `res/font` in the app.
- `assets/icons`: Lucide icons (ISC). They become vector drawables in the app.
- `assets/icon/musyx.png`: the app icon, drawn by `tool/make_icon.py`.
- `tool/`: scripts that generate the icon, banner and vector drawables.
- `reference/`: a read-only snapshot of the desktop sources at musyx `44f4a1f`, to port from.
Nothing here is built.
- `reference/ym-api`: the API client. It is the spec for the Kotlin client: endpoints,
device-flow sign-in and token refresh, `/get-file-info` signing, and the AES-CTR
decryption of lossless streams. `tests/live.rs` covers the live calls.
- `reference/musyx`: the desktop app. The queue and My Wave logic (`player/`), screens,
settings, and the Russian strings (`i18n/ru.rs`, for `values-ru/strings.xml`).
## Licences
Musyx Mobile is MIT. Onest and Unbounded are OFL (`assets/fonts`), and Lucide icons are ISC
(`assets/icons/LICENSE.txt`).
+81
View File
@@ -0,0 +1,81 @@
import java.util.Properties
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.kotlin.serialization)
}
android {
namespace = "it.panov.musyx.tv"
compileSdk = 37
defaultConfig {
applicationId = "it.panov.musyx.tv"
// Compose (and so Compose for TV) needs API 23.
minSdk = 23
targetSdk = 37
versionCode = 1
versionName = "0.1.0"
}
// A release key comes from keystore.properties (gitignored): storeFile, storePassword,
// keyAlias, keyPassword. Without one, release builds use the debug key so they still install.
val keystore = rootProject.file("keystore.properties").takeIf { it.exists() }?.let { file ->
Properties().apply { file.inputStream().use(::load) }
}
signingConfigs {
if (keystore != null) {
create("release") {
storeFile = rootProject.file(keystore.getProperty("storeFile"))
storePassword = keystore.getProperty("storePassword")
keyAlias = keystore.getProperty("keyAlias")
keyPassword = keystore.getProperty("keyPassword")
}
}
}
buildTypes {
release {
signingConfig = signingConfigs.findByName("release") ?: signingConfigs.getByName("debug")
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
buildFeatures {
compose = true
buildConfig = true
}
testOptions {
// PlayerCore logs through android.util.Log; JVM tests get no-op stubs.
unitTests.isReturnDefaultValues = true
}
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(platform(libs.compose.bom))
implementation(libs.compose.ui)
implementation(libs.compose.ui.graphics)
implementation(libs.compose.foundation)
implementation(libs.compose.ui.tooling.preview)
implementation(libs.tv.material)
debugImplementation(libs.compose.ui.tooling)
implementation(libs.media3.exoplayer)
implementation(libs.media3.session)
implementation(libs.okhttp)
implementation(libs.kotlinx.serialization.json)
implementation(libs.coil.compose)
implementation(libs.coil.network.okhttp)
implementation(libs.zxing.core)
testImplementation(libs.junit)
testImplementation(libs.kotlinx.coroutines.test)
}
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<lint>
<!-- The whole Lucide set is converted up front; screens adopt icons as they are built. -->
<issue id="UnusedResources">
<ignore path="src/main/res/drawable/ic_*.xml" />
</issue>
<!-- Android TV wants the 320x180 launcher banner in drawable-xhdpi only. -->
<issue id="IconMissingDensityFolder" severity="ignore" />
<!-- The language setting overrides the activity locale; the APK ships every language, no bundles. -->
<issue id="AppBundleLocaleChanges" severity="ignore" />
</lint>
+1
View File
@@ -0,0 +1 @@
# Project-specific R8 rules. The libraries in use ship their own consumer rules.
+53
View File
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- A TV app that also installs on other devices: neither Leanback nor touch is required. -->
<uses-feature
android:name="android.software.leanback"
android:required="false" />
<uses-feature
android:name="android.hardware.touchscreen"
android:required="false" />
<application
android:name=".Musyx"
android:allowBackup="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:banner="@drawable/banner"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.Musyx">
<activity
android:name=".MainActivity"
android:configChanges="keyboard|keyboardHidden|navigation|screenSize|smallestScreenSize|screenLayout|orientation|uiMode"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".player.PlaybackService"
android:exported="true"
android:foregroundServiceType="mediaPlayback"
tools:ignore="ExportedService">
<!-- Exported so the system and remotes can reach the media session. -->
<intent-filter>
<action android:name="androidx.media3.session.MediaSessionService" />
</intent-filter>
</service>
</application>
</manifest>
@@ -0,0 +1,91 @@
package it.panov.musyx.tv
import android.content.ComponentName
import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import android.view.KeyEvent
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.snapshotFlow
import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken
import com.google.common.util.concurrent.ListenableFuture
import it.panov.musyx.tv.data.Appearance
import it.panov.musyx.tv.data.SettingsStore
import it.panov.musyx.tv.player.PlaybackService
import it.panov.musyx.tv.player.Status
import it.panov.musyx.tv.ui.MusyxApp
import it.panov.musyx.tv.ui.theme.MusyxTheme
import it.panov.musyx.tv.ui.theme.isMusyxDark
import kotlinx.coroutines.flow.drop
import java.util.Locale
class MainActivity : ComponentActivity() {
/** Binds the playback service so it can go foreground when playback starts. */
private var controller: ListenableFuture<MediaController>? = null
/** The interface language follows the setting, not only the system. */
override fun attachBaseContext(newBase: Context) {
val tag = SettingsStore(newBase).language().tag
if (tag == null) return super.attachBaseContext(newBase)
val config = Configuration(newBase.resources.configuration)
val locale = Locale.forLanguageTag(tag)
Locale.setDefault(locale)
config.setLocale(locale)
super.attachBaseContext(newBase.createConfigurationContext(config))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val state = Musyx.graph(this).state
state.start()
setContent {
val dark = when (state.settings.appearance) {
Appearance.System -> isMusyxDark()
Appearance.Light -> false
Appearance.Dark -> true
}
// A new interface language means new resources: rebuild the activity in it.
LaunchedEffect(Unit) {
snapshotFlow { state.settings.language }.drop(1).collect { recreate() }
}
MusyxTheme(dark = dark, typeScale = state.settings.fontSize.scale) {
MusyxApp(state, onExit = { finish() })
}
}
}
override fun onStart() {
super.onStart()
val token = SessionToken(this, ComponentName(this, PlaybackService::class.java))
controller = MediaController.Builder(this, token).buildAsync()
}
override fun onStop() {
controller?.let { MediaController.releaseFuture(it) }
controller = null
super.onStop()
}
/** Remote media keys while the app is in front go straight to the player. */
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
val playback = Musyx.graph(this).state.playback
when (keyCode) {
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_HEADSETHOOK -> playback.toggle()
KeyEvent.KEYCODE_MEDIA_PLAY -> playback.setPlaying(true)
KeyEvent.KEYCODE_MEDIA_PAUSE -> if (playback.state.status == Status.Playing) playback.toggle()
KeyEvent.KEYCODE_MEDIA_NEXT -> playback.next()
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> playback.previous()
KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> playback.seekBy(SEEK_STEP_MS)
KeyEvent.KEYCODE_MEDIA_REWIND -> playback.seekBy(-SEEK_STEP_MS)
else -> return super.onKeyDown(keyCode, event)
}
return true
}
companion object {
const val SEEK_STEP_MS = 10_000L
}
}
@@ -0,0 +1,57 @@
// The application: one AppState for the activity and the playback service to share.
package it.panov.musyx.tv
import android.app.Application
import android.content.Context
import android.content.res.Resources
import androidx.core.os.ConfigurationCompat
import coil3.ImageLoader
import coil3.PlatformContext
import coil3.SingletonImageLoader
import coil3.disk.DiskCache
import coil3.disk.directory
import coil3.memory.MemoryCache
import coil3.network.okhttp.OkHttpNetworkFetcherFactory
import coil3.request.crossfade
import it.panov.musyx.tv.data.CredentialStore
import it.panov.musyx.tv.data.SettingsStore
import it.panov.musyx.tv.state.AppState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.withContext
class Musyx : Application(), SingletonImageLoader.Factory {
/** Lives as long as the process; everything in it runs on the main thread. */
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
val state: AppState by lazy {
AppState(
context = this,
scope = scope,
credentialStore = CredentialStore(this),
settingsStore = SettingsStore(this),
systemLanguage = { ConfigurationCompat.getLocales(Resources.getSystem().configuration)[0]?.language.orEmpty() },
clearCovers = {
withContext(Dispatchers.IO) { SingletonImageLoader.get(this@Musyx).diskCache?.clear() }
},
)
}
/** Covers: kept in memory and on disk so rows of cards open instantly the second time. */
override fun newImageLoader(context: PlatformContext): ImageLoader = ImageLoader.Builder(context)
.components { add(OkHttpNetworkFetcherFactory()) }
.memoryCache { MemoryCache.Builder().maxSizePercent(context, 0.2).build() }
.diskCache {
DiskCache.Builder().directory(cacheDir.resolve("covers")).maxSizeBytes(COVER_CACHE_BYTES).build()
}
.crossfade(true)
.build()
companion object {
private const val COVER_CACHE_BYTES = 200L * 1024 * 1024
/** The app state, from any context of this app. */
fun graph(context: Context): Musyx = context.applicationContext as Musyx
}
}
@@ -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.tv.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,46 @@
// What the credential store keeps. `toString` never prints the tokens.
package it.panov.musyx.tv.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.tv.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,58 @@
// Lyrics: synced (LRC) or plain text. Port of ym-api edit.rs.
package it.panov.musyx.tv.api
/** One line of lyrics; synced lyrics carry the moment it's sung. */
data class LyricLine(val atMs: Long?, val text: String)
data class Lyrics(val lines: List<LyricLine>, val synced: Boolean, val writers: List<String>) {
/** 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 }
}
companion object {
/** Plain text: one line per line, blank lines kept as paragraph breaks. */
fun fromText(text: String, writers: List<String>) =
Lyrics(text.lines().map { LyricLine(null, it.trimEnd()) }, synced = false, writers = writers)
/** LRC: `[mm:ss.xx] words`. Lines with several stamps repeat; metadata tags are dropped. */
fun fromLrc(lrc: String, writers: List<String>): 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)
}
/** `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,497 @@
// 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.tv.api
import it.panov.musyx.tv.ui.theme.CoverHues
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)
data class AlbumRef(val id: Long, val title: String)
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,
) {
/** `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 album = t.list("albums").firstNotNullOfOrNull { a ->
a.long("id")?.let { AlbumRef(it, a.str("title").orEmpty()) }
}
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
},
)
}
/** 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) } }
enum class AlbumKind {
Album, Single, Compilation, Podcast, Audiobook;
companion object {
fun from(metaType: String?, type: String?): AlbumKind = when {
metaType == "podcast" || type == "podcast" -> Podcast
type == "audiobook" || metaType == "audiobook" -> Audiobook
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.tv.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.tv.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.tv.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,565 @@
// An authenticated Yandex Music client. Port of ym-api's client.rs, with yamuse's wire
// behaviour inlined.
package it.panov.musyx.tv.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() })
}
/** 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.tv.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.tv.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.tv.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,73 @@
// Preferences kept between launches. Port of the desktop store.rs.
package it.panov.musyx.tv.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. Large is the original TV size. */
enum class FontSize(val key: String, val scale: Float) {
Small("small", 1.2f),
Medium("medium", 1.35f),
Large("large", 1.5f),
}
/** 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.Large,
val language: Locale = Locale.System,
)
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,
)
}
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)
}
}
/** 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.tv.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.tv.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.tv.api.CLIENT_HEADER
import it.panov.musyx.tv.api.Stream
import it.panov.musyx.tv.api.Track
import it.panov.musyx.tv.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.tv.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.tv.api.MY_WAVE
import it.panov.musyx.tv.api.Stream
import it.panov.musyx.tv.api.Track
import it.panov.musyx.tv.api.WaveSettings
import it.panov.musyx.tv.api.YmClient
import it.panov.musyx.tv.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) =
apply { core.play(tracks, start, if (shuffle) true else null) }
fun playNext(track: Track) = apply { core.playNext(track) }
fun append(track: Track) = apply { core.append(track) }
fun playWave(station: String) = apply { core.playWave(station) }
fun waveRestart() = apply { core.waveRestart() }
fun toggle() = apply { core.toggle() }
fun next() = apply { core.next() }
fun previous() = apply { core.previous() }
fun toggleShuffle() = apply { core.toggleShuffle() }
fun cycleRepeat() = apply { core.cycleRepeat() }
fun jumpTo(orderPos: Int) = apply { core.jumpTo(orderPos) }
fun seek(toMs: Long) = apply {
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 apply(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?) = apply { core.onLoaded(generation, durationMs) }
override fun position(generation: Long, positionMs: Long) {
core.onPosition(generation, positionMs)
this.positionMs = core.positionMs
}
override fun ended(generation: Long) = apply { core.onEnded(generation) }
override fun failed(generation: Long, reason: String) = apply { 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) }
apply { 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)
}
apply { 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,94 @@
// Background audio and remote control: the media session that the TV's Now Playing card,
// the remote's media keys and Google Assistant talk to.
package it.panov.musyx.tv.player
import android.app.PendingIntent
import android.content.Intent
import androidx.media3.common.Player
import androidx.annotation.OptIn
import androidx.media3.common.util.UnstableApi
import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
import it.panov.musyx.tv.MainActivity
import it.panov.musyx.tv.Musyx
@OptIn(UnstableApi::class)
class PlaybackService : MediaSessionService() {
private var session: MediaSession? = null
override fun onCreate() {
super.onCreate()
val open = PendingIntent.getActivity(
this,
0,
Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
session = MediaSession.Builder(this, Musyx.graph(this).state.playback.sessionPlayer)
.setSessionActivity(open)
.build()
}
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = session
override fun onTaskRemoved(rootIntent: Intent?) {
val player = session?.player
if (player == null || !player.playWhenReady || player.mediaItemCount == 0) stopSelf()
}
override fun onDestroy() {
// The player belongs to the app and outlives the service.
session?.release()
session = null
super.onDestroy()
}
}
/**
* 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) :
androidx.media3.common.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,476 @@
// 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.tv.player
import it.panov.musyx.tv.api.PlayReport
import it.panov.musyx.tv.api.Stream
import it.panov.musyx.tv.api.Track
import it.panov.musyx.tv.api.WaveBatch
import it.panov.musyx.tv.api.WaveEvent
import it.panov.musyx.tv.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()
}
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.tv.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,795 @@
// 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.tv.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.tv.R
import it.panov.musyx.tv.api.Account
import it.panov.musyx.tv.api.AlbumPage
import it.panov.musyx.tv.api.AlbumSummary
import it.panov.musyx.tv.api.ArtistPage
import it.panov.musyx.tv.api.ArtistSummary
import it.panov.musyx.tv.api.Auth
import it.panov.musyx.tv.api.Clip
import it.panov.musyx.tv.api.ContentLanguage
import it.panov.musyx.tv.api.Credentials
import it.panov.musyx.tv.api.Genre
import it.panov.musyx.tv.api.Home
import it.panov.musyx.tv.api.LibraryPlaylists
import it.panov.musyx.tv.api.LikedIds
import it.panov.musyx.tv.api.Lyrics
import it.panov.musyx.tv.api.MY_WAVE
import it.panov.musyx.tv.api.PlaylistId
import it.panov.musyx.tv.api.PlaylistPage
import it.panov.musyx.tv.api.PlaylistSummary
import it.panov.musyx.tv.api.Station
import it.panov.musyx.tv.api.Track
import it.panov.musyx.tv.api.WaveSettings
import it.panov.musyx.tv.api.YmClient
import it.panov.musyx.tv.api.YmError
import it.panov.musyx.tv.data.Appearance
import it.panov.musyx.tv.data.FontSize
import it.panov.musyx.tv.data.CredentialStore
import it.panov.musyx.tv.data.Locale
import it.panov.musyx.tv.data.Quality
import it.panov.musyx.tv.data.Settings
import it.panov.musyx.tv.data.SettingsStore
import it.panov.musyx.tv.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. */
fun wantLyrics(track: Track) {
if (lyrics.containsKey(track.id)) return
lyrics[track.id] = Loadable.Loading
load({ it.lyrics(track.id) }) { 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))
/** 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.tv.state
import androidx.annotation.PluralsRes
import androidx.annotation.StringRes
import androidx.compose.runtime.Immutable
import it.panov.musyx.tv.api.PlaylistId
import it.panov.musyx.tv.api.Track
import it.panov.musyx.tv.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,69 @@
// Every place the content area can show, and the back stack between them.
package it.panov.musyx.tv.state
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import it.panov.musyx.tv.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)
}
}
/** 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()
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.tv.state
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import it.panov.musyx.tv.api.SearchKind
import it.panov.musyx.tv.api.SearchResults
import it.panov.musyx.tv.api.YmClient
import it.panov.musyx.tv.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,131 @@
// 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.tv.state
import android.os.SystemClock
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import it.panov.musyx.tv.R
import it.panov.musyx.tv.api.Auth
import it.panov.musyx.tv.api.Credentials
import it.panov.musyx.tv.api.DeviceCode
import it.panov.musyx.tv.api.Poll
import it.panov.musyx.tv.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
},
)
/** `ABCD1234` → `ABCD 1234` for easier reading; codes with separators stay as they are. */
fun spaced(code: String): String =
if (code.length == 8 && code.all { it.isLetterOrDigit() && it.code < 128 }) "${code.take(4)} ${code.drop(4)}" else code
}
}
@@ -0,0 +1,121 @@
// Words and numbers as the interface shows them, in the interface language.
package it.panov.musyx.tv.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.platform.LocalResources
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import it.panov.musyx.tv.R
import it.panov.musyx.tv.api.AlbumKind
import it.panov.musyx.tv.api.AlbumSummary
import it.panov.musyx.tv.api.Clip
import it.panov.musyx.tv.api.PlaylistSummary
import it.panov.musyx.tv.api.Track
import it.panov.musyx.tv.state.UiText
@Composable
fun text(ui: UiText): String {
val res = LocalResources.current
fun resolve(t: UiText): String = when (t) {
is UiText.Raw -> t.text
is UiText.Res -> res.getString(t.id, *t.args.map { if (it is UiText) resolve(it) else it }.toTypedArray())
is UiText.Plural -> res.getQuantityString(t.id, t.count, *t.args.map { if (it is UiText) resolve(it) else it }.toTypedArray())
}
return resolve(ui)
}
@Composable
@ReadOnlyComposable
fun Track.artistsOrUnknown(): String = artistLine ?: stringResource(R.string.unknown_artist)
@Composable
@ReadOnlyComposable
fun Clip.artistsOrUnknown(): String = artistLine ?: stringResource(R.string.unknown_artist)
@Composable
@ReadOnlyComposable
fun kindLabel(kind: AlbumKind): String = stringResource(
when (kind) {
AlbumKind.Album -> R.string.kind_album
AlbumKind.Single -> R.string.kind_single
AlbumKind.Compilation -> R.string.kind_compilation
AlbumKind.Podcast -> R.string.kind_podcast
AlbumKind.Audiobook -> R.string.kind_audiobook
},
)
/** "Кино · 1988", the line under a card. Podcasts often list no artist: "Podcast · 2022". */
@Composable
@ReadOnlyComposable
fun AlbumSummary.subtitle(): String {
val who = artistLine ?: kindLabel(kind)
return if (year != null) "$who · $year" else who
}
@Composable
@ReadOnlyComposable
fun PlaylistSummary.subtitle(): String {
val count = tracksWord(trackCount)
return if (ownerName.isEmpty()) count else "$ownerName · $count"
}
/** "1 track", "12 tracks". */
@Composable
@ReadOnlyComposable
fun tracksWord(n: Int): String = pluralStringResource(R.plurals.tracks, n, n)
/** "47 min" or "1 h 12 min". */
@Composable
@ReadOnlyComposable
fun durationWords(ms: Long): String {
val mins = (ms / 60_000).toInt()
return if (mins >= 60) stringResource(R.string.duration_h_min, mins / 60, mins % 60)
else stringResource(R.string.duration_min, mins)
}
/** `m:ss`, or `h:mm:ss` for podcast-length items. */
fun clock(ms: Long): String {
val s = (ms.coerceAtLeast(0) / 1000)
val (h, m, sec) = Triple(s / 3600, (s / 60) % 60, s % 60)
return if (h > 0) "%d:%02d:%02d".format(h, m, sec) else "%d:%02d".format(m, sec)
}
/** "4.1M", "830K", "912"; in Russian "4,1 млн", "830 тыс.", "912". */
fun compact(n: Long, russian: Boolean): String {
val (value, en, ru) = when {
n >= 1_000_000 -> Triple("%.1f".format(java.util.Locale.US, n / 1e6), "M", " млн")
n >= 10_000 -> Triple((n / 1000).toString(), "K", " тыс.")
n >= 1_000 -> Triple("%.1f".format(java.util.Locale.US, n / 1e3), "K", " тыс.")
else -> return n.toString()
}
val v = value.removeSuffix(".0")
return if (russian) v.replace('.', ',') + ru else v + en
}
@Composable
@ReadOnlyComposable
fun isRussian(): Boolean = stringResource(R.string.lang_code) == "ru"
/** A compact count and its noun: "4.1M listeners a month", "3 лайка". */
@Composable
@ReadOnlyComposable
fun counted(n: Long, plural: Int): String {
// An abbreviated number ("4,1 млн") reads as many.
val form = if (n >= 1_000) 5 else n.toInt().coerceAtLeast(0)
return pluralStringResource(plural, form, compact(n, isRussian()))
}
/** `2027-01-05T00:00:00+03:00` → `5 January 2027` (`5 января 2027`). */
@Composable
@ReadOnlyComposable
fun humanDate(iso: String): String? {
if (iso.length < 10) return null
val parts = iso.substring(0, 10).split('-')
if (parts.size != 3) return null
val year = parts[0].toIntOrNull() ?: return null
val month = parts[1].toIntOrNull()?.takeIf { it in 1..12 } ?: return null
val day = parts[2].toIntOrNull() ?: return null
val months = LocalResources.current.getStringArray(R.array.months_genitive)
return "$day ${months[month - 1]} $year"
}
@@ -0,0 +1,249 @@
// The app's frame: the full-screen sign-in states, and once signed in the navigation
// drawer, the routed content, the mini player, dialogs and toasts.
package it.panov.musyx.tv.ui
import androidx.activity.compose.BackHandler
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Border
import androidx.tv.material3.Icon
import androidx.tv.material3.LocalContentColor
import androidx.tv.material3.NavigationDrawer
import androidx.tv.material3.NavigationDrawerItem
import androidx.tv.material3.NavigationDrawerItemDefaults
import androidx.tv.material3.NavigationDrawerScope
import androidx.tv.material3.Text
import it.panov.musyx.tv.R
import it.panov.musyx.tv.state.AppState
import it.panov.musyx.tv.state.Route
import it.panov.musyx.tv.state.Session
import it.panov.musyx.tv.ui.components.FocusEntry
import it.panov.musyx.tv.ui.screens.AlbumScreen
import it.panov.musyx.tv.ui.screens.ArtistScreen
import it.panov.musyx.tv.ui.screens.ChartScreen
import it.panov.musyx.tv.ui.screens.CollectionScreen
import it.panov.musyx.tv.ui.screens.GenreScreen
import it.panov.musyx.tv.ui.screens.HoldingScreen
import it.panov.musyx.tv.ui.screens.HomeScreen
import it.panov.musyx.tv.ui.screens.MiniPlayer
import it.panov.musyx.tv.ui.screens.NowPlayingScreen
import it.panov.musyx.tv.ui.screens.PlaylistScreen
import it.panov.musyx.tv.ui.screens.PodcastsScreen
import it.panov.musyx.tv.ui.screens.SearchScreen
import it.panov.musyx.tv.ui.screens.SettingsScreen
import it.panov.musyx.tv.ui.screens.SheetHost
import it.panov.musyx.tv.ui.screens.SignInScreen
import it.panov.musyx.tv.ui.screens.ToastHost
import it.panov.musyx.tv.ui.screens.UnreachableScreen
import it.panov.musyx.tv.ui.screens.WaveScreen
import it.panov.musyx.tv.ui.theme.MusyxTheme
private const val WORDMARK = "musyx"
@Composable
fun MusyxApp(state: AppState, onExit: () -> Unit) {
val c = MusyxTheme.colors
Box(Modifier.fillMaxSize().background(c.bg)) {
when (val s = state.session) {
Session.Restoring -> HoldingScreen(stringResource(R.string.session_checking))
is Session.Connecting -> HoldingScreen(stringResource(R.string.session_signing_in))
Session.Unreachable -> UnreachableScreen(state)
is Session.SignedOut -> SignInScreen(s.signIn)
is Session.SignedIn -> Shell(state, onExit)
}
ToastHost(state)
}
}
/** A drawer destination. */
private class NavItem(val route: Route, @param:StringRes val label: Int, @param:DrawableRes val icon: Int)
private val NAV = listOf(
NavItem(Route.Home, R.string.nav_home, R.drawable.ic_house),
NavItem(Route.Wave, R.string.nav_wave, R.drawable.ic_audio_lines),
NavItem(Route.Search, R.string.nav_search, R.drawable.ic_search),
NavItem(Route.Collection, R.string.nav_collection, R.drawable.ic_library),
NavItem(Route.Podcasts, R.string.nav_podcasts, R.drawable.ic_podcast),
)
private val SETTINGS = NavItem(Route.Settings, R.string.nav_settings, R.drawable.ic_settings)
/** The drawer item a route belongs to: detail pages light up where they're usually reached from. */
private fun Route.section(): Route = when (this) {
Route.Chart, is Route.Album, is Route.Artist, is Route.Playlist -> Route.Home
is Route.Genre -> Route.Search
else -> this
}
@Composable
private fun Shell(state: AppState, onExit: () -> Unit) {
val c = MusyxTheme.colors
val route = state.nav.current
val entry = remember { FocusEntry() }
val pages = rememberSaveableStateHolder()
// Each newly shown screen puts focus on its first control.
LaunchedEffect(route) { entry.pending = true }
BackHandler { if (!state.back()) onExit() }
NavigationDrawer(
drawerContent = { Drawer(current = route.section(), onNavigate = state::navigate) },
modifier = Modifier.background(c.bg),
) {
Column(Modifier.fillMaxSize().background(c.bg)) {
Box(Modifier.weight(1f).fillMaxWidth()) {
pages.SaveableStateProvider(route.toString()) {
Page(state, route, entry)
}
}
if (route != Route.NowPlaying && state.playback.state.hasTrack) MiniPlayer(state)
}
}
SheetHost(state)
}
@Composable
private fun Page(state: AppState, route: Route, entry: FocusEntry) {
when (route) {
Route.Home -> HomeScreen(state, entry)
Route.Wave -> WaveScreen(state, entry)
Route.Search -> SearchScreen(state, entry)
Route.Collection -> CollectionScreen(state, entry)
Route.Podcasts -> PodcastsScreen(state, entry)
Route.Settings -> SettingsScreen(state, entry)
Route.NowPlaying -> NowPlayingScreen(state, entry)
Route.Chart -> ChartScreen(state, entry)
is Route.Genre -> GenreScreen(state, route.index, entry)
is Route.Album -> AlbumScreen(state, route, entry)
is Route.Artist -> ArtistScreen(state, route, entry)
is Route.Playlist -> PlaylistScreen(state, route, entry)
}
}
@Composable
private fun NavigationDrawerScope.Drawer(current: Route, onNavigate: (Route) -> Unit) {
val c = MusyxTheme.colors
val space = MusyxTheme.space
val selectedItem = remember { FocusRequester() }
Column(
modifier = Modifier
.fillMaxHeight()
.background(c.panel)
.padding(horizontal = space.m, vertical = space.safeY)
.selectableGroup()
// Entering the drawer lands on the current destination, not the nearest item.
.focusProperties { onEnter = { selectedItem.requestFocus() } }
.focusGroup(),
verticalArrangement = Arrangement.spacedBy(space.xxs),
) {
Wordmark(expanded = hasFocus, modifier = Modifier.padding(start = space.s10, bottom = space.xl))
NAV.forEach { DrawerItem(it, current, selectedItem, onNavigate) }
Spacer(Modifier.weight(1f))
DrawerItem(SETTINGS, current, selectedItem, onNavigate)
}
}
@Composable
private fun NavigationDrawerScope.DrawerItem(item: NavItem, current: Route, selectedItem: FocusRequester, onNavigate: (Route) -> Unit) {
val c = MusyxTheme.colors
val shape = RoundedCornerShape(MusyxTheme.radius.control)
val selected = item.route == current
val ring = Border(BorderStroke(2.dp, c.accent), shape = shape)
NavigationDrawerItem(
selected = selected,
onClick = { onNavigate(item.route) },
modifier = if (selected) Modifier.focusRequester(selectedItem) else Modifier,
leadingContent = {
Icon(
painter = painterResource(item.icon),
contentDescription = null,
tint = if (selected) c.accent else LocalContentColor.current,
)
},
shape = NavigationDrawerItemDefaults.shape(shape),
colors = NavigationDrawerItemDefaults.colors(
containerColor = Color.Transparent,
contentColor = c.muted,
inactiveContentColor = c.muted,
focusedContainerColor = c.raised,
focusedContentColor = c.fg,
pressedContainerColor = c.raised,
pressedContentColor = c.fg,
selectedContainerColor = c.raised,
selectedContentColor = c.fg,
focusedSelectedContainerColor = c.raised,
focusedSelectedContentColor = c.fg,
pressedSelectedContainerColor = c.raised,
pressedSelectedContentColor = c.fg,
),
border = NavigationDrawerItemDefaults.border(
focusedBorder = ring,
focusedSelectedBorder = ring,
pressedBorder = ring,
pressedSelectedBorder = ring,
),
glow = NavigationDrawerItemDefaults.glow(),
) {
Text(stringResource(item.label), style = MusyxTheme.type.bodyMedium, maxLines = 1)
}
}
/** `musyx` and the amber dot; only the dot while the drawer is collapsed to its rail. */
@Composable
fun Wordmark(modifier: Modifier = Modifier, expanded: Boolean = true) {
val c = MusyxTheme.colors
val scale = MusyxTheme.type.scale
val dot = (7 * scale).dp
Row(modifier = modifier) {
if (expanded) {
Text(WORDMARK, style = MusyxTheme.type.wordmark, color = c.fg, modifier = Modifier.alignByBaseline())
Spacer(Modifier.width((3 * scale).dp))
}
// The dot sits on the baseline, as in the desktop sidebar.
Box(
Modifier
.alignBy { it.measuredHeight }
.size(dot)
.background(c.accent, CircleShape),
)
}
}
/** Fades content in and out, for toasts and the like. */
@Composable
fun Fade(visible: Boolean, modifier: Modifier = Modifier, content: @Composable () -> Unit) {
AnimatedVisibility(visible, modifier, enter = fadeIn(), exit = fadeOut()) { content() }
}
@@ -0,0 +1,265 @@
// Buttons, chips, tabs and the focus plumbing every screen uses. Desktop hover becomes TV
// focus: the raised fill, plus the mockup's amber focus ring.
package it.panov.musyx.tv.ui.components
import androidx.annotation.DrawableRes
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Border
import androidx.tv.material3.ClickableSurfaceDefaults
import androidx.tv.material3.Icon
import androidx.tv.material3.LocalContentColor
import androidx.tv.material3.Surface
import androidx.tv.material3.Text
import it.panov.musyx.tv.ui.theme.MusyxTheme
import it.panov.musyx.tv.ui.theme.TV_TYPE_SCALE
/** Icons are 18 px on the desktop; on TV they grow with the type. */
val IconSize: Dp = (18 * TV_TYPE_SCALE).dp
/**
* Where focus lands when a screen opens. The shell marks it pending on navigation; the
* screen tags its first control with [entry], which takes focus as soon as it's laid out,
* so content that arrives late still gets it.
*/
@Stable
class FocusEntry {
val requester = FocusRequester()
var pending by mutableStateOf(false)
}
fun Modifier.entry(entry: FocusEntry?): Modifier {
if (entry == null) return this
return focusRequester(entry.requester).onGloballyPositioned {
if (entry.pending && runCatching { entry.requester.requestFocus() }.isSuccess) entry.pending = false
}
}
/** A focusable area: transparent at rest, raised with an amber ring when focused. */
@Composable
fun Focusable(
onClick: () -> Unit,
modifier: Modifier = Modifier,
onLongClick: (() -> Unit)? = null,
enabled: Boolean = true,
shape: Shape = RoundedCornerShape(MusyxTheme.radius.control),
container: Color = Color.Transparent,
focusedContainer: Color = MusyxTheme.colors.raised,
contentColor: Color = MusyxTheme.colors.fg,
focusedContentColor: Color = contentColor,
scale: Float = 1f,
ring: Boolean = true,
ringColor: Color = MusyxTheme.colors.accent,
content: @Composable BoxScope.() -> Unit,
) {
val c = MusyxTheme.colors
Surface(
onClick = onClick,
onLongClick = onLongClick,
enabled = enabled,
modifier = modifier,
shape = ClickableSurfaceDefaults.shape(shape),
colors = ClickableSurfaceDefaults.colors(
containerColor = container,
contentColor = contentColor,
focusedContainerColor = focusedContainer,
focusedContentColor = focusedContentColor,
pressedContainerColor = focusedContainer,
pressedContentColor = focusedContentColor,
disabledContainerColor = container,
disabledContentColor = c.muted.copy(alpha = 0.5f),
),
scale = ClickableSurfaceDefaults.scale(focusedScale = scale),
border = if (ring) {
ClickableSurfaceDefaults.border(
focusedBorder = Border(BorderStroke(2.dp, ringColor), shape = shape),
pressedBorder = Border(BorderStroke(2.dp, ringColor), shape = shape),
)
} else {
ClickableSurfaceDefaults.border()
},
glow = ClickableSurfaceDefaults.glow(),
content = content,
)
}
@Composable
fun MusyxIcon(@DrawableRes icon: Int, modifier: Modifier = Modifier, tint: Color = LocalContentColor.current, size: Dp = IconSize) {
Icon(painterResource(icon), contentDescription = null, tint = tint, modifier = modifier.size(size))
}
/** The amber pill: Play, Get sign-in code, Try again. */
@Composable
fun PrimaryButton(
label: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
@DrawableRes icon: Int? = null,
enabled: Boolean = true,
) {
val c = MusyxTheme.colors
val shape = RoundedCornerShape(MusyxTheme.radius.pill)
Focusable(
onClick = onClick,
enabled = enabled,
modifier = modifier,
shape = shape,
container = c.accent,
focusedContainer = c.accent,
contentColor = c.accentInk,
scale = 1.06f,
// Amber on amber wouldn't show; the ring is the text colour instead.
ringColor = c.fg,
) {
ButtonContent(label, icon, PaddingValues(horizontal = 26.dp, vertical = 14.dp))
}
}
/** The outlined pill: Shuffle, Sign out, Rename. */
@Composable
fun GhostButton(
label: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
@DrawableRes icon: Int? = null,
enabled: Boolean = true,
danger: Boolean = false,
) {
val c = MusyxTheme.colors
val shape = RoundedCornerShape(MusyxTheme.radius.pill)
Focusable(
onClick = onClick,
enabled = enabled,
modifier = modifier,
shape = shape,
container = if (danger) c.like else c.raised,
focusedContainer = if (danger) c.like else c.line,
contentColor = if (danger) Color.White else c.fg,
scale = 1.05f,
) {
ButtonContent(label, icon, PaddingValues(horizontal = 22.dp, vertical = 12.dp))
}
}
@Composable
private fun ButtonContent(label: String, @DrawableRes icon: Int?, padding: PaddingValues) {
Row(
Modifier.padding(padding),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
if (icon != null) MusyxIcon(icon)
Text(label, style = MusyxTheme.type.bodyMedium, maxLines = 1)
}
}
/** A round icon-only button: like, more, transport. `on` tints it amber. */
@Composable
fun IconButton(
@DrawableRes icon: Int,
onClick: () -> Unit,
modifier: Modifier = Modifier,
tint: Color = MusyxTheme.colors.muted,
focusedTint: Color = MusyxTheme.colors.fg,
size: Dp = IconSize,
padding: Dp = 10.dp,
enabled: Boolean = true,
) {
Focusable(
onClick = onClick,
enabled = enabled,
modifier = modifier,
shape = RoundedCornerShape(MusyxTheme.radius.pill),
contentColor = tint,
focusedContentColor = focusedTint,
scale = 1.1f,
) {
MusyxIcon(icon, size = size, modifier = Modifier.padding(padding))
}
}
/** A choice among a few: quality, appearance, wave mood. */
@Composable
fun Chip(label: String, on: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true) {
val c = MusyxTheme.colors
Focusable(
onClick = onClick,
enabled = enabled,
modifier = modifier,
shape = RoundedCornerShape(MusyxTheme.radius.pill),
container = if (on) c.accent else c.raised,
focusedContainer = if (on) c.accent else c.line,
contentColor = if (on) c.accentInk else c.fg,
scale = 1.05f,
) {
Text(label, style = MusyxTheme.type.meta, maxLines = 1, modifier = Modifier.padding(horizontal = 18.dp, vertical = 10.dp))
}
}
/** A tab with an amber underline when selected, and an optional count beside it. */
@Composable
fun Tab(label: String, on: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, count: String? = null) {
val c = MusyxTheme.colors
Focusable(onClick = onClick, modifier = modifier, contentColor = if (on) c.fg else c.muted, focusedContentColor = c.fg) {
// As wide as the label, so the underline doesn't stretch the tab across the row.
Column(Modifier.width(IntrinsicSize.Max).padding(horizontal = 14.dp, vertical = 8.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(label, style = MusyxTheme.type.bodyMedium, maxLines = 1)
if (count != null) Text(count, style = MusyxTheme.type.small, color = c.muted, maxLines = 1)
}
Box(
Modifier
.padding(top = 8.dp)
.height(3.dp)
.fillMaxWidth()
.background(if (on) c.accent else Color.Transparent, RoundedCornerShape(2.dp)),
)
}
}
}
@Composable
fun TabBar(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
Row(modifier, horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
content()
}
}
/** A thin rule between sections. */
@Composable
fun Divider(modifier: Modifier = Modifier) {
Box(modifier.fillMaxWidth().height(1.dp).background(MusyxTheme.colors.line))
}
@Composable
fun Spacer(width: Dp = 0.dp, height: Dp = 0.dp) {
androidx.compose.foundation.layout.Spacer(Modifier.width(width).height(height))
}
@@ -0,0 +1,181 @@
// Covers, cards, rows of cards and grids.
package it.panov.musyx.tv.ui.components
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Border
import androidx.tv.material3.Card
import androidx.tv.material3.CardDefaults
import androidx.tv.material3.Text
import coil3.compose.AsyncImage
import it.panov.musyx.tv.R
import it.panov.musyx.tv.ui.theme.CoverPlaceholder
import it.panov.musyx.tv.ui.theme.MusyxTheme
/** Cover sizes asked of the image server. */
const val COVER_SMALL = 100
const val COVER_LARGE = 400
/** Desktop cards are 168 px wide; on TV they keep that in dp and grow on focus. */
val CardWidth = 168.dp
private const val FOCUSED_SCALE = 1.08f
/** A cover image, with the two-hue placeholder while it loads or when there's none. */
@Composable
fun Cover(url: String?, hues: Pair<Float, Float>, modifier: Modifier = Modifier, shape: Shape = RoundedCornerShape(MusyxTheme.radius.smallCover)) {
Box(modifier.clip(shape)) {
CoverPlaceholder(hues, Modifier.fillMaxSize())
if (url != null) {
AsyncImage(
model = url,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
)
}
}
}
/** What a card shows. */
class CardData(
val key: Any,
val title: String,
val subtitle: String,
val cover: String?,
val hues: Pair<Float, Float>,
val round: Boolean = false,
val liked: Boolean? = null,
val onClick: () -> Unit,
val onLongClick: (() -> Unit)? = null,
)
@Composable
fun MediaCard(card: CardData, modifier: Modifier = Modifier, width: Dp = CardWidth) {
val c = MusyxTheme.colors
val shape = if (card.round) CircleShape else RoundedCornerShape(MusyxTheme.radius.cover)
Column(Modifier.width(width), verticalArrangement = Arrangement.spacedBy(9.dp)) {
Card(
onClick = card.onClick,
onLongClick = card.onLongClick,
modifier = modifier.fillMaxWidth().aspectRatio(1f),
shape = CardDefaults.shape(shape),
colors = CardDefaults.colors(containerColor = c.raised),
scale = CardDefaults.scale(focusedScale = FOCUSED_SCALE),
border = CardDefaults.border(focusedBorder = Border(BorderStroke(3.dp, c.accent), inset = 0.dp, shape = shape)),
glow = CardDefaults.glow(),
) {
Box(Modifier.fillMaxSize()) {
Cover(card.cover, card.hues, Modifier.fillMaxSize(), shape)
if (card.liked == true) {
MusyxIcon(
R.drawable.ic_heart_fill,
tint = c.like,
modifier = Modifier.align(Alignment.TopEnd).padding(10.dp),
)
}
}
}
Column(Modifier.padding(top = MusyxTheme.space.xs)) {
Text(card.title, style = MusyxTheme.type.bodyMedium, color = c.fg, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(card.subtitle, style = MusyxTheme.type.meta, color = c.muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
/** A heading over a horizontal row of cards, the TV way to show a shelf. */
@Composable
fun CardShelf(title: String?, cards: List<CardData>, modifier: Modifier = Modifier, entry: FocusEntry? = null) {
val space = MusyxTheme.space
Column(modifier, verticalArrangement = Arrangement.spacedBy(space.s)) {
if (title != null) SectionTitle(title, Modifier.padding(horizontal = space.safeX))
LazyRow(
horizontalArrangement = Arrangement.spacedBy(space.xl),
// Room for the focused card to grow without being clipped by the row.
contentPadding = PaddingValues(vertical = space.m, horizontal = space.safeX),
) {
itemsIndexed(cards, key = { _, it -> it.key }) { i, card ->
MediaCard(card, if (i == 0) Modifier.entry(entry) else Modifier)
}
}
}
}
/** Cards wrapped into as many columns as fit, for lists that are the whole page. */
@Composable
fun CardGrid(cards: List<CardData>, entry: FocusEntry? = null) {
val space = MusyxTheme.space
BoxWithConstraints(Modifier.padding(horizontal = space.safeX).padding(top = space.m)) {
val columns = ((maxWidth + space.xl) / (CardWidth + space.xl)).toInt().coerceAtLeast(1)
GridRows(cards, columns, entry)
}
}
@Composable
private fun GridRows(cards: List<CardData>, columns: Int, entry: FocusEntry?) {
val space = MusyxTheme.space
Column(verticalArrangement = Arrangement.spacedBy(space.xl)) {
cards.chunked(columns).forEachIndexed { r, row ->
Row(horizontalArrangement = Arrangement.spacedBy(space.xl)) {
row.forEachIndexed { i, card ->
MediaCard(card, if (r == 0 && i == 0) Modifier.entry(entry) else Modifier)
}
}
}
}
}
@Composable
fun SectionTitle(title: String, modifier: Modifier = Modifier, trailing: (@Composable () -> Unit)? = null) {
Row(modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(title, style = MusyxTheme.type.section, color = MusyxTheme.colors.fg, modifier = Modifier.weight(1f))
trailing?.invoke()
}
}
@Composable
fun ScreenTitle(title: String, modifier: Modifier = Modifier) {
Text(
title,
style = MusyxTheme.type.displayS,
color = MusyxTheme.colors.fg,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = modifier.padding(horizontal = MusyxTheme.space.safeX),
)
}
/** A small square cover for rows and the mini player. */
@Composable
fun Thumb(url: String?, hues: Pair<Float, Float>, size: Dp, round: Boolean = false) {
Cover(
url,
hues,
Modifier.size(size).height(size),
if (round) CircleShape else RoundedCornerShape(MusyxTheme.radius.smallCover),
)
}
@@ -0,0 +1,46 @@
// Loading text, failures with a retry button, empty states.
package it.panov.musyx.tv.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Text
import it.panov.musyx.tv.R
import it.panov.musyx.tv.api.YmError
import it.panov.musyx.tv.ui.theme.MusyxTheme
/** Muted running text inside the safe margin. */
@Composable
fun Note(text: String, modifier: Modifier = Modifier) {
Text(
text,
style = MusyxTheme.type.body,
color = MusyxTheme.colors.muted,
modifier = modifier.padding(horizontal = MusyxTheme.space.safeX).widthIn(max = 720.dp),
)
}
/**
* A failure with a retry button. `what` is the object of "Couldn't load …", such as
* "your albums", already in the interface language.
*/
@Composable
fun Failure(error: YmError, what: String, onRetry: () -> Unit, entry: FocusEntry? = null) {
Column(
Modifier.padding(horizontal = MusyxTheme.space.safeX),
verticalArrangement = Arrangement.spacedBy(MusyxTheme.space.l),
) {
Text(
if (error is YmError.Network) stringResource(R.string.load_failed_network, what) else stringResource(R.string.load_failed, what),
style = MusyxTheme.type.body,
color = MusyxTheme.colors.muted,
modifier = Modifier.widthIn(max = 720.dp),
)
PrimaryButton(stringResource(R.string.action_try_again), onClick = onRetry, modifier = Modifier.entry(entry))
}
}
@@ -0,0 +1,191 @@
// Track rows and the play bar above lists. A row plays on select and opens its menu on a
// long press; the heart and "more" sit to its right for D-pad users.
package it.panov.musyx.tv.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Text
import it.panov.musyx.tv.R
import it.panov.musyx.tv.api.PlaylistId
import it.panov.musyx.tv.api.Track
import it.panov.musyx.tv.state.AppState
import it.panov.musyx.tv.state.PlaylistSlot
import it.panov.musyx.tv.state.Sheet
import it.panov.musyx.tv.ui.artistsOrUnknown
import it.panov.musyx.tv.ui.clock
import it.panov.musyx.tv.ui.theme.MusyxTheme
import it.panov.musyx.tv.ui.theme.tabular
/** Which columns a list shows. Album pages drop the cover and album. */
data class Columns(val cover: Boolean = true, val album: Boolean = true) {
companion object {
val FULL = Columns()
val ALBUM_PAGE = Columns(cover = false, album = false)
}
}
/**
* The rows of a track list, as items of the page's lazy column. Selecting a row plays
* the list from it; `shifts` adds chart movement; `playlist` adds edit actions.
*/
fun LazyListScope.trackItems(
state: AppState,
tracks: List<Track>,
columns: Columns = Columns.FULL,
shifts: List<Int>? = null,
playlist: PlaylistId? = null,
/** Server indices of `tracks` in `playlist`. */
positions: List<Int>? = null,
entry: FocusEntry? = null,
keyPrefix: String = "t",
) {
itemsIndexed(tracks, key = { i, t -> "$keyPrefix:$i:${t.id}" }) { i, track ->
TrackRow(
index = i,
track = track,
playing = state.playback.state.track?.id == track.id,
liked = state.liked.contains(track.id),
columns = columns,
shift = shifts?.getOrNull(i),
onPlay = { state.playTracks(tracks, i) },
onLike = { state.likeTrack(track, !state.liked.contains(track.id)) },
onMore = {
val at = positions ?: tracks.indices.toList()
state.openSheet(Sheet.TrackMenu(track, playlist?.let { PlaylistSlot(it, at[i], at.getOrNull(i - 1), at.getOrNull(i + 1)) }))
},
modifier = if (i == 0) Modifier.entry(entry) else Modifier,
)
}
}
@Composable
fun TrackRow(
index: Int,
track: Track,
playing: Boolean,
liked: Boolean,
columns: Columns,
shift: Int?,
onPlay: () -> Unit,
onLike: () -> Unit,
onMore: () -> Unit,
modifier: Modifier = Modifier,
) {
val c = MusyxTheme.colors
val space = MusyxTheme.space
val titleColor = when {
!track.available -> c.muted
playing -> c.accent
else -> c.fg
}
Row(
Modifier.fillMaxWidth().padding(horizontal = space.safeX - 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
Focusable(
onClick = { if (track.available) onPlay() },
onLongClick = onMore,
modifier = modifier.weight(1f),
) {
Row(
Modifier.padding(horizontal = 12.dp).height(MusyxTheme.shell.trackRow * 1.3f),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(14.dp),
) {
Box(Modifier.width(40.dp), contentAlignment = Alignment.Center) {
if (playing) {
MusyxIcon(R.drawable.ic_audio_lines, tint = c.accent)
} else {
Text("${index + 1}", style = MusyxTheme.type.meta.tabular(), color = c.muted)
}
}
if (shift != null) ShiftMarker(shift)
if (columns.cover) Thumb(track.coverUrl(COVER_SMALL), track.hues, 48.dp)
Column(Modifier.weight(22f)) {
Text(track.fullTitle, style = MusyxTheme.type.bodyMedium, color = titleColor, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(track.artistsOrUnknown(), style = MusyxTheme.type.meta, color = c.muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (columns.album) {
Text(
track.album?.title.orEmpty(),
style = MusyxTheme.type.meta,
color = c.muted,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(14f),
)
}
Text(
clock(track.durationMs),
style = MusyxTheme.type.meta.tabular(),
color = c.muted,
textAlign = TextAlign.End,
modifier = Modifier.width(64.dp),
)
}
}
IconButton(
if (liked) R.drawable.ic_heart_fill else R.drawable.ic_heart,
onClick = onLike,
tint = if (liked) c.like else c.muted.copy(alpha = 0.5f),
focusedTint = if (liked) c.like else c.fg,
)
IconButton(R.drawable.ic_ellipsis, onClick = onMore)
}
}
/** The arrow beside a chart position. */
@Composable
fun ShiftMarker(shift: Int) {
val c = MusyxTheme.colors
val (glyph, colour) = when {
shift > 0 -> "▲" to c.ok
shift < 0 -> "▼" to c.like
else -> "–" to c.muted
}
Text(glyph, style = MusyxTheme.type.small, color = colour, modifier = Modifier.width(18.dp), textAlign = TextAlign.Center)
}
/** Play and Shuffle with a summary on the left. Shared by every page with tracks. */
@Composable
fun PlayBar(state: AppState, tracks: List<Track>, modifier: Modifier = Modifier, summary: String = "", entry: FocusEntry? = null) {
val space = MusyxTheme.space
Row(
modifier.fillMaxWidth().padding(horizontal = space.safeX),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(space.m),
) {
PrimaryButton(
stringResource(R.string.action_play),
onClick = { state.playTracks(tracks, 0) },
icon = R.drawable.ic_play_fill,
enabled = tracks.isNotEmpty(),
modifier = Modifier.entry(entry),
)
GhostButton(
stringResource(R.string.action_shuffle),
onClick = { state.playTracks(tracks, 0, shuffle = true) },
icon = R.drawable.ic_shuffle,
enabled = tracks.isNotEmpty(),
)
if (summary.isNotEmpty()) {
Text(summary, style = MusyxTheme.type.meta, color = MusyxTheme.colors.muted, modifier = Modifier.padding(start = space.s))
}
}
}
@@ -0,0 +1,210 @@
// Pieces several screens share: the page column, card builders, genre tiles, loading states.
package it.panov.musyx.tv.ui.screens
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import androidx.annotation.StringRes
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.core.net.toUri
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Text
import it.panov.musyx.tv.R
import it.panov.musyx.tv.api.AlbumSummary
import it.panov.musyx.tv.api.ArtistSummary
import it.panov.musyx.tv.api.Clip
import it.panov.musyx.tv.api.Genre
import it.panov.musyx.tv.api.PlaylistSummary
import it.panov.musyx.tv.state.AppState
import it.panov.musyx.tv.state.Loadable
import it.panov.musyx.tv.state.Route
import it.panov.musyx.tv.state.UiText
import it.panov.musyx.tv.ui.artistsOrUnknown
import it.panov.musyx.tv.ui.clock
import it.panov.musyx.tv.ui.components.COVER_LARGE
import it.panov.musyx.tv.ui.components.CardData
import it.panov.musyx.tv.ui.components.CardShelf
import it.panov.musyx.tv.ui.components.CardWidth
import it.panov.musyx.tv.ui.components.Failure
import it.panov.musyx.tv.ui.components.FocusEntry
import it.panov.musyx.tv.ui.components.Focusable
import it.panov.musyx.tv.ui.components.Note
import it.panov.musyx.tv.ui.components.SectionTitle
import it.panov.musyx.tv.ui.components.entry
import it.panov.musyx.tv.ui.subtitle
import it.panov.musyx.tv.ui.theme.MusyxTheme
import it.panov.musyx.tv.ui.theme.mix
/** A scrolling page: sections stacked with the section gap, inside the TV's safe area. */
@Composable
fun PageColumn(content: LazyListScope.() -> Unit) {
val space = MusyxTheme.space
LazyColumn(
state = rememberLazyListState(),
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(top = space.safeY, bottom = space.safeY * 2),
verticalArrangement = Arrangement.spacedBy(space.s),
content = content,
)
}
/** Space between two sections of a page. */
fun LazyListScope.gap(key: Any) {
item(key = key) { androidx.compose.foundation.layout.Spacer(Modifier.height(MusyxTheme.space.section - MusyxTheme.space.s)) }
}
@Composable
fun albumCard(state: AppState, a: AlbumSummary) = CardData(
key = "al${a.id}",
title = a.fullTitle,
subtitle = a.subtitle(),
cover = a.coverUrl(COVER_LARGE),
hues = a.hues,
liked = a.id in state.likes.albums,
onClick = { state.navigate(Route.Album(a.id)) },
)
@Composable
fun artistCard(state: AppState, a: ArtistSummary) = CardData(
key = "ar${a.id}",
title = a.name,
subtitle = a.genres.firstOrNull() ?: stringResource(R.string.kind_artist),
cover = a.coverUrl(COVER_LARGE),
hues = a.hues,
round = true,
onClick = { state.navigate(Route.Artist(a.id)) },
)
@Composable
fun playlistCard(state: AppState, p: PlaylistSummary, subtitle: String? = null) = CardData(
key = "pl${p.id.key}",
title = p.title,
subtitle = subtitle ?: p.subtitle(),
cover = p.coverUrl(COVER_LARGE),
hues = p.hues,
onClick = { state.navigate(Route.Playlist(p.id)) },
)
/** A music video. It opens in the browser; a long press likes or unlikes it. */
@Composable
fun clipCard(state: AppState, clip: Clip): CardData {
val context = LocalContext.current
val liked = clip.id in state.likes.clips
return CardData(
key = "cl${clip.id}",
title = clip.title,
subtitle = "${clip.artistsOrUnknown()} · ${clock(clip.durationSec * 1000)}",
cover = clip.coverUrl(COVER_LARGE),
hues = clip.hues,
liked = liked,
onClick = { openClip(context, state, clip) },
onLongClick = { state.likeClip(clip, !liked) },
)
}
private fun openClip(context: Context, state: AppState, clip: Clip) {
try {
context.startActivity(Intent(Intent.ACTION_VIEW, clip.url.toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
state.toast(UiText.Res(R.string.toast_opening_clip, clip.title))
} catch (_: ActivityNotFoundException) {
state.toast(UiText.Res(R.string.toast_no_browser))
}
}
/**
* What to show for a [Loadable] list section: nothing yet, a note while loading, a retry on
* failure, or `loaded` with the value.
*/
fun <T> LazyListScope.loadable(
key: String,
value: Loadable<T>,
loading: @Composable () -> String,
what: @Composable () -> String,
retry: () -> Unit,
entry: FocusEntry?,
loaded: LazyListScope.(T) -> Unit,
) {
when (value) {
is Loadable.Loaded -> loaded(value.value)
is Loadable.Failed -> item(key = "$key-failed") { Failure(value.error, what(), retry, entry) }
else -> item(key = "$key-loading") { Note(loading()) }
}
}
/** Genre tiles in a shelf; sub-genres are reached from their parent's page. */
fun LazyListScope.genreShelf(state: AppState, entry: FocusEntry?) {
item(key = "genres-title") { SectionTitle(stringResource(R.string.section_genres), Modifier.padding(horizontal = MusyxTheme.space.safeX)) }
loadable(
"genres",
state.genres,
loading = { stringResource(R.string.loading_genres) },
what = { stringResource(R.string.what_genres) },
retry = state::loadGenres,
entry = entry,
) { list ->
val top = list.withIndex().filter { (_, g) -> list.none { p -> p.subGenres.any { it.id == g.id } } }
item(key = "genres-row") {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(MusyxTheme.space.m),
contentPadding = PaddingValues(horizontal = MusyxTheme.space.safeX, vertical = MusyxTheme.space.m),
) {
itemsIndexed(top, key = { _, g -> g.value.id }) { i, (index, genre) ->
GenreTile(genre, { state.navigate(Route.Genre(index)) }, if (i == 0) Modifier.entry(entry) else Modifier)
}
}
}
}
}
@Composable
fun GenreTile(genre: Genre, onClick: () -> Unit, modifier: Modifier = Modifier) {
val tint = genre.color?.let(::parseHex) ?: MusyxTheme.colors.raised
val shape = RoundedCornerShape(MusyxTheme.radius.cover)
Focusable(onClick = onClick, modifier = modifier, shape = shape, scale = 1.06f) {
Box(
Modifier
.width(CardWidth)
.height(88.dp)
.background(Brush.linearGradient(listOf(tint, mix(tint, Color.Black, 0.45f))), shape)
.padding(horizontal = 16.dp),
contentAlignment = Alignment.CenterStart,
) {
Text(genre.title, style = MusyxTheme.type.bodyMedium, color = Color.White, maxLines = 2)
}
}
}
/** `#rrggbb` → colour. */
fun parseHex(s: String): Color? {
val h = s.removePrefix("#").takeIf { s.startsWith('#') && it.length == 6 } ?: return null
val n = h.toLongOrNull(16) ?: return null
return Color(0xFF000000 or n)
}
/** A shelf of cards as one item of a page. */
fun LazyListScope.shelf(key: String, @StringRes title: Int?, cards: @Composable () -> List<CardData>, entry: FocusEntry? = null) {
item(key = key) {
val list = cards()
if (list.isNotEmpty()) CardShelf(title?.let { stringResource(it) }, list, entry = entry)
}
}
@@ -0,0 +1,235 @@
// Album, artist and playlist pages: a cover header, then tracks and shelves.
package it.panov.musyx.tv.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Text
import it.panov.musyx.tv.R
import it.panov.musyx.tv.api.AlbumPage
import it.panov.musyx.tv.api.ArtistPage
import it.panov.musyx.tv.api.PlaylistPage
import it.panov.musyx.tv.api.YmError
import it.panov.musyx.tv.state.AppState
import it.panov.musyx.tv.state.Loadable
import it.panov.musyx.tv.state.Page
import it.panov.musyx.tv.state.Route
import it.panov.musyx.tv.state.Sheet
import it.panov.musyx.tv.ui.components.COVER_LARGE
import it.panov.musyx.tv.ui.components.Columns
import it.panov.musyx.tv.ui.components.Cover
import it.panov.musyx.tv.ui.components.Failure
import it.panov.musyx.tv.ui.components.FocusEntry
import it.panov.musyx.tv.ui.components.GhostButton
import it.panov.musyx.tv.ui.components.IconButton
import it.panov.musyx.tv.ui.components.Note
import it.panov.musyx.tv.ui.components.PlayBar
import it.panov.musyx.tv.ui.components.trackItems
import it.panov.musyx.tv.ui.counted
import it.panov.musyx.tv.ui.durationWords
import it.panov.musyx.tv.ui.kindLabel
import it.panov.musyx.tv.ui.theme.MusyxTheme
import it.panov.musyx.tv.ui.tracksWord
/** How a page talks about what it's loading. */
private class What(val loading: Int, val gone: Int, val retry: Int)
/** The shared frame: loading, gone, failure, or the page. */
@Composable
private fun DetailPage(state: AppState, route: Route, what: What, entry: FocusEntry, content: LazyListScope.(Page) -> Unit) {
PageColumn {
when (val page = state.pages[route] ?: Loadable.Loading) {
is Loadable.Loaded -> content(page.value)
is Loadable.Failed -> item(key = "failed") {
if (page.error is YmError.NotFound) Note(stringResource(what.gone))
else Failure(page.error, stringResource(what.retry), { state.retryPage(route) }, entry)
}
else -> item(key = "loading") { Note(stringResource(what.loading)) }
}
}
}
/** Cover on the left; kind, title, byline, meta and actions on the right. */
@Composable
private fun Head(
cover: String?,
hues: Pair<Float, Float>,
round: Boolean,
kind: String,
title: String,
by: String?,
meta: String,
actions: @Composable () -> Unit,
) {
val c = MusyxTheme.colors
val space = MusyxTheme.space
Row(
Modifier.padding(horizontal = space.safeX).fillMaxWidth(),
verticalAlignment = Alignment.Bottom,
horizontalArrangement = Arrangement.spacedBy(28.dp),
) {
Cover(cover, hues, Modifier.size(200.dp), if (round) CircleShape else RoundedCornerShape(MusyxTheme.radius.cover))
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(kind, style = MusyxTheme.type.meta, color = c.muted, maxLines = 1)
Text(title, style = MusyxTheme.type.displayL, color = c.fg, maxLines = 2, overflow = TextOverflow.Ellipsis)
if (by != null) Text(by, style = MusyxTheme.type.bodyMedium, color = c.fg, maxLines = 1)
if (meta.isNotEmpty()) Text(meta, style = MusyxTheme.type.meta, color = c.muted, maxLines = 1)
Row(horizontalArrangement = Arrangement.spacedBy(space.s), verticalAlignment = Alignment.CenterVertically) { actions() }
}
}
}
/** A round heart that adds or removes something from the collection. */
@Composable
private fun LikeButton(liked: Boolean, onClick: () -> Unit) {
val c = MusyxTheme.colors
IconButton(
if (liked) R.drawable.ic_heart_fill else R.drawable.ic_heart,
onClick = onClick,
tint = if (liked) c.like else c.fg,
focusedTint = if (liked) c.like else c.fg,
padding = 12.dp,
)
}
@Composable
fun AlbumScreen(state: AppState, route: Route.Album, entry: FocusEntry) {
DetailPage(state, route, What(R.string.loading_album, R.string.gone_album, R.string.what_album), entry) { page ->
val info = (page as Page.OfAlbum).info
albumPage(state, info, entry)
}
}
private fun LazyListScope.albumPage(state: AppState, info: AlbumPage, entry: FocusEntry) {
val a = info.album
item(key = "head") {
val kind = kindLabel(a.kind).let { if (a.year != null) "$it · ${a.year}" else it }
val length = "${tracksWord(info.tracks.size)} · ${durationWords(info.tracks.sumOf { it.durationMs })}"
val liked = a.id in state.likes.albums
Head(
a.coverUrl(COVER_LARGE), a.hues, false, kind, a.fullTitle, a.artistLine,
listOfNotNull(length, info.label).joinToString(" · "),
) {
LikeButton(liked) { state.likeAlbum(a.id, !liked) }
a.artists.firstOrNull { it.id != null }?.let { artist ->
GhostButton(artist.name, onClick = { state.navigate(Route.Artist(artist.id!!)) }, icon = R.drawable.ic_chevron_right)
}
}
}
gap("play-gap")
item(key = "play") { PlayBar(state, info.tracks, entry = entry) }
trackItems(state, info.tracks, Columns.ALBUM_PAGE, keyPrefix = "album")
}
@Composable
fun ArtistScreen(state: AppState, route: Route.Artist, entry: FocusEntry) {
DetailPage(state, route, What(R.string.loading_artist, R.string.gone_artist, R.string.what_artist), entry) { page ->
artistPage(state, (page as Page.OfArtist).info, entry)
}
}
private fun LazyListScope.artistPage(state: AppState, info: ArtistPage, entry: FocusEntry) {
val a = info.artist
item(key = "head") {
val kind = if (a.genres.isEmpty()) stringResource(R.string.kind_artist)
else stringResource(R.string.kind_artist_genres, a.genres.joinToString(", "))
val meta = info.monthlyListeners?.let { counted(it, R.plurals.listeners_a_month) }
?: a.likes?.let { counted(it, R.plurals.likes) }
?: ""
val liked = a.id in state.likes.artists
Head(a.coverUrl(COVER_LARGE), a.hues, true, kind, a.name, null, meta) {
LikeButton(liked) { state.likeArtist(a.id, !liked) }
}
}
if (info.popular.isNotEmpty()) {
gap("popular-gap")
item(key = "popular-title") {
Text(
stringResource(R.string.section_popular),
style = MusyxTheme.type.section,
color = MusyxTheme.colors.fg,
modifier = Modifier.padding(horizontal = MusyxTheme.space.safeX),
)
}
item(key = "play") { PlayBar(state, info.popular, entry = entry) }
trackItems(state, info.popular, keyPrefix = "popular")
}
if (info.albums.isNotEmpty()) {
gap("albums-gap")
shelf("albums", R.string.tab_albums, { info.albums.map { albumCard(state, it) } })
}
if (info.alsoAlbums.isNotEmpty()) {
gap("also-gap")
shelf("also", R.string.section_appears_on, { info.alsoAlbums.map { albumCard(state, it) } })
}
if (info.clips.isNotEmpty()) {
gap("clips-gap")
shelf("clips", R.string.tab_clips, { info.clips.map { clipCard(state, it) } })
}
if (info.similar.isNotEmpty()) {
gap("similar-gap")
shelf("similar", R.string.section_similar_artists, { info.similar.map { artistCard(state, it) } })
}
}
@Composable
fun PlaylistScreen(state: AppState, route: Route.Playlist, entry: FocusEntry) {
DetailPage(state, route, What(R.string.loading_playlist, R.string.gone_playlist, R.string.what_playlist), entry) { page ->
playlistPage(state, (page as Page.OfPlaylist).info, entry)
}
}
private fun LazyListScope.playlistPage(state: AppState, info: PlaylistPage, entry: FocusEntry) {
val p = info.playlist
val own = p.id.owner == state.account?.uid
item(key = "head") {
val kind = stringResource(R.string.kind_playlist_by, stringResource(if (p.public) R.string.visibility_public else R.string.visibility_private))
val meta = "${tracksWord(info.tracks.size)} · ${durationWords(info.tracks.sumOf { it.durationMs })}"
Head(p.coverUrl(COVER_LARGE), p.hues, false, kind, p.title, p.ownerName.takeIf { it.isNotEmpty() }, meta) {
if (own) {
GhostButton(stringResource(R.string.action_rename), onClick = { state.openSheet(Sheet.Rename(p.id, p.title)) }, icon = R.drawable.ic_pencil)
GhostButton(
stringResource(if (p.public) R.string.action_make_private else R.string.action_make_public),
onClick = { state.setPlaylistPublic(p.id, !p.public) },
icon = if (p.public) R.drawable.ic_lock else R.drawable.ic_globe,
)
GhostButton(stringResource(R.string.action_delete), onClick = { state.openSheet(Sheet.ConfirmDelete(p.id, p.title)) }, icon = R.drawable.ic_trash_2)
} else {
val liked = p.id in state.likes.playlists
LikeButton(liked) { state.likePlaylist(p.id, !liked) }
}
}
}
info.description?.let { d ->
item(key = "description") {
Text(
d,
style = MusyxTheme.type.meta,
color = MusyxTheme.colors.muted,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = MusyxTheme.space.safeX).widthIn(max = 760.dp),
)
}
}
gap("play-gap")
if (info.tracks.isEmpty()) {
item(key = "empty") { Note(stringResource(R.string.playlist_empty)) }
return
}
item(key = "play") { PlayBar(state, info.tracks, entry = entry) }
trackItems(state, info.tracks, playlist = if (own) p.id else null, positions = info.positions, keyPrefix = "pl")
}
@@ -0,0 +1,323 @@
// Home and My Wave: the animated hero, the picks, station settings and other stations.
package it.panov.musyx.tv.ui.screens
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Text
import it.panov.musyx.tv.R
import it.panov.musyx.tv.api.Character
import it.panov.musyx.tv.api.Language
import it.panov.musyx.tv.api.MY_WAVE
import it.panov.musyx.tv.api.Mood
import it.panov.musyx.tv.api.Station
import it.panov.musyx.tv.api.WaveSettings
import it.panov.musyx.tv.player.Status
import it.panov.musyx.tv.state.AppState
import it.panov.musyx.tv.state.Route
import it.panov.musyx.tv.ui.components.CardWidth
import it.panov.musyx.tv.ui.components.Chip
import coil3.compose.AsyncImage
import it.panov.musyx.tv.ui.components.FocusEntry
import it.panov.musyx.tv.ui.components.Focusable
import it.panov.musyx.tv.ui.components.Note
import it.panov.musyx.tv.ui.components.PrimaryButton
import it.panov.musyx.tv.ui.components.SectionTitle
import it.panov.musyx.tv.ui.components.entry
import it.panov.musyx.tv.ui.components.trackItems
import it.panov.musyx.tv.ui.theme.MusyxTheme
import it.panov.musyx.tv.ui.theme.mix
import kotlin.math.PI
import kotlin.math.ceil
import kotlin.math.sin
/** Chart rows shown on Home before "Show all". */
private const val HOME_CHART = 10
/** Cards per Home shelf. */
private const val HOME_CARDS = 12
@Composable
fun HomeScreen(state: AppState, entry: FocusEntry) {
PageColumn {
item(key = "hero") { WaveHero(state, big = false, entry = entry) }
// Only worth a section when it has something; a failure stays in the log.
state.recent.get()?.takeIf { it.isNotEmpty() }?.let { recent ->
gap("recent-gap")
item(key = "recent-title") { SectionTitle(stringResource(R.string.section_recent), Modifier.padding(horizontal = MusyxTheme.space.safeX)) }
trackItems(state, recent, keyPrefix = "recent")
}
gap("home-gap")
loadable(
"home",
state.home,
loading = { stringResource(R.string.loading_home) },
what = { stringResource(R.string.what_home) },
retry = state::loadHome,
entry = null,
) { home ->
if (home.personal.isNotEmpty()) {
shelf("personal", R.string.section_made_for_you, {
home.personal.map { p -> playlistCard(state, p.playlist, subtitle = p.description) }
})
}
if (home.chart.isNotEmpty()) {
gap("chart-gap")
item(key = "chart-title") {
SectionTitle(
stringResource(R.string.section_chart),
Modifier.padding(horizontal = MusyxTheme.space.safeX),
) {
Focusable(onClick = { state.navigate(Route.Chart) }, contentColor = MusyxTheme.colors.muted, focusedContentColor = MusyxTheme.colors.fg) {
Text(
stringResource(R.string.action_show_all_n, home.chart.size),
style = MusyxTheme.type.meta,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
)
}
}
}
val top = home.chart.take(HOME_CHART)
trackItems(state, top.map { it.track }, shifts = top.map { it.shift }, keyPrefix = "chart")
}
if (home.newReleases.isNotEmpty()) {
gap("releases-gap")
shelf("releases", R.string.section_new_releases, { home.newReleases.take(HOME_CARDS).map { albumCard(state, it) } })
}
if (home.newPlaylists.isNotEmpty()) {
gap("playlists-gap")
shelf("new-playlists", R.string.section_new_playlists, { home.newPlaylists.take(HOME_CARDS).map { playlistCard(state, it) } })
}
}
gap("genres-gap")
genreShelf(state, null)
}
}
/** Whether My Wave itself is what's playing, and how. */
private fun myWaveStatus(state: AppState): Status? =
state.playback.state.takeIf { it.waveStation == MY_WAVE }?.status
/** The My Wave hero, on Home (`big = false`) and the My Wave screen. */
@Composable
fun WaveHero(state: AppState, big: Boolean, entry: FocusEntry?) {
val c = MusyxTheme.colors
val space = MusyxTheme.space
val status = myWaveStatus(state)
val playing = status == Status.Playing
val settings = state.waveShown
val blurb = if (settings != null && !settings.isDefault) {
stringResource(
R.string.wave_tuned,
stringResource(moodLabel(settings.mood)).lowercase(),
stringResource(characterLabel(settings.character)).lowercase(),
stringResource(languageLabel(settings.language)).lowercase(),
)
} else {
stringResource(R.string.wave_blurb)
}
val (label, icon, action) = when (status) {
Status.Playing, Status.Loading -> Triple(R.string.action_pause, R.drawable.ic_pause_fill) { state.playback.toggle() }
null -> Triple(R.string.wave_play, R.drawable.ic_play_fill) { state.playWave(MY_WAVE) }
else -> Triple(R.string.action_resume, R.drawable.ic_play_fill) { state.playback.toggle() }
}
val shape = RoundedCornerShape(MusyxTheme.radius.hero)
Box(
Modifier
.padding(horizontal = space.safeX)
.fillMaxWidth()
.height(if (big) 240.dp else 200.dp)
.clip(shape)
.background(Brush.horizontalGradient(listOf(c.panel, mix(c.panel, c.accent, 0.10f))), shape),
) {
WaveArt(playing, Modifier.fillMaxSize())
Row(
Modifier.align(Alignment.BottomStart).fillMaxWidth().padding(horizontal = 28.dp, vertical = 24.dp),
verticalAlignment = Alignment.Bottom,
horizontalArrangement = Arrangement.spacedBy(28.dp),
) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(stringResource(R.string.nav_wave), style = if (big) MusyxTheme.type.displayXl else MusyxTheme.type.displayM, color = c.fg)
Text(blurb, style = MusyxTheme.type.meta, color = c.muted, modifier = Modifier.widthIn(max = 520.dp))
}
PrimaryButton(stringResource(label), onClick = action, icon = icon, modifier = Modifier.entry(entry))
}
}
}
/** Lines drifting across the hero. They move only while My Wave plays. */
@Composable
private fun WaveArt(playing: Boolean, modifier: Modifier) {
val accent = MusyxTheme.colors.accent
val transition = rememberInfiniteTransition(label = "wave")
val drift by transition.animateFloat(
initialValue = 0f,
targetValue = (2 * PI * 20).toFloat(),
animationSpec = infiniteRepeatable(tween(durationMillis = 120_000, easing = LinearEasing), RepeatMode.Restart),
label = "phase",
)
val phase = if (playing) drift else 0f
val energy = if (playing) 1f else 0.45f
Canvas(modifier) {
val (w, h) = size.width to size.height
val lines = 14
for (k in 0 until lines) {
val kf = k.toFloat()
val base = h * (0.22f + kf * 0.028f)
val amp = h * (0.05f + kf * 0.006f) * energy
val freq = 1.6f + kf * 0.09f
val ph = phase * (0.35f + kf * 0.02f) + kf * 0.5f
val path = Path()
val steps = ceil(w / 8f).toInt()
for (i in 0..steps) {
val x = i * 8f
val u = x / w
val y = base + sin(u * PI.toFloat() * freq + ph) * amp + sin(u * PI.toFloat() * 4.2f - ph * 0.7f) * amp * 0.35f
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
}
val alpha = 0.08f + (kf / lines) * 0.55f
drawPath(path, accent.copy(alpha = alpha), style = Stroke(width = 1.5f + kf * 0.12f))
}
}
}
fun moodLabel(m: Mood) = when (m) {
Mood.Any -> R.string.wave_any
Mood.Energetic -> R.string.mood_energetic
Mood.Cheerful -> R.string.mood_cheerful
Mood.Calm -> R.string.mood_calm
Mood.Sad -> R.string.mood_sad
}
fun characterLabel(ch: Character) = when (ch) {
Character.Default -> R.string.wave_any
Character.Favourite -> R.string.character_favourite
Character.Unfamiliar -> R.string.character_unfamiliar
Character.Popular -> R.string.character_popular
}
fun languageLabel(l: Language) = when (l) {
Language.Any -> R.string.wave_any
Language.Russian -> R.string.language_russian
Language.Foreign -> R.string.language_foreign
}
@Composable
fun WaveScreen(state: AppState, entry: FocusEntry) {
val space = MusyxTheme.space
PageColumn {
item(key = "hero") { WaveHero(state, big = true, entry = entry) }
gap("settings-gap")
val shown = state.waveShown
val saving = state.waveSaving != null
if (shown != null) {
item(key = "mood") {
SettingRow(stringResource(R.string.wave_mood), Mood.entries.map { m ->
Triple(stringResource(moodLabel(m)), m == shown.mood, shown.copy(mood = m))
}, saving, state::setWaveSettings)
}
item(key = "character") {
SettingRow(stringResource(R.string.wave_character), Character.entries.map { ch ->
Triple(stringResource(characterLabel(ch)), ch == shown.character, shown.copy(character = ch))
}, saving, state::setWaveSettings)
}
item(key = "language") {
SettingRow(stringResource(R.string.wave_language), Language.entries.map { l ->
Triple(stringResource(languageLabel(l)), l == shown.language, shown.copy(language = l))
}, saving, state::setWaveSettings)
}
} else {
loadable(
"wave-settings",
state.waveSettings,
loading = { stringResource(R.string.loading_wave_settings) },
what = { stringResource(R.string.what_wave_settings) },
retry = state::loadWave,
entry = null,
) {}
}
gap("stations-gap")
item(key = "stations-title") { SectionTitle(stringResource(R.string.section_stations), Modifier.padding(horizontal = space.safeX)) }
loadable(
"stations",
state.stations,
loading = { stringResource(R.string.loading_stations) },
what = { stringResource(R.string.what_stations) },
retry = state::loadWave,
entry = null,
) { list ->
val others = list.filter { it.id != MY_WAVE }
if (others.isEmpty()) {
item(key = "no-stations") { Note(stringResource(R.string.stations_none)) }
} else {
item(key = "stations-row") {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(space.xl),
contentPadding = PaddingValues(horizontal = space.safeX, vertical = space.m),
) {
itemsIndexed(others, key = { _, s -> s.id }) { _, s -> StationTile(s) { state.playWave(s.id) } }
}
}
}
}
}
}
@Composable
private fun SettingRow(title: String, options: List<Triple<String, Boolean, WaveSettings>>, saving: Boolean, pick: (WaveSettings) -> Unit) {
val space = MusyxTheme.space
Column(Modifier.padding(horizontal = space.safeX, vertical = space.s), verticalArrangement = Arrangement.spacedBy(space.s)) {
Text(title, style = MusyxTheme.type.bodyMedium, color = MusyxTheme.colors.muted)
Row(horizontalArrangement = Arrangement.spacedBy(space.s)) {
options.forEach { (label, on, next) -> Chip(label, on, onClick = { if (!on && !saving) pick(next) }) }
}
}
}
@Composable
private fun StationTile(station: Station, onClick: () -> Unit) {
val c = MusyxTheme.colors
val tint = station.color?.let(::parseHex) ?: c.raised
val shape = RoundedCornerShape(MusyxTheme.radius.cover)
Column(Modifier.width(CardWidth), verticalArrangement = Arrangement.spacedBy(9.dp)) {
Focusable(onClick = onClick, shape = shape, container = tint, focusedContainer = tint, scale = 1.08f) {
Box(Modifier.size(CardWidth), contentAlignment = Alignment.Center) {
val icon = station.iconUrl(200)
if (icon != null) AsyncImage(model = icon, contentDescription = null, modifier = Modifier.size(96.dp))
}
}
Text(station.name, style = MusyxTheme.type.bodyMedium, color = c.fg, maxLines = 1)
}
}
@@ -0,0 +1,242 @@
// Collection, the chart, genres and podcasts.
package it.panov.musyx.tv.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import it.panov.musyx.tv.R
import it.panov.musyx.tv.state.AppState
import it.panov.musyx.tv.state.CollectionTab
import it.panov.musyx.tv.state.Liked
import it.panov.musyx.tv.state.Loadable
import it.panov.musyx.tv.state.Route
import it.panov.musyx.tv.ui.components.CardGrid
import it.panov.musyx.tv.ui.components.Chip
import it.panov.musyx.tv.ui.components.Failure
import it.panov.musyx.tv.ui.components.FocusEntry
import it.panov.musyx.tv.ui.components.Note
import it.panov.musyx.tv.ui.components.PlayBar
import it.panov.musyx.tv.ui.components.PrimaryButton
import it.panov.musyx.tv.ui.components.ScreenTitle
import it.panov.musyx.tv.ui.components.Tab
import it.panov.musyx.tv.ui.components.TabBar
import it.panov.musyx.tv.ui.components.entry
import it.panov.musyx.tv.ui.components.trackItems
import it.panov.musyx.tv.ui.durationWords
import it.panov.musyx.tv.ui.theme.MusyxTheme
import it.panov.musyx.tv.ui.tracksWord
private fun tabLabel(tab: CollectionTab) = when (tab) {
CollectionTab.Tracks -> R.string.tab_liked_tracks
CollectionTab.Albums -> R.string.tab_albums
CollectionTab.Artists -> R.string.tab_artists
CollectionTab.Playlists -> R.string.tab_playlists
CollectionTab.Clips -> R.string.tab_clips
}
@Composable
fun CollectionScreen(state: AppState, entry: FocusEntry) {
val space = MusyxTheme.space
PageColumn {
item(key = "title") { ScreenTitle(stringResource(R.string.nav_collection)) }
item(key = "tabs") {
TabBar(Modifier.padding(horizontal = space.safeX - 14.dp)) {
CollectionTab.entries.forEachIndexed { i, tab ->
val count = when (tab) {
CollectionTab.Tracks -> state.liked.tracks()?.size
CollectionTab.Albums -> state.albums.get()?.size
CollectionTab.Artists -> state.artists.get()?.size
CollectionTab.Playlists -> state.playlists.get()?.let { it.own.size + it.liked.size }
CollectionTab.Clips -> state.clips.get()?.size
}
Tab(
stringResource(tabLabel(tab)),
tab == state.collectionTab,
{ state.selectTab(tab) },
modifier = if (i == 0) Modifier.entry(entry) else Modifier,
count = count?.toString(),
)
}
}
}
gap("body-gap")
when (state.collectionTab) {
CollectionTab.Tracks -> when (val liked = state.liked) {
Liked.NotLoaded, Liked.Loading -> item(key = "loading") { Note(stringResource(R.string.loading_liked)) }
is Liked.Failed -> item(key = "failed") {
Failure(liked.error, stringResource(R.string.what_liked), state::loadLiked)
}
is Liked.Loaded -> if (liked.tracks.isEmpty()) {
item(key = "empty") { Note(stringResource(R.string.empty_liked)) }
} else {
item(key = "play") {
PlayBar(
state,
liked.tracks,
summary = "${tracksWord(liked.tracks.size)} · ${durationWords(liked.tracks.sumOf { it.durationMs })}",
)
}
trackItems(state, liked.tracks, keyPrefix = "liked")
}
}
CollectionTab.Albums -> loadable(
"albums", state.albums,
loading = { stringResource(R.string.loading_what, stringResource(R.string.what_albums)) },
what = { stringResource(R.string.what_albums) },
retry = { state.forceLoadTab(CollectionTab.Albums) },
entry = null,
) { albums ->
item(key = "grid") {
if (albums.isEmpty()) Note(stringResource(R.string.empty_albums))
else CardGrid(albums.map { albumCard(state, it) })
}
}
CollectionTab.Artists -> loadable(
"artists", state.artists,
loading = { stringResource(R.string.loading_what, stringResource(R.string.what_artists)) },
what = { stringResource(R.string.what_artists) },
retry = { state.forceLoadTab(CollectionTab.Artists) },
entry = null,
) { artists ->
item(key = "grid") {
if (artists.isEmpty()) Note(stringResource(R.string.empty_artists))
else CardGrid(artists.map { artistCard(state, it) })
}
}
CollectionTab.Playlists -> loadable(
"playlists", state.playlists,
loading = { stringResource(R.string.loading_what, stringResource(R.string.what_playlists)) },
what = { stringResource(R.string.what_playlists) },
retry = { state.forceLoadTab(CollectionTab.Playlists) },
entry = null,
) { p ->
item(key = "new") {
Box(Modifier.padding(horizontal = space.safeX)) {
Chip(stringResource(R.string.action_new_playlist), false, { state.openSheet(it.panov.musyx.tv.state.Sheet.NewPlaylist(null)) })
}
}
if (p.own.isEmpty() && p.liked.isEmpty()) {
item(key = "empty") { Note(stringResource(R.string.empty_playlists)) }
}
if (p.own.isNotEmpty()) shelf("own", R.string.section_your_playlists, { p.own.map { playlistCard(state, it) } })
if (p.liked.isNotEmpty()) {
gap("liked-gap")
shelf("liked", R.string.section_liked_playlists, { p.liked.map { playlistCard(state, it) } })
}
}
CollectionTab.Clips -> loadable(
"clips", state.clips,
loading = { stringResource(R.string.loading_what, stringResource(R.string.what_clips)) },
what = { stringResource(R.string.what_clips) },
retry = { state.forceLoadTab(CollectionTab.Clips) },
entry = null,
) { clips ->
item(key = "grid") {
if (clips.isEmpty()) Note(stringResource(R.string.empty_clips))
else CardGrid(clips.map { clipCard(state, it) })
}
item(key = "hint") { Note(stringResource(R.string.clips_hint)) }
}
}
}
}
@Composable
fun ChartScreen(state: AppState, entry: FocusEntry) {
PageColumn {
item(key = "title") { ScreenTitle(stringResource(R.string.section_chart)) }
loadable(
"chart", state.home,
loading = { stringResource(R.string.loading_chart) },
what = { stringResource(R.string.what_chart) },
retry = state::loadHome,
entry = entry,
) { home ->
if (home.chart.isEmpty()) {
item(key = "empty") { Note(stringResource(R.string.chart_empty)) }
return@loadable
}
val tracks = home.chart.map { it.track }
item(key = "play") { PlayBar(state, tracks, summary = stringResource(R.string.chart_blurb), entry = entry) }
trackItems(state, tracks, shifts = home.chart.map { it.shift }, keyPrefix = "chart")
}
}
}
@Composable
fun GenreScreen(state: AppState, index: Int, entry: FocusEntry) {
val space = MusyxTheme.space
val genres = state.genres.get().orEmpty()
val genre = genres.getOrNull(index)
PageColumn {
if (genre == null) {
// The list itself may still be on its way (after a language switch).
item(key = "gone") {
Note(stringResource(if (state.genres.get() == null) R.string.loading_genres else R.string.genre_gone))
}
return@PageColumn
}
item(key = "title") {
Row(
Modifier.fillMaxWidth().padding(end = space.safeX),
verticalAlignment = Alignment.CenterVertically,
) {
Box(Modifier.weight(1f)) { ScreenTitle(genre.title) }
PrimaryButton(
stringResource(R.string.action_play_radio),
onClick = { state.playWave("genre:${genre.id}") },
icon = R.drawable.ic_audio_lines,
modifier = Modifier.entry(entry),
)
}
}
val subs = genre.subGenres.mapNotNull { s -> genres.indexOfFirst { it.id == s.id }.takeIf { it >= 0 }?.let { it to s } }
if (subs.isNotEmpty()) {
item(key = "subs") {
Row(Modifier.padding(horizontal = space.safeX), horizontalArrangement = Arrangement.spacedBy(space.s)) {
subs.take(8).forEach { (i, s) -> Chip(s.title, false, { state.navigate(Route.Genre(i)) }) }
}
}
}
gap("playlists-gap")
val playlists = state.genrePlaylists[index] ?: Loadable.Loading
loadable(
"playlists", playlists,
loading = { stringResource(R.string.loading_playlists) },
what = { stringResource(R.string.what_the_playlists) },
retry = { state.loadGenre(index, force = true) },
entry = null,
) { list ->
if (list.isEmpty()) item(key = "empty") { Note(stringResource(R.string.genre_empty)) }
else item(key = "grid") { CardGrid(list.map { playlistCard(state, it) }) }
}
}
}
@Composable
fun PodcastsScreen(state: AppState, entry: FocusEntry) {
PageColumn {
item(key = "title") { ScreenTitle(stringResource(R.string.podcasts_title)) }
val mine = state.albums.get()?.filter { it.isPodcast }.orEmpty()
if (mine.isNotEmpty()) {
shelf("yours", R.string.section_yours, { mine.map { albumCard(state, it) } }, entry)
gap("featured-gap")
}
loadable(
"featured", state.podcasts,
loading = { stringResource(R.string.loading_podcasts) },
what = { stringResource(R.string.what_podcasts) },
retry = state::loadPodcasts,
entry = entry,
) { list ->
shelf("featured", R.string.section_featured, { list.map { albumCard(state, it) } }, if (mine.isEmpty()) entry else null)
}
}
}
@@ -0,0 +1,389 @@
// Now Playing: the full-screen player with the queue and lyrics, and the mini player that
// sits under every other screen.
package it.panov.musyx.tv.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Text
import it.panov.musyx.tv.MainActivity
import it.panov.musyx.tv.R
import it.panov.musyx.tv.api.Lyrics
import it.panov.musyx.tv.api.Track
import it.panov.musyx.tv.player.Notice
import it.panov.musyx.tv.player.PlaybackState
import it.panov.musyx.tv.player.Repeat
import it.panov.musyx.tv.player.Status
import it.panov.musyx.tv.state.AppState
import it.panov.musyx.tv.state.Loadable
import it.panov.musyx.tv.state.Route
import it.panov.musyx.tv.state.Sheet
import it.panov.musyx.tv.ui.artistsOrUnknown
import it.panov.musyx.tv.ui.clock
import it.panov.musyx.tv.ui.components.COVER_LARGE
import it.panov.musyx.tv.ui.components.COVER_SMALL
import it.panov.musyx.tv.ui.components.Cover
import it.panov.musyx.tv.ui.components.FocusEntry
import it.panov.musyx.tv.ui.components.Focusable
import it.panov.musyx.tv.ui.components.IconButton
import it.panov.musyx.tv.ui.components.MusyxIcon
import it.panov.musyx.tv.ui.components.PrimaryButton
import it.panov.musyx.tv.ui.components.Tab
import it.panov.musyx.tv.ui.components.TabBar
import it.panov.musyx.tv.ui.components.Thumb
import it.panov.musyx.tv.ui.components.entry
import it.panov.musyx.tv.ui.theme.MusyxTheme
import it.panov.musyx.tv.ui.theme.tabular
/** Upcoming items listed at once; a long liked list would otherwise build thousands of rows. */
private const val QUEUE_SHOWN = 100
@Composable
private fun noticeText(notice: Notice): String = when (notice) {
Notice.StationDry -> stringResource(R.string.notice_station_dry)
Notice.TooManyFailures -> stringResource(R.string.notice_too_many)
is Notice.Skipped -> stringResource(R.string.notice_skipped, notice.title)
}
@Composable
fun NowPlayingScreen(state: AppState, entry: FocusEntry) {
val p = state.playback.state
val c = MusyxTheme.colors
val space = MusyxTheme.space
val track = p.track
Row(
Modifier.fillMaxSize().padding(start = space.safeX, end = space.safeX, top = space.safeY, bottom = space.safeY),
horizontalArrangement = Arrangement.spacedBy(space.section),
) {
Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(space.m)) {
if (track == null) {
Text(stringResource(R.string.nothing_playing), style = MusyxTheme.type.displayS, color = c.fg)
Text(p.notice?.let { noticeText(it) } ?: stringResource(R.string.pick_a_track), style = MusyxTheme.type.body, color = c.muted)
return@Column
}
Row(horizontalArrangement = Arrangement.spacedBy(space.xl), verticalAlignment = Alignment.Bottom) {
Cover(track.coverUrl(COVER_LARGE), track.hues, Modifier.size(180.dp), RoundedCornerShape(MusyxTheme.radius.cover))
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {
p.stream?.let { s ->
val label = if (s.preview) stringResource(R.string.badge_preview) else s.label
Text(
label,
style = MusyxTheme.type.small,
color = if (s.lossless) c.accent else c.muted,
modifier = Modifier
.border(1.dp, c.line, RoundedCornerShape(4.dp))
.padding(horizontal = 8.dp, vertical = 2.dp),
)
}
Text(track.fullTitle, style = MusyxTheme.type.wordmark, color = c.fg, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text(track.artistsOrUnknown(), style = MusyxTheme.type.bodyMedium, color = c.muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
track.album?.let { Text(it.title, style = MusyxTheme.type.meta, color = c.muted, maxLines = 1, overflow = TextOverflow.Ellipsis) }
TrackActions(state, track)
val notice = p.notice
if (notice != null && (p.status == Status.Loading || p.status == Status.Paused)) {
Text(noticeText(notice), style = MusyxTheme.type.meta, color = c.like, maxLines = 2)
}
}
}
androidx.compose.foundation.layout.Spacer(Modifier.weight(1f))
SeekBar(state, p)
Transport(state, p, track, entry)
}
SidePanel(state, p, Modifier.width(340.dp).fillMaxHeight())
}
}
/** Position and length around a bar; focused, left and right step through the track. */
@Composable
private fun SeekBar(state: AppState, p: PlaybackState) {
val c = MusyxTheme.colors
val position = state.playback.positionMs.coerceAtMost(p.durationMs)
val interaction = remember { MutableInteractionSource() }
val focused by interaction.collectIsFocusedAsState()
val fraction = if (p.durationMs > 0) position.toFloat() / p.durationMs else 0f
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
Text(clock(position), style = MusyxTheme.type.meta.tabular(), color = c.muted)
Box(
Modifier
.weight(1f)
.height(28.dp)
.onPreviewKeyEvent { e ->
if (e.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
when (e.key) {
Key.DirectionLeft -> { state.playback.seekBy(-MainActivity.SEEK_STEP_MS); true }
Key.DirectionRight -> { state.playback.seekBy(MainActivity.SEEK_STEP_MS); true }
else -> false
}
}
.focusable(interactionSource = interaction),
contentAlignment = Alignment.CenterStart,
) {
val track = if (focused) 8.dp else 5.dp
Box(Modifier.fillMaxWidth().height(track).background(c.raised, RoundedCornerShape(4.dp)))
Box(Modifier.fillMaxWidth(fraction.coerceIn(0f, 1f)).height(track).background(if (focused) c.accent else c.fg, RoundedCornerShape(4.dp)))
}
Text(clock(p.durationMs), style = MusyxTheme.type.meta.tabular(), color = c.muted)
}
}
@Composable
private fun Transport(state: AppState, p: PlaybackState, track: Track, entry: FocusEntry) {
val c = MusyxTheme.colors
val playback = state.playback
val playing = p.status == Status.Playing || p.status == Status.Loading
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
// A station decides its own order.
IconButton(
R.drawable.ic_shuffle, onClick = playback::toggleShuffle,
tint = if (p.shuffle) c.accent else c.muted, focusedTint = if (p.shuffle) c.accent else c.fg,
enabled = p.waveStation == null,
)
IconButton(R.drawable.ic_skip_back, onClick = playback::previous, tint = c.fg)
// The play disc: amber, round, with the text colour as its focus ring.
Focusable(
onClick = playback::toggle,
modifier = Modifier.entry(entry),
shape = CircleShape,
container = c.accent,
focusedContainer = c.accent,
contentColor = c.accentInk,
ringColor = c.fg,
scale = 1.08f,
) {
MusyxIcon(if (playing) R.drawable.ic_pause_fill else R.drawable.ic_play_fill, Modifier.padding(18.dp), size = 30.dp)
}
IconButton(R.drawable.ic_skip_forward, onClick = playback::next, tint = c.fg)
IconButton(
if (p.repeat == Repeat.One) R.drawable.ic_repeat_1 else R.drawable.ic_repeat,
onClick = playback::cycleRepeat,
tint = if (p.repeat != Repeat.Off) c.accent else c.muted,
focusedTint = if (p.repeat != Repeat.Off) c.accent else c.fg,
)
}
}
/** Like, "don't recommend" and the track menu, under the title. */
@Composable
private fun TrackActions(state: AppState, track: Track) {
val c = MusyxTheme.colors
val liked = state.liked.contains(track.id)
val disliked = track.id in state.likes.dislikedTracks
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
IconButton(
if (liked) R.drawable.ic_heart_fill else R.drawable.ic_heart,
onClick = { state.likeTrack(track, !liked) },
tint = if (liked) c.like else c.muted,
focusedTint = if (liked) c.like else c.fg,
)
IconButton(
R.drawable.ic_ban,
onClick = { state.dislikeTrack(track, !disliked) },
tint = if (disliked) c.like else c.muted,
)
IconButton(R.drawable.ic_ellipsis, onClick = { state.openSheet(Sheet.TrackMenu(track)) })
}
}
private enum class Panel { Queue, Lyrics }
@Composable
private fun SidePanel(state: AppState, p: PlaybackState, modifier: Modifier) {
val c = MusyxTheme.colors
var panel by rememberSaveable { mutableStateOf(Panel.Queue) }
Column(
modifier.background(c.panel, RoundedCornerShape(MusyxTheme.radius.card)).padding(vertical = 12.dp),
) {
TabBar(Modifier.padding(horizontal = 8.dp)) {
Tab(stringResource(R.string.panel_queue), panel == Panel.Queue, { panel = Panel.Queue })
Tab(stringResource(R.string.panel_lyrics), panel == Panel.Lyrics, { panel = Panel.Lyrics })
}
val track = p.track
when {
panel == Panel.Queue -> QueueList(state, p)
track == null -> PanelNote(stringResource(R.string.lyrics_play_first))
else -> {
LaunchedEffect(track.id) { state.wantLyrics(track) }
when (val l = state.lyrics[track.id] ?: Loadable.Loading) {
is Loadable.Loaded -> l.value?.let { LyricsList(state, it) } ?: PanelNote(stringResource(R.string.lyrics_none))
is Loadable.Failed -> Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(R.string.lyrics_failed), style = MusyxTheme.type.meta, color = c.muted)
PrimaryButton(stringResource(R.string.action_try_again), onClick = { state.retryLyrics(track) })
}
else -> PanelNote(stringResource(R.string.lyrics_loading))
}
}
}
}
}
@Composable
private fun PanelNote(text: String) {
Text(text, style = MusyxTheme.type.meta, color = MusyxTheme.colors.muted, modifier = Modifier.padding(16.dp))
}
@Composable
private fun QueueList(state: AppState, p: PlaybackState) {
val track = p.track
if (track == null) {
PanelNote(stringResource(R.string.queue_empty))
return
}
LazyColumn(contentPadding = PaddingValues(8.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
heading("now", R.string.queue_now)
item(key = "current") { QueueItem(track, now = true, onClick = null) }
item(key = "next-heading") {
val n = p.upcoming.size
Heading(if (n == 0) stringResource(R.string.queue_nothing_after) else stringResource(R.string.queue_next_up, n))
}
itemsIndexed(p.upcoming.take(QUEUE_SHOWN), key = { _, (pos, t) -> "$pos:${t.id}" }) { _, (pos, t) ->
QueueItem(t, now = false, onClick = { state.playback.jumpTo(pos) })
}
if (p.upcoming.size > QUEUE_SHOWN) {
item(key = "more") { Heading(pluralStringResource(R.plurals.queue_and_more, p.upcoming.size - QUEUE_SHOWN, p.upcoming.size - QUEUE_SHOWN)) }
}
}
}
private fun LazyListScope.heading(key: String, id: Int) {
item(key = key) { Heading(stringResource(id)) }
}
@Composable
private fun Heading(text: String) {
Text(text, style = MusyxTheme.type.small, color = MusyxTheme.colors.muted, modifier = Modifier.padding(start = 8.dp, top = 12.dp, bottom = 6.dp))
}
@Composable
private fun QueueItem(track: Track, now: Boolean, onClick: (() -> Unit)?) {
val c = MusyxTheme.colors
Focusable(onClick = { onClick?.invoke() }, modifier = Modifier.fillMaxWidth()) {
Row(
Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Thumb(track.coverUrl(COVER_SMALL), track.hues, 40.dp)
Column(Modifier.weight(1f)) {
Text(track.fullTitle, style = MusyxTheme.type.meta, color = if (now) c.accent else c.fg, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(track.artistsOrUnknown(), style = MusyxTheme.type.small, color = c.muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Text(clock(track.durationMs), style = MusyxTheme.type.small.tabular(), color = c.muted)
}
}
}
/** Synced lyrics follow the song and seek on select; plain lyrics just scroll. */
@Composable
private fun LyricsList(state: AppState, lyrics: Lyrics) {
val c = MusyxTheme.colors
val current = lyrics.current(state.playback.positionMs)
val list = rememberLazyListState()
LaunchedEffect(current) { if (current != null) list.animateScrollToItem((current - 2).coerceAtLeast(0)) }
LazyColumn(state = list, contentPadding = PaddingValues(8.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
itemsIndexed(lyrics.lines) { i, line ->
val (color, style) = when {
current == i -> c.fg to MusyxTheme.type.bodyMedium
current != null && i < current -> c.muted.copy(alpha = 0.6f) to MusyxTheme.type.meta
lyrics.synced -> c.muted to MusyxTheme.type.meta
else -> c.fg to MusyxTheme.type.meta
}
val at = line.atMs
Focusable(onClick = { if (at != null) state.playback.seek(at) }, modifier = Modifier.fillMaxWidth()) {
Text(line.text.ifEmpty { "♪" }, style = style, color = color, modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp))
}
}
if (lyrics.writers.isNotEmpty()) {
item(key = "writers") {
Text(
stringResource(R.string.lyrics_writers, lyrics.writers.joinToString(", ")),
style = MusyxTheme.type.small,
color = c.muted,
modifier = Modifier.padding(10.dp),
)
}
}
}
}
/** The bar under every other screen: what's playing, play/pause and next. */
@Composable
fun MiniPlayer(state: AppState) {
val p = state.playback.state
val track = p.track ?: return
val c = MusyxTheme.colors
val space = MusyxTheme.space
val playing = p.status == Status.Playing || p.status == Status.Loading
val fraction = if (p.durationMs > 0) state.playback.positionMs.toFloat() / p.durationMs else 0f
Column(Modifier.fillMaxWidth().background(c.panel)) {
Box(Modifier.fillMaxWidth().height(2.dp).background(c.raised)) {
Box(Modifier.fillMaxWidth(fraction.coerceIn(0f, 1f)).height(2.dp).background(c.accent))
}
Row(
Modifier.padding(horizontal = space.safeX - 10.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(space.s),
) {
Focusable(onClick = { state.navigate(Route.NowPlaying) }, modifier = Modifier.weight(1f)) {
Row(
Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(14.dp),
) {
Thumb(track.coverUrl(COVER_SMALL), track.hues, 44.dp)
Column(Modifier.weight(1f)) {
Text(track.fullTitle, style = MusyxTheme.type.bodyMedium, color = c.fg, maxLines = 1, overflow = TextOverflow.Ellipsis)
val notice = p.notice?.takeIf { p.status == Status.Loading || p.status == Status.Paused }
Text(
notice?.let { noticeText(it) } ?: track.artistsOrUnknown(),
style = MusyxTheme.type.meta,
color = if (notice != null) c.like else c.muted,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
MusyxIcon(R.drawable.ic_list_music, tint = c.muted)
}
}
IconButton(if (playing) R.drawable.ic_pause_fill else R.drawable.ic_play_fill, onClick = state.playback::toggle, tint = c.fg)
IconButton(R.drawable.ic_skip_forward, onClick = state.playback::next, tint = c.fg)
}
}
}
@@ -0,0 +1,225 @@
// Search: a field the TV keyboard fills, suggestions, results by kind, more on request.
// With no query it shows genres to browse.
package it.panov.musyx.tv.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Text
import it.panov.musyx.tv.R
import it.panov.musyx.tv.api.BestMatch
import it.panov.musyx.tv.api.SearchKind
import it.panov.musyx.tv.state.ALL_TAB_TRACKS
import it.panov.musyx.tv.state.AppState
import it.panov.musyx.tv.state.Route
import it.panov.musyx.tv.ui.artistsOrUnknown
import it.panov.musyx.tv.ui.compact
import it.panov.musyx.tv.ui.components.COVER_LARGE
import it.panov.musyx.tv.ui.components.CardGrid
import it.panov.musyx.tv.ui.components.Cover
import it.panov.musyx.tv.ui.components.FocusEntry
import it.panov.musyx.tv.ui.components.Focusable
import it.panov.musyx.tv.ui.components.GhostButton
import it.panov.musyx.tv.ui.components.MusyxIcon
import it.panov.musyx.tv.ui.components.Note
import it.panov.musyx.tv.ui.components.PlayBar
import it.panov.musyx.tv.ui.components.ScreenTitle
import it.panov.musyx.tv.ui.components.SectionTitle
import it.panov.musyx.tv.ui.components.Tab
import it.panov.musyx.tv.ui.components.TabBar
import it.panov.musyx.tv.ui.components.entry
import it.panov.musyx.tv.ui.components.trackItems
import it.panov.musyx.tv.ui.isRussian
import it.panov.musyx.tv.ui.kindLabel
import it.panov.musyx.tv.ui.theme.MusyxTheme
fun searchKindLabel(kind: SearchKind) = when (kind) {
SearchKind.All -> R.string.search_all
SearchKind.Tracks -> R.string.search_tracks
SearchKind.Albums -> R.string.search_albums
SearchKind.Artists -> R.string.search_artists
SearchKind.Playlists -> R.string.search_playlists
SearchKind.Podcasts -> R.string.search_podcasts
}
@Composable
fun SearchScreen(state: AppState, entry: FocusEntry) {
val search = state.search
val space = MusyxTheme.space
PageColumn {
item(key = "field") {
Row(
Modifier.padding(horizontal = space.safeX).fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(space.m),
) {
MusyxIcon(R.drawable.ic_search, tint = MusyxTheme.colors.muted)
TextInput(
value = search.text,
onChange = search::change,
placeholder = stringResource(R.string.search_placeholder),
onSubmit = search::submit,
imeAction = ImeAction.Search,
modifier = Modifier.weight(1f).entry(entry),
)
}
}
if (search.suggestions.isNotEmpty()) {
items(search.suggestions.size, key = { "s$it" }) { i ->
val s = search.suggestions[i]
Focusable(onClick = { search.pick(s) }, modifier = Modifier.padding(horizontal = space.safeX).fillMaxWidth()) {
Row(
Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
MusyxIcon(R.drawable.ic_search, tint = MusyxTheme.colors.muted)
Text(s, style = MusyxTheme.type.body)
}
}
}
}
gap("title-gap")
if (search.query.isEmpty()) {
item(key = "browse") { ScreenTitle(stringResource(R.string.search_browse)) }
genreShelf(state, null)
return@PageColumn
}
item(key = "title") { ScreenTitle(stringResource(R.string.search_results_for, search.query)) }
search.results.get()?.data?.corrected?.let { corrected ->
item(key = "corrected") { Note(stringResource(R.string.search_corrected, corrected)) }
}
item(key = "tabs") {
val russian = isRussian()
TabBar(Modifier.padding(horizontal = space.safeX - 14.dp)) {
SearchKind.entries.forEach { kind ->
val total = search.results.get()?.data?.totals?.get(kind)?.takeIf { it > 0 }
Tab(stringResource(searchKindLabel(kind)), kind == search.kind, { search.tab(kind) }, count = total?.let { compact(it.toLong(), russian) })
}
}
}
loadable(
"results",
search.results,
loading = { stringResource(R.string.searching) },
what = { stringResource(R.string.what_results) },
retry = search::retry,
entry = null,
) { r ->
val d = r.data
if (d.isEmpty) {
item(key = "empty") { Note(stringResource(R.string.search_nothing, search.query)) }
return@loadable
}
when (search.kind) {
SearchKind.All -> {
d.best?.let { best -> item(key = "best") { BestCard(state, best) } }
if (d.tracks.isNotEmpty()) {
gap("tracks-gap")
item(key = "tracks-title") {
SectionTitle(stringResource(R.string.search_tracks), Modifier.padding(horizontal = space.safeX)) {
Focusable(onClick = { search.tab(SearchKind.Tracks) }, contentColor = MusyxTheme.colors.muted, focusedContentColor = MusyxTheme.colors.fg) {
Text(stringResource(R.string.action_show_all), style = MusyxTheme.type.meta, modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp))
}
}
}
trackItems(state, d.tracks.take(ALL_TAB_TRACKS), keyPrefix = "top")
}
if (d.artists.isNotEmpty()) {
gap("artists-gap")
shelf("artists", R.string.search_artists, { d.artists.map { artistCard(state, it) } })
}
if (d.albums.isNotEmpty()) {
gap("albums-gap")
shelf("albums", R.string.search_albums, { d.albums.map { albumCard(state, it) } })
}
if (d.playlists.isNotEmpty()) {
gap("playlists-gap")
shelf("playlists", R.string.search_playlists, { d.playlists.map { playlistCard(state, it) } })
}
if (d.podcasts.isNotEmpty()) {
gap("podcasts-gap")
shelf("podcasts", R.string.search_podcasts, { d.podcasts.map { albumCard(state, it) } })
}
}
SearchKind.Tracks -> {
item(key = "play") { PlayBar(state, d.tracks) }
trackItems(state, d.tracks, keyPrefix = "all")
}
SearchKind.Albums -> item(key = "grid") { CardGrid(d.albums.map { albumCard(state, it) }) }
SearchKind.Artists -> item(key = "grid") { CardGrid(d.artists.map { artistCard(state, it) }) }
SearchKind.Playlists -> item(key = "grid") { CardGrid(d.playlists.map { playlistCard(state, it) }) }
SearchKind.Podcasts -> item(key = "grid") { CardGrid(d.podcasts.map { albumCard(state, it) }) }
}
if (search.hasMore(r)) {
item(key = "more") {
Box(Modifier.padding(horizontal = space.safeX, vertical = space.l)) {
GhostButton(
stringResource(if (r.loadingMore) R.string.loading else R.string.action_show_more),
onClick = search::more,
enabled = !r.loadingMore,
)
}
}
}
}
}
}
/** The top result as a wide card: cover, name, kind, and the action it implies. */
@Composable
private fun BestCard(state: AppState, best: BestMatch) {
val c = MusyxTheme.colors
val space = MusyxTheme.space
data class Shown(val cover: String?, val hues: Pair<Float, Float>, val round: Boolean, val title: String, val kind: String, val go: () -> Unit)
val shown = when (best) {
is BestMatch.OfArtist -> Shown(best.artist.coverUrl(COVER_LARGE), best.artist.hues, true, best.artist.name, stringResource(R.string.kind_artist)) {
state.navigate(Route.Artist(best.artist.id))
}
is BestMatch.OfAlbum -> Shown(
best.album.coverUrl(COVER_LARGE), best.album.hues, false, best.album.fullTitle,
listOfNotNull(kindLabel(best.album.kind), best.album.artistLine).joinToString(" · "),
) { state.navigate(Route.Album(best.album.id)) }
is BestMatch.OfPlaylist -> Shown(
best.playlist.coverUrl(COVER_LARGE), best.playlist.hues, false, best.playlist.title,
stringResource(R.string.kind_playlist_by, best.playlist.ownerName),
) { state.navigate(Route.Playlist(best.playlist.id)) }
is BestMatch.OfTrack -> Shown(
best.track.coverUrl(COVER_LARGE), best.track.hues, false, best.track.fullTitle,
stringResource(R.string.kind_track_by, best.track.artistsOrUnknown()),
) { state.playTracks(listOf(best.track), 0) }
}
Focusable(
onClick = shown.go,
modifier = Modifier.padding(horizontal = space.safeX).fillMaxWidth(),
shape = RoundedCornerShape(MusyxTheme.radius.card),
container = c.panel,
) {
Row(Modifier.padding(18.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(20.dp)) {
Cover(shown.cover, shown.hues, Modifier.size(108.dp), if (shown.round) CircleShape else RoundedCornerShape(MusyxTheme.radius.cover))
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(stringResource(R.string.search_top_result), style = MusyxTheme.type.small, color = c.muted)
Text(shown.title, style = MusyxTheme.type.displayS, color = c.fg, maxLines = 1)
Text(shown.kind, style = MusyxTheme.type.meta, color = c.muted, maxLines = 1)
}
MusyxIcon(
if (best is BestMatch.OfTrack) R.drawable.ic_play_fill else R.drawable.ic_chevron_right,
tint = c.accent,
modifier = Modifier.width(32.dp),
)
}
}
}
@@ -0,0 +1,342 @@
// The full-screen states outside a session: checking, unreachable, and sign-in.
package it.panov.musyx.tv.ui.screens
import android.os.SystemClock
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Text
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.qrcode.QRCodeWriter
import it.panov.musyx.tv.R
import it.panov.musyx.tv.state.AppState
import it.panov.musyx.tv.state.SignInState
import it.panov.musyx.tv.ui.Wordmark
import it.panov.musyx.tv.ui.components.Focusable
import it.panov.musyx.tv.ui.components.GhostButton
import it.panov.musyx.tv.ui.components.MusyxIcon
import it.panov.musyx.tv.ui.components.PrimaryButton
import it.panov.musyx.tv.ui.text
import it.panov.musyx.tv.ui.theme.MusyxTheme
import it.panov.musyx.tv.ui.theme.mix
import kotlinx.coroutines.delay
/** Shown while the stored session is checked or a new one connects. */
@Composable
fun HoldingScreen(label: String) {
Column(
Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Wordmark()
Spacer(Modifier.height(MusyxTheme.space.l))
Text(label, style = MusyxTheme.type.body, color = MusyxTheme.colors.muted)
}
}
/** Stored credentials exist but Yandex can't be reached. */
@Composable
fun UnreachableScreen(state: AppState) {
val focus = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { focus.requestFocus() } }
Column(
Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(MusyxTheme.space.l, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Wordmark()
Text(stringResource(R.string.unreachable_title), style = MusyxTheme.type.displayS, color = MusyxTheme.colors.fg)
Text(
stringResource(R.string.unreachable_body),
style = MusyxTheme.type.body,
color = MusyxTheme.colors.muted,
modifier = Modifier.widthIn(max = 560.dp),
)
Row(horizontalArrangement = Arrangement.spacedBy(MusyxTheme.space.m)) {
PrimaryButton(stringResource(R.string.action_try_again), onClick = state::restore, modifier = Modifier.focusRequester(focus))
GhostButton(stringResource(R.string.action_sign_out), onClick = state::signOut, icon = R.drawable.ic_log_out)
}
}
}
@Composable
fun SignInScreen(signIn: SignInState) {
val c = MusyxTheme.colors
val space = MusyxTheme.space
val focus = remember { FocusRequester() }
LaunchedEffect(signIn.stage::class) {
// The new stage's control is placed on the next frame.
withFrameNanos { }
runCatching { focus.requestFocus() }
}
Row(Modifier.fillMaxSize()) {
Column(
Modifier
.weight(3f)
.fillMaxHeight()
// The token field can push past the bottom; focus scrolls it into view.
.verticalScroll(rememberScrollState())
.padding(horizontal = space.safeX, vertical = space.safeY),
verticalArrangement = Arrangement.spacedBy(space.l),
) {
Wordmark()
val waiting = signIn.stage is SignInState.Stage.Waiting
Text(
stringResource(R.string.signin_title),
style = if (waiting) MusyxTheme.type.section else MusyxTheme.type.displayS,
color = c.fg,
)
// While a code is up, the steps need the room.
if (!waiting) Text(stringResource(R.string.signin_blurb), style = MusyxTheme.type.meta, color = c.muted)
when (val stage = signIn.stage) {
SignInState.Stage.Idle -> PrimaryButton(
stringResource(R.string.signin_get_code),
onClick = signIn::getCode,
modifier = Modifier.focusRequester(focus),
)
SignInState.Stage.Requesting -> PrimaryButton(
stringResource(R.string.signin_getting_code),
onClick = {},
enabled = false,
)
is SignInState.Stage.Waiting -> Steps(signIn, stage, focus)
}
signIn.error?.let { Text(text(it), style = MusyxTheme.type.meta, color = c.like) }
if (!waiting) TokenFallback(signIn)
Spacer(Modifier.height(space.s))
if (!waiting) Text(stringResource(R.string.signin_footer), style = MusyxTheme.type.small, color = c.muted)
}
Box(
Modifier
.weight(2f)
.fillMaxHeight()
.background(Brush.linearGradient(listOf(c.panel, mix(c.panel, c.accent, 0.14f)))),
contentAlignment = Alignment.Center,
) {
QrCard((signIn.stage as? SignInState.Stage.Waiting)?.code?.verificationUrl)
}
}
}
@Composable
private fun Steps(signIn: SignInState, stage: SignInState.Stage.Waiting, focus: FocusRequester) {
val c = MusyxTheme.colors
val code = stage.code
val host = code.verificationUrl.removePrefix("https://").removePrefix("http://").trimEnd('/')
val remaining by produceState(stage.deadline - SystemClock.elapsedRealtime(), stage) {
while (true) {
value = (stage.deadline - SystemClock.elapsedRealtime()).coerceAtLeast(0)
delay(1_000)
}
}
Column(verticalArrangement = Arrangement.spacedBy(MusyxTheme.space.m)) {
Step(1, stringResource(R.string.signin_step_open, host), stringResource(R.string.signin_step_open_hint))
Row(horizontalArrangement = Arrangement.spacedBy(MusyxTheme.space.l)) {
Badge(2)
Column(verticalArrangement = Arrangement.spacedBy(MusyxTheme.space.s)) {
Text(stringResource(R.string.signin_step_code), style = MusyxTheme.type.bodyMedium, color = c.fg)
Text(
SignInState.spaced(code.userCode),
style = MusyxTheme.type.displayS,
color = c.fg,
maxLines = 1,
softWrap = false,
modifier = Modifier
.background(c.panel, RoundedCornerShape(MusyxTheme.radius.card))
.border(BorderStroke(1.dp, c.line), RoundedCornerShape(MusyxTheme.radius.card))
.padding(horizontal = 20.dp, vertical = 8.dp),
)
}
}
Step(3, stringResource(R.string.signin_step_back), stringResource(R.string.signin_step_back_hint))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(MusyxTheme.space.m)) {
Box(Modifier.size(10.dp).background(c.accent, CircleShape))
val secs = remaining / 1000
Text(
stringResource(R.string.signin_waiting, "%d:%02d".format(secs / 60, secs % 60)),
style = MusyxTheme.type.meta,
color = c.muted,
modifier = Modifier.weight(1f, fill = false),
)
GhostButton(stringResource(R.string.action_cancel), onClick = signIn::cancel, modifier = Modifier.focusRequester(focus))
}
}
}
@Composable
private fun Step(n: Int, title: String, hint: String) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(MusyxTheme.space.l)) {
Badge(n)
Column {
Text(title, style = MusyxTheme.type.bodyMedium, color = MusyxTheme.colors.fg)
Text(hint, style = MusyxTheme.type.small, color = MusyxTheme.colors.muted)
}
}
}
@Composable
private fun Badge(n: Int) {
val c = MusyxTheme.colors
Box(
Modifier.size(36.dp).border(BorderStroke(1.dp, c.line), CircleShape),
contentAlignment = Alignment.Center,
) {
Text("$n", style = MusyxTheme.type.meta, color = c.muted)
}
}
/** Sign-in with a token someone already has; handy where the phone flow isn't. */
@Composable
private fun TokenFallback(signIn: SignInState) {
val c = MusyxTheme.colors
Column(verticalArrangement = Arrangement.spacedBy(MusyxTheme.space.s)) {
Focusable(onClick = signIn::toggleToken, contentColor = c.muted, focusedContentColor = c.fg) {
Text(
stringResource(if (signIn.tokenOpen) R.string.signin_token_hide else R.string.signin_token_show),
style = MusyxTheme.type.meta,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
)
}
if (signIn.tokenOpen) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(MusyxTheme.space.m)) {
TextInput(
value = signIn.token,
onChange = { signIn.token = it },
placeholder = stringResource(R.string.signin_token_placeholder),
secret = true,
onSubmit = signIn::useToken,
modifier = Modifier.width(320.dp),
)
GhostButton(stringResource(R.string.action_sign_in), onClick = signIn::useToken, enabled = signIn.token.isNotBlank())
}
}
}
}
/** A text field that the TV keyboard edits; the amber ring shows it's focused. */
@Composable
fun TextInput(
value: String,
onChange: (String) -> Unit,
placeholder: String,
modifier: Modifier = Modifier,
secret: Boolean = false,
onSubmit: () -> Unit = {},
imeAction: ImeAction = ImeAction.Done,
) {
val c = MusyxTheme.colors
val shape = RoundedCornerShape(MusyxTheme.radius.pill)
var focused by remember { mutableStateOf(false) }
BasicTextField(
value = value,
onValueChange = onChange,
singleLine = true,
textStyle = MusyxTheme.type.body.copy(color = c.fg),
cursorBrush = SolidColor(c.accent),
visualTransformation = if (secret) PasswordVisualTransformation() else androidx.compose.ui.text.input.VisualTransformation.None,
keyboardOptions = KeyboardOptions(
keyboardType = if (secret) KeyboardType.Password else KeyboardType.Text,
imeAction = imeAction,
),
keyboardActions = KeyboardActions(onDone = { onSubmit() }, onSearch = { onSubmit() }, onGo = { onSubmit() }),
modifier = modifier.onFocusChanged { focused = it.isFocused },
decorationBox = { field ->
Box(
Modifier
.background(c.raised, shape)
.border(BorderStroke(2.dp, if (focused) c.accent else c.line), shape)
.padding(horizontal = 20.dp, vertical = 12.dp),
) {
if (value.isEmpty()) Text(placeholder, style = MusyxTheme.type.body, color = c.muted, maxLines = 1)
field()
}
},
)
}
/** The QR for the sign-in page, on a white card; a lock until a code exists. */
@Composable
private fun QrCard(url: String?) {
val matrix = remember(url) {
url?.let {
runCatching {
QRCodeWriter().encode(it, BarcodeFormat.QR_CODE, 0, 0, mapOf(EncodeHintType.MARGIN to 1))
}.getOrNull()
}
}
val ink = Color(0xFF1C1A22)
Column(
Modifier
.width(280.dp)
.background(Color.White, RoundedCornerShape(MusyxTheme.radius.hero))
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
Box(Modifier.size(220.dp), contentAlignment = Alignment.Center) {
if (matrix != null) {
Canvas(Modifier.fillMaxSize()) {
val cell = size.width / matrix.width
for (y in 0 until matrix.height) for (x in 0 until matrix.width) {
if (matrix[x, y]) drawRect(ink, Offset(x * cell, y * cell), Size(cell + 0.5f, cell + 0.5f))
}
}
} else {
MusyxIcon(R.drawable.ic_lock, tint = Color(0xFF686178), size = 48.dp)
}
}
Text(
stringResource(if (matrix != null) R.string.signin_qr_scan else R.string.signin_qr_later),
style = MusyxTheme.type.small,
color = Color(0xFF4A4458),
textAlign = TextAlign.Center,
)
}
}
@@ -0,0 +1,174 @@
// Settings: account, streaming quality, appearance, font size, language, storage.
package it.panov.musyx.tv.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Text
import it.panov.musyx.tv.BuildConfig
import it.panov.musyx.tv.R
import it.panov.musyx.tv.data.Appearance
import it.panov.musyx.tv.data.FontSize
import it.panov.musyx.tv.data.Locale
import it.panov.musyx.tv.data.Quality
import it.panov.musyx.tv.state.AppState
import it.panov.musyx.tv.state.qualityLabel
import it.panov.musyx.tv.ui.components.Chip
import it.panov.musyx.tv.ui.components.FocusEntry
import it.panov.musyx.tv.ui.components.GhostButton
import it.panov.musyx.tv.ui.components.ScreenTitle
import it.panov.musyx.tv.ui.components.entry
import it.panov.musyx.tv.ui.humanDate
import it.panov.musyx.tv.ui.theme.MusyxTheme
private fun qualityDetail(q: Quality) = when (q) {
Quality.Lossless -> R.string.quality_lossless_detail
Quality.Best -> R.string.quality_best_detail
Quality.Balanced -> R.string.quality_balanced_detail
Quality.DataSaver -> R.string.quality_data_saver_detail
}
private fun appearanceLabel(a: Appearance) = when (a) {
Appearance.System -> R.string.match_system
Appearance.Light -> R.string.appearance_light
Appearance.Dark -> R.string.appearance_dark
}
private fun fontSizeLabel(f: FontSize) = when (f) {
FontSize.Small -> R.string.font_size_small
FontSize.Medium -> R.string.font_size_medium
FontSize.Large -> R.string.font_size_large
}
@Composable
fun SettingsScreen(state: AppState, entry: FocusEntry) {
val settings = state.settings
PageColumn {
item(key = "title") { ScreenTitle(stringResource(R.string.nav_settings)) }
item(key = "account") { AccountCard(state) }
item(key = "quality") {
Section(stringResource(R.string.settings_quality)) {
Row(horizontalArrangement = Arrangement.spacedBy(MusyxTheme.space.s)) {
Quality.entries.forEachIndexed { i, q ->
Chip(
stringResource(qualityLabel(q)),
q == settings.quality,
{ if (q != settings.quality) state.setQuality(q) },
if (i == 0) Modifier.entry(entry) else Modifier,
)
}
}
Text(stringResource(qualityDetail(settings.quality)), style = MusyxTheme.type.meta, color = MusyxTheme.colors.muted)
}
}
item(key = "appearance") {
Section(stringResource(R.string.settings_appearance)) {
Row(horizontalArrangement = Arrangement.spacedBy(MusyxTheme.space.s)) {
Appearance.entries.forEach { a ->
Chip(stringResource(appearanceLabel(a)), a == settings.appearance, { state.setAppearance(a) })
}
}
}
}
item(key = "font-size") {
Section(stringResource(R.string.settings_font_size)) {
Row(horizontalArrangement = Arrangement.spacedBy(MusyxTheme.space.s)) {
FontSize.entries.forEach { f ->
Chip(stringResource(fontSizeLabel(f)), f == settings.fontSize, { state.setFontSize(f) })
}
}
}
}
item(key = "language") {
Section(stringResource(R.string.settings_language)) {
Row(horizontalArrangement = Arrangement.spacedBy(MusyxTheme.space.s)) {
Locale.entries.forEach { l ->
// Language names stay in their own language so they can be found in either.
val label = when (l) {
Locale.System -> stringResource(R.string.match_system)
Locale.English -> "English"
Locale.Russian -> "Русский"
}
Chip(label, l == settings.language, { if (l != settings.language) state.setLanguage(l) })
}
}
}
}
item(key = "storage") {
Section(stringResource(R.string.settings_storage)) {
Text(stringResource(R.string.settings_storage_detail), style = MusyxTheme.type.meta, color = MusyxTheme.colors.muted)
GhostButton(stringResource(R.string.action_clear_covers), onClick = state::clearCoverCache, icon = R.drawable.ic_trash_2)
}
}
item(key = "version") {
Text(
stringResource(R.string.settings_version, BuildConfig.VERSION_NAME),
style = MusyxTheme.type.small,
color = MusyxTheme.colors.muted,
modifier = Modifier.padding(horizontal = MusyxTheme.space.safeX, vertical = MusyxTheme.space.l),
)
}
}
}
@Composable
private fun Section(title: String, content: @Composable () -> Unit) {
val space = MusyxTheme.space
Column(
Modifier
.padding(horizontal = space.safeX, vertical = space.s)
.fillMaxWidth()
.background(MusyxTheme.colors.panel, RoundedCornerShape(MusyxTheme.radius.card))
.padding(24.dp),
verticalArrangement = Arrangement.spacedBy(space.l),
) {
Text(title, style = MusyxTheme.type.section, color = MusyxTheme.colors.fg)
content()
}
}
@Composable
private fun AccountCard(state: AppState) {
val me = state.account ?: return
val c = MusyxTheme.colors
val space = MusyxTheme.space
val end = me.subscriptionEnd?.let { humanDate(it) }
val plan = when {
me.hasPlus && end != null -> stringResource(R.string.plus_until, end)
me.hasPlus -> stringResource(R.string.plus)
else -> stringResource(R.string.plus_none)
}
Row(
Modifier
.padding(horizontal = space.safeX, vertical = space.s)
.fillMaxWidth()
.background(c.panel, RoundedCornerShape(MusyxTheme.radius.card))
.padding(24.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(18.dp),
) {
Box(Modifier.size(64.dp).background(c.accent, CircleShape), contentAlignment = Alignment.Center) {
Text(me.initial, style = MusyxTheme.type.section, color = Color(0xFF1C1A22))
}
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(me.name, style = MusyxTheme.type.section, color = c.fg)
Text(me.login, style = MusyxTheme.type.body, color = c.muted)
Text(plan, style = MusyxTheme.type.meta, color = if (me.hasPlus) c.ok else c.muted, modifier = Modifier.widthIn(max = 560.dp))
}
GhostButton(stringResource(R.string.action_sign_out), onClick = state::signOut, icon = R.drawable.ic_log_out)
}
}
@@ -0,0 +1,251 @@
// Dialogs over the screen (track actions, new/rename playlist, delete confirmation) and the
// toast that floats above everything after an action.
package it.panov.musyx.tv.ui.screens
import androidx.annotation.DrawableRes
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.tv.material3.Text
import it.panov.musyx.tv.R
import it.panov.musyx.tv.state.AppState
import it.panov.musyx.tv.state.Route
import it.panov.musyx.tv.state.Sheet
import it.panov.musyx.tv.ui.artistsOrUnknown
import it.panov.musyx.tv.ui.components.Divider
import it.panov.musyx.tv.ui.components.Focusable
import it.panov.musyx.tv.ui.components.GhostButton
import it.panov.musyx.tv.ui.components.MusyxIcon
import it.panov.musyx.tv.ui.components.PrimaryButton
import it.panov.musyx.tv.ui.text
import it.panov.musyx.tv.ui.theme.MusyxTheme
import kotlinx.coroutines.delay
/** How long a status message stays up. */
private const val TOAST_MS = 4_000L
@Composable
fun SheetHost(state: AppState) {
val sheet = state.sheet ?: return
Dialog(onDismissRequest = state::closeSheet) {
val c = MusyxTheme.colors
Column(
Modifier
.width(520.dp)
.background(c.panel, RoundedCornerShape(MusyxTheme.radius.card))
.border(1.dp, c.line, RoundedCornerShape(MusyxTheme.radius.card))
.padding(20.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
when (sheet) {
is Sheet.TrackMenu -> if (sheet.choosing) ChoosePlaylist(state, sheet) else TrackMenu(state, sheet)
is Sheet.NewPlaylist -> NameDialog(
title = stringResource(R.string.sheet_new_playlist),
initial = "",
hint = stringResource(if (sheet.add != null) R.string.sheet_new_hint_track else R.string.sheet_new_hint),
confirm = stringResource(R.string.action_create),
onCancel = state::closeSheet,
) { state.createPlaylist(it, sheet.add) }
is Sheet.Rename -> NameDialog(
title = stringResource(R.string.sheet_rename_playlist),
initial = sheet.name,
hint = null,
confirm = stringResource(R.string.action_rename),
onCancel = state::closeSheet,
) { state.renamePlaylist(sheet.id, it) }
is Sheet.ConfirmDelete -> {
Title(stringResource(R.string.sheet_delete_title, sheet.title), null)
Text(stringResource(R.string.sheet_delete_body), style = MusyxTheme.type.meta, color = c.muted)
val focus = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { focus.requestFocus() } }
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
GhostButton(stringResource(R.string.action_cancel), onClick = state::closeSheet, modifier = Modifier.focusRequester(focus))
GhostButton(stringResource(R.string.action_delete), onClick = { state.deletePlaylist(sheet.id) }, danger = true)
}
}
}
}
}
}
@Composable
private fun Title(title: String, subtitle: String?) {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(title, style = MusyxTheme.type.section, color = MusyxTheme.colors.fg, maxLines = 2, overflow = TextOverflow.Ellipsis)
if (subtitle != null) Text(subtitle, style = MusyxTheme.type.meta, color = MusyxTheme.colors.muted, maxLines = 1)
}
}
/** A list of actions that takes focus on its first item when it opens. */
@Composable
private fun Actions(content: LazyListScope.(FocusRequester) -> Unit) {
val first = remember { FocusRequester() }
LaunchedEffect(Unit) {
delay(50)
runCatching { first.requestFocus() }
}
LazyColumn(Modifier.heightIn(max = 420.dp), contentPadding = PaddingValues(vertical = 2.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
content(first)
}
}
@Composable
private fun Item(@DrawableRes icon: Int, label: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
Focusable(onClick = onClick, modifier = modifier.fillMaxWidth()) {
Row(
Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(14.dp),
) {
MusyxIcon(icon, tint = MusyxTheme.colors.muted)
Text(label, style = MusyxTheme.type.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
@Composable
private fun TrackMenu(state: AppState, sheet: Sheet.TrackMenu) {
val track = sheet.track
val playing = state.playback.state.track?.id == track.id
val liked = state.liked.contains(track.id)
val disliked = track.id in state.likes.dislikedTracks
Title(track.fullTitle, track.artistsOrUnknown())
Actions { first ->
item {
if (playing) Item(R.drawable.ic_skip_forward, stringResource(R.string.menu_next_track), Modifier.focusRequester(first), state::skipFromMenu)
else Item(R.drawable.ic_skip_forward, stringResource(R.string.menu_play_next), Modifier.focusRequester(first)) { state.playNext(track) }
}
item { Item(R.drawable.ic_list_music, stringResource(R.string.menu_add_to_queue)) { state.addToQueue(track) } }
item {
Item(
if (liked) R.drawable.ic_heart_fill else R.drawable.ic_heart,
stringResource(if (liked) R.string.menu_unlike else R.string.menu_like),
) {
state.closeSheet()
state.likeTrack(track, !liked)
}
}
item { Item(R.drawable.ic_plus, stringResource(R.string.menu_add_to_playlist)) { state.openSheet(sheet.copy(choosing = true)) } }
item { Item(R.drawable.ic_audio_lines, stringResource(R.string.menu_play_similar)) { state.playSimilar(track) } }
track.album?.let { album ->
item { Item(R.drawable.ic_disc_3, stringResource(R.string.menu_go_to_album)) { state.navigate(Route.Album(album.id)) } }
}
track.artists.filter { it.id != null }.take(3).forEach { artist ->
item {
Item(R.drawable.ic_mic_vocal, stringResource(R.string.menu_go_to_artist_named, artist.name)) {
state.navigate(Route.Artist(artist.id!!))
}
}
}
item {
Item(R.drawable.ic_ban, stringResource(if (disliked) R.string.menu_undislike else R.string.menu_dislike)) {
state.dislikeTrack(track, !disliked)
}
}
sheet.playlist?.let { slot ->
item { Divider(Modifier.padding(vertical = 6.dp)) }
slot.up?.let { up ->
item {
Item(R.drawable.ic_chevron_left, stringResource(R.string.menu_move_up)) {
state.movePlaylistTrack(slot.id, track, slot.index, up)
}
}
}
// Delete-then-insert: the row below shifts up one, so inserting at its old index lands after it.
slot.down?.let { down ->
item {
Item(R.drawable.ic_chevron_right, stringResource(R.string.menu_move_down)) {
state.movePlaylistTrack(slot.id, track, slot.index, down)
}
}
}
item { Item(R.drawable.ic_trash_2, stringResource(R.string.menu_remove_from_playlist)) { state.removeFromPlaylist(slot.id, slot.index) } }
}
}
}
@Composable
private fun ChoosePlaylist(state: AppState, sheet: Sheet.TrackMenu) {
val own = state.playlists.get()?.own.orEmpty()
Title(stringResource(R.string.sheet_add_to_playlist), sheet.track.fullTitle)
Actions { first ->
item {
Item(R.drawable.ic_plus, stringResource(R.string.menu_new_playlist), Modifier.focusRequester(first)) {
state.openSheet(Sheet.NewPlaylist(sheet.track))
}
}
own.forEach { p ->
item(key = p.id.key) { Item(R.drawable.ic_list_music, p.title) { state.addToPlaylist(p.id, sheet.track) } }
}
}
}
@Composable
private fun NameDialog(title: String, initial: String, hint: String?, confirm: String, onCancel: () -> Unit, onConfirm: (String) -> Unit) {
var name by remember { mutableStateOf(initial) }
val focus = remember { FocusRequester() }
LaunchedEffect(Unit) {
delay(50)
runCatching { focus.requestFocus() }
}
Title(title, null)
TextInput(
value = name,
onChange = { name = it },
placeholder = stringResource(R.string.sheet_playlist_name),
onSubmit = { if (name.isNotBlank()) onConfirm(name) },
modifier = Modifier.fillMaxWidth().focusRequester(focus),
)
if (hint != null) Text(hint, style = MusyxTheme.type.meta, color = MusyxTheme.colors.muted)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
GhostButton(stringResource(R.string.action_cancel), onClick = onCancel)
PrimaryButton(confirm, onClick = { onConfirm(name) }, enabled = name.isNotBlank())
}
}
/** The status line that floats above the bottom of the screen after an action. */
@Composable
fun ToastHost(state: AppState) {
val toast = state.toast ?: return
LaunchedEffect(toast.serial) {
delay(TOAST_MS)
state.dismissToast(toast.serial)
}
val c = MusyxTheme.colors
Box(Modifier.fillMaxSize().padding(bottom = 96.dp), contentAlignment = Alignment.BottomCenter) {
Text(
text(toast.text),
style = MusyxTheme.type.bodyMedium,
color = c.bg,
modifier = Modifier
.background(c.fg, RoundedCornerShape(MusyxTheme.radius.pill))
.padding(horizontal = 24.dp, vertical = 12.dp),
)
}
}
@@ -0,0 +1,379 @@
// Design tokens and the Compose theme. Mirrors DESIGN.md and the desktop app's
// `src/ui/theme.rs`; change all three together.
package it.panov.musyx.tv.ui.theme
import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.em
import androidx.compose.ui.unit.sp
import androidx.tv.material3.ColorScheme
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Shapes
import androidx.tv.material3.Typography
import androidx.tv.material3.darkColorScheme
import androidx.tv.material3.lightColorScheme
import it.panov.musyx.tv.R
import kotlin.math.abs
// ---- Colour ----
/** Colour tokens for one theme mode. */
@Immutable
data class MusyxColors(
val bg: Color,
val panel: Color,
val raised: Color,
val line: Color,
val fg: Color,
val muted: Color,
val accent: Color,
val accentInk: Color,
val like: Color,
val ok: Color,
val isDark: Boolean,
)
val DarkColors = MusyxColors(
bg = Color(0xFF1C1A22),
panel = Color(0xFF23202B),
raised = Color(0xFF2D2937),
line = Color(0xFF3A3546),
fg = Color(0xFFEEEAF3),
muted = Color(0xFFA39CB0),
accent = Color(0xFFF0B23E),
accentInk = Color(0xFF2A1D04),
like = Color(0xFFF27286),
ok = Color(0xFF7FCB9B),
isDark = true,
)
val LightColors = MusyxColors(
bg = Color(0xFFF3F1F6),
panel = Color(0xFFFFFFFF),
raised = Color(0xFFEAE6F0),
line = Color(0xFFDCD6E4),
fg = Color(0xFF1F1B27),
muted = Color(0xFF686178),
accent = Color(0xFFA86C05),
accentInk = Color(0xFFFFF7E6),
like = Color(0xFFD2405A),
ok = Color(0xFF2E8A55),
isDark = false,
)
/**
* Musyx is dark-first: it goes light only when the system explicitly asks for it, so an
* undefined night mode (common on TVs) stays dark. `values-notnight/colors.xml` matches this.
*/
@Composable
@ReadOnlyComposable
fun isMusyxDark(): Boolean =
LocalConfiguration.current.uiMode and Configuration.UI_MODE_NIGHT_MASK != Configuration.UI_MODE_NIGHT_NO
private fun MusyxColors.toColorScheme(): ColorScheme =
(if (isDark) darkColorScheme() else lightColorScheme()).copy(
primary = accent,
onPrimary = accentInk,
primaryContainer = raised,
onPrimaryContainer = fg,
inversePrimary = accent,
secondary = muted,
onSecondary = bg,
secondaryContainer = raised,
onSecondaryContainer = fg,
tertiary = ok,
onTertiary = bg,
tertiaryContainer = raised,
onTertiaryContainer = fg,
background = bg,
onBackground = fg,
surface = panel,
onSurface = fg,
surfaceVariant = raised,
onSurfaceVariant = muted,
surfaceTint = raised,
inverseSurface = fg,
inverseOnSurface = bg,
error = like,
onError = accentInk,
errorContainer = raised,
onErrorContainer = like,
border = line,
borderVariant = line,
)
// ---- Type ----
val Onest = FontFamily(
Font(R.font.onest_regular, FontWeight.Normal),
Font(R.font.onest_medium, FontWeight.Medium),
Font(R.font.onest_semibold, FontWeight.SemiBold),
)
val Unbounded = FontFamily(Font(R.font.unbounded_semibold, FontWeight.SemiBold))
/**
* Desktop sizes are in px at arm's length. The TV is read from across the room, so every
* size is multiplied by this once; tune it here rather than per style. The font size setting
* swaps in its own scale for text; icons and controls stay at this one.
*/
const val TV_TYPE_SCALE = 1.5f
/** The type roles of DESIGN.md, at TV size. Line heights and tracking follow the mockup. */
@Immutable
data class MusyxType(
/** My Wave hero, big (46). */
val displayXl: TextStyle,
/** Detail page titles (40). */
val displayL: TextStyle,
/** My Wave hero, sign-in headline (34). */
val displayM: TextStyle,
/** Screen titles (30). */
val displayS: TextStyle,
/** `musyx` + the amber dot (20). */
val wordmark: TextStyle,
/** Section headings such as "Made for you" (19). */
val section: TextStyle,
/** Rows and running text (14). */
val body: TextStyle,
/** Titles in rows and cards, nav labels (14, Medium). */
val bodyMedium: TextStyle,
/** Subtitles and secondary lines (13). */
val meta: TextStyle,
/** Table heads, small labels (12.5). */
val small: TextStyle,
/** The multiplier applied to the desktop sizes, for things drawn to match the text. */
val scale: Float,
)
private fun display(scale: Float, size: Float, lineHeight: Float, tracking: Float) = TextStyle(
fontFamily = Unbounded,
fontWeight = FontWeight.SemiBold,
fontSize = (size * scale).sp,
lineHeight = lineHeight.em,
letterSpacing = tracking.em,
)
private fun onest(scale: Float, size: Float, weight: FontWeight = FontWeight.Normal) = TextStyle(
fontFamily = Onest,
fontWeight = weight,
fontSize = (size * scale).sp,
lineHeight = 1.45.em,
)
/** The type roles with every desktop size multiplied by [scale]. */
fun musyxType(scale: Float = TV_TYPE_SCALE) = MusyxType(
displayXl = display(scale, 46f, 1.05f, -0.02f),
displayL = display(scale, 40f, 1.08f, -0.02f),
displayM = display(scale, 34f, 1.05f, -0.02f),
displayS = display(scale, 30f, 1.15f, -0.015f),
wordmark = display(scale, 20f, 1f, -0.01f),
section = onest(scale, 19f, FontWeight.SemiBold).copy(lineHeight = 1.2.em, letterSpacing = (-0.005).em),
body = onest(scale, 14f),
bodyMedium = onest(scale, 14f, FontWeight.Medium),
meta = onest(scale, 13f),
small = onest(scale, 12.5f),
scale = scale,
)
val MusyxTypeScale = musyxType()
/** Durations and counts use tabular figures. */
fun TextStyle.tabular(): TextStyle = copy(fontFeatureSettings = "tnum")
private fun MusyxType.toTypography() = Typography(
displayLarge = displayXl,
displayMedium = displayL,
displaySmall = displayM,
headlineLarge = displayS,
headlineMedium = wordmark,
headlineSmall = section,
titleLarge = section,
titleMedium = bodyMedium,
titleSmall = bodyMedium,
bodyLarge = body,
bodyMedium = body,
bodySmall = meta,
labelLarge = bodyMedium,
labelMedium = meta,
labelSmall = small,
)
// ---- Space and shape ----
/** Spacing steps 2 · 4 · 6 · 8 · 10 · 12 · 14 · 18 · 22 · 28 · 34, named as in theme.rs. */
@Immutable
data class MusyxSpacing(
val xxs: Dp = 2.dp,
val xs: Dp = 4.dp,
val s6: Dp = 6.dp,
val s: Dp = 8.dp,
val s10: Dp = 10.dp,
val m: Dp = 12.dp,
val s14: Dp = 14.dp,
val l: Dp = 18.dp,
val xl: Dp = 22.dp,
/** Content gutter. */
val gutter: Dp = 28.dp,
/** Gap between sections. */
val section: Dp = 34.dp,
/** TV overscan: keep content inside 5% of the 960×540 dp screen (Android TV guidance). */
val safeX: Dp = 48.dp,
val safeY: Dp = 27.dp,
)
@Immutable
data class MusyxRadius(
val cover: Dp = 10.dp,
val control: Dp = 8.dp,
val smallCover: Dp = 6.dp,
val pill: Dp = 999.dp,
val hero: Dp = 16.dp,
/** Window cards (empty state, device-code box). */
val card: Dp = 14.dp,
)
/** Shell dimensions from the desktop app; the sidebar is the TV navigation drawer. */
@Immutable
data class MusyxShell(
val sidebar: Dp = 232.dp,
val player: Dp = 80.dp,
val drawer: Dp = 320.dp,
val trackRow: Dp = 52.dp,
val icon: Dp = 18.dp,
)
private fun MusyxRadius.toShapes() = Shapes(
extraSmall = RoundedCornerShape(smallCover),
small = RoundedCornerShape(control),
medium = RoundedCornerShape(cover),
large = RoundedCornerShape(card),
extraLarge = RoundedCornerShape(hero),
)
// ---- Cover placeholder ----
/** 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() },
)
}
/** Placeholder art for an item without a cover yet: two hues on a 135° diagonal. */
fun coverBrush(h1: Float, h2: Float): Brush = Brush.linearGradient(
0f to hsl(h1, 0.70f, 0.60f),
0.55f to hsl((h1 + h2) / 2f, 0.45f, 0.30f),
1f to hsl(h2, 0.40f, 0.16f),
start = Offset.Zero,
end = Offset.Infinite,
)
@Composable
fun CoverPlaceholder(hues: Pair<Float, Float>, modifier: Modifier = Modifier) {
Box(modifier.background(coverBrush(hues.first, hues.second)))
}
internal fun hsl(h: Float, s: Float, l: Float): Color {
val c = (1f - abs(2f * l - 1f)) * s
val hp = h.mod(360f) / 60f
val x = c * (1f - abs(hp % 2f - 1f))
val (r, g, b) = when (hp.toInt()) {
0 -> Triple(c, x, 0f)
1 -> Triple(x, c, 0f)
2 -> Triple(0f, c, x)
3 -> Triple(0f, x, c)
4 -> Triple(x, 0f, c)
else -> Triple(c, 0f, x)
}
val m = l - c / 2f
return Color(r + m, g + m, b + m)
}
/** Linear blend of two colours; `amount` is the share of `b`. */
fun mix(a: Color, b: Color, amount: Float): Color = Color(
red = a.red + (b.red - a.red) * amount,
green = a.green + (b.green - a.green) * amount,
blue = a.blue + (b.blue - a.blue) * amount,
alpha = a.alpha + (b.alpha - a.alpha) * amount,
)
// ---- Theme ----
val LocalMusyxColors = staticCompositionLocalOf { DarkColors }
val LocalMusyxType = staticCompositionLocalOf { MusyxTypeScale }
val LocalMusyxSpacing = staticCompositionLocalOf { MusyxSpacing() }
val LocalMusyxRadius = staticCompositionLocalOf { MusyxRadius() }
val LocalMusyxShell = staticCompositionLocalOf { MusyxShell() }
/**
* The Musyx theme over tv-material's [MaterialTheme]. Material components get a colour scheme,
* type scale and shapes built from the tokens; Musyx code reads the tokens through [MusyxTheme].
*/
@Composable
fun MusyxTheme(
dark: Boolean = isMusyxDark(),
typeScale: Float = TV_TYPE_SCALE,
content: @Composable () -> Unit,
) {
val colors = if (dark) DarkColors else LightColors
val type = remember(typeScale) { musyxType(typeScale) }
val radius = MusyxRadius()
CompositionLocalProvider(
LocalMusyxColors provides colors,
LocalMusyxType provides type,
LocalMusyxSpacing provides MusyxSpacing(),
LocalMusyxRadius provides radius,
LocalMusyxShell provides MusyxShell(),
) {
MaterialTheme(
colorScheme = colors.toColorScheme(),
shapes = radius.toShapes(),
typography = type.toTypography(),
content = content,
)
}
}
/** Token access for the current composition, like `MaterialTheme.colorScheme`. */
object MusyxTheme {
val colors: MusyxColors
@Composable @ReadOnlyComposable get() = LocalMusyxColors.current
val type: MusyxType
@Composable @ReadOnlyComposable get() = LocalMusyxType.current
val space: MusyxSpacing
@Composable @ReadOnlyComposable get() = LocalMusyxSpacing.current
val radius: MusyxRadius
@Composable @ReadOnlyComposable get() = LocalMusyxRadius.current
val shell: MusyxShell
@Composable @ReadOnlyComposable get() = LocalMusyxShell.current
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide audio-lines (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 2 10 v 3"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 6 6 v 11"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 10 3 v 18"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 14 8 v 7"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 18 5 v 13"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 22 10 v 3"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide ban (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 2 12 a 10 10 0 1 0 20 0 a 10 10 0 1 0 -20 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="m 4.9 4.9 14.2 14.2"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide chevron-left (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="m 15 18 -6 -6 6 -6"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide chevron-right (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="m 9 18 6 -6 -6 -6"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide clock-3 (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 2 12 a 10 10 0 1 0 20 0 a 10 10 0 1 0 -20 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 12 6 L 12 12 L 16.5 12"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide copy (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 10 8 h 10 a 2 2 0 0 1 2 2 v 10 a 2 2 0 0 1 -2 2 h -10 a 2 2 0 0 1 -2 -2 v -10 a 2 2 0 0 1 2 -2 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 4 16 c -1.1 0 -2 -0.9 -2 -2 V 4 c 0 -1.1 0.9 -2 2 -2 h 10 c 1.1 0 2 0.9 2 2"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide disc-3 (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 2 12 a 10 10 0 1 0 20 0 a 10 10 0 1 0 -20 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 6 12 c 0 -1.7 0.7 -3.2 1.8 -4.2"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 10 12 a 2 2 0 1 0 4 0 a 2 2 0 1 0 -4 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 18 12 c 0 1.7 -0.7 3.2 -1.8 4.2"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide ellipsis (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 11 12 a 1 1 0 1 0 2 0 a 1 1 0 1 0 -2 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 18 12 a 1 1 0 1 0 2 0 a 1 1 0 1 0 -2 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 4 12 a 1 1 0 1 0 2 0 a 1 1 0 1 0 -2 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide globe (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 2 12 a 10 10 0 1 0 20 0 a 10 10 0 1 0 -20 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 12 2 a 14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0 -20"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 2 12 h 20"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide grip-vertical (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 8 12 a 1 1 0 1 0 2 0 a 1 1 0 1 0 -2 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 8 5 a 1 1 0 1 0 2 0 a 1 1 0 1 0 -2 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 8 19 a 1 1 0 1 0 2 0 a 1 1 0 1 0 -2 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 14 12 a 1 1 0 1 0 2 0 a 1 1 0 1 0 -2 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 14 5 a 1 1 0 1 0 2 0 a 1 1 0 1 0 -2 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 14 19 a 1 1 0 1 0 2 0 a 1 1 0 1 0 -2 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide heart (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 19 14 c 1.49 -1.46 3 -3.21 3 -5.5 A 5.5 5.5 0 0 0 16.5 3 c -1.76 0 -3 0.5 -4.5 2 -1.5 -1.5 -2.74 -2 -4.5 -2 A 5.5 5.5 0 0 0 2 8.5 c 0 2.3 1.5 4.05 3 5.5 l 7 7 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide heart-fill (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 19 14 c 1.49 -1.46 3 -3.21 3 -5.5 A 5.5 5.5 0 0 0 16.5 3 c -1.76 0 -3 0.5 -4.5 2 -1.5 -1.5 -2.74 -2 -4.5 -2 A 5.5 5.5 0 0 0 2 8.5 c 0 2.3 1.5 4.05 3 5.5 l 7 7 Z"
android:fillColor="@android:color/white"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide house (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 15 21 v -8 a 1 1 0 0 0 -1 -1 h -4 a 1 1 0 0 0 -1 1 v 8"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 3 10 a 2 2 0 0 1 0.709 -1.528 l 7 -5.999 a 2 2 0 0 1 2.582 0 l 7 5.999 A 2 2 0 0 1 21 10 v 9 a 2 2 0 0 1 -2 2 H 5 a 2 2 0 0 1 -2 -2 z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide library (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="m 16 6 4 14"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 12 6 v 14"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 8 8 v 12"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 4 4 v 16"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide list-music (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 21 15 V 6"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 18.5 18 a 2.5 2.5 0 1 0 0 -5 2.5 2.5 0 0 0 0 5 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 12 12 H 3"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 16 6 H 3"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 12 18 H 3"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide lock (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 5 11 h 14 a 2 2 0 0 1 2 2 v 7 a 2 2 0 0 1 -2 2 h -14 a 2 2 0 0 1 -2 -2 v -7 a 2 2 0 0 1 2 -2 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 7 11 V 7 a 5 5 0 0 1 10 0 v 4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide log-out (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 9 21 H 5 a 2 2 0 0 1 -2 -2 V 5 a 2 2 0 0 1 2 -2 h 4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 16 17 L 21 12 L 16 7"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 21 12 L 9 12"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide mic-vocal (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="m 11 7.601 -5.994 8.19 a 1 1 0 0 0 0.1 1.298 l 0.817 0.818 a 1 1 0 0 0 1.314 0.087 L 15.09 12"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 16.5 21.174 C 15.5 20.5 14.372 20 13 20 c -2.058 0 -3.928 2.356 -6 2 -2.072 -0.356 -2.775 -3.369 -1.5 -4.5"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 11 7 a 5 5 0 1 0 10 0 a 5 5 0 1 0 -10 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide pause (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 15 4 h 2 a 1 1 0 0 1 1 1 v 14 a 1 1 0 0 1 -1 1 h -2 a 1 1 0 0 1 -1 -1 v -14 a 1 1 0 0 1 1 -1 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 7 4 h 2 a 1 1 0 0 1 1 1 v 14 a 1 1 0 0 1 -1 1 h -2 a 1 1 0 0 1 -1 -1 v -14 a 1 1 0 0 1 1 -1 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide pause-fill (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 15 4 h 2 a 1 1 0 0 1 1 1 v 14 a 1 1 0 0 1 -1 1 h -2 a 1 1 0 0 1 -1 -1 v -14 a 1 1 0 0 1 1 -1 Z"
android:fillColor="@android:color/white"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 7 4 h 2 a 1 1 0 0 1 1 1 v 14 a 1 1 0 0 1 -1 1 h -2 a 1 1 0 0 1 -1 -1 v -14 a 1 1 0 0 1 1 -1 Z"
android:fillColor="@android:color/white"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide pencil (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 21.174 6.812 a 1 1 0 0 0 -3.986 -3.987 L 3.842 16.174 a 2 2 0 0 0 -0.5 0.83 l -1.321 4.352 a 0.5 0.5 0 0 0 0.623 0.622 l 4.353 -1.32 a 2 2 0 0 0 0.83 -0.497 z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="m 15 5 4 4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide play (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 6 3 L 20 12 L 6 21 L 6 3 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide play-fill (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 6 3 L 20 12 L 6 21 L 6 3 Z"
android:fillColor="@android:color/white"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide plus (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 5 12 h 14"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 12 5 v 14"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide podcast (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 16.85 18.58 a 9 9 0 1 0 -9.7 0"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 8 14 a 5 5 0 1 1 8 0"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 11 11 a 1 1 0 1 0 2 0 a 1 1 0 1 0 -2 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 13 17 a 1 1 0 1 0 -2 0 l 0.5 4.5 a 0.5 0.5 0 1 0 1 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide repeat (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="m 17 2 4 4 -4 4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 3 11 v -1 a 4 4 0 0 1 4 -4 h 14"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="m 7 22 -4 -4 4 -4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 21 13 v 1 a 4 4 0 0 1 -4 4 H 3"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+38
View File
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide repeat-1 (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="m 17 2 4 4 -4 4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 3 11 v -1 a 4 4 0 0 1 4 -4 h 14"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="m 7 22 -4 -4 4 -4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 21 13 v 1 a 4 4 0 0 1 -4 4 H 3"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 11 10 h 1 v 4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide search (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 3 11 a 8 8 0 1 0 16 0 a 8 8 0 1 0 -16 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="m 21 21 -4.3 -4.3"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide settings (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 12.22 2 h -0.44 a 2 2 0 0 0 -2 2 v 0.18 a 2 2 0 0 1 -1 1.73 l -0.43 0.25 a 2 2 0 0 1 -2 0 l -0.15 -0.08 a 2 2 0 0 0 -2.73 0.73 l -0.22 0.38 a 2 2 0 0 0 0.73 2.73 l 0.15 0.1 a 2 2 0 0 1 1 1.72 v 0.51 a 2 2 0 0 1 -1 1.74 l -0.15 0.09 a 2 2 0 0 0 -0.73 2.73 l 0.22 0.38 a 2 2 0 0 0 2.73 0.73 l 0.15 -0.08 a 2 2 0 0 1 2 0 l 0.43 0.25 a 2 2 0 0 1 1 1.73 V 20 a 2 2 0 0 0 2 2 h 0.44 a 2 2 0 0 0 2 -2 v -0.18 a 2 2 0 0 1 1 -1.73 l 0.43 -0.25 a 2 2 0 0 1 2 0 l 0.15 0.08 a 2 2 0 0 0 2.73 -0.73 l 0.22 -0.39 a 2 2 0 0 0 -0.73 -2.73 l -0.15 -0.08 a 2 2 0 0 1 -1 -1.74 v -0.5 a 2 2 0 0 1 1 -1.74 l 0.15 -0.09 a 2 2 0 0 0 0.73 -2.73 l -0.22 -0.38 a 2 2 0 0 0 -2.73 -0.73 l -0.15 0.08 a 2 2 0 0 1 -2 0 l -0.43 -0.25 a 2 2 0 0 1 -1 -1.73 V 4 a 2 2 0 0 0 -2 -2 z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 9 12 a 3 3 0 1 0 6 0 a 3 3 0 1 0 -6 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+38
View File
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide shuffle (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 2 18 h 1.4 c 1.3 0 2.5 -0.6 3.3 -1.7 l 6.1 -8.6 c 0.7 -1.1 2 -1.7 3.3 -1.7 H 22"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="m 18 2 4 4 -4 4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 2 6 h 1.9 c 1.5 0 2.9 0.9 3.6 2.2"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 22 18 h -5.9 c -1.3 0 -2.6 -0.7 -3.3 -1.8 l -0.5 -0.8"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="m 18 14 4 4 -4 4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide skip-back (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 19 20 L 9 12 L 19 4 L 19 20 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 5 19 L 5 5"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide skip-forward (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 5 4 L 15 12 L 5 20 L 5 4 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 19 5 L 19 19"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide sliders-horizontal (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 21 4 L 14 4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 10 4 L 3 4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 21 12 L 12 12"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 8 12 L 3 12"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 21 20 L 16 20"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 12 20 L 3 20"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 14 2 L 14 6"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 8 10 L 8 14"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 16 18 L 16 22"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+38
View File
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide trash-2 (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 3 6 h 18"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 19 6 v 14 c 0 1 -1 2 -2 2 H 7 c -1 0 -2 -1 -2 -2 V 6"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 8 6 V 4 c 0 -1 1 -2 2 -2 h 4 c 1 0 2 1 2 2 v 2"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 10 11 L 10 17"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 14 11 L 14 17"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide trending-up (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 22 7 L 13.5 15.5 L 8.5 10.5 L 2 17"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 16 7 L 22 7 L 22 13"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide volume-2 (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 11 4.702 a 0.705 0.705 0 0 0 -1.203 -0.498 L 6.413 7.587 A 1.4 1.4 0 0 1 5.416 8 H 3 a 1 1 0 0 0 -1 1 v 6 a 1 1 0 0 0 1 1 h 2.416 a 1.4 1.4 0 0 1 0.997 0.413 l 3.383 3.384 A 0.705 0.705 0 0 0 11 19.298 z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 16 9 a 5 5 0 0 1 0 6"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 19.364 18.364 a 9 9 0 0 0 0 -12.728"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide volume-x (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 11 4.702 a 0.705 0.705 0 0 0 -1.203 -0.498 L 6.413 7.587 A 1.4 1.4 0 0 1 5.416 8 H 3 a 1 1 0 0 0 -1 1 v 6 a 1 1 0 0 0 1 1 h 2.416 a 1.4 1.4 0 0 1 0.997 0.413 l 3.383 3.384 A 0.705 0.705 0 0 0 11 19.298 z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 22 9 L 16 15"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 16 9 L 22 15"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
+20
View File
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide x (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 18 6 6 18"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="m 6 6 12 12"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="bg">#F3F1F6</color>
</resources>
+334
View File
@@ -0,0 +1,334 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Terms follow the Yandex Music apps ("Моя волна", "Мне нравится", "Чарт"), as on the desktop. -->
<resources>
<string name="lang_code">ru</string>
<string name="nav_home">Главная</string>
<string name="nav_wave">Моя волна</string>
<string name="nav_search">Поиск</string>
<string name="nav_collection">Коллекция</string>
<string name="nav_podcasts">Подкасты</string>
<string name="nav_settings">Настройки</string>
<string name="unknown_artist">Неизвестный исполнитель</string>
<string name="session_checking">Проверяем вход…</string>
<string name="session_signing_in">Входим…</string>
<string name="unreachable_title">Яндекс Музыка недоступна</string>
<string name="unreachable_body">Вы по-прежнему в аккаунте. Проверьте подключение к интернету и попробуйте ещё раз.</string>
<string name="signin_title">Войдите с аккаунтом Яндекса</string>
<string name="signin_blurb">Musyx играет вашу коллекцию Яндекс Музыки, Мою волну и плейлисты. Вход подтверждается на странице самого Яндекса, поэтому пароль никогда не проходит через это приложение.</string>
<string name="signin_footer">Musyx — неофициальный клиент, не связанный с Яндексом. Токен входа хранится на этом устройстве в зашифрованном виде.</string>
<string name="signin_get_code">Получить код для входа</string>
<string name="signin_getting_code">Получаем код…</string>
<string name="signin_step_open">Откройте %1$s</string>
<string name="signin_step_open_hint">На телефоне или компьютере. Можно и отсканировать QR-код.</string>
<string name="signin_step_code">Введите этот код</string>
<string name="signin_step_back">Вернитесь сюда</string>
<string name="signin_step_back_hint">Musyx войдёт, как только вы разрешите доступ.</string>
<string name="signin_waiting">Ждём подтверждения · код действует ещё %1$s</string>
<string name="signin_token_show">Войти с готовым токеном</string>
<string name="signin_token_hide">Скрыть вход по токену</string>
<string name="signin_token_placeholder">Вставьте OAuth-токен</string>
<string name="signin_qr_scan">Отсканируйте, чтобы открыть страницу входа</string>
<string name="signin_qr_later">QR-код появится вместе с кодом для входа</string>
<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="action_play">Слушать</string>
<string name="action_shuffle">Вперемешку</string>
<string name="action_pause">Пауза</string>
<string name="action_resume">Продолжить</string>
<string name="action_try_again">Повторить</string>
<string name="action_cancel">Отмена</string>
<string name="action_sign_in">Войти</string>
<string name="action_sign_out">Выйти</string>
<string name="action_show_all">Показать все</string>
<string name="action_show_all_n">Показать все %1$d</string>
<string name="action_show_more">Показать ещё</string>
<string name="action_play_radio">Включить радио</string>
<string name="action_rename">Переименовать</string>
<string name="action_make_private">Сделать закрытым</string>
<string name="action_make_public">Сделать открытым</string>
<string name="action_delete">Удалить</string>
<string name="action_create">Создать</string>
<string name="action_new_playlist">Новый плейлист…</string>
<string name="action_clear_covers">Очистить кеш обложек</string>
<string name="section_recent">Вы недавно слушали</string>
<string name="section_made_for_you">Собрано для вас</string>
<string name="section_chart">Чарт</string>
<string name="section_new_releases">Новые релизы</string>
<string name="section_new_playlists">Новые плейлисты</string>
<string name="section_genres">Жанры</string>
<string name="section_stations">Станции</string>
<string name="section_your_playlists">Ваши плейлисты</string>
<string name="section_liked_playlists">Понравившиеся плейлисты</string>
<string name="section_popular">Популярные треки</string>
<string name="section_appears_on">Участвует в</string>
<string name="section_similar_artists">Похожие исполнители</string>
<string name="section_yours">Ваши</string>
<string name="section_featured">Рекомендуем</string>
<string name="chart_blurb">Самые популярные треки Яндекс Музыки сегодня</string>
<string name="chart_empty">Чарт сейчас пуст.</string>
<string name="genre_gone">Этот жанр больше недоступен.</string>
<string name="genre_empty">В этом жанре пока нет плейлистов.</string>
<string name="podcasts_title">Подкасты и книги</string>
<string name="loading">Загрузка…</string>
<string name="loading_what">Загружаем %1$s…</string>
<string name="load_failed_network">Не удалось загрузить %1$s. Проверьте подключение и попробуйте ещё раз.</string>
<string name="load_failed">Не удалось загрузить %1$s. Попробуйте чуть позже.</string>
<string name="loading_home">Подбираем музыку для вас…</string>
<string name="loading_chart">Загружаем чарт…</string>
<string name="loading_genres">Загружаем жанры…</string>
<string name="loading_podcasts">Загружаем подкасты…</string>
<string name="loading_playlists">Загружаем плейлисты…</string>
<string name="loading_liked">Загружаем ваши любимые треки…</string>
<string name="loading_album">Загружаем альбом…</string>
<string name="loading_artist">Загружаем исполнителя…</string>
<string name="loading_playlist">Загружаем плейлист…</string>
<string name="loading_wave_settings">Загружаем настройки…</string>
<string name="loading_stations">Загружаем станции…</string>
<string name="what_home">главную страницу</string>
<string name="what_chart">чарт</string>
<string name="what_genres">жанры</string>
<string name="what_podcasts">подкасты</string>
<string name="what_stations">станции</string>
<string name="what_wave_settings">настройки волны</string>
<string name="what_albums">ваши альбомы</string>
<string name="what_artists">ваших исполнителей</string>
<string name="what_playlists">ваши плейлисты</string>
<string name="what_clips">ваши клипы</string>
<string name="what_liked">ваши любимые треки</string>
<string name="what_album">альбом</string>
<string name="what_artist">исполнителя</string>
<string name="what_playlist">плейлист</string>
<string name="what_the_playlists">плейлисты</string>
<string name="what_results">результаты</string>
<string name="tab_liked_tracks">Мне нравится</string>
<string name="tab_albums">Альбомы</string>
<string name="tab_artists">Исполнители</string>
<string name="tab_playlists">Плейлисты</string>
<string name="tab_clips">Клипы</string>
<string name="empty_liked">Любимых треков пока нет. Нажмите на сердечко у любого трека, и он появится здесь.</string>
<string name="empty_albums">Понравившихся альбомов пока нет. Отметьте альбом сердечком, и он появится здесь.</string>
<string name="empty_artists">Понравившихся исполнителей пока нет. Отметьте исполнителя сердечком, и он появится здесь.</string>
<string name="empty_playlists">Плейлистов пока нет. Здесь появятся ваши плейлисты и те, что вам понравились.</string>
<string name="empty_clips">Понравившихся клипов пока нет. Отметьте клип на странице исполнителя, и он появится здесь.</string>
<string name="clips_hint">Клипы открываются в браузере. Удерживайте кнопку выбора на клипе, чтобы отметить его или снять отметку.</string>
<string name="kind_album">Альбом</string>
<string name="kind_single">Сингл</string>
<string name="kind_compilation">Сборник</string>
<string name="kind_podcast">Подкаст</string>
<string name="kind_audiobook">Аудиокнига</string>
<string name="kind_artist">Исполнитель</string>
<string name="kind_artist_genres">Исполнитель · %1$s</string>
<string name="kind_playlist_by">Плейлист · %1$s</string>
<string name="kind_track_by">Трек · %1$s</string>
<string name="visibility_public">Открытый</string>
<string name="visibility_private">Закрытый</string>
<string name="gone_album">Этого альбома больше нет в Яндекс Музыке.</string>
<string name="gone_artist">Этого исполнителя больше нет в Яндекс Музыке.</string>
<string name="gone_playlist">Этого плейлиста больше нет в Яндекс Музыке.</string>
<string name="playlist_empty">В этом плейлисте пока пусто.</string>
<string name="search_placeholder">Исполнители, треки, подкасты</string>
<string name="search_browse">Обзор</string>
<string name="search_all">Всё</string>
<string name="search_tracks">Треки</string>
<string name="search_albums">Альбомы</string>
<string name="search_artists">Исполнители</string>
<string name="search_playlists">Плейлисты</string>
<string name="search_podcasts">Подкасты</string>
<string name="search_results_for">Результаты по запросу «%1$s»</string>
<string name="search_nothing">По запросу «%1$s» ничего не нашлось. Проверьте написание или сократите запрос.</string>
<string name="search_corrected">Показаны результаты по запросу «%1$s»</string>
<string name="search_top_result">Лучшее совпадение</string>
<string name="searching">Ищем…</string>
<string name="wave_play">Слушать Мою волну</string>
<string name="wave_blurb">Бесконечный поток музыки, который подстраивается под то, что вы слушаете, лайкаете и пропускаете.</string>
<string name="wave_tuned">Настроено: настроение — %1$s, характер — %2$s, язык — %3$s.</string>
<string name="wave_mood">Настроение</string>
<string name="wave_character">Характер</string>
<string name="wave_language">Язык</string>
<string name="wave_any">Не важно</string>
<string name="mood_energetic">Бодрое</string>
<string name="mood_cheerful">Весёлое</string>
<string name="mood_calm">Спокойное</string>
<string name="mood_sad">Грустное</string>
<string name="character_favourite">Любимое</string>
<string name="character_unfamiliar">Незнакомое</string>
<string name="character_popular">Популярное</string>
<string name="language_russian">Русский</string>
<string name="language_foreign">Иностранный</string>
<string name="stations_none">Других станций сейчас не предлагается.</string>
<string name="settings_quality">Качество звука</string>
<string name="quality_lossless">Без потерь</string>
<string name="quality_best">Лучшее</string>
<string name="quality_balanced">Оптимальное</string>
<string name="quality_data_saver">Экономия трафика</string>
<string name="quality_lossless_detail">FLAC, если Яндекс даёт его для вашей подписки и региона, иначе лучшее из доступного. Трафика в 3–5 раз больше, чем у MP3, и треки дольше запускаются.</string>
<string name="quality_best_detail">Самый высокий битрейт MP3, который даёт Яндекс, до 320 кбит/с.</string>
<string name="quality_balanced_detail">До 192 кбит/с. Примерно на 40% меньше трафика.</string>
<string name="quality_data_saver_detail">До 128 кбит/с, для медленного или платного интернета.</string>
<string name="settings_appearance">Оформление</string>
<string name="match_system">Как в системе</string>
<string name="appearance_light">Светлое</string>
<string name="appearance_dark">Тёмное</string>
<string name="settings_font_size">Размер шрифта</string>
<string name="font_size_small">Мелкий</string>
<string name="font_size_medium">Средний</string>
<string name="font_size_large">Крупный</string>
<string name="settings_language">Язык</string>
<string name="settings_storage">Хранилище</string>
<string name="settings_storage_detail">Обложки хранятся на диске, чтобы страницы открывались мгновенно. Очистка освободит место, а обложки снова загрузятся по мере просмотра.</string>
<string name="settings_version">Musyx %1$s · неофициальный клиент Яндекс Музыки</string>
<string name="plus">Яндекс Плюс</string>
<string name="plus_until">Яндекс Плюс до %1$s</string>
<string name="plus_none">Нет подписки Плюс. Треки играют фрагментами по 30 секунд.</string>
<string name="nothing_playing">Ничего не играет</string>
<string name="pick_a_track">Выберите трек</string>
<string name="badge_preview">Фрагмент</string>
<string name="panel_queue">Очередь</string>
<string name="panel_lyrics">Текст</string>
<string name="queue_now">Сейчас играет</string>
<string name="queue_nothing_after">Дальше ничего нет</string>
<string name="queue_next_up">Далее · %1$d</string>
<string name="queue_empty">Очередь пока пуста. Здесь появятся треки, которые вы включите, и те, что за ними.</string>
<string name="lyrics_play_first">Включите трек, чтобы увидеть его текст.</string>
<string name="lyrics_none">У Яндекс Музыки нет текста этого трека.</string>
<string name="lyrics_failed">Не удалось загрузить текст. Проверьте подключение и попробуйте ещё раз.</string>
<string name="lyrics_loading">Загружаем текст…</string>
<string name="lyrics_writers">Авторы: %1$s</string>
<string name="notice_station_dry">Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз.</string>
<string name="notice_too_many">Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз.</string>
<string name="notice_skipped">Не удалось воспроизвести «%1$s», трек пропущен.</string>
<string name="menu_next_track">Следующий трек</string>
<string name="menu_play_next">Играть следующим</string>
<string name="menu_add_to_queue">Добавить в очередь</string>
<string name="menu_like">Добавить в «Мне нравится»</string>
<string name="menu_unlike">Убрать из «Мне нравится»</string>
<string name="menu_add_to_playlist">Добавить в плейлист…</string>
<string name="menu_play_similar">Слушать похожие</string>
<string name="menu_go_to_album">Перейти к альбому</string>
<string name="menu_go_to_artist_named">Перейти: %1$s</string>
<string name="menu_dislike">Не рекомендовать этот трек</string>
<string name="menu_undislike">Снова рекомендовать этот трек</string>
<string name="menu_move_up">Переместить выше</string>
<string name="menu_move_down">Переместить ниже</string>
<string name="menu_remove_from_playlist">Удалить из этого плейлиста</string>
<string name="menu_new_playlist">Новый плейлист…</string>
<string name="sheet_add_to_playlist">Добавить в плейлист</string>
<string name="sheet_new_playlist">Новый плейлист</string>
<string name="sheet_rename_playlist">Переименовать плейлист</string>
<string name="sheet_playlist_name">Название плейлиста</string>
<string name="sheet_new_hint_track">Трек добавится, как только плейлист будет создан.</string>
<string name="sheet_new_hint">Его видите только вы, пока не сделаете его открытым.</string>
<string name="sheet_delete_title">Удалить «%1$s»?</string>
<string name="sheet_delete_body">Плейлист и порядок треков удалятся навсегда. Сами треки останутся в Яндекс Музыке.</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_opening_clip">Открываем «%1$s» в браузере</string>
<string name="toast_no_browser">На этом телевизоре нет браузера, чтобы открыть клип.</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>
<string name="duration_min">%1$d мин</string>
<string name="duration_h_min">%1$d ч %2$d мин</string>
<plurals name="queue_and_more">
<item quantity="one">и ещё %1$d</item>
<item quantity="few">и ещё %1$d</item>
<item quantity="many">и ещё %1$d</item>
<item quantity="other">и ещё %1$d</item>
</plurals>
<plurals name="tracks">
<item quantity="one">%1$d трек</item>
<item quantity="few">%1$d трека</item>
<item quantity="many">%1$d треков</item>
<item quantity="other">%1$d трека</item>
</plurals>
<plurals name="listeners_a_month">
<item quantity="one">%1$s слушатель в месяц</item>
<item quantity="few">%1$s слушателя в месяц</item>
<item quantity="many">%1$s слушателей в месяц</item>
<item quantity="other">%1$s слушателя в месяц</item>
</plurals>
<plurals name="likes">
<item quantity="one">%1$s лайк</item>
<item quantity="few">%1$s лайка</item>
<item quantity="many">%1$s лайков</item>
<item quantity="other">%1$s лайка</item>
</plurals>
<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>
<string-array name="months_genitive">
<item>января</item>
<item>февраля</item>
<item>марта</item>
<item>апреля</item>
<item>мая</item>
<item>июня</item>
<item>июля</item>
<item>августа</item>
<item>сентября</item>
<item>октября</item>
<item>ноября</item>
<item>декабря</item>
</string-array>
</resources>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- DESIGN.md `bg`, dark. The light value is in values-notnight. -->
<color name="bg">#1C1A22</color>
</resources>
Loaded 100 of 217 files, more files were not shown because too many files have changed in this diff. Show more