commit 46610d95fac3d79c91d9e88ab51f9c1d144b4b48 Author: Yuriy Panov Date: Fri Oct 16 22:14:54 2026 +0600 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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f122f34 --- /dev/null +++ b/.gitignore @@ -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 diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000..a061874 --- /dev/null +++ b/DESIGN.md @@ -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. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6bef991 --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2097495 --- /dev/null +++ b/README.md @@ -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_.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`). diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..99d6e7f --- /dev/null +++ b/app/build.gradle.kts @@ -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) +} diff --git a/app/lint.xml b/app/lint.xml new file mode 100644 index 0000000..db42816 --- /dev/null +++ b/app/lint.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..0525298 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1 @@ +# Project-specific R8 rules. The libraries in use ship their own consumer rules. diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..b4688f7 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/it/panov/musyx/tv/MainActivity.kt b/app/src/main/java/it/panov/musyx/tv/MainActivity.kt new file mode 100644 index 0000000..61dbf45 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/MainActivity.kt @@ -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? = 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 + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/Musyx.kt b/app/src/main/java/it/panov/musyx/tv/Musyx.kt new file mode 100644 index 0000000..065259d --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/Musyx.kt @@ -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 + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/api/Auth.kt b/app/src/main/java/it/panov/musyx/tv/api/Auth.kt new file mode 100644 index 0000000..b626c16 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/api/Auth.kt @@ -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): 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') +} diff --git a/app/src/main/java/it/panov/musyx/tv/api/Credentials.kt b/app/src/main/java/it/panov/musyx/tv/api/Credentials.kt new file mode 100644 index 0000000..5eb260d --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/api/Credentials.kt @@ -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(, 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")) + } + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/api/Json.kt b/app/src/main/java/it/panov/musyx/tv/api/Json.kt new file mode 100644 index 0000000..d67068b --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/api/Json.kt @@ -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 = this[key].arr.orEmpty() + +internal fun JsonElement?.strings(key: String): List = list(key).mapNotNull { it.asString() } + +/** The API wraps payloads as `{"result": …}`; this unwraps when it does. */ +internal fun JsonElement.result(): JsonElement = this["result"] ?: this diff --git a/app/src/main/java/it/panov/musyx/tv/api/Lyrics.kt b/app/src/main/java/it/panov/musyx/tv/api/Lyrics.kt new file mode 100644 index 0000000..f563e6e --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/api/Lyrics.kt @@ -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, val synced: Boolean, val writers: List) { + /** 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) = + 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): Lyrics { + val lines = mutableListOf() + for (raw in lrc.lines()) { + var rest = raw.trim() + val stamps = mutableListOf() + 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 } + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/api/Models.kt b/app/src/main/java/it/panov/musyx/tv/api/Models.kt new file mode 100644 index 0000000..f9ba355 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/api/Models.kt @@ -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): 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, + 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 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): List = + 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, + 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 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, + val likes: Long?, + private val coverUri: String?, +) { + fun coverUrl(size: Int): String? = coverUrl(coverUri, size) + val hues: Pair 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 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, val liked: List) + +data class AlbumPage( + val album: AlbumSummary, + val tracks: List, + 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, + val albums: List, + /** Compilations and features the artist appears on. */ + val alsoAlbums: List, + val similar: List, + val monthlyListeners: Long?, + /** Music videos; filled by a second request. */ + val clips: List = 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, + /** + * 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 = 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, + 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 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 = emptyList(), + val albums: List = emptyList(), + val artists: List = emptyList(), + val playlists: List = emptyList(), + val podcasts: List = 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 = emptyList(), + val chart: List = emptyList(), + val newReleases: List = emptyList(), + val newPlaylists: List = 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, +) { + 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): List { + 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 = emptySet(), + val artists: Set = emptySet(), + val playlists: Set = emptySet(), + val dislikedTracks: Set = emptySet(), + val clips: Set = 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, + /** "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})" +} diff --git a/app/src/main/java/it/panov/musyx/tv/api/Signing.kt b/app/src/main/java/it/panov/musyx/tv/api/Signing.kt new file mode 100644 index 0000000..0926c36 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/api/Signing.kt @@ -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("", 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) } +} diff --git a/app/src/main/java/it/panov/musyx/tv/api/Transport.kt b/app/src/main/java/it/panov/musyx/tv/api/Transport.kt new file mode 100644 index 0000000..ebbdc49 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/api/Transport.kt @@ -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>() + + fun add(key: String, value: Any?): Params { + if (value != null) pairs += key to value.toString() + return this + } + + fun addAll(key: String, values: Iterable): 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") +} diff --git a/app/src/main/java/it/panov/musyx/tv/api/Wave.kt b/app/src/main/java/it/panov/musyx/tv/api/Wave.kt new file mode 100644 index 0000000..2bc9aaa --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/api/Wave.kt @@ -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 = 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, 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("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() diff --git a/app/src/main/java/it/panov/musyx/tv/api/YmClient.kt b/app/src/main/java/it/panov/musyx/tv/api/YmClient.kt new file mode 100644 index 0000000..4189f2b --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/api/YmClient.kt @@ -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): List = + 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 { + 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 = + 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 { + val ids = likedAlbumIds(http.get("/users/${me()}/likes/albums")) + return albums(ids) + } + + private fun likedAlbumIds(likes: JsonElement): List = + likes.arr.orEmpty().mapNotNull { it["album"].long("id") ?: it.long("id") } + + private suspend fun albums(ids: List): List = + ids.chunked(BATCH).flatMap { chunk -> + http.postForm("/albums", Params().addAll("album-ids", chunk)).arr.orEmpty().mapNotNull { AlbumSummary.from(it) } + } + + suspend fun likedArtists(): List = + http.get("/users/${me()}/likes/artists").arr.orEmpty().mapNotNull { ArtistSummary.from(it) } + + private fun likedPlaylistIds(likes: JsonElement): List = + 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): List = + 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 = + 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 = + 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 = + tracks(recentTrackIds(http.get("/music-history", Params().add("fullModelsCount", 0)), limit)) + + suspend fun genres(): List = http.get("/genres").arr.orEmpty().mapNotNull { Genre.from(it) } + + /** Editorial playlists filed under a genre or mood tag. */ + suspend fun tagPlaylists(tag: String): List { + 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 { + 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 = + 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): 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("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 = + 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 { + val pageSize = 100 + val entries = mutableListOf() // 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() + val found = mutableMapOf() + 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, 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 { + 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 { + 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, 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 { 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 = + 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 { + val seen = HashSet() + 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() + val releases = mutableListOf() + val playlists = mutableListOf() + val chart = mutableListOf() + 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) +} diff --git a/app/src/main/java/it/panov/musyx/tv/api/YmError.kt b/app/src/main/java/it/panov/musyx/tv/api/YmError.kt new file mode 100644 index 0000000..b5afdc8 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/api/YmError.kt @@ -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) + } + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/data/CredentialStore.kt b/app/src/main/java/it/panov/musyx/tv/data/CredentialStore.kt new file mode 100644 index 0000000..9e713ae --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/data/CredentialStore.kt @@ -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" + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/data/SettingsStore.kt b/app/src/main/java/it/panov/musyx/tv/data/SettingsStore.kt new file mode 100644 index 0000000..9f0c0cf --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/data/SettingsStore.kt @@ -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 +} diff --git a/app/src/main/java/it/panov/musyx/tv/player/AesCtrDataSource.kt b/app/src/main/java/it/panov/musyx/tv/player/AesCtrDataSource.kt new file mode 100644 index 0000000..7ab1bf1 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/player/AesCtrDataSource.kt @@ -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> = 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() +} diff --git a/app/src/main/java/it/panov/musyx/tv/player/ExoEngine.kt b/app/src/main/java/it/panov/musyx/tv/player/ExoEngine.kt new file mode 100644 index 0000000..c8445e9 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/player/ExoEngine.kt @@ -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() + + val exo: ExoPlayer + + private var generation = 0L + private var ready = false + private var mirrors: List = 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 + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/player/PlaybackController.kt b/app/src/main/java/it/panov/musyx/tv/player/PlaybackController.kt new file mode 100644 index 0000000..c993d1f --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/player/PlaybackController.kt @@ -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> = 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, 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) { + 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) { + 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" + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/player/PlaybackService.kt b/app/src/main/java/it/panov/musyx/tv/player/PlaybackService.kt new file mode 100644 index 0000000..f5cc683 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/player/PlaybackService.kt @@ -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() + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/player/PlayerCore.kt b/app/src/main/java/it/panov/musyx/tv/player/PlayerCore.kt new file mode 100644 index 0000000..7f4df53 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/player/PlayerCore.kt @@ -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, 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 = 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? = 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? = 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, start: Int, shuffle: Boolean? = null): List { + 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 { + 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 { + val q = queue ?: return play(listOf(track), 0) + q.extend(listOf(track)) + return prefetchNext() + } + + /** Start a station (`type:tag`). */ + fun playWave(station: String): List { + 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 { + // 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 { + 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 = step(user = true, finished = false) + + fun previous(): List { + 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 { + // A station decides its own order. + if (wave != null) return emptyList() + shuffle = !shuffle + queue?.setShuffle(shuffle) + return prefetchNext() + } + + fun cycleRepeat(): List { + repeat = repeat.next() + return prefetchNext() + } + + fun jumpTo(orderPos: Int): List { + 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): List { + 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) { + result.onSuccess { prefetched = trackId to it } + .onFailure { android.util.Log.w("Musyx", "prefetch $trackId: $it") } + } + + // ---- Engine events ---- + + fun onLoaded(generation: Long, durationMs: Long?): List { + 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() + 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 = + if (generation == this.generation) step(user = false, finished = true) else emptyList() + + fun onFailed(generation: Long, reason: String): List { + 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 { + 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 { + 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.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 { + 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): List { + // 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() + 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 { + 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 { + 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 { + 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) + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/player/Queue.kt b/app/src/main/java/it/panov/musyx/tv/player/Queue.kt new file mode 100644 index 0000000..dcfa85e --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/player/Queue.kt @@ -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 private constructor( + private val items: MutableList, + /** Indices into [items] in play order. */ + private var order: MutableList, + /** 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> = + (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 = order.takeLast(n).map { items[it] } + + /** Adds items to the end of the play order (radio batches arriving). */ + fun extend(more: Iterable) { + 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 of(items: List, start: Int, shuffle: Boolean, random: Random = Random.Default): Queue? { + 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 + } + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/state/AppState.kt b/app/src/main/java/it/panov/musyx/tv/state/AppState.kt new file mode 100644 index 0000000..c56e68e --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/state/AppState.kt @@ -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> by mutableStateOf(Loadable.NotLoaded) + private set + var artists: Loadable> by mutableStateOf(Loadable.NotLoaded) + private set + var playlists: Loadable by mutableStateOf(Loadable.NotLoaded) + private set + var clips: Loadable> 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 by mutableStateOf(Loadable.NotLoaded) + private set + /** The last tracks played on any device. Reloaded on every visit to Home. */ + var recent: Loadable> by mutableStateOf(Loadable.NotLoaded) + private set + /** Top-level genres followed by their sub-genres, so a `Route.Genre` index finds either. */ + var genres: Loadable> by mutableStateOf(Loadable.NotLoaded) + private set + var podcasts: Loadable> by mutableStateOf(Loadable.NotLoaded) + private set + val genrePlaylists = mutableStateMapOf>>() + + // My Wave + var waveSettings: Loadable by mutableStateOf(Loadable.NotLoaded) + private set + var stations: Loadable> 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>() + /** Lyrics per track id, fetched while the lyrics tab is open. */ + val lyrics = mutableStateMapOf>() + + 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 load(block: suspend (YmClient) -> T, done: (Loadable) -> 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( + { + 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, 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 +} diff --git a/app/src/main/java/it/panov/musyx/tv/state/Common.kt b/app/src/main/java/it/panov/musyx/tv/state/Common.kt new file mode 100644 index 0000000..816bed8 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/state/Common.kt @@ -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 { + data object NotLoaded : Loadable + data object Loading : Loadable + data class Loaded(val value: T) : Loadable + data class Failed(val error: YmError) : Loadable + + /** Not loaded yet, or failed: worth (re)requesting. */ + val needsLoad: Boolean get() = this is NotLoaded || this is Failed + + fun get(): T? = (this as? Loaded)?.value + + companion object { + fun of(result: Result): Loadable = + 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) : Liked { + val ids: Set = 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? = (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?) diff --git a/app/src/main/java/it/panov/musyx/tv/state/Route.kt b/app/src/main/java/it/panov/musyx/tv/state/Route.kt new file mode 100644 index 0000000..f1b4f18 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/state/Route.kt @@ -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 = 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 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 + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/state/SearchState.kt b/app/src/main/java/it/panov/musyx/tv/state/SearchState.kt new file mode 100644 index 0000000..3217a18 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/state/SearchState.kt @@ -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 by mutableStateOf(Loadable.NotLoaded) + private set + var suggestions: List 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() + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/state/SignInState.kt b/app/src/main/java/it/panov/musyx/tv/state/SignInState.kt new file mode 100644 index 0000000..fa1dfb1 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/state/SignInState.kt @@ -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 + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/Format.kt b/app/src/main/java/it/panov/musyx/tv/ui/Format.kt new file mode 100644 index 0000000..6aefcc6 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/Format.kt @@ -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" +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/MusyxApp.kt b/app/src/main/java/it/panov/musyx/tv/ui/MusyxApp.kt new file mode 100644 index 0000000..bfcf4b7 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/MusyxApp.kt @@ -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() } +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/components/Controls.kt b/app/src/main/java/it/panov/musyx/tv/ui/components/Controls.kt new file mode 100644 index 0000000..21ab78b --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/components/Controls.kt @@ -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)) +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/components/Media.kt b/app/src/main/java/it/panov/musyx/tv/ui/components/Media.kt new file mode 100644 index 0000000..02ca02e --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/components/Media.kt @@ -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, 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, + 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, 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, 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, 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, size: Dp, round: Boolean = false) { + Cover( + url, + hues, + Modifier.size(size).height(size), + if (round) CircleShape else RoundedCornerShape(MusyxTheme.radius.smallCover), + ) +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/components/Status.kt b/app/src/main/java/it/panov/musyx/tv/ui/components/Status.kt new file mode 100644 index 0000000..adc4c23 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/components/Status.kt @@ -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)) + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/components/Tracks.kt b/app/src/main/java/it/panov/musyx/tv/ui/components/Tracks.kt new file mode 100644 index 0000000..505136f --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/components/Tracks.kt @@ -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, + columns: Columns = Columns.FULL, + shifts: List? = null, + playlist: PlaylistId? = null, + /** Server indices of `tracks` in `playlist`. */ + positions: List? = 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, 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)) + } + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/screens/Common.kt b/app/src/main/java/it/panov/musyx/tv/ui/screens/Common.kt new file mode 100644 index 0000000..dbea258 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/screens/Common.kt @@ -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 LazyListScope.loadable( + key: String, + value: Loadable, + 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, entry: FocusEntry? = null) { + item(key = key) { + val list = cards() + if (list.isNotEmpty()) CardShelf(title?.let { stringResource(it) }, list, entry = entry) + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/screens/Detail.kt b/app/src/main/java/it/panov/musyx/tv/ui/screens/Detail.kt new file mode 100644 index 0000000..dd769f1 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/screens/Detail.kt @@ -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, + 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") +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/screens/HomeWave.kt b/app/src/main/java/it/panov/musyx/tv/ui/screens/HomeWave.kt new file mode 100644 index 0000000..3ec3a0d --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/screens/HomeWave.kt @@ -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>, 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) + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/screens/Library.kt b/app/src/main/java/it/panov/musyx/tv/ui/screens/Library.kt new file mode 100644 index 0000000..ccf4732 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/screens/Library.kt @@ -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) + } + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/screens/Player.kt b/app/src/main/java/it/panov/musyx/tv/ui/screens/Player.kt new file mode 100644 index 0000000..f4095d6 --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/screens/Player.kt @@ -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) + } + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/screens/Search.kt b/app/src/main/java/it/panov/musyx/tv/ui/screens/Search.kt new file mode 100644 index 0000000..a526acf --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/screens/Search.kt @@ -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, 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), + ) + } + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/screens/SessionScreens.kt b/app/src/main/java/it/panov/musyx/tv/ui/screens/SessionScreens.kt new file mode 100644 index 0000000..ea8b17c --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/screens/SessionScreens.kt @@ -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, + ) + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/screens/Settings.kt b/app/src/main/java/it/panov/musyx/tv/ui/screens/Settings.kt new file mode 100644 index 0000000..895537f --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/screens/Settings.kt @@ -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) + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/screens/Sheets.kt b/app/src/main/java/it/panov/musyx/tv/ui/screens/Sheets.kt new file mode 100644 index 0000000..0307e1b --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/screens/Sheets.kt @@ -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), + ) + } +} diff --git a/app/src/main/java/it/panov/musyx/tv/ui/theme/Theme.kt b/app/src/main/java/it/panov/musyx/tv/ui/theme/Theme.kt new file mode 100644 index 0000000..27acf9c --- /dev/null +++ b/app/src/main/java/it/panov/musyx/tv/ui/theme/Theme.kt @@ -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 = + (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 = 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, 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 +} diff --git a/app/src/main/res/drawable-xhdpi/banner.png b/app/src/main/res/drawable-xhdpi/banner.png new file mode 100644 index 0000000..6a671fb Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/banner.png differ diff --git a/app/src/main/res/drawable/ic_audio_lines.xml b/app/src/main/res/drawable/ic_audio_lines.xml new file mode 100644 index 0000000..ca5e6cd --- /dev/null +++ b/app/src/main/res/drawable/ic_audio_lines.xml @@ -0,0 +1,44 @@ + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_ban.xml b/app/src/main/res/drawable/ic_ban.xml new file mode 100644 index 0000000..5765099 --- /dev/null +++ b/app/src/main/res/drawable/ic_ban.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_chevron_left.xml b/app/src/main/res/drawable/ic_chevron_left.xml new file mode 100644 index 0000000..d4e839b --- /dev/null +++ b/app/src/main/res/drawable/ic_chevron_left.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_chevron_right.xml b/app/src/main/res/drawable/ic_chevron_right.xml new file mode 100644 index 0000000..a499100 --- /dev/null +++ b/app/src/main/res/drawable/ic_chevron_right.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_clock_3.xml b/app/src/main/res/drawable/ic_clock_3.xml new file mode 100644 index 0000000..9fbf73f --- /dev/null +++ b/app/src/main/res/drawable/ic_clock_3.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_copy.xml b/app/src/main/res/drawable/ic_copy.xml new file mode 100644 index 0000000..db20574 --- /dev/null +++ b/app/src/main/res/drawable/ic_copy.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_disc_3.xml b/app/src/main/res/drawable/ic_disc_3.xml new file mode 100644 index 0000000..3598abc --- /dev/null +++ b/app/src/main/res/drawable/ic_disc_3.xml @@ -0,0 +1,32 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/ic_ellipsis.xml b/app/src/main/res/drawable/ic_ellipsis.xml new file mode 100644 index 0000000..a73675a --- /dev/null +++ b/app/src/main/res/drawable/ic_ellipsis.xml @@ -0,0 +1,26 @@ + + + + + + + diff --git a/app/src/main/res/drawable/ic_globe.xml b/app/src/main/res/drawable/ic_globe.xml new file mode 100644 index 0000000..64416b1 --- /dev/null +++ b/app/src/main/res/drawable/ic_globe.xml @@ -0,0 +1,26 @@ + + + + + + + diff --git a/app/src/main/res/drawable/ic_grip_vertical.xml b/app/src/main/res/drawable/ic_grip_vertical.xml new file mode 100644 index 0000000..5745587 --- /dev/null +++ b/app/src/main/res/drawable/ic_grip_vertical.xml @@ -0,0 +1,44 @@ + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_heart.xml b/app/src/main/res/drawable/ic_heart.xml new file mode 100644 index 0000000..d1b7be8 --- /dev/null +++ b/app/src/main/res/drawable/ic_heart.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_heart_fill.xml b/app/src/main/res/drawable/ic_heart_fill.xml new file mode 100644 index 0000000..b766b24 --- /dev/null +++ b/app/src/main/res/drawable/ic_heart_fill.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_house.xml b/app/src/main/res/drawable/ic_house.xml new file mode 100644 index 0000000..eb6a476 --- /dev/null +++ b/app/src/main/res/drawable/ic_house.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_library.xml b/app/src/main/res/drawable/ic_library.xml new file mode 100644 index 0000000..ee28bf8 --- /dev/null +++ b/app/src/main/res/drawable/ic_library.xml @@ -0,0 +1,32 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/ic_list_music.xml b/app/src/main/res/drawable/ic_list_music.xml new file mode 100644 index 0000000..306b3b6 --- /dev/null +++ b/app/src/main/res/drawable/ic_list_music.xml @@ -0,0 +1,38 @@ + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_lock.xml b/app/src/main/res/drawable/ic_lock.xml new file mode 100644 index 0000000..1c595ee --- /dev/null +++ b/app/src/main/res/drawable/ic_lock.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_log_out.xml b/app/src/main/res/drawable/ic_log_out.xml new file mode 100644 index 0000000..d9de18d --- /dev/null +++ b/app/src/main/res/drawable/ic_log_out.xml @@ -0,0 +1,26 @@ + + + + + + + diff --git a/app/src/main/res/drawable/ic_mic_vocal.xml b/app/src/main/res/drawable/ic_mic_vocal.xml new file mode 100644 index 0000000..c960071 --- /dev/null +++ b/app/src/main/res/drawable/ic_mic_vocal.xml @@ -0,0 +1,26 @@ + + + + + + + diff --git a/app/src/main/res/drawable/ic_pause.xml b/app/src/main/res/drawable/ic_pause.xml new file mode 100644 index 0000000..a907b18 --- /dev/null +++ b/app/src/main/res/drawable/ic_pause.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_pause_fill.xml b/app/src/main/res/drawable/ic_pause_fill.xml new file mode 100644 index 0000000..95afe43 --- /dev/null +++ b/app/src/main/res/drawable/ic_pause_fill.xml @@ -0,0 +1,22 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_pencil.xml b/app/src/main/res/drawable/ic_pencil.xml new file mode 100644 index 0000000..847c43f --- /dev/null +++ b/app/src/main/res/drawable/ic_pencil.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_play.xml b/app/src/main/res/drawable/ic_play.xml new file mode 100644 index 0000000..99560c9 --- /dev/null +++ b/app/src/main/res/drawable/ic_play.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_play_fill.xml b/app/src/main/res/drawable/ic_play_fill.xml new file mode 100644 index 0000000..45545fc --- /dev/null +++ b/app/src/main/res/drawable/ic_play_fill.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_plus.xml b/app/src/main/res/drawable/ic_plus.xml new file mode 100644 index 0000000..ef345aa --- /dev/null +++ b/app/src/main/res/drawable/ic_plus.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_podcast.xml b/app/src/main/res/drawable/ic_podcast.xml new file mode 100644 index 0000000..77e33cb --- /dev/null +++ b/app/src/main/res/drawable/ic_podcast.xml @@ -0,0 +1,32 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/ic_repeat.xml b/app/src/main/res/drawable/ic_repeat.xml new file mode 100644 index 0000000..c45d05a --- /dev/null +++ b/app/src/main/res/drawable/ic_repeat.xml @@ -0,0 +1,32 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/ic_repeat_1.xml b/app/src/main/res/drawable/ic_repeat_1.xml new file mode 100644 index 0000000..6742a85 --- /dev/null +++ b/app/src/main/res/drawable/ic_repeat_1.xml @@ -0,0 +1,38 @@ + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_search.xml b/app/src/main/res/drawable/ic_search.xml new file mode 100644 index 0000000..291375d --- /dev/null +++ b/app/src/main/res/drawable/ic_search.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_settings.xml b/app/src/main/res/drawable/ic_settings.xml new file mode 100644 index 0000000..de09c5c --- /dev/null +++ b/app/src/main/res/drawable/ic_settings.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_shuffle.xml b/app/src/main/res/drawable/ic_shuffle.xml new file mode 100644 index 0000000..5374549 --- /dev/null +++ b/app/src/main/res/drawable/ic_shuffle.xml @@ -0,0 +1,38 @@ + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_skip_back.xml b/app/src/main/res/drawable/ic_skip_back.xml new file mode 100644 index 0000000..fed7d98 --- /dev/null +++ b/app/src/main/res/drawable/ic_skip_back.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_skip_forward.xml b/app/src/main/res/drawable/ic_skip_forward.xml new file mode 100644 index 0000000..a9c4ec6 --- /dev/null +++ b/app/src/main/res/drawable/ic_skip_forward.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_sliders_horizontal.xml b/app/src/main/res/drawable/ic_sliders_horizontal.xml new file mode 100644 index 0000000..db7abab --- /dev/null +++ b/app/src/main/res/drawable/ic_sliders_horizontal.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_trash_2.xml b/app/src/main/res/drawable/ic_trash_2.xml new file mode 100644 index 0000000..8d88f08 --- /dev/null +++ b/app/src/main/res/drawable/ic_trash_2.xml @@ -0,0 +1,38 @@ + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_trending_up.xml b/app/src/main/res/drawable/ic_trending_up.xml new file mode 100644 index 0000000..012fe0c --- /dev/null +++ b/app/src/main/res/drawable/ic_trending_up.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_volume_2.xml b/app/src/main/res/drawable/ic_volume_2.xml new file mode 100644 index 0000000..6bb1c0d --- /dev/null +++ b/app/src/main/res/drawable/ic_volume_2.xml @@ -0,0 +1,26 @@ + + + + + + + diff --git a/app/src/main/res/drawable/ic_volume_x.xml b/app/src/main/res/drawable/ic_volume_x.xml new file mode 100644 index 0000000..99fe04a --- /dev/null +++ b/app/src/main/res/drawable/ic_volume_x.xml @@ -0,0 +1,26 @@ + + + + + + + diff --git a/app/src/main/res/drawable/ic_x.xml b/app/src/main/res/drawable/ic_x.xml new file mode 100644 index 0000000..303db65 --- /dev/null +++ b/app/src/main/res/drawable/ic_x.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/app/src/main/res/font/onest_medium.ttf b/app/src/main/res/font/onest_medium.ttf new file mode 100644 index 0000000..bf4d81d Binary files /dev/null and b/app/src/main/res/font/onest_medium.ttf differ diff --git a/app/src/main/res/font/onest_regular.ttf b/app/src/main/res/font/onest_regular.ttf new file mode 100644 index 0000000..c5d8299 Binary files /dev/null and b/app/src/main/res/font/onest_regular.ttf differ diff --git a/app/src/main/res/font/onest_semibold.ttf b/app/src/main/res/font/onest_semibold.ttf new file mode 100644 index 0000000..25c2dc5 Binary files /dev/null and b/app/src/main/res/font/onest_semibold.ttf differ diff --git a/app/src/main/res/font/unbounded_semibold.ttf b/app/src/main/res/font/unbounded_semibold.ttf new file mode 100644 index 0000000..5a15398 Binary files /dev/null and b/app/src/main/res/font/unbounded_semibold.ttf differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..da57987 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..3e3d14f Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..b47501a Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..3101957 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..3fae2f5 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/values-notnight/colors.xml b/app/src/main/res/values-notnight/colors.xml new file mode 100644 index 0000000..baad351 --- /dev/null +++ b/app/src/main/res/values-notnight/colors.xml @@ -0,0 +1,4 @@ + + + #F3F1F6 + diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml new file mode 100644 index 0000000..c695a02 --- /dev/null +++ b/app/src/main/res/values-ru/strings.xml @@ -0,0 +1,334 @@ + + + + ru + + Главная + Моя волна + Поиск + Коллекция + Подкасты + Настройки + Неизвестный исполнитель + + Проверяем вход… + Входим… + Яндекс Музыка недоступна + Вы по-прежнему в аккаунте. Проверьте подключение к интернету и попробуйте ещё раз. + + Войдите с аккаунтом Яндекса + Musyx играет вашу коллекцию Яндекс Музыки, Мою волну и плейлисты. Вход подтверждается на странице самого Яндекса, поэтому пароль никогда не проходит через это приложение. + Musyx — неофициальный клиент, не связанный с Яндексом. Токен входа хранится на этом устройстве в зашифрованном виде. + Получить код для входа + Получаем код… + Откройте %1$s + На телефоне или компьютере. Можно и отсканировать QR-код. + Введите этот код + Вернитесь сюда + Musyx войдёт, как только вы разрешите доступ. + Ждём подтверждения · код действует ещё %1$s + Войти с готовым токеном + Скрыть вход по токену + Вставьте OAuth-токен + Отсканируйте, чтобы открыть страницу входа + QR-код появится вместе с кодом для входа + Яндекс не принял этот токен. Проверьте его и вставьте ещё раз. + Срок действия кода истёк до подтверждения. Получите новый код и попробуйте снова. + Доступ отклонён на странице Яндекса. Если это ошибка, получите новый код. + Яндекс недоступен. Проверьте подключение и попробуйте ещё раз. + Яндекс не принял вход. Получите новый код и попробуйте снова. + Яндекс прислал неожиданный ответ. Попробуйте чуть позже. + + Слушать + Вперемешку + Пауза + Продолжить + Повторить + Отмена + Войти + Выйти + Показать все + Показать все %1$d + Показать ещё + Включить радио + Переименовать + Сделать закрытым + Сделать открытым + Удалить + Создать + Новый плейлист… + Очистить кеш обложек + + Вы недавно слушали + Собрано для вас + Чарт + Новые релизы + Новые плейлисты + Жанры + Станции + Ваши плейлисты + Понравившиеся плейлисты + Популярные треки + Участвует в + Похожие исполнители + Ваши + Рекомендуем + Самые популярные треки Яндекс Музыки сегодня + Чарт сейчас пуст. + Этот жанр больше недоступен. + В этом жанре пока нет плейлистов. + Подкасты и книги + + Загрузка… + Загружаем %1$s… + Не удалось загрузить %1$s. Проверьте подключение и попробуйте ещё раз. + Не удалось загрузить %1$s. Попробуйте чуть позже. + Подбираем музыку для вас… + Загружаем чарт… + Загружаем жанры… + Загружаем подкасты… + Загружаем плейлисты… + Загружаем ваши любимые треки… + Загружаем альбом… + Загружаем исполнителя… + Загружаем плейлист… + Загружаем настройки… + Загружаем станции… + главную страницу + чарт + жанры + подкасты + станции + настройки волны + ваши альбомы + ваших исполнителей + ваши плейлисты + ваши клипы + ваши любимые треки + альбом + исполнителя + плейлист + плейлисты + результаты + + Мне нравится + Альбомы + Исполнители + Плейлисты + Клипы + Любимых треков пока нет. Нажмите на сердечко у любого трека, и он появится здесь. + Понравившихся альбомов пока нет. Отметьте альбом сердечком, и он появится здесь. + Понравившихся исполнителей пока нет. Отметьте исполнителя сердечком, и он появится здесь. + Плейлистов пока нет. Здесь появятся ваши плейлисты и те, что вам понравились. + Понравившихся клипов пока нет. Отметьте клип на странице исполнителя, и он появится здесь. + Клипы открываются в браузере. Удерживайте кнопку выбора на клипе, чтобы отметить его или снять отметку. + + Альбом + Сингл + Сборник + Подкаст + Аудиокнига + Исполнитель + Исполнитель · %1$s + Плейлист · %1$s + Трек · %1$s + Открытый + Закрытый + + Этого альбома больше нет в Яндекс Музыке. + Этого исполнителя больше нет в Яндекс Музыке. + Этого плейлиста больше нет в Яндекс Музыке. + В этом плейлисте пока пусто. + + Исполнители, треки, подкасты + Обзор + Всё + Треки + Альбомы + Исполнители + Плейлисты + Подкасты + Результаты по запросу «%1$s» + По запросу «%1$s» ничего не нашлось. Проверьте написание или сократите запрос. + Показаны результаты по запросу «%1$s» + Лучшее совпадение + Ищем… + + Слушать Мою волну + Бесконечный поток музыки, который подстраивается под то, что вы слушаете, лайкаете и пропускаете. + Настроено: настроение — %1$s, характер — %2$s, язык — %3$s. + Настроение + Характер + Язык + Не важно + Бодрое + Весёлое + Спокойное + Грустное + Любимое + Незнакомое + Популярное + Русский + Иностранный + Других станций сейчас не предлагается. + + Качество звука + Без потерь + Лучшее + Оптимальное + Экономия трафика + FLAC, если Яндекс даёт его для вашей подписки и региона, иначе лучшее из доступного. Трафика в 3–5 раз больше, чем у MP3, и треки дольше запускаются. + Самый высокий битрейт MP3, который даёт Яндекс, до 320 кбит/с. + До 192 кбит/с. Примерно на 40% меньше трафика. + До 128 кбит/с, для медленного или платного интернета. + Оформление + Как в системе + Светлое + Тёмное + Размер шрифта + Мелкий + Средний + Крупный + Язык + Хранилище + Обложки хранятся на диске, чтобы страницы открывались мгновенно. Очистка освободит место, а обложки снова загрузятся по мере просмотра. + Musyx %1$s · неофициальный клиент Яндекс Музыки + Яндекс Плюс + Яндекс Плюс до %1$s + Нет подписки Плюс. Треки играют фрагментами по 30 секунд. + + Ничего не играет + Выберите трек + Фрагмент + Очередь + Текст + Сейчас играет + Дальше ничего нет + Далее · %1$d + Очередь пока пуста. Здесь появятся треки, которые вы включите, и те, что за ними. + Включите трек, чтобы увидеть его текст. + У Яндекс Музыки нет текста этого трека. + Не удалось загрузить текст. Проверьте подключение и попробуйте ещё раз. + Загружаем текст… + Авторы: %1$s + Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз. + Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз. + Не удалось воспроизвести «%1$s», трек пропущен. + + Следующий трек + Играть следующим + Добавить в очередь + Добавить в «Мне нравится» + Убрать из «Мне нравится» + Добавить в плейлист… + Слушать похожие + Перейти к альбому + Перейти: %1$s + Не рекомендовать этот трек + Снова рекомендовать этот трек + Переместить выше + Переместить ниже + Удалить из этого плейлиста + Новый плейлист… + Добавить в плейлист + Новый плейлист + Переименовать плейлист + Название плейлиста + Трек добавится, как только плейлист будет создан. + Его видите только вы, пока не сделаете его открытым. + Удалить «%1$s»? + Плейлист и порядок треков удалятся навсегда. Сами треки останутся в Яндекс Музыке. + + «%1$s» уже играет + «%1$s» зазвучит следующим + «%1$s» добавлен в очередь + Ищем треки в духе «%1$s»… + У Яндекса нет похожих треков для «%1$s» + Не удалось найти похожие треки. Попробуйте ещё раз. + Открываем «%1$s» в браузере + На этом телевизоре нет браузера, чтобы открыть клип. + Добавлено в «Мне нравится» + Убрано из «Мне нравится» + Не удалось изменить отметку. Попробуйте ещё раз. + Этот трек больше не будет попадаться в рекомендациях + Трек снова может попадаться в рекомендациях + Не удалось это изменить. Попробуйте ещё раз. + Альбом добавлен в коллекцию + Альбом убран из коллекции + Исполнитель добавлен в коллекцию + Исполнитель убран из коллекции + Плейлист добавлен в коллекцию + Плейлист убран из коллекции + Клип добавлен в коллекцию + Клип убран из коллекции + Добавлено в «%1$s» + Добавлено в плейлист + Не удалось добавить в «%1$s». Попробуйте ещё раз. + Не удалось добавить в плейлист. Попробуйте ещё раз. + Плейлист «%1$s» создан + Плейлист «%1$s» создан, трек добавлен + Не удалось создать плейлист. Попробуйте ещё раз. + Плейлист переименован в «%1$s» + Не удалось переименовать плейлист. Попробуйте ещё раз. + Теперь плейлист видят все, у кого есть ссылка + Теперь плейлист видите только вы + Не удалось изменить доступ. Попробуйте ещё раз. + Плейлист «%1$s» удалён + Не удалось удалить «%1$s». Попробуйте ещё раз. + Удалено из плейлиста + Не удалось удалить трек. Попробуйте ещё раз. + Перемещено + Не удалось переместить трек. Попробуйте ещё раз. + Качество звука: %1$s. Применится со следующего трека. + Кеш обложек очищен + Не удалось очистить кеш обложек. + + %1$d мин + %1$d ч %2$d мин + + + и ещё %1$d + и ещё %1$d + и ещё %1$d + и ещё %1$d + + + %1$d трек + %1$d трека + %1$d треков + %1$d трека + + + %1$s слушатель в месяц + %1$s слушателя в месяц + %1$s слушателей в месяц + %1$s слушателя в месяц + + + %1$s лайк + %1$s лайка + %1$s лайков + %1$s лайка + + + Играем %1$d трек в духе «%2$s» + Играем %1$d трека в духе «%2$s» + Играем %1$d треков в духе «%2$s» + Играем %1$d трека в духе «%2$s» + + + + января + февраля + марта + апреля + мая + июня + июля + августа + сентября + октября + ноября + декабря + + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..7bdc3d6 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,5 @@ + + + + #1C1A22 + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..403191f --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,341 @@ + + + Musyx + + en + + + Home + My Wave + Search + Collection + Podcasts + Settings + Unknown artist + + + Checking your sign-in… + Signing in… + Can\'t reach Yandex Music + You\'re still signed in. Check your internet connection, then try again. + + + Sign in with your Yandex account + Musyx plays your Yandex Music library, My Wave and playlists. You confirm sign-in on Yandex\'s own page, so your password never passes through this app. + Musyx is an unofficial client and isn\'t affiliated with Yandex. Your sign-in token is kept encrypted on this device. + Get sign-in code + Getting a code… + Open %1$s + On your phone or computer. You can also scan the QR code. + Enter this code + Come back here + Musyx signs you in as soon as you allow access. + Waiting for confirmation · code expires in %1$s + Sign in with an existing token instead + Hide token sign-in + Paste OAuth token + Scan to open the sign-in page + A QR code appears with your sign-in code + Yandex didn\'t accept that token. Check it and paste it again. + The code expired before it was confirmed. Get a new code to try again. + Access was declined on Yandex\'s page. Get a new code if that was a mistake. + Can\'t reach Yandex. Check your connection and try again. + Yandex didn\'t accept the sign-in. Get a new code to try again. + Yandex sent an unexpected answer. Try again in a moment. + + + Play + Shuffle + Pause + Resume + Try again + Cancel + Sign in + Sign out + Show all + Show all %1$d + Show more + Play radio + Rename + Make private + Make public + Delete + Create + New playlist… + Clear cover cache + + + Recently played + Made for you + Chart + New releases + New playlists + Genres + Stations + Your playlists + Liked playlists + Popular tracks + Appears on + Similar artists + Yours + Featured + The most played tracks on Yandex Music today + The chart is empty right now. + This genre isn\'t available any more. + No playlists in this genre yet. + Podcasts and books + + + Loading… + Loading %1$s… + Couldn\'t load %1$s. Check your connection and try again. + Couldn\'t load %1$s. Try again in a moment. + Loading your picks… + Loading the chart… + Loading genres… + Loading podcasts… + Loading playlists… + Loading your liked tracks… + Loading the album… + Loading the artist… + Loading the playlist… + Loading your settings… + Loading stations… + your home page + the chart + genres + podcasts + stations + your station settings + your albums + your artists + your playlists + your clips + your liked tracks + the album + the artist + the playlist + the playlists + the results + + + Liked tracks + Albums + Artists + Playlists + Clips + No liked tracks yet. Select the heart on any track and it lands here. + No liked albums yet. Like an album and it lands here. + No liked artists yet. Like an artist and they land here. + No playlists yet. Playlists you make or like show up here. + No liked clips yet. Like a clip on an artist\'s page and it lands here. + Clips open in the browser. Hold select on a clip to like or unlike it. + + + Album + Single + Compilation + Podcast + Audiobook + Artist + Artist · %1$s + Playlist · %1$s + Track · %1$s + Public + Private + + + This album isn\'t available on Yandex Music any more. + This artist isn\'t available on Yandex Music any more. + This playlist isn\'t available on Yandex Music any more. + This playlist is empty. + + + Search artists, tracks, podcasts + Browse + All + Tracks + Albums + Artists + Playlists + Podcasts + Results for “%1$s” + Nothing found for “%1$s”. Check the spelling or try fewer words. + Showing results for “%1$s” + Top result + Searching… + + + Play My Wave + An endless stream picked from what you play, like and skip. + Tuned to: %1$s mood, %2$s tracks, %3$s language. + Mood + Character + Language + Any + Energetic + Cheerful + Calm + Sad + Favourite + Unfamiliar + Popular + Russian + Foreign + No other stations suggested right now. + + + Streaming quality + Lossless + Best + Balanced + Data saver + FLAC when Yandex offers it for your subscription and region, otherwise the best it allows. About 3–5 times the data of MP3, and tracks take longer to start. + Highest MP3 bitrate Yandex offers, up to 320 kbps. + Up to 192 kbps. About 40% less data. + Up to 128 kbps, for slow or metered connections. + Appearance + Match system + Light + Dark + Font size + Small + Medium + Large + Language + Storage + Covers are kept on disk so pages open instantly next time. Clearing them frees the space; they download again as you browse. + Musyx %1$s · unofficial Yandex Music client + Yandex Plus + Yandex Plus until %1$s + No Plus subscription. Tracks play as 30-second previews. + + + Nothing playing + Pick a track to start + Preview + Queue + Lyrics + Now playing + Nothing after this + Next up · %1$d + Nothing queued yet. Tracks you play, and the ones lined up after them, show up here. + Play a track to see its lyrics. + Yandex Music has no lyrics for this track. + Couldn\'t load the lyrics. Check your connection and try again. + Loading lyrics… + Written by %1$s + Couldn\'t load more of this station. Check your connection and try again. + Several tracks in a row couldn\'t be played. Check your connection and try again. + Couldn\'t play “%1$s”, so it was skipped. + + + Next track + Play next + Add to queue + Add to Liked tracks + Remove from Liked tracks + Add to playlist… + Play similar tracks + Go to album + Go to %1$s + Don\'t recommend this track + Recommend this track again + Move up + Move down + Remove from this playlist + New playlist… + Add to playlist + New playlist + Rename playlist + Playlist name + The track goes in once it\'s created. + Only you can see it until you make it public. + Delete “%1$s”? + The playlist and its track order go away for good. The tracks stay in Yandex Music. + + + “%1$s” is already playing + “%1$s” plays next + Added “%1$s” to the queue + Finding tracks like “%1$s”… + Yandex has no similar tracks for “%1$s” + Couldn\'t find similar tracks. Try again. + Opening “%1$s” in the browser + There\'s no browser on this TV to play clips in. + Added to Liked tracks + Removed from Liked tracks + Couldn\'t change the like. Try again. + You won\'t be recommended this track + Recommendations for this track restored + Couldn\'t change that. Try again. + Album added to your collection + Album removed from your collection + Artist added to your collection + Artist removed from your collection + Playlist added to your collection + Playlist removed from your collection + Clip added to your collection + Clip removed from your collection + Added to “%1$s” + Added to the playlist + Couldn\'t add to “%1$s”. Try again. + Couldn\'t add to the playlist. Try again. + Created “%1$s” + Created “%1$s” with the track + Couldn\'t create the playlist. Try again. + Renamed to “%1$s” + Couldn\'t rename the playlist. Try again. + Anyone with the link can now see this playlist + Only you can see this playlist now + Couldn\'t change who can see it. Try again. + Deleted “%1$s” + Couldn\'t delete “%1$s”. Try again. + Removed from the playlist + Couldn\'t remove the track. Try again. + Moved + Couldn\'t move the track. Try again. + Streaming quality: %1$s. Applies from the next track. + Cover cache cleared + Couldn\'t clear the cover cache. + + + %1$d min + %1$d h %2$d min + + + and %1$d more + and %1$d more + + + %1$d track + %1$d tracks + + + %1$s listener a month + %1$s listeners a month + + + %1$s like + %1$s likes + + + Playing %1$d track like “%2$s” + Playing %1$d tracks like “%2$s” + + + + January + February + March + April + May + June + July + August + September + October + November + December + + diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..9ac6b60 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,8 @@ + + + + + diff --git a/app/src/main/res/xml/backup_rules.xml b/app/src/main/res/xml/backup_rules.xml new file mode 100644 index 0000000..e082e78 --- /dev/null +++ b/app/src/main/res/xml/backup_rules.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 0000000..f34e78e --- /dev/null +++ b/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + diff --git a/app/src/test/java/it/panov/musyx/tv/api/ApiTest.kt b/app/src/test/java/it/panov/musyx/tv/api/ApiTest.kt new file mode 100644 index 0000000..21d7a1a --- /dev/null +++ b/app/src/test/java/it/panov/musyx/tv/api/ApiTest.kt @@ -0,0 +1,434 @@ +package it.panov.musyx.tv.api + +import it.panov.musyx.tv.player.ctrCipher +import it.panov.musyx.tv.player.hexKey +import kotlinx.serialization.json.JsonPrimitive +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import javax.crypto.Cipher +import javax.crypto.spec.IvParameterSpec +import javax.crypto.spec.SecretKeySpec + +/** Ports the ym-api unit tests, plus yamuse's signing vectors. */ +class ApiTest { + private fun json(s: String) = parseJson(s) + + // ---- Models ---- + + @Test + fun trackConvertsWithArtistsAlbumAndCover() { + val t = Track.from( + json( + """{"id":"12345","title":"Звезда по имени Солнце","durationMs":225000, + "artists":[{"id":1,"name":"Кино"}],"albums":[{"id":77,"title":"Звезда по имени Солнце"}], + "coverUri":"avatars.yandex.net/get-music-content/x/%%","lyricsAvailable":true}""", + ), + )!! + assertEquals("12345", t.id) + assertEquals("Кино", t.artistLine) + assertEquals(77L, t.album!!.id) + assertEquals(225_000L, t.durationMs) + assertEquals("https://avatars.yandex.net/get-music-content/x/200x200", t.coverUrl(200)) + assertTrue(t.available && t.lyricsAvailable && !t.explicit) + assertEquals("12345:77", t.fullId) + } + + @Test + fun numericIdsAndVersions() { + val t = Track.from(json("""{"id":42,"title":"Song","version":"Live","artists":[]}"""))!! + assertEquals("42", t.id) + assertEquals("Song (Live)", t.fullTitle) + assertNull(t.artistLine) + assertNull(Track.from(json("""{"title":"no id"}"""))) + } + + @Test + fun lyricsInfoWinsOverTheOldFlag() { + val t = Track.from(json("""{"id":1,"lyricsAvailable":true,"lyricsInfo":{"hasAvailableSyncLyrics":false}}"""))!! + assertFalse(t.lyricsAvailable) + assertTrue(Track.from(json("""{"id":1,"contentWarning":"explicit"}"""))!!.explicit) + } + + @Test + fun coverUrlsNormalise() { + assertEquals("https://a/100x100", coverUrl("a/%%", 100)) + assertEquals("https://x.y/%z", coverUrl("https://x.y/%z", 100)) + assertNull(coverUrl("", 100)) + assertEquals("https://host/x/50x50", coverUrl("//host/x/%%", 50)) + } + + @Test + fun albumPageFlattensVolumes() { + val page = AlbumPage.from( + json( + """{"id":5,"title":"Группа крови","year":1988,"type":"","artists":[{"id":1,"name":"Кино"}], + "coverUri":"a/%%","labels":[{"name":"Мелодия"}], + "volumes":[[{"id":1,"title":"A","durationMs":1000}],[{"id":2,"title":"B","durationMs":2000}]]}""", + ), + )!! + assertEquals(2, page.tracks.size) + assertEquals(3_000L, page.tracks.sumOf { it.durationMs }) + assertEquals(AlbumKind.Album, page.album.kind) + assertEquals("Мелодия", page.label) + assertEquals("https://a/100x100", page.album.coverUrl(100)) + assertEquals("Мелодия", AlbumPage.from(json("""{"id":5,"labels":["Мелодия"]}"""))!!.label) + } + + @Test + fun albumKinds() { + assertEquals(AlbumKind.Single, AlbumKind.from(null, "single")) + assertEquals(AlbumKind.Podcast, AlbumKind.from("podcast", null)) + assertEquals(AlbumKind.Audiobook, AlbumKind.from(null, "audiobook")) + assertEquals(AlbumKind.Album, AlbumKind.from("music", null)) + } + + @Test + fun playlistNeedsOwnerAndKindAndUsesMosaicCover() { + val s = PlaylistSummary.from( + json( + """{"owner":{"uid":9,"name":"Юрий"},"kind":1003,"title":"Дорога","trackCount":14, + "visibility":"private","cover":{"type":"mosaic","itemsUri":["m/%%"]}}""", + ), + )!! + assertEquals(PlaylistId(9, 1003), s.id) + assertFalse(s.public) + assertEquals(14, s.trackCount) + assertEquals("https://m/200x200", s.coverUrl(200)) + assertNull(PlaylistSummary.from(json("""{"title":"x"}"""))) + } + + @Test + fun artistPageFromBriefInfo() { + val page = ArtistPage.from( + json( + """{"artist":{"id":3,"name":"Земфира","genres":["rock"],"cover":{"uri":"z/%%"}}, + "popularTracks":[{"id":10,"title":"Хочешь?"}],"albums":[{"id":20,"title":"Вендетта","year":2005}], + "similarArtists":[{"id":4,"name":"Сплин"}],"stats":{"lastMonthListeners":4100000}}""", + ), + )!! + assertEquals("Земфира", page.artist.name) + assertEquals(1, page.popular.size) + assertEquals(2005, page.albums[0].year) + assertEquals("Сплин", page.similar[0].name) + assertEquals(4_100_000L, page.monthlyListeners) + } + + @Test + fun clipsFromBothShapes() { + val raw = json( + """{"items":[{"type":"clip","data":{"artists":[{"id":41075,"name":"КИНО"}], + "clip":{"id":578780,"title":"Звезда","duration":263,"cover":{"uri":"https://avatars.yandex.net/c/%%"}}}}]}""", + ) + val c = raw.list("items").mapNotNull { Clip.from(it["data"]["clip"], it["data"]["artists"]) }.single() + assertEquals(578780L, c.id) + assertEquals("КИНО", c.artistLine) + assertEquals("https://avatars.yandex.net/c/200x200", c.coverUrl(200)) + assertEquals("https://music.yandex.ru/video?ids=578780", c.url) + val d = Clip.from(json("""{"clipId":7,"title":"T","thumbnail":"a/%%","explicit":true,"artists":[{"id":"3","name":"A"}]}"""))!! + assertEquals(7L, d.id) + assertTrue(d.explicit) + assertEquals(listOf(ArtistRef(3, "A")), d.artists) + } + + @Test + fun searchResultsConvertWithBestMatchAndTotals() { + val r = SearchResults.from( + json( + """{"best":{"type":"artist","result":{"id":3,"name":"Земфира"}}, + "tracks":{"total":120,"results":[{"id":1,"title":"Хочешь?"}]}, + "albums":{"total":40,"results":[{"id":5,"title":"Вендетта"}]}, + "misspellCorrected":true,"misspellResult":"земфира"}""", + ), + ) + assertEquals("Земфира", (r.best as BestMatch.OfArtist).artist.name) + assertEquals(1, r.tracks.size) + assertEquals(120, r.totals[SearchKind.Tracks]) + assertEquals(40, r.totals[SearchKind.Albums]) + assertEquals("земфира", r.corrected) + assertFalse(r.isEmpty) + assertTrue(SearchResults.from(json("{}")).isEmpty) + } + + @Test + fun landingBlocksSplitByEntityType() { + val home = homeFromLanding( + json( + """{"blocks":[ + {"type":"personal-playlists","entities":[{"type":"personal-playlist","data":{ + "data":{"uid":1,"kind":3,"title":"Плейлист дня","owner":{"uid":1}},"previewDescription":"Updated every day"}}]}, + {"type":"new-releases","entities":[{"type":"album","data":{"id":9,"title":"New"}}]}, + {"type":"chart","entities":[{"type":"chart-item","data":{"track":{"id":7,"title":"Top"},"chart":{"position":1,"shift":0}}}]} + ]}""", + ), + ) + assertEquals("Плейлист дня", home.personal[0].playlist.title) + assertEquals("Updated every day", home.personal[0].description) + assertEquals(9L, home.newReleases[0].id) + assertEquals(1, home.chart[0].position) + } + + @Test + fun chartEntryReadsPositionAndShift() { + val e = ChartEntry.from(json("""{"id":1,"track":{"id":1,"title":"Хит"},"chart":{"position":3,"shift":-2}}"""))!! + assertEquals(3 to -2, e.position to e.shift) + } + + @Test + fun genreTitleFallsBackAndFlattens() { + val g = Genre.from(json("""{"id":"rock","titles":{"en":{"title":"Rock"}},"color":"#ff0000","subGenres":[{"id":"punk","title":"Punk"}]}"""))!! + assertEquals("Rock", g.title) + assertEquals("punk", g.subGenres[0].id) + assertEquals("#ff0000", g.color) + fun genre(id: String, vararg subs: String) = Genre(id, id, null, subs.map { Genre(it, it, null, emptyList()) }) + val flat = Genre.flatten(listOf(genre("rock", "punk", "metal"), genre("metal", "doom"), genre("pop", "punk"))) + assertEquals(listOf("rock", "metal", "pop", "punk", "doom"), flat.map { it.id }) + } + + @Test + fun accountPrefersDisplayNameAndReadsPlus() { + val a = Account.from( + json( + """{"account":{"uid":42,"login":"yuriy.panov","displayName":"Юрий","fullName":"Юрий Панов"}, + "plus":{"hasPlus":true},"subscription":{"end":"2027-01-01T00:00:00+03:00"}}""", + ), + )!! + assertEquals(42L, a.uid) + assertEquals("Юрий", a.name) + assertEquals("Ю", a.initial) + assertTrue(a.hasPlus) + assertEquals("2027-01-01T00:00:00+03:00", a.subscriptionEnd) + val b = Account.from(json("""{"account":{"uid":7,"login":"listener","displayName":" "}}"""))!! + assertEquals("listener", b.name) + assertFalse(b.hasPlus) + assertNull(Account.from(json("""{"account":{"now":"2026-10-15"}}"""))) + } + + @Test + fun tagIdsAcceptObjectsAndStrings() { + assertEquals( + listOf(PlaylistId(1, 2), PlaylistId(3, 4)), + tagPlaylistIds(json("""{"ids":[{"uid":1,"kind":2},"3:4",null,{"uid":5}]}""")), + ) + } + + @Test + fun recentIdsWalkDaysAndSkipRepeats() { + val history = json( + """{"historyTabs":[ + {"date":"2026-10-15","items":[{"context":{"type":"wave"},"tracks":[ + {"type":"track","data":{"itemId":{"trackId":"1","albumId":"10"}}}, + {"type":"track","data":{"itemId":{"trackId":"2"}}}]}]}, + {"date":"2026-10-14","items":[{"tracks":[ + {"type":"track","data":{"itemId":{"trackId":"1","albumId":"10"}}}, + {"type":"track","data":{}}, + {"type":"track","data":{"itemId":{"trackId":"3","albumId":"30"}}}, + {"type":"track","data":{"itemId":{"trackId":"4","albumId":"40"}}}]}]}]}""", + ) + assertEquals(listOf("1:10", "2", "3:30"), recentTrackIds(history, 3)) + assertEquals(4, recentTrackIds(history, 10).size) + } + + @Test + fun bestVariantPrefersFullMp3AtTopBitrate() { + val v = json( + """[{"codec":"aac","bitrateInKbps":256,"downloadInfoUrl":"a"}, + {"codec":"mp3","bitrateInKbps":192,"downloadInfoUrl":"b"}, + {"codec":"mp3","bitrateInKbps":320,"downloadInfoUrl":"c"}, + {"codec":"mp3","bitrateInKbps":320,"downloadInfoUrl":"p","preview":true}, + {"codec":"flac","bitrateInKbps":900,"downloadInfoUrl":"f"}]""", + ).arr!! + assertEquals("c", bestVariant(v, null).str("downloadInfoUrl")) + assertEquals("b", bestVariant(v, 192).str("downloadInfoUrl")) + assertEquals("nothing fits: take the smallest", "b", bestVariant(v, 64).str("downloadInfoUrl")) + val previews = json("""[{"codec":"mp3","bitrateInKbps":128,"downloadInfoUrl":"p","preview":true}]""").arr!! + assertEquals(true, bestVariant(previews, null).bool("preview")) + assertNull(bestVariant(emptyList(), null)) + } + + @Test + fun fileInfoRepliesBecomeStreamsExceptHeAac() { + val flac = fileInfoStream(json("""{"codec":"flac-mp4","bitrate":0,"transport":"encraw","key":"00ff","urls":["https://a","https://b"]}"""))!! + assertEquals(listOf("https://a", "https://b"), flac.urls) + assertEquals("FLAC" to "mp4", flac.label to flac.container) + assertEquals("00ff", flac.key) + assertFalse("key leaked into toString", "00ff" in flac.toString()) + assertTrue(flac.lossless) + val aac = fileInfoStream(json("""{"codec":"aac-mp4","bitrate":192,"key":"00ff","urls":["https://a"]}"""))!! + assertEquals(Triple("AAC 192", "mp4", false), Triple(aac.label, aac.container, aac.lossless)) + assertNull(fileInfoStream(json("""{"codec":"he-aac-mp4","bitrate":64,"urls":["https://a"]}"""))) + assertNull(fileInfoStream(json("""{"codec":"flac","urls":[]}"""))) + val mp3 = Stream(emptyList(), "mp3", 320, false, null) + assertEquals("MP3 320" to "mp3", mp3.label to mp3.container) + } + + // ---- Waves ---- + + @Test + fun settingsRoundTripAndBecomeSeeds() { + val s = WaveSettings.from(json("""{"moodEnergy":"calm","diversity":"discover","language":"not-russian"}""")) + assertEquals(WaveSettings(Mood.Calm, Character.Unfamiliar, Language.Foreign), s) + assertEquals(WaveSettings(), WaveSettings.from(json("{}"))) + assertTrue(WaveSettings().seeds().isEmpty()) + assertEquals( + listOf("settingMoodEnergy:calm", "settingDiversity:discover", "settingLanguage:russian"), + WaveSettings(Mood.Calm, Character.Unfamiliar, Language.Russian).seeds(), + ) + } + + @Test + fun feedbackEventsSerialiseLikeTheOfficialClients() { + val skip = WaveEvent.Skipped("1:2", 1500).toJson("T") + assertEquals("skip", skip.str("type")) + assertEquals("1:2", skip.str("trackId")) + assertEquals(JsonPrimitive(1.5), skip["totalPlayedSeconds"]) + assertEquals(setOf("type", "timestamp"), WaveEvent.Started.toJson("T").keys) + } + + @Test + fun sessionBatchAndStationParse() { + val b = WaveBatch.from(json("""{"radioSessionId":"s1","batchId":"b1","sequence":[{"type":"track","track":{"id":"7","title":"A"}},{"type":"ad"}]}""")) + assertEquals(Triple("s1", "b1", 1), Triple(b.sessionId, b.batchId, b.tracks.size)) + val s = Station.from( + json("""{"station":{"id":{"type":"genre","tag":"rock"},"name":"Рок","icon":{"backgroundColor":"#ff4444","imageUrl":"avatars.yandex.net/x/%%"}}}"""), + )!! + assertEquals("genre:rock", s.id) + assertEquals("#ff4444", s.color) + assertEquals("https://avatars.yandex.net/x/200x200", s.iconUrl(200)) + } + + @Test + fun isoMillisAlwaysHasThreeFractionDigits() { + assertEquals("1970-01-01T00:00:00.000Z", isoMillis(0)) + assertEquals("2026-10-15T15:40:01.042Z", isoMillis(1_792_078_801_042)) + assertEquals("2000-02-29T00:00:00.000Z", isoMillis(951_782_400_000)) + } + + @Test + fun numericIds() { + assertEquals(123L, numericId("123")) + assertEquals(123L, numericId("123:456")) + assertNull(numericId("abc-upload")) + } + + // ---- Lyrics ---- + + @Test + fun lrcParsesStampsAndDropsTags() { + val l = Lyrics.fromLrc("[ar:Кино]\n[00:12.50] Первая\n[00:20.1]Вторая\n[01:02.345][00:05.00] Повтор\n\nбез метки", emptyList()) + assertEquals( + listOf(5_000L to "Повтор", 12_500L to "Первая", 20_100L to "Вторая", 62_345L to "Повтор"), + l.lines.map { it.atMs!! to it.text }, + ) + assertTrue(l.synced) + } + + @Test + fun currentLineFollowsPosition() { + val l = Lyrics.fromLrc("[00:10.00]a\n[00:20.00]b", emptyList()) + assertNull(l.current(5_000)) + assertEquals(0, l.current(10_000)) + assertEquals(1, l.current(25_000)) + assertNull(Lyrics.fromText("a\nb", emptyList()).current(25_000)) + } + + @Test + fun badStampsAreNotLyrics() { + assertEquals(62_000L, Lyrics.parseStamp("01:02")) + assertNull(Lyrics.parseStamp("1:75")) + assertNull(Lyrics.parseStamp("ti")) + assertNull(Lyrics.parseStamp("00:01.1234")) + } + + // ---- Auth, errors, signing ---- + + @Test + fun credentialsRoundTripAndRefreshNearExpiry() { + val week = 7L * 24 * 3600 + val c = Credentials("a", "r", 10 * week) + assertEquals(c, Credentials.fromJson(c.toJson())) + assertFalse("secret" in Credentials("secret-access", "secret-refresh", 1).toString()) + assertFalse(c.needsRefresh(8 * week)) + assertTrue(c.needsRefresh(9 * week + 1)) + val pasted = Credentials.fromToken(" a \n") + assertEquals("a", pasted.accessToken) + assertFalse(pasted.needsRefresh(Long.MAX_VALUE / 2)) + assertEquals(Credentials.fromToken("a"), Credentials.fromJson("""{"access_token":"a"}""")) + } + + @Test + fun oauthCodesMapToActionableErrors() { + assertTrue(YmError.fromOAuth("expired_token: code expired") is YmError.CodeExpired) + assertTrue(YmError.fromOAuth("device authorization timed out") is YmError.CodeExpired) + assertTrue(YmError.fromOAuth("access_denied") is YmError.Denied) + assertTrue(YmError.fromOAuth("invalid_grant") is YmError.Unauthorized) + assertTrue(YmError.fromOAuth("something new") is YmError.Api) + assertTrue(YmError.Network("dns").isRetryable) + assertFalse(YmError.Unauthorized("").isRetryable) + } + + @Test + fun errorBodiesAndStatuses() { + assertEquals("validate: bad", errorMessage(json("""{"error":{"name":"validate","message":"bad"}}"""), 400)) + assertEquals("authorization_pending wait", errorMessage(json("""{"error":"authorization_pending","error_description":"wait"}"""), 400)) + assertEquals("http 418", errorMessage(json("nope"), 418)) + assertTrue(statusError(401, json("{}"), "x") is YmError.Unauthorized) + assertTrue(statusError(404, json("{}"), "x") is YmError.NotFound) + assertTrue(statusError(502, json("{}"), "x") is YmError.Network) + assertTrue(statusError(429, json("{}"), "x") is YmError.Network) + val server = statusError(503, json("{}"), "x") + assertTrue("other 5xx aren't the connection, so lossless falls back to MP3", server is YmError.Server) + assertTrue(server.isRetryable) + assertTrue(statusError(400, json("{}"), "x") is YmError.Api) + } + + @Test + fun acknowledgements() { + assertTrue(acknowledged(JsonPrimitive("ok"))) + assertTrue(acknowledged(json("""{"revision":3}"""))) + assertFalse(acknowledged(json("{}"))) + assertTrue(acknowledged(json("{}"), loosely = true)) + } + + @Test + fun signingMatchesYamuseVectors() { + assertEquals("5Xma89MBvxVhn4bCHIDRA/W8OGjHoibkEZj5b0DbRp8", Signing.fileInfo(1_700_000_000, 42, "lossless")) + assertEquals("xbCyTDmnI1xqeQil9/hP1qB2FtKWwefJgL9dAJueaYs=", Signing.lyrics(42, 1_700_000_000)) + } + + @Test + fun mp3LinkFromDownloadInfo() { + val xml = "s1.yandex.net/a/b.mp30061-1xyz" + val sign = Signing.md5Hex("XGRlBW9FXlekgbPrRHuSiA" + "a/b.mp3" + "xyz") + assertEquals("https://s1.yandex.net/get-mp3/$sign/0061/a/b.mp3", Signing.mp3Link(xml)) + assertNull(Signing.mp3Link("h")) + } + + @Test + fun yandexHostsSeeTheToken() { + assertTrue(isYandexHost("api.music.yandex.net")) + assertTrue(isYandexHost("oauth.yandex.ru")) + assertFalse(isYandexHost("evil-yandex.net")) + assertFalse(isYandexHost("example.com")) + } + + // ---- encraw decryption ---- + + @Test + fun ctrDecryptsFromAnyOffset() { + val key = hexKey("00112233445566778899aabbccddeeff")!! + val plain = ByteArray(100) { it.toByte() } + val whole = Cipher.getInstance("AES/CTR/NoPadding").apply { + init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(ByteArray(16))) + }.doFinal(plain) + for (offset in listOf(0L, 1L, 15L, 16L, 37L, 64L)) { + val part = ctrCipher(key, offset).update(whole, offset.toInt(), whole.size - offset.toInt()) + assertArrayEquals("offset $offset", plain.copyOfRange(offset.toInt(), plain.size), part) + } + assertNull(hexKey("abc")) + assertEquals(32, hexKey("0".repeat(64))!!.size) + } +} diff --git a/app/src/test/java/it/panov/musyx/tv/player/PlayerCoreTest.kt b/app/src/test/java/it/panov/musyx/tv/player/PlayerCoreTest.kt new file mode 100644 index 0000000..75638c1 --- /dev/null +++ b/app/src/test/java/it/panov/musyx/tv/player/PlayerCoreTest.kt @@ -0,0 +1,304 @@ +package it.panov.musyx.tv.player + +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 org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Ports the desktop player/mod.rs tests. */ +class PlayerCoreTest { + private fun track(id: String, secs: Long = 100) = Track.bare(id, durationMs = secs * 1000) + + private fun stream() = Stream(listOf("u"), "mp3", 320, false, null) + + private fun List.fetchGeneration(): Long? = filterIsInstance().firstOrNull()?.generation + + private fun playing(n: Int, start: Int): PlayerCore { + val p = PlayerCore() + val gen = p.play((0 until n).map { track("$it") }, start).fetchGeneration()!! + p.fetched(gen, Result.success(stream())) + p.onLoaded(gen, null) + return p + } + + private fun PlayerCore.upcomingIds() = queue!!.upcoming().map { it.second.id } + + @Test + fun playFetchesThenPlaysAndPrefetchesNext() { + val p = PlayerCore() + val effects = p.play(listOf(track("a", 10), track("b", 20)), 0) + assertEquals(listOf(Effect.Fetch(1, "a")), effects.filterIsInstance()) + assertEquals(Status.Loading, p.status) + assertTrue(p.fetched(1, Result.success(stream())).isEmpty()) + val loaded = p.onLoaded(1, null) + assertEquals(Status.Playing, p.status) + assertEquals(10_000L, p.durationMs) + assertEquals(listOf(Effect.Prefetch("b")), loaded) + } + + @Test + fun prefetchedStreamIsUsedWithoutAnotherFetch() { + val p = playing(3, 0) + p.prefetched("1", Result.success(stream())) + val effects = p.onEnded(p.generation) + assertTrue(effects.none { it is Effect.Fetch }) + assertEquals("1", p.track!!.id) + } + + @Test + fun staleEventsAreIgnored() { + val p = playing(3, 0) + val old = p.generation + p.next() + p.onPosition(old, 50_000) + assertEquals(0L, p.positionMs) + assertTrue(p.fetched(old, Result.success(stream())).isEmpty()) + } + + @Test + fun endOfQueueStopsAndPlayRestartsLastTrack() { + val p = playing(1, 0) + val effects = p.onEnded(p.generation) + val report = (effects.single() as Effect.Report).report + assertEquals(100_000L, report.playedMs) + assertEquals(FROM_LIST, report.from) + assertEquals(Status.Ended, p.status) + val again = p.toggle() + assertNull("replay reuses the stream", again.fetchGeneration()) + assertEquals(Status.Loading, p.status) + } + + @Test + fun repeatOneReplaysWithoutFetching() { + val p = playing(3, 1) + p.cycleRepeat() + p.cycleRepeat() + assertEquals(Repeat.One, p.repeat) + val effects = p.onEnded(p.generation) + assertTrue(effects.none { it is Effect.Fetch }) + assertEquals("1", p.track!!.id) + } + + @Test + fun previousRestartsAfterThreeSeconds() { + val p = playing(3, 1) + p.onPosition(p.generation, 10_000) + p.previous() + assertEquals("1", p.track!!.id) + assertEquals(0L, p.positionMs) + p.previous() + assertEquals("0", p.track!!.id) + } + + @Test + fun unplayableTracksAreSkippedThenGivenUpOn() { + val p = playing(5, 0) + for (expected in 1 until 3) { + p.next() + p.fetched(p.generation, Result.failure(YmError.Api("gone"))) + assertEquals(expected, p.skips) + assertTrue(p.notice is Notice.Skipped) + } + val effects = p.fetched(p.generation, Result.failure(YmError.Api("gone"))) + assertTrue(effects.isEmpty()) + assertEquals(Notice.TooManyFailures, p.notice) + } + + @Test + fun expiredTokenSignsOut() { + val p = PlayerCore() + p.play(listOf(track("a", 10)), 0) + assertEquals(listOf(Effect.SignedOut), p.fetched(1, Result.failure(YmError.Unauthorized("401")))) + } + + @Test + fun shufflePlayTurnsShuffleOn() { + val p = PlayerCore() + p.play((0 until 20).map { track("$it", 10) }, 0, shuffle = true) + assertTrue(p.shuffle) + assertEquals(19, p.queue!!.upcomingCount) + } + + @Test + fun resetDropsTheQueue() { + val p = playing(3, 0) + p.reset() + assertNull(p.track) + } + + private fun waveWith(n: Int): PlayerCore { + val p = PlayerCore() + val start = p.playWave("user:onyourwave") + assertEquals(listOf(Effect.WaveFetch("user:onyourwave", null, emptyList(), 1)), start) + val batch = WaveBatch("s1", (0 until n).map { track("w$it") }, "b1") + val effects = p.waveBatch("user:onyourwave", 1, Result.success(batch)) + assertEquals(Effect.WaveFeedback("s1", WaveEvent.Started, "b1"), effects[0]) + val fetch = effects[1] as Effect.Fetch + p.fetched(fetch.generation, Result.success(stream())) + return p + } + + private fun PlayerCore.loaded() = onLoaded(generation, null) + + @Test + fun waveReportsStartAndTopsUpWhenLow() { + val p = waveWith(3) + val effects = p.loaded() + assertTrue(effects.contains(Effect.WaveFeedback("s1", WaveEvent.TrackStarted("w0"), "b1"))) + assertTrue("two still queued", effects.none { it is Effect.WaveFetch }) + + p.onPosition(p.generation, 20_000) + val skip = p.next() + assertTrue(skip.contains(Effect.WaveFeedback("s1", WaveEvent.Skipped("w0", 20_000), "b1"))) + assertTrue(skip.any { it is Effect.Report && it.report.from == FROM_WAVE }) + + p.fetched(p.generation, Result.success(stream())) + val more = p.loaded().filterIsInstance().single() + assertEquals("s1", more.sessionId) + assertEquals("w2", more.queue.last()) + } + + @Test + fun feedbackNamesEachTracksOwnBatch() { + val p = waveWith(2) + p.loaded() + p.waveBatch("user:onyourwave", 1, Result.success(WaveBatch("s1", listOf(track("n0", 10)), "b2"))) + val effects = p.next() + assertTrue(effects.any { it is Effect.WaveFeedback && it.event is WaveEvent.Skipped && it.batchId == "b1" }) + } + + @Test + fun waveWaitsForTheNextBatchWhenDry() { + val p = waveWith(1) + p.loaded() + val effects = p.onEnded(p.generation) + assertTrue(effects.any { it is Effect.WaveFeedback && it.event is WaveEvent.TrackFinished }) + assertEquals("a wave doesn't end", Status.Loading, p.status) + val next = p.waveBatch("user:onyourwave", 1, Result.success(WaveBatch("s1", listOf(track("w9", 50)), "b2"))) + assertEquals("w9", (next.first() as Effect.Fetch).trackId) + } + + @Test + fun newSettingsStartANewSession() { + val p = waveWith(3) + p.loaded() + assertEquals(listOf(Effect.WaveFetch("user:onyourwave", null, listOf("w0"), 2)), p.waveRestart()) + assertEquals(0, p.queue!!.upcomingCount) + } + + @Test + fun batchesForAnotherStationAreIgnored() { + val p = waveWith(2) + assertTrue(p.waveBatch("genre:rock", 1, Result.success(WaveBatch(null, listOf(track("x", 10)), null))).isEmpty()) + assertEquals(2, p.queue!!.size) + } + + @Test + fun playingAListLeavesWaveModeAndShuffleIsIgnoredInWaves() { + val p = waveWith(2) + p.toggleShuffle() + assertTrue(!p.shuffle) + p.play(listOf(track("a", 10)), 0) + assertNull(p.waveStation) + } + + @Test + fun playNextAndAppend() { + val p = playing(3, 0) + p.playNext(track("n", 5)) + p.append(track("z", 5)) + assertEquals(listOf("n", "1", "2", "z"), p.upcomingIds()) + val empty = PlayerCore() + assertTrue(empty.append(track("solo", 5)).any { it is Effect.Fetch && it.trackId == "solo" }) + } + + @Test + fun playNextWinsOverAnAlreadyPrefetchedTrack() { + val p = playing(3, 0) + p.prefetched("1", Result.success(stream())) + assertTrue(p.playNext(track("n", 5)).contains(Effect.Prefetch("n"))) + p.onEnded(p.generation) + assertEquals("n", p.track!!.id) + // A late prefetch for the old next track must not be played instead. + p.prefetched("1", Result.success(stream())) + assertEquals("n", p.track!!.id) + } + + @Test + fun playNextOnThePlayingTrackChangesNothing() { + val p = playing(3, 0) + assertTrue(p.playNext(track("0")).isEmpty()) + p.next() + assertEquals("skip moves on instead of replaying", "1", p.track!!.id) + } + + @Test + fun playNextInAWave() { + val p = waveWith(3) + p.loaded() + p.playNext(track("n", 5)) + p.next() + assertEquals("n", p.track!!.id) + } + + @Test + fun pausingWhileLoadingStopsTheOldTrackAndHoldsTheNewOne() { + val engine = FakeEngine() + val p = PlayerCore().also { it.engine = engine } + val gen = p.play(listOf(track("a"), track("b")), 0).fetchGeneration()!! + p.fetched(gen, Result.success(stream())) + p.onLoaded(gen, null) + engine.calls.clear() + p.next() + assertTrue("the old track stops while the next is fetched", "pause" in engine.calls) + assertEquals(Status.Loading, p.status) + p.toggle() + assertEquals(Status.Paused, p.status) + p.fetched(p.generation, Result.success(stream())) + assertEquals("load:false", engine.calls.last()) + p.onLoaded(p.generation, null) + assertEquals("it stays paused once loaded", Status.Paused, p.status) + p.toggle() + assertEquals(Status.Playing, p.status) + assertEquals("play", engine.calls.last()) + } + + @Test + fun resumingWhileStillFetchingLetsItStart() { + val engine = FakeEngine() + val p = PlayerCore().also { it.engine = engine } + p.play(listOf(track("a")), 0) + p.toggle() + p.toggle() + assertEquals(Status.Loading, p.status) + p.fetched(p.generation, Result.success(stream())) + assertEquals("load:true", engine.calls.last()) + } + + @Test + fun batchesAskedForBeforeASettingsChangeAreDropped() { + val p = waveWith(2) + p.loaded() + val restart = p.waveRestart().single() as Effect.WaveFetch + // A top-up from the old session lands after the restart. + assertTrue(p.waveBatch("user:onyourwave", 1, Result.success(WaveBatch("s1", listOf(track("old")), "b9"))).isEmpty()) + assertEquals(0, p.queue!!.upcomingCount) + val fresh = p.waveBatch("user:onyourwave", restart.epoch, Result.success(WaveBatch("s2", listOf(track("new")), "c1"))) + assertTrue(fresh.contains(Effect.WaveFeedback("s2", WaveEvent.Started, "c1"))) + assertEquals("new", p.queue!!.upcoming().single().second.id) + } + + private class FakeEngine : Engine { + val calls = mutableListOf() + override fun load(generation: Long, track: Track, stream: Stream, play: Boolean) { calls += "load:$play" } + override fun play() { calls += "play" } + override fun pause() { calls += "pause" } + override fun seek(positionMs: Long) { calls += "seek" } + override fun stop() { calls += "stop" } + } +} diff --git a/app/src/test/java/it/panov/musyx/tv/player/QueueTest.kt b/app/src/test/java/it/panov/musyx/tv/player/QueueTest.kt new file mode 100644 index 0000000..849a587 --- /dev/null +++ b/app/src/test/java/it/panov/musyx/tv/player/QueueTest.kt @@ -0,0 +1,131 @@ +package it.panov.musyx.tv.player + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Ports the desktop queue.rs tests. */ +class QueueTest { + private fun q(n: Int, start: Int) = Queue.of((0 until n).toList(), start, shuffle = false)!! + + private fun Queue.next() = upcoming().map { it.second } + + @Test + fun emptyListHasNoQueue() = assertNull(Queue.of(emptyList(), 0, false)) + + @Test + fun startIsClamped() = assertEquals(2, q(3, 99).current) + + @Test + fun advanceStopsAtEndWithoutRepeat() { + val q = q(2, 0) + assertTrue(q.advance(Repeat.Off, true)) + assertEquals(1, q.current) + assertFalse(q.advance(Repeat.Off, true)) + assertEquals(1, q.current) + } + + @Test + fun repeatAllWrapsBothWays() { + val q = q(3, 2) + assertTrue(q.advance(Repeat.All, true)) + assertEquals(0, q.current) + assertTrue(q.back(Repeat.All)) + assertEquals(2, q.current) + } + + @Test + fun repeatOneReplaysOnFinishButSkipMovesOn() { + val q = q(3, 1) + assertTrue(q.advance(Repeat.One, true)) + assertEquals(1, q.current) + assertTrue(q.advance(Repeat.One, false)) + assertEquals(2, q.current) + } + + @Test + fun backStopsAtStartWithoutRepeat() { + val q = q(3, 0) + assertFalse(q.back(Repeat.Off)) + assertEquals(0, q.current) + } + + @Test + fun peekMatchesAdvance() { + for (repeat in Repeat.entries) for (start in 0 until 3) { + val q = q(3, start) + val peeked = q.peekNext(repeat) + val moved = q.advance(repeat, true) + assertEquals("$repeat from $start", peeked, if (moved) q.current else null) + } + } + + @Test + fun shuffleKeepsCurrentAndCoversEverything() { + val q = q(50, 17) + q.setShuffle(true) + assertEquals(17, q.current) + assertEquals((0 until 50).toList(), (listOf(17) + q.next()).sorted()) + q.advance(Repeat.Off, false) + val now = q.current + q.setShuffle(false) + assertEquals("unshuffling keeps the current item", now, q.current) + assertEquals(49 - now, q.upcomingCount) + } + + @Test + fun extendAppendsAfterEverything() { + val q = q(2, 1) + assertFalse(q.advance(Repeat.Off, true)) + q.extend(listOf(10, 11)) + assertTrue(q.advance(Repeat.Off, true)) + assertEquals(10, q.current) + assertEquals(listOf(11), q.next()) + } + + @Test + fun clearUpcomingKeepsHistoryAndCurrent() { + val q = q(5, 0) + q.setShuffle(true) + q.advance(Repeat.Off, false) + val first = q.tail(5).first() + val now = q.current + q.clearUpcoming() + assertEquals(2, q.size) + assertEquals(now, q.current) + assertEquals(0, q.upcomingCount) + assertTrue(q.back(Repeat.Off)) + assertEquals(first, q.current) + } + + @Test + fun insertNextPlaysAfterCurrentEvenWhenShuffled() { + val q = q(4, 1) + q.setShuffle(true) + assertTrue(q.insertNext(99) { a, b -> a == b }) + assertEquals(99, q.next().first()) + assertEquals(1, q.current) + } + + @Test + fun insertNextMovesInsteadOfDuplicatingAndIgnoresCurrent() { + val q = q(5, 1) + assertFalse("the current item stays put", q.insertNext(1) { a, b -> a == b }) + assertEquals(listOf(2, 3, 4), q.next()) + assertTrue(q.insertNext(4) { a, b -> a == b }) + assertEquals(listOf(4, 2, 3), q.next()) + assertEquals("moved, not added", 5, q.size) + } + + @Test + fun jumpMovesToUpcomingPosition() { + val q = q(5, 0) + val (pos, item) = q.upcoming()[2] + q.jump(pos) + assertEquals(item, q.current) + q.jump(99) + assertEquals(item, q.current) + } +} diff --git a/app/src/test/java/it/panov/musyx/tv/state/StateTest.kt b/app/src/test/java/it/panov/musyx/tv/state/StateTest.kt new file mode 100644 index 0000000..b823f63 --- /dev/null +++ b/app/src/test/java/it/panov/musyx/tv/state/StateTest.kt @@ -0,0 +1,72 @@ +package it.panov.musyx.tv.state + +import it.panov.musyx.tv.api.PlaylistId +import it.panov.musyx.tv.api.Track +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Ports the desktop route.rs and collection.rs tests. */ +class StateTest { + @Test + fun backReturnsToPreviousRoute() { + val nav = Navigator(Route.Home) + nav.go(Route.Search) + nav.go(Route.Collection) + assertTrue(nav.back()) + assertEquals(Route.Search, nav.current) + nav.back() + assertEquals(Route.Home, nav.current) + assertFalse(nav.canGoBack) + assertFalse(nav.back()) + assertEquals(Route.Home, nav.current) + } + + @Test + fun revisitingTheCurrentRouteDoesNotGrowHistory() { + val nav = Navigator(Route.Home) + nav.go(Route.Home) + assertFalse(nav.canGoBack) + } + + @Test + fun historyIsBounded() { + val nav = Navigator(Route.Home) + repeat(200) { nav.go(if (it % 2 == 0) Route.Search else Route.Home) } + assertEquals(50, nav.depth) + } + + @Test + fun leavingADeletedPageGoesBackAndForgetsIt() { + val nav = Navigator(Route.Home) + val gone = Route.Playlist(PlaylistId(1, 2)) + nav.go(gone) + nav.go(Route.Search) + nav.go(gone) + nav.leave(gone) + assertEquals(Route.Search, nav.current) + nav.back() + assertEquals(Route.Home, nav.current) + } + + @Test + fun likedAddsOnTopAndRemoves() { + val base = Liked.Loaded(listOf(Track.bare("1"), Track.bare("2"))) + assertTrue(base.contains("2") && !base.contains("3")) + val added = base.with(Track.bare("3"), true) + assertEquals("3", added.tracks()!![0].id) + val removed = added.with(Track.bare("1"), false) + assertTrue(!removed.contains("1") && removed.contains("2")) + assertSame("a no-op keeps the list", removed, removed.with(Track.bare("2"), true)) + assertSame(Liked.NotLoaded, Liked.NotLoaded.with(Track.bare("9"), true)) + } + + @Test + fun spacedCodes() { + assertEquals("QX7K 29PM", SignInState.spaced("QX7K29PM")) + assertEquals("QX7-K29", SignInState.spaced("QX7-K29")) + assertEquals("1234567", SignInState.spaced("1234567")) + } +} diff --git a/app/src/test/java/it/panov/musyx/tv/ui/theme/ThemeTest.kt b/app/src/test/java/it/panov/musyx/tv/ui/theme/ThemeTest.kt new file mode 100644 index 0000000..923e5cd --- /dev/null +++ b/app/src/test/java/it/panov/musyx/tv/ui/theme/ThemeTest.kt @@ -0,0 +1,46 @@ +package it.panov.musyx.tv.ui.theme + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.sp +import it.panov.musyx.tv.data.FontSize +import org.junit.Assert.assertEquals +import org.junit.Test + +/** Ports the desktop theme.rs tests, plus parity checks for the placeholder hues. */ +class ThemeTest { + @Test + fun accentMatchesDesign() { + assertEquals(Color(0xF0, 0xB2, 0x3E), DarkColors.accent) + assertEquals(Color(0xA8, 0x6C, 0x05), LightColors.accent) + } + + @Test + fun hslPrimaries() { + val red = hsl(0f, 1f, 0.5f) + assertEquals(1f, red.red, 1e-5f) + assertEquals(0f, red.green, 1e-5f) + assertEquals(0f, red.blue, 1e-5f) + val blue = hsl(240f, 1f, 0.5f) + assertEquals(1f, blue.blue, 1e-5f) + assertEquals(0f, blue.red, 1e-5f) + } + + // Expected values come from ym-api's `hues_for` and its per-kind seeds (u64 wrapping maths). + @Test + fun huesMatchTheDesktop() { + assertEquals(47f to 221f, CoverHues.album(1)) + assertEquals(329f to 335f, CoverHues.album(-1)) + assertEquals(233f to 119f, CoverHues.artist(42)) + assertEquals(2f to 356f, CoverHues.playlist(owner = 503_646_255, kind = 3)) + assertEquals(295f to 85f, CoverHues.track("12345:678", albumId = null)) + assertEquals(CoverHues.album(7), CoverHues.track("12345:678", albumId = 7)) + } + + // Large is the size the app shipped with; the others only shrink it. + @Test + fun fontSizeScalesType() { + assertEquals(MusyxTypeScale, musyxType(FontSize.Large.scale)) + assertEquals(21.sp, musyxType(FontSize.Large.scale).body.fontSize) + assertEquals(16.8f, musyxType(FontSize.Small.scale).body.fontSize.value, 1e-4f) + } +} diff --git a/assets/fonts/OFL-Onest.txt b/assets/fonts/OFL-Onest.txt new file mode 100644 index 0000000..b6f4f91 --- /dev/null +++ b/assets/fonts/OFL-Onest.txt @@ -0,0 +1,93 @@ +Copyright 2021 The Onest Project Authors (https://github.com/googlefonts/onest) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/OFL-Unbounded.txt b/assets/fonts/OFL-Unbounded.txt new file mode 100644 index 0000000..1c7db28 --- /dev/null +++ b/assets/fonts/OFL-Unbounded.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Unbounded Project Authors (https://github.com/googlefonts/unbounded) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/Onest-Medium.ttf b/assets/fonts/Onest-Medium.ttf new file mode 100644 index 0000000..bf4d81d Binary files /dev/null and b/assets/fonts/Onest-Medium.ttf differ diff --git a/assets/fonts/Onest-Regular.ttf b/assets/fonts/Onest-Regular.ttf new file mode 100644 index 0000000..c5d8299 Binary files /dev/null and b/assets/fonts/Onest-Regular.ttf differ diff --git a/assets/fonts/Onest-SemiBold.ttf b/assets/fonts/Onest-SemiBold.ttf new file mode 100644 index 0000000..25c2dc5 Binary files /dev/null and b/assets/fonts/Onest-SemiBold.ttf differ diff --git a/assets/fonts/Unbounded-SemiBold.ttf b/assets/fonts/Unbounded-SemiBold.ttf new file mode 100644 index 0000000..5a15398 Binary files /dev/null and b/assets/fonts/Unbounded-SemiBold.ttf differ diff --git a/assets/icon/musyx.png b/assets/icon/musyx.png new file mode 100644 index 0000000..99008df Binary files /dev/null and b/assets/icon/musyx.png differ diff --git a/assets/icons/LICENSE.txt b/assets/icons/LICENSE.txt new file mode 100644 index 0000000..325e8ff --- /dev/null +++ b/assets/icons/LICENSE.txt @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2022. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/assets/icons/audio-lines.svg b/assets/icons/audio-lines.svg new file mode 100644 index 0000000..d8ff24a --- /dev/null +++ b/assets/icons/audio-lines.svg @@ -0,0 +1,20 @@ + + + + + + + + + diff --git a/assets/icons/ban.svg b/assets/icons/ban.svg new file mode 100644 index 0000000..b8069ee --- /dev/null +++ b/assets/icons/ban.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/chevron-left.svg b/assets/icons/chevron-left.svg new file mode 100644 index 0000000..23d3767 --- /dev/null +++ b/assets/icons/chevron-left.svg @@ -0,0 +1,15 @@ + + + + diff --git a/assets/icons/chevron-right.svg b/assets/icons/chevron-right.svg new file mode 100644 index 0000000..54f2be6 --- /dev/null +++ b/assets/icons/chevron-right.svg @@ -0,0 +1,15 @@ + + + + diff --git a/assets/icons/clock-3.svg b/assets/icons/clock-3.svg new file mode 100644 index 0000000..e1ff7b7 --- /dev/null +++ b/assets/icons/clock-3.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/copy.svg b/assets/icons/copy.svg new file mode 100644 index 0000000..db06853 --- /dev/null +++ b/assets/icons/copy.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/disc-3.svg b/assets/icons/disc-3.svg new file mode 100644 index 0000000..92a5044 --- /dev/null +++ b/assets/icons/disc-3.svg @@ -0,0 +1,18 @@ + + + + + + + diff --git a/assets/icons/ellipsis.svg b/assets/icons/ellipsis.svg new file mode 100644 index 0000000..72e7577 --- /dev/null +++ b/assets/icons/ellipsis.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/assets/icons/globe.svg b/assets/icons/globe.svg new file mode 100644 index 0000000..0e8ae33 --- /dev/null +++ b/assets/icons/globe.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/assets/icons/grip-vertical.svg b/assets/icons/grip-vertical.svg new file mode 100644 index 0000000..86863cd --- /dev/null +++ b/assets/icons/grip-vertical.svg @@ -0,0 +1,20 @@ + + + + + + + + + diff --git a/assets/icons/heart-fill.svg b/assets/icons/heart-fill.svg new file mode 100644 index 0000000..978a267 --- /dev/null +++ b/assets/icons/heart-fill.svg @@ -0,0 +1,15 @@ + + + + diff --git a/assets/icons/heart.svg b/assets/icons/heart.svg new file mode 100644 index 0000000..03f455a --- /dev/null +++ b/assets/icons/heart.svg @@ -0,0 +1,15 @@ + + + + diff --git a/assets/icons/house.svg b/assets/icons/house.svg new file mode 100644 index 0000000..cd91b33 --- /dev/null +++ b/assets/icons/house.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/library.svg b/assets/icons/library.svg new file mode 100644 index 0000000..1204985 --- /dev/null +++ b/assets/icons/library.svg @@ -0,0 +1,18 @@ + + + + + + + diff --git a/assets/icons/list-music.svg b/assets/icons/list-music.svg new file mode 100644 index 0000000..c579b54 --- /dev/null +++ b/assets/icons/list-music.svg @@ -0,0 +1,19 @@ + + + + + + + + diff --git a/assets/icons/lock.svg b/assets/icons/lock.svg new file mode 100644 index 0000000..224ce2a --- /dev/null +++ b/assets/icons/lock.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/log-out.svg b/assets/icons/log-out.svg new file mode 100644 index 0000000..2a223be --- /dev/null +++ b/assets/icons/log-out.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/assets/icons/mic-vocal.svg b/assets/icons/mic-vocal.svg new file mode 100644 index 0000000..af184fe --- /dev/null +++ b/assets/icons/mic-vocal.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/assets/icons/pause-fill.svg b/assets/icons/pause-fill.svg new file mode 100644 index 0000000..0714a8f --- /dev/null +++ b/assets/icons/pause-fill.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/pause.svg b/assets/icons/pause.svg new file mode 100644 index 0000000..bf54784 --- /dev/null +++ b/assets/icons/pause.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/pencil.svg b/assets/icons/pencil.svg new file mode 100644 index 0000000..9cfbaac --- /dev/null +++ b/assets/icons/pencil.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/play-fill.svg b/assets/icons/play-fill.svg new file mode 100644 index 0000000..06454c7 --- /dev/null +++ b/assets/icons/play-fill.svg @@ -0,0 +1,15 @@ + + + + diff --git a/assets/icons/play.svg b/assets/icons/play.svg new file mode 100644 index 0000000..16c345d --- /dev/null +++ b/assets/icons/play.svg @@ -0,0 +1,15 @@ + + + + diff --git a/assets/icons/plus.svg b/assets/icons/plus.svg new file mode 100644 index 0000000..5ec5837 --- /dev/null +++ b/assets/icons/plus.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/podcast.svg b/assets/icons/podcast.svg new file mode 100644 index 0000000..da3fae8 --- /dev/null +++ b/assets/icons/podcast.svg @@ -0,0 +1,18 @@ + + + + + + + diff --git a/assets/icons/repeat-1.svg b/assets/icons/repeat-1.svg new file mode 100644 index 0000000..1ddf541 --- /dev/null +++ b/assets/icons/repeat-1.svg @@ -0,0 +1,19 @@ + + + + + + + + diff --git a/assets/icons/repeat.svg b/assets/icons/repeat.svg new file mode 100644 index 0000000..74a799a --- /dev/null +++ b/assets/icons/repeat.svg @@ -0,0 +1,18 @@ + + + + + + + diff --git a/assets/icons/search.svg b/assets/icons/search.svg new file mode 100644 index 0000000..d99a347 --- /dev/null +++ b/assets/icons/search.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/settings.svg b/assets/icons/settings.svg new file mode 100644 index 0000000..b1bf775 --- /dev/null +++ b/assets/icons/settings.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/shuffle.svg b/assets/icons/shuffle.svg new file mode 100644 index 0000000..18002ec --- /dev/null +++ b/assets/icons/shuffle.svg @@ -0,0 +1,19 @@ + + + + + + + + diff --git a/assets/icons/skip-back.svg b/assets/icons/skip-back.svg new file mode 100644 index 0000000..f4d3924 --- /dev/null +++ b/assets/icons/skip-back.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/skip-forward.svg b/assets/icons/skip-forward.svg new file mode 100644 index 0000000..dfe1176 --- /dev/null +++ b/assets/icons/skip-forward.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/sliders-horizontal.svg b/assets/icons/sliders-horizontal.svg new file mode 100644 index 0000000..e54381d --- /dev/null +++ b/assets/icons/sliders-horizontal.svg @@ -0,0 +1,23 @@ + + + + + + + + + + + + diff --git a/assets/icons/trash-2.svg b/assets/icons/trash-2.svg new file mode 100644 index 0000000..df96c4a --- /dev/null +++ b/assets/icons/trash-2.svg @@ -0,0 +1,19 @@ + + + + + + + + diff --git a/assets/icons/trending-up.svg b/assets/icons/trending-up.svg new file mode 100644 index 0000000..6ee61e2 --- /dev/null +++ b/assets/icons/trending-up.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/assets/icons/volume-2.svg b/assets/icons/volume-2.svg new file mode 100644 index 0000000..3517757 --- /dev/null +++ b/assets/icons/volume-2.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/assets/icons/volume-x.svg b/assets/icons/volume-x.svg new file mode 100644 index 0000000..075b54c --- /dev/null +++ b/assets/icons/volume-x.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/assets/icons/x.svg b/assets/icons/x.svg new file mode 100644 index 0000000..7067a86 --- /dev/null +++ b/assets/icons/x.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..86acfea --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,5 @@ +plugins { + alias(libs.plugins.android.application) apply false + alias(libs.plugins.kotlin.compose) apply false + alias(libs.plugins.kotlin.serialization) apply false +} diff --git a/design/mockup.html b/design/mockup.html new file mode 100644 index 0000000..288aa01 --- /dev/null +++ b/design/mockup.html @@ -0,0 +1,841 @@ +Musyx Desktop Mockup + + + + + +
+

Musyx mockup

+

Sample data throughout. Covers are generated art; the app will show real artwork from Yandex Music.

+
+
+ +
+ + + + + + + +
+
+ + +
+ + +
+
+ +
+

My Wave

An endless stream picked from what you play, like and skip. Tuned to: any mood, favourites.

+ + +
+
+

Made for you

+

Chart

+

Albums you might like

+
+ + + + + + + + + + + + + + + + + + + + + +
+ + + + + +
+
+ +
Звезда по имени СолнцеКино
+ + +
+
+
+ + + + + +
+
1:12
3:45
+
+
+ MP3 320 + + +
+
+
+
+ + + diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..91035ed --- /dev/null +++ b/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8 +org.gradle.caching=true +org.gradle.configuration-cache=true +android.useAndroidX=true +android.nonTransitiveRClass=true +kotlin.code.style=official diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..944a97b --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,42 @@ +[versions] +agp = "9.4.1" +kotlin = "2.4.21" +compose-bom = "2026.09.00" +tv-material = "1.1.0" +activity-compose = "1.13.0" +core-ktx = "1.19.1" +lifecycle = "2.11.0" +media3 = "1.11.1" +okhttp = "5.5.0" +kotlinx-serialization = "1.11.0" +junit = "4.13.2" +coil = "3.6.3" +zxing = "3.5.4" +coroutines = "1.10.2" + +[libraries] +androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "core-ktx" } +androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activity-compose" } +androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" } +compose-bom = { module = "androidx.compose:compose-bom", version.ref = "compose-bom" } +compose-ui = { module = "androidx.compose.ui:ui" } +compose-ui-graphics = { module = "androidx.compose.ui:ui-graphics" } +compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" } +compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" } +compose-foundation = { module = "androidx.compose.foundation:foundation" } +tv-material = { module = "androidx.tv:tv-material", version.ref = "tv-material" } +media3-exoplayer = { module = "androidx.media3:media3-exoplayer", version.ref = "media3" } +media3-session = { module = "androidx.media3:media3-session", version.ref = "media3" } +okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } +kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization" } +junit = { module = "junit:junit", version.ref = "junit" } +coil-compose = { module = "io.coil-kt.coil3:coil-compose", version.ref = "coil" } +coil-network-okhttp = { module = "io.coil-kt.coil3:coil-network-okhttp", version.ref = "coil" } +zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" } +kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" } +androidx-lifecycle-process = { module = "androidx.lifecycle:lifecycle-process", version.ref = "lifecycle" } + +[plugins] +android-application = { id = "com.android.application", version.ref = "agp" } +kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..eddabd2 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a4818a2 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,10 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.1-bin.zip +distributionSha256Sum=dce76f55f8e251a3a1f130eb120f30b3d271de2b76c9b0729d316b5a1b6dc01f +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..249efbb --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..8508ef6 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/reference/musyx/examples/api_probe.rs b/reference/musyx/examples/api_probe.rs new file mode 100644 index 0000000..6833caa --- /dev/null +++ b/reference/musyx/examples/api_probe.rs @@ -0,0 +1,124 @@ +//! Read-only check of the discovery endpoints with the signed-in account: +//! `cargo run -p musyx --example api_probe`. Prints counts and a few titles. +use ym_api::auth::Credentials; +use ym_api::{SearchKind, YmClient}; + +#[tokio::main(flavor = "current_thread")] +async fn main() { + let raw = keyring::Entry::new("musyx", "yandex-music") + .and_then(|e| e.get_password()) + .expect("sign in with Musyx first"); + let credentials: Credentials = serde_json::from_str(&raw).expect("stored credentials"); + let (client, account) = YmClient::connect(&credentials, ym_api::ContentLanguage::English).await.expect("connect"); + println!("account: {} (plus: {})", account.login, account.has_plus); + + match client.home().await { + Ok(h) => println!( + "home: {} personal {:?}, {} chart, {} new releases, {} new playlists", + h.personal.len(), + h.personal.iter().map(|p| p.playlist.title.as_str()).collect::>(), + h.chart.len(), + h.new_releases.len(), + h.new_playlists.len() + ), + Err(e) => println!("home: ERROR {e}"), + } + match client.genres().await { + Ok(g) => { + println!("genres: {} {:?}", g.len(), g.iter().take(8).map(|g| (&g.id, &g.title)).collect::>()); + for genre in g.iter().skip(1).take(4) { + match client.tag_playlists(&genre.id).await { + Ok(p) => println!("tag {}: {} playlists {:?}", genre.id, p.len(), p.iter().take(2).map(|p| &p.title).collect::>()), + Err(e) => println!("tag {}: ERROR {e}", genre.id), + } + } + } + Err(e) => println!("genres: ERROR {e}"), + } + match client.featured_podcasts().await { + Ok(p) => println!("podcasts: {} {:?}", p.len(), p.iter().take(3).map(|a| &a.title).collect::>()), + Err(e) => println!("podcasts: ERROR {e}"), + } + match client.search("земфира", SearchKind::All, 0).await { + Ok(r) => println!( + "search: best {:?}, {} tracks ({}), {} albums, {} artists, {} playlists, {} podcasts", + r.best.as_ref().map(|b| format!("{b:?}").chars().take(60).collect::()), + r.tracks.len(), r.totals.tracks, r.albums.len(), r.artists.len(), r.playlists.len(), r.podcasts.len() + ), + Err(e) => println!("search: ERROR {e}"), + } + match client.stations().await { + Ok(st) => println!("stations: {} {:?}", st.len(), st.iter().take(6).map(|s| (&s.id, &s.name)).collect::>()), + Err(e) => println!("stations: ERROR {e}"), + } + match client.wave_settings(ym_api::MY_WAVE).await { + Ok(s) => println!("wave settings: {s:?}"), + Err(e) => println!("wave settings: ERROR {e}"), + } + match client.wave_start(ym_api::MY_WAVE, None).await { + Ok(b) => println!( + "wave session {:?} batch {:?}: {:?}", + b.session_id, + b.batch_id, + b.tracks.iter().map(|t| format!("{} — {}", t.artist_line(), t.title)).collect::>() + ), + Err(e) => println!("wave: ERROR {e}"), + } + match client.liked_ids().await { + Ok(l) => println!( + "liked ids: {} albums, {} artists, {} playlists, {} disliked tracks", + l.albums.len(), l.artists.len(), l.playlists.len(), l.disliked_tracks.len() + ), + Err(e) => println!("liked ids: ERROR {e}"), + } + if let Ok(found) = client.search("eminem without me", SearchKind::Tracks, 0).await { + for track in found.tracks.iter().take(2) { + println!("track {} {} lyrics_available={}", track.id, track.title, track.lyrics_available); + match client.lyrics(&track.id).await { + Ok(Some(l)) => println!( + "lyrics {}: synced={} lines={} first_stamp={:?}", + track.id, l.synced, l.lines.len(), l.lines.first().and_then(|x| x.at) + ), + Ok(None) => println!("lyrics {}: none", track.id), + Err(e) => println!("lyrics {}: ERROR {e}", track.id), + } + } + } + if let Ok(chart) = client.chart().await { + for entry in chart.iter().take(3) { + println!("chart {} lyrics_available={}", entry.track.id, entry.track.lyrics_available); + match client.lyrics(&entry.track.id).await { + Ok(Some(l)) => println!( + "lyrics {}: synced={} lines={} first_stamp={:?}", + entry.track.id, l.synced, l.lines.len(), l.lines.first().and_then(|x| x.at) + ), + Ok(None) => println!("lyrics {}: none", entry.track.id), + Err(e) => println!("lyrics {}: ERROR {e}", entry.track.id), + } + } + } + match client.recently_played(10).await { + Ok(r) => println!("recently played: {} {:?}", r.len(), r.iter().take(3).map(|t| t.full_title()).collect::>()), + Err(e) => println!("recently played: ERROR {e}"), + } + match client.similar_tracks("85507364").await { + Ok(s) => println!("similar: {} {:?}", s.len(), s.iter().take(3).map(|t| format!("{} — {}", t.artist_line(), t.title)).collect::>()), + Err(e) => println!("similar: ERROR {e}"), + } + match client.artist_clips(675068).await { + Ok(c) => println!( + "artist clips: {} {:?}", + c.len(), + c.iter().take(3).map(|c| format!("{} {} — {} ({}s)", c.id, c.artist_line(), c.title, c.duration.as_secs())).collect::>() + ), + Err(e) => println!("artist clips: ERROR {e}"), + } + match client.liked_clips().await { + Ok(c) => println!("liked clips: {} {:?}", c.len(), c.iter().take(3).map(|c| &c.title).collect::>()), + Err(e) => println!("liked clips: ERROR {e}"), + } + match client.suggest("зем").await { + Ok(s) => println!("suggest: {:?}", s.iter().take(5).collect::>()), + Err(e) => println!("suggest: ERROR {e}"), + } +} diff --git a/reference/musyx/examples/audio_probe.rs b/reference/musyx/examples/audio_probe.rs new file mode 100644 index 0000000..2d59db7 --- /dev/null +++ b/reference/musyx/examples/audio_probe.rs @@ -0,0 +1,23 @@ +//! Lists output devices and tries to open each one: `cargo run -p musyx --example audio_probe`. +use rodio::DeviceSinkBuilder; +use rodio::cpal::traits::{DeviceTrait, HostTrait}; + +fn main() { + let host = rodio::cpal::default_host(); + let default = host.default_output_device(); + println!("default: {:?}", default.as_ref().and_then(|d| d.description().ok()).map(|d| d.name().to_string())); + for device in host.output_devices().expect("devices") { + let name = device.description().map(|d| d.name().to_string()).unwrap_or_default(); + let config = device.default_output_config(); + println!("\n{name}\n default config: {config:?}"); + match DeviceSinkBuilder::from_device(device.clone()).map(|b| b.open_stream()) { + Ok(Ok(_)) => println!(" open (rodio defaults): ok"), + Ok(Err(e)) => println!(" open (rodio defaults): {e:?}"), + Err(e) => println!(" builder: {e:?}"), + } + if let Ok(config) = config { + let r = DeviceSinkBuilder::default().with_device(device.clone()).with_supported_config(&config).open_stream(); + println!(" open (device default buffer): {:?}", r.map(|_| "ok")); + } + } +} diff --git a/reference/musyx/examples/stream_probe.rs b/reference/musyx/examples/stream_probe.rs new file mode 100644 index 0000000..4d6e850 --- /dev/null +++ b/reference/musyx/examples/stream_probe.rs @@ -0,0 +1,47 @@ +//! Read-only check of lossless streaming with the signed-in account: +//! `cargo run -p musyx --example stream_probe [query]`. Asks for FLAC, downloads +//! and decrypts it, and decodes the start to show the format. +use std::io::Cursor; +use std::time::Instant; + +use rodio::Source; +use ym_api::auth::Credentials; +use ym_api::{SearchKind, YmClient}; + +#[tokio::main(flavor = "current_thread")] +async fn main() { + let raw = keyring::Entry::new("musyx", "yandex-music") + .and_then(|e| e.get_password()) + .expect("sign in with Musyx first"); + let credentials: Credentials = serde_json::from_str(&raw).expect("stored credentials"); + let (client, account) = YmClient::connect(&credentials, ym_api::ContentLanguage::English).await.expect("connect"); + println!("account: {} (plus: {})", account.login, account.has_plus); + + let query = std::env::args().nth(1).unwrap_or_else(|| "земфира хочешь".into()); + let found = client.search(&query, SearchKind::Tracks, 0).await.expect("search"); + let track = found.tracks.first().expect("no tracks found"); + println!("track: {} — {} ({})", track.artist_line(), track.title, track.id); + + let started = Instant::now(); + let stream = client.lossless_stream(&track.id).await.expect("stream"); + println!("stream: {stream:?} label={} in {:?}", stream.label(), started.elapsed()); + let started = Instant::now(); + let bytes = client.fetch(&stream).await.expect("fetch"); + println!("fetched {:.1} MB in {:?}, starts with {:?}", bytes.len() as f64 / 1e6, started.elapsed(), String::from_utf8_lossy(&bytes[..12])); + + let decoder = rodio::Decoder::builder() + .with_data(Cursor::new(bytes.to_vec())) + .with_byte_len(bytes.len() as u64) + .with_hint(stream.container()) + .with_seekable(true) + .build() + .expect("decode"); + println!( + "decoded: {} Hz, {} ch, duration {:?}", + decoder.sample_rate(), + decoder.channels(), + decoder.total_duration() + ); + let samples = decoder.take(48_000).filter(|s| s.abs() > 0.0).count(); + println!("non-silent samples in the first 48k: {samples}"); +} diff --git a/reference/musyx/src/app.rs b/reference/musyx/src/app.rs new file mode 100644 index 0000000..2761837 --- /dev/null +++ b/reference/musyx/src/app.rs @@ -0,0 +1,1350 @@ +//! Application state, messages and the window layout. + +mod edit; + +use crate::i18n::{tr, trf}; +use std::collections::HashMap; +use std::sync::Arc; + +use iced::theme::Mode; +use iced::widget::{column, container, row, scrollable, space, stack}; +use iced::{Element, Fill, Subscription, Task, Theme}; +use ym_api::auth::Credentials; +use ym_api::{ + Account, AlbumSummary, ArtistSummary, Clip, Error, Genre, Home, LibraryPlaylists, LikedIds, Lyrics, MY_WAVE, + PlaylistId, PlaylistSummary, Station, Track, WaveSettings, YmClient, +}; + +use crate::covers::Covers; +use crate::player::{self, Audio, Effect, Player}; +use crate::route::{Navigator, Route}; +use crate::screens::browse::{self, Discover, HomeData}; +use crate::screens::collection::{Library, Liked, Tab}; +use crate::screens::search::{self, Search}; +use crate::screens::wave::WaveScreen; +use crate::screens::detail::{self, Page}; +use crate::screens::{self, Loadable, sign_in}; +use crate::session::{self, Restored}; +use crate::store::{self, Appearance, Locale, Quality, Settings}; +use crate::ui::theme::{self, shell}; +use crate::widgets::drawer::{self, Panel}; +use crate::widgets::player_bar; +use crate::widgets::sheet::{self, Sheet}; +use crate::widgets::track_list::Env; +use crate::widgets::{sidebar, topbar}; + +/// Where sign-in stands. Everything but `SignedIn` takes the whole window. +pub enum Session { + /// Reading the keychain and checking the stored token. + Restoring, + SignedOut(Box), + /// Fresh credentials are being checked. `pasted` picks the error wording if they fail. + Connecting { pasted: bool }, + Unreachable, + SignedIn { client: YmClient, account: Account }, +} + +pub struct App { + theme: Theme, + /// Set by a snapshot run so the system appearance can't override it. + forced_mode: Option, + session: Session, + nav: Navigator, + search: Search, + drawer: Option, + player: Player, + library: Library, + /// Album, artist and playlist pages visited this session. + pages: HashMap>, + discover: Discover, + genre_playlists: HashMap>>, + wave: WaveScreen, + /// Drives the My Wave hero animation. + wave_phase: f32, + covers: Covers, + /// Albums, artists and playlists liked, and tracks disliked, by id. + likes: LikedIds, + sheet: Option, + toast: Option<(String, std::time::Instant)>, + /// Lyrics per track id, fetched while the lyrics panel is open. + lyrics: HashMap>>>, + /// The synced line last scrolled to. + lyric_line: Option, + settings: Settings, + /// The OS appearance, used when settings say "Match system". + system_mode: Mode, + /// Volume changed and not yet saved; saved once the slider settles. + settings_dirty: Option, + /// Media keys and the system's Now Playing widget. + media: crate::media::Media, + /// The menu bar mini player shown while the window is minimised. + mini_player: crate::menubar::MiniPlayer, + /// A live snapshot run opens this route once signed in. + #[cfg(feature = "snapshot")] + snapshot_route: Option, +} + +#[derive(Debug, Clone)] +pub enum Message { + ThemeChanged(Mode), + Restore, + Restored(Restored), + SignIn(sign_in::Msg), + Connected(Result<(YmClient, Account), Error>), + AccountRefreshed(Result), + SignOut, + SignedOut, + Navigate(Route), + Back, + Search(search::Msg), + ToggleDrawer(Panel), + CloseDrawer, + Player(player::Msg), + PlayTracks { tracks: Arc<[Track]>, start: usize, shuffle: bool }, + LoadLiked, + LikedLoaded(Result, Error>), + CollectionTab(Tab), + LoadLibrary(Tab), + AlbumsLoaded(Result, Error>), + ArtistsLoaded(Result, Error>), + PlaylistsLoaded(Result), + ClipsLoaded(Result, Error>), + /// Clips play on the Yandex Music website. + OpenClip(Clip), + LikeClip(Clip, bool), + PageLoaded(Route, Result), + LoadHome, + HomeLoaded(Result), + LoadRecent, + RecentLoaded(Result, Error>), + LoadGenres, + GenresLoaded(Result, Error>), + GenreLoaded(usize, Result, Error>), + LoadPodcasts, + PodcastsLoaded(Result, Error>), + PlayWave(String), + LoadWave, + WaveSettingsLoaded(Result), + StationsLoaded(Result, Error>), + SetWaveSettings(WaveSettings), + WaveSettingsSaved(WaveSettings, Result<(), Error>), + WaveTick, + SetQuality(Quality), + SetAppearance(Appearance), + SetLanguage(Locale), + LanguageSwitched(Result), + SaveSettings, + SettingsSaved(Result<(), String>), + ClearCoverCache, + CoverCacheCleared(Result<(), String>), + Media(crate::media::Command), + LoadLikedIds, + LikedIdsLoaded(Result), + LikeTrack(Track, bool), + DislikeTrack(Track, bool), + LikeAlbum(i64, bool), + LikeArtist(i64, bool), + LikePlaylist(PlaylistId, bool), + OpenSheet(Sheet), + CloseSheet, + SheetText(String), + PlayNext(Track), + /// "Next track" in the menu of the track playing now. + SkipFromMenu, + AddToQueue(Track), + /// Plays the tracks Yandex finds similar to this one. + PlaySimilar(Track), + SimilarLoaded(Track, Result, Error>), + AddToPlaylist(PlaylistId, Track), + CreatePlaylist, + RenamePlaylist, + SetPlaylistPublic(PlaylistId, bool), + DeletePlaylist(PlaylistId), + RemoveFromPlaylist(PlaylistId, usize), + MovePlaylistTrack { id: PlaylistId, track: Track, from: usize, to: usize }, + Edited(Box), + LyricsLoaded(String, Result>, Error>), + RetryLyrics, + ToastTick, + CoverWanted(String), + CoverLoaded(String, Option>), + CoversTick, +} + +impl App { + pub fn new() -> (Self, Task) { + let app = Self { + theme: theme::for_mode(Mode::Dark), + forced_mode: None, + session: Session::Restoring, + nav: Navigator::new(Route::Home), + search: Search::default(), + drawer: None, + player: Player::default(), + library: Library::default(), + pages: HashMap::new(), + discover: Discover::default(), + genre_playlists: HashMap::new(), + wave: WaveScreen::default(), + wave_phase: 0.0, + covers: Covers::default(), + likes: LikedIds::default(), + sheet: None, + toast: None, + lyrics: HashMap::new(), + lyric_line: None, + settings: Settings::default(), + system_mode: Mode::Dark, + settings_dirty: None, + media: crate::media::Media::new(), + mini_player: crate::menubar::MiniPlayer::new(), + #[cfg(feature = "snapshot")] + snapshot_route: None, + }; + let mut app = app; + app.settings = store::load(); + crate::i18n::set(app.settings.language.resolve()); + app.player.volume = app.settings.volume; + app.apply_theme(); + let app = app; + let appearance = iced::system::theme().map(Message::ThemeChanged); + + #[cfg(feature = "snapshot")] + if let Some(config) = crate::snapshot::Config::from_env() { + let mut app = app; + app.drawer = config.drawer; + app.forced_mode = config.mode; + if let Some(lang) = config.lang { + crate::i18n::set(lang); + } + if let Some(mode) = config.mode { + app.theme = theme::for_mode(mode); + } + if config.live { + app.snapshot_route = config.route; + return (app, Task::batch([appearance, restore(), config.capture()])); + } + app.session = config.session(); + app.library.liked = Liked::loaded(config.sample_liked(), &Liked::NotLoaded); + app.pages.insert(Route::Album(1), Loadable::Loaded(config.sample_album())); + if let Some(route) = config.route { + app.nav = Navigator::new(route); + } + return (app, Task::batch([appearance, config.capture()])); + } + + (app, Task::batch([appearance, restore()])) + } + + pub fn title(&self) -> String { + match (&self.session, self.nav.current()) { + (Session::SignedIn { .. }, route) if route != Route::Home => { + format!("{} · Musyx", route.label()) + } + _ => "Musyx".into(), + } + } + + pub fn theme(&self) -> Theme { + self.theme.clone() + } + + /// Snapshot override, then the user's choice, then the system appearance. + fn apply_theme(&mut self) { + let mode = self.forced_mode.unwrap_or(match self.settings.appearance { + Appearance::System => self.system_mode, + Appearance::Light => Mode::Light, + Appearance::Dark => Mode::Dark, + }); + self.theme = theme::for_mode(mode); + } + + pub fn subscription(&self) -> Subscription { + let appearance = iced::system::theme_changes().map(Message::ThemeChanged); + let audio = player::engine::subscription().map(|e| Message::Player(player::Msg::Engine(e))); + let keys = crate::media::subscription().map(Message::Media); + let mut subs = vec![appearance, audio, keys]; + if let Session::SignedOut(sign_in) = &self.session { + subs.push(sign_in.subscription().map(Message::SignIn)); + } + // The hero's lines drift only while My Wave plays and the hero is on screen. + let hero_visible = matches!(self.nav.current(), Route::Home | Route::Wave); + let wave_playing = self.player.wave_station() == Some(MY_WAVE) + && self.player.status() == player::Status::Playing; + if hero_visible && wave_playing && matches!(self.session, Session::SignedIn { .. }) { + subs.push(iced::time::every(std::time::Duration::from_millis(33)).map(|_| Message::WaveTick)); + } + if self.settings_dirty.is_some() { + subs.push(iced::time::every(std::time::Duration::from_millis(500)).map(|_| Message::SaveSettings)); + } + if self.toast.is_some() { + subs.push(iced::time::every(std::time::Duration::from_millis(500)).map(|_| Message::ToastTick)); + } + // Show arriving covers in batches instead of rebuilding lists for each one. + if self.covers.dirty() { + subs.push(iced::time::every(std::time::Duration::from_millis(150)).map(|_| Message::CoversTick)); + } + Subscription::batch(subs) + } + + fn client(&self) -> Option<&YmClient> { + match &self.session { + Session::SignedIn { client, .. } => Some(client), + _ => None, + } + } + + /// A rejected token ends the session; anything else is logged and shown by the caller. + fn failed(&mut self, what: &str, e: &Error) -> Option> { + eprintln!("{what}: {e}"); + matches!(e, Error::Unauthorized(_)).then(|| self.update(Message::SignOut)) + } + + fn signed_in(&mut self, client: YmClient, account: Account) -> Task { + self.nav = Navigator::new(Route::Home); + self.session = Session::SignedIn { client, account }; + // Liked tracks drive the hearts; playlists fill the sidebar; Home is the first page. + #[allow(unused_mut)] + let mut first = Route::Home; + #[cfg(feature = "snapshot")] + if let Some(route) = self.snapshot_route { + self.nav = Navigator::new(route); + first = route; + } + Task::batch([ + self.update(Message::LoadLiked), + self.update(Message::LoadLikedIds), + self.update(Message::LoadLibrary(Tab::Playlists)), + self.on_enter(first), + ]) + } + + pub fn update(&mut self, message: Message) -> Task { + let traced = trace(&message); + let task = self.update_inner(message); + if traced { + let now = self.player.track().map_or("-".to_owned(), |t| t.full_title()); + let next: Vec = self + .player + .queue() + .map(|q| q.upcoming().take(3).map(|(_, t)| t.full_title()).collect()) + .unwrap_or_default(); + eprintln!("trace: now: {now} | next: {}", next.join(" / ")); + } + task + } + + fn update_inner(&mut self, message: Message) -> Task { + match message { + Message::ThemeChanged(mode) => { + self.system_mode = mode; + self.apply_theme(); + } + Message::SetQuality(quality) => { + self.settings.quality = quality; + self.toast(trf("Streaming quality: {}. Applies from the next track.", &[&quality.label()])); + return self.update(Message::SaveSettings); + } + Message::SetLanguage(locale) => { + self.settings.language = locale; + let lang = locale.resolve(); + let changed = lang != crate::i18n::lang(); + crate::i18n::set(lang); + let save = self.update(Message::SaveSettings); + if !changed { + return save; + } + // Yandex's own titles (genres, Home blocks, stations) follow too. + let Some(client) = self.client().cloned() else { return save }; + let switch = Task::future(async move { client.in_language(lang.content()).await }) + .map(Message::LanguageSwitched); + return Task::batch([save, switch]); + } + Message::LanguageSwitched(Ok(client)) => { + if let Session::SignedIn { client: current, .. } = &mut self.session { + *current = client; + } + // Load Yandex's titles again in the new language. + self.discover = Discover::default(); + self.genre_playlists.clear(); + self.wave = WaveScreen::default(); + return self.on_enter(self.nav.current()); + } + Message::LanguageSwitched(Err(e)) => { + // The interface has switched; Yandex's titles stay as they were until restart. + if let Some(task) = self.failed("switch content language", &e) { + return task; + } + } + Message::SetAppearance(appearance) => { + self.settings.appearance = appearance; + self.apply_theme(); + return self.update(Message::SaveSettings); + } + Message::SaveSettings => { + // Wait for the volume slider to settle before writing. + if self.settings_dirty.is_some_and(|at| at.elapsed() < std::time::Duration::from_millis(800)) { + return Task::none(); + } + self.settings_dirty = None; + return Task::future(store::save(self.settings)).map(Message::SettingsSaved); + } + Message::SettingsSaved(result) => { + if let Err(e) = result { + eprintln!("settings: {e}"); + self.toast(tr("Couldn't save your settings. They'll apply until Musyx quits.")); + } + } + Message::ClearCoverCache => { + return self.covers.clear_disk().map(Message::CoverCacheCleared); + } + Message::CoverCacheCleared(Ok(())) => self.toast(tr("Cover cache cleared")), + Message::CoverCacheCleared(Err(e)) => { + eprintln!("clear covers: {e}"); + self.toast(tr("Couldn't clear the cover cache.")); + } + Message::Restore => { + self.session = Session::Restoring; + return restore(); + } + Message::Restored(Restored::SignedIn(client, account)) => { + return self.signed_in(client, account); + } + Message::Restored(Restored::SignedOut) => self.session = Session::SignedOut(Box::default()), + Message::Restored(Restored::Unreachable) => self.session = Session::Unreachable, + Message::SignIn(msg) => { + let Session::SignedOut(sign_in) = &mut self.session else { + return Task::none(); + }; + match sign_in.update(msg) { + sign_in::Outcome::Continue(task) => return task.map(Message::SignIn), + sign_in::Outcome::Granted(credentials) => { + let pasted = credentials.refresh_token.is_none(); + self.session = Session::Connecting { pasted }; + return connect(credentials); + } + } + } + Message::Connected(Ok((client, account))) => return self.signed_in(client, account), + Message::Connected(Err(e)) => { + eprintln!("sign-in: {e}"); + let pasted = matches!(self.session, Session::Connecting { pasted: true }); + self.session = Session::SignedOut(Box::new(match &e { + Error::Unauthorized(_) if pasted => sign_in::SignIn::rejected_token(), + _ => sign_in::SignIn::with_error(&e), + })); + // Don't keep credentials that just failed. + return Task::future(session::clear()).discard(); + } + Message::SignOut => { + return Task::future(session::clear()).map(|result| { + if let Err(e) = result { + eprintln!("keychain: {e}"); + } + Message::SignedOut + }); + } + Message::SignedOut => { + self.session = Session::SignedOut(Box::default()); + self.nav = Navigator::new(Route::Home); + self.drawer = None; + self.player.reset(); + self.mini_player.update(None, self.player.status()); + self.library = Library::default(); + self.pages.clear(); + self.discover = Discover::default(); + self.genre_playlists.clear(); + self.search = Search::default(); + self.wave = WaveScreen::default(); + self.likes = LikedIds::default(); + self.sheet = None; + self.lyrics.clear(); + } + Message::Navigate(route) => { + self.sheet = None; + self.nav.go(route); + let (close, _) = self.search.update(search::Msg::CloseSuggestions, None); + return Task::batch([close, self.on_enter(route)]); + } + Message::AccountRefreshed(Ok(fresh)) => { + if let Session::SignedIn { account, .. } = &mut self.session { + *account = fresh; + } + } + Message::AccountRefreshed(Err(e)) => { + if let Some(task) = self.failed("account refresh", &e) { + return task; + } + } + Message::Back => { + self.nav.back(); + return self.on_enter(self.nav.current()); + } + Message::Search(msg) => { + let client = self.client().cloned(); + let (task, after) = self.search.update(msg, client.as_ref()); + if let search::After::ShowResults = after { + self.nav.go(Route::Search); + return Task::batch([task, self.on_enter(Route::Search)]); + } + return task; + } + Message::ToggleDrawer(panel) => { + self.drawer = if self.drawer == Some(panel) { None } else { Some(panel) }; + self.lyric_line = None; + return self.want_lyrics(); + } + Message::CloseDrawer => self.drawer = None, + Message::Player(msg) => { + let before = self.player.track().map(|t| t.id.clone()); + let seeked = matches!(msg, player::Msg::Seek(_) | player::Msg::SeekCommit); + let effects = self.player.update(msg); + self.media.update(self.player.track(), self.player.status(), self.player.position(), seeked); + self.mini_player.update(self.player.track(), self.player.status()); + if self.player.volume != self.settings.volume { + self.settings.volume = self.player.volume; + self.settings_dirty = Some(std::time::Instant::now()); + } + let run = self.run(effects); + if self.player.track().map(|t| t.id.as_str()) != before.as_deref() { + self.lyric_line = None; + return Task::batch([run, self.want_lyrics()]); + } + return Task::batch([run, self.follow_lyrics()]); + } + Message::PlayNext(track) => { + self.sheet = None; + if self.player.track().is_some_and(|t| t.id == track.id) { + self.toast(trf("“{}” is already playing", &[&track.full_title()])); + return Task::none(); + } + self.toast(trf("“{}” plays next", &[&track.full_title()])); + return self.update(Message::Player(player::Msg::PlayNext(track))); + } + Message::Media(command) => { + use crate::media::Command as C; + let status = self.player.status(); + let msg = match command { + C::Play if status != player::Status::Playing => player::Msg::Toggle, + C::Pause if status == player::Status::Playing => player::Msg::Toggle, + C::Play | C::Pause => return Task::none(), + C::Toggle => player::Msg::Toggle, + C::Next => player::Msg::Next, + C::Previous => player::Msg::Previous, + C::SeekTo(at) => player::Msg::Seek(at), + C::SeekBy { forward, by } => { + let now = self.player.position(); + player::Msg::Seek(if forward { now + by } else { now.saturating_sub(by) }) + } + }; + return self.update(Message::Player(msg)); + } + Message::SkipFromMenu => { + self.sheet = None; + return self.update(Message::Player(player::Msg::Next)); + } + Message::AddToQueue(track) => { + self.sheet = None; + self.toast(trf("Added “{}” to the queue", &[&track.full_title()])); + return self.update(Message::Player(player::Msg::Append(track))); + } + Message::PlaySimilar(track) => { + self.sheet = None; + let Some(client) = self.client().cloned() else { return Task::none() }; + self.toast(trf("Finding tracks like “{}”…", &[&track.full_title()])); + return Task::future(async move { + let result = client.similar_tracks(&track.id).await; + Message::SimilarLoaded(track, result) + }); + } + Message::SimilarLoaded(track, result) => match result { + Ok(tracks) if tracks.is_empty() => { + self.toast(trf("Yandex has no similar tracks for “{}”", &[&track.full_title()])); + } + Ok(tracks) => { + self.toast(trf("Playing {} like “{}”", &[&crate::ui::tracks_word(tracks.len()), &track.full_title()])); + return self.update(Message::PlayTracks { tracks: tracks.into(), start: 0, shuffle: false }); + } + Err(e) => { + if let Some(task) = self.failed("similar tracks", &e) { + return task; + } + self.toast(tr("Couldn't find similar tracks. Try again.")); + } + }, + Message::OpenSheet(sheet) => { + let focus = matches!(sheet, Sheet::NewPlaylist { .. } | Sheet::Rename { .. }); + self.sheet = Some(sheet); + if focus { + return iced::widget::operation::focus(sheet::INPUT_ID); + } + } + Message::CloseSheet => self.sheet = None, + Message::SheetText(text) => { + if let Some(Sheet::NewPlaylist { name, .. } | Sheet::Rename { name, .. }) = &mut self.sheet { + *name = text; + } + } + Message::LoadLikedIds => { + let Some(client) = self.client().cloned() else { return Task::none() }; + return Task::future(async move { client.liked_ids().await }).map(Message::LikedIdsLoaded); + } + Message::LikedIdsLoaded(Ok(ids)) => self.likes = ids, + Message::LikedIdsLoaded(Err(e)) => { + if let Some(task) = self.failed("liked ids", &e) { + return task; + } + } + Message::LyricsLoaded(id, result) => { + if let Err(e) = &result + && let Some(task) = self.failed("lyrics", e) + { + return task; + } + self.lyrics.insert(id, Loadable::from_result(result)); + } + Message::RetryLyrics => { + if let Some(id) = self.player.track().map(|t| t.id.clone()) { + self.lyrics.remove(&id); + } + return self.want_lyrics(); + } + Message::ToastTick => { + if self.toast_expired() { + self.toast = None; + } + } + m @ (Message::LikeTrack(..) + | Message::DislikeTrack(..) + | Message::LikeAlbum(..) + | Message::LikeArtist(..) + | Message::LikePlaylist(..) + | Message::LikeClip(..) + | Message::AddToPlaylist(..) + | Message::CreatePlaylist + | Message::RenamePlaylist + | Message::SetPlaylistPublic(..) + | Message::DeletePlaylist(..) + | Message::RemoveFromPlaylist(..) + | Message::MovePlaylistTrack { .. } + | Message::Edited(..)) => return self.update_edit(m), + Message::PlayTracks { tracks, start, shuffle } => { + return self.update(Message::Player(player::Msg::Play { + tracks, + start, + shuffle: shuffle.then_some(true), + })); + } + Message::LoadLiked => { + let Some(client) = self.client().cloned() else { return Task::none() }; + if matches!(self.library.liked, Liked::Loading) { + return Task::none(); + } + self.library.liked = Liked::Loading; + return Task::future(async move { client.liked_tracks().await }).map(Message::LikedLoaded); + } + Message::LikedLoaded(Ok(tracks)) => { + self.library.liked = Liked::loaded(tracks, &self.library.liked); + } + Message::LikedLoaded(Err(e)) => { + if let Some(task) = self.failed("liked tracks", &e) { + return task; + } + self.library.liked = Liked::Failed(e); + } + Message::CollectionTab(tab) => { + self.library.tab = tab; + return self.load_tab(tab); + } + Message::LoadLibrary(tab) => { + return match tab { + Tab::Tracks => self.update(Message::LoadLiked), + _ => self.force_load_tab(tab), + }; + } + Message::AlbumsLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("liked albums", e) + { + return task; + } + self.library.albums = Loadable::from_result(result); + } + Message::ArtistsLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("liked artists", e) + { + return task; + } + self.library.artists = Loadable::from_result(result); + } + Message::PlaylistsLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("playlists", e) + { + return task; + } + self.library.playlists = Loadable::from_result(result); + } + Message::ClipsLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("liked clips", e) + { + return task; + } + self.library.clips = Loadable::from_result(result); + } + Message::OpenClip(clip) => match open::that_detached(clip.url()) { + Ok(()) => self.toast(trf("Opening “{}” in your browser", &[&clip.title])), + Err(e) => { + eprintln!("open clip: {e}"); + self.toast(tr("Couldn't open your browser.")); + } + }, + Message::PageLoaded(route, result) => { + if let Err(e) = &result + && let Some(task) = self.failed("page", e) + { + return task; + } + self.pages.insert(route, Loadable::from_result(result)); + } + Message::LoadHome => { + let Some(client) = self.client().cloned() else { return Task::none() }; + self.discover.home = Loadable::Loading; + return Task::future(async move { client.home().await }).map(Message::HomeLoaded); + } + Message::HomeLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("home", e) + { + return task; + } + self.discover.home = Loadable::from_result(result.map(HomeData::new)); + } + Message::LoadRecent => { + let Some(client) = self.client().cloned() else { return Task::none() }; + // A reload keeps showing the previous list until the new one arrives. + if !matches!(self.discover.recent, Loadable::Loaded(_)) { + self.discover.recent = Loadable::Loading; + } + return Task::future(async move { client.recently_played(browse::RECENT).await }) + .map(Message::RecentLoaded); + } + Message::RecentLoaded(result) => { + match result { + Ok(tracks) => self.discover.recent = Loadable::Loaded(tracks.into()), + Err(e) => { + if let Some(task) = self.failed("recently played", &e) { + return task; + } + // Keep an older list rather than dropping the section. + if !matches!(self.discover.recent, Loadable::Loaded(_)) { + self.discover.recent = Loadable::Failed(e); + } + } + } + } + Message::LoadGenres => { + let Some(client) = self.client().cloned() else { return Task::none() }; + self.discover.genres = Loadable::Loading; + return Task::future(async move { client.genres().await }).map(Message::GenresLoaded); + } + Message::GenresLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("genres", e) + { + return task; + } + self.discover.genres = Loadable::from_result(result.map(browse::flatten)); + } + Message::GenreLoaded(index, result) => { + if let Err(e) = &result + && let Some(task) = self.failed("genre playlists", e) + { + return task; + } + self.genre_playlists.insert(index, Loadable::from_result(result)); + } + Message::LoadPodcasts => { + let Some(client) = self.client().cloned() else { return Task::none() }; + self.discover.podcasts = Loadable::Loading; + return Task::future(async move { client.featured_podcasts().await }) + .map(Message::PodcastsLoaded); + } + Message::PodcastsLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("podcasts", e) + { + return task; + } + self.discover.podcasts = Loadable::from_result(result); + } + Message::PlayWave(station) => { + return self.update(Message::Player(player::Msg::PlayWave { station })); + } + Message::LoadWave => { + let Some(client) = self.client().cloned() else { return Task::none() }; + let mut tasks = Vec::new(); + if self.wave.settings.needs_load() { + self.wave.settings = Loadable::Loading; + let c = client.clone(); + tasks.push( + Task::future(async move { c.wave_settings(MY_WAVE).await }).map(Message::WaveSettingsLoaded), + ); + } + if self.wave.stations.needs_load() { + self.wave.stations = Loadable::Loading; + tasks.push(Task::future(async move { client.stations().await }).map(Message::StationsLoaded)); + } + return Task::batch(tasks); + } + Message::WaveSettingsLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("wave settings", e) + { + return task; + } + self.wave.settings = Loadable::from_result(result); + } + Message::StationsLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("stations", e) + { + return task; + } + self.wave.stations = Loadable::from_result(result); + } + Message::SetWaveSettings(settings) => { + let Some(client) = self.client().cloned() else { return Task::none() }; + self.wave.saving = Some(settings); + return Task::future(async move { client.set_wave_settings(MY_WAVE, settings).await }) + .map(move |r| Message::WaveSettingsSaved(settings, r)); + } + Message::WaveSettingsSaved(settings, result) => { + self.wave.saving = None; + match result { + Ok(()) => { + self.wave.settings = Loadable::Loaded(settings); + // A playing My Wave picks the new settings up from the next track. + if self.player.wave_station() == Some(MY_WAVE) { + return self.update(Message::Player(player::Msg::WaveRestart)); + } + } + Err(e) => { + if let Some(task) = self.failed("save wave settings", &e) { + return task; + } + } + } + } + Message::WaveTick => self.wave_phase = (self.wave_phase + 0.04) % 10_000.0, + Message::CoverWanted(url) => { + let Some(client) = self.client().cloned() else { return Task::none() }; + return self.covers.want(url, &client); + } + Message::CoverLoaded(url, bytes) => self.covers.loaded(url, bytes), + Message::CoversTick => self.covers.flush(), + } + Task::none() + } + + /// Loads what a route shows on first visit, and retries after a failure. + fn on_enter(&mut self, route: Route) -> Task { + match route { + Route::Collection => { + let retry_liked = matches!(self.library.liked, Liked::Failed(_)); + let tab = self.load_tab(self.library.tab); + if retry_liked { Task::batch([tab, self.update(Message::LoadLiked)]) } else { tab } + } + // Settings shows the subscription, which can change outside the app. + Route::Settings => match self.client().cloned() { + Some(client) => { + Task::future(async move { client.account().await }).map(Message::AccountRefreshed) + } + None => Task::none(), + }, + Route::Home => { + let home = if self.discover.home.needs_load() { self.update(Message::LoadHome) } else { Task::none() }; + // History changes with every listen, so it's re-read on each visit. + let recent = if matches!(self.discover.recent, Loadable::Loading) { + Task::none() + } else { + self.update(Message::LoadRecent) + }; + Task::batch([home, recent, self.genres_if_needed(), self.update(Message::LoadWave)]) + } + Route::Wave => self.update(Message::LoadWave), + Route::Search => self.genres_if_needed(), + Route::Chart if self.discover.home.needs_load() => self.update(Message::LoadHome), + Route::Genre(index) => { + if self.genre_playlists.get(&index).is_some_and(|p| !p.needs_load()) { + return Task::none(); + } + let (Some(client), Some(genre)) = ( + self.client().cloned(), + self.discover.genres.get().and_then(|g| g.get(index)).cloned(), + ) else { + return Task::none(); + }; + self.genre_playlists.insert(index, Loadable::Loading); + Task::future(async move { client.tag_playlists(&genre.id).await }) + .map(move |r| Message::GenreLoaded(index, r)) + } + Route::Podcasts => { + let featured = + if self.discover.podcasts.needs_load() { self.update(Message::LoadPodcasts) } else { Task::none() }; + // "Yours" comes from liked albums. + Task::batch([featured, self.load_tab(Tab::Albums)]) + } + Route::Album(_) | Route::Artist(_) | Route::Playlist(_) => { + if self.pages.get(&route).is_some_and(|p| !p.needs_load()) { + return Task::none(); + } + let Some(task) = self.client().and_then(|c| detail::load(c, route)) else { + return Task::none(); + }; + self.pages.insert(route, Loadable::Loading); + task + } + _ => Task::none(), + } + } + + /// Scrolls the lyrics so the line being sung stays in view. + fn follow_lyrics(&mut self) -> Task { + if self.drawer != Some(Panel::Lyrics) { + return Task::none(); + } + let Some(Loadable::Loaded(Some(lyrics))) = self.player.track().and_then(|t| self.lyrics.get(&t.id)) else { + return Task::none(); + }; + let line = lyrics.current(self.player.position()); + if line == self.lyric_line { + return Task::none(); + } + self.lyric_line = line; + let Some(line) = line else { return Task::none() }; + let y = (line as f32 / lyrics.lines.len().max(1) as f32).clamp(0.0, 1.0); + iced::widget::operation::snap_to(drawer::LYRICS_ID, iced::widget::operation::RelativeOffset { x: 0.0, y }) + } + + fn genres_if_needed(&mut self) -> Task { + if self.discover.genres.needs_load() { self.update(Message::LoadGenres) } else { Task::none() } + } + + fn load_tab(&mut self, tab: Tab) -> Task { + let needed = match tab { + Tab::Tracks => matches!(self.library.liked, Liked::NotLoaded), + Tab::Albums => self.library.albums.needs_load(), + Tab::Artists => self.library.artists.needs_load(), + Tab::Playlists => self.library.playlists.needs_load(), + Tab::Clips => self.library.clips.needs_load(), + }; + if needed { self.update(Message::LoadLibrary(tab)) } else { Task::none() } + } + + fn force_load_tab(&mut self, tab: Tab) -> Task { + let Some(client) = self.client().cloned() else { return Task::none() }; + match tab { + Tab::Tracks => Task::none(), + Tab::Albums => { + self.library.albums = Loadable::Loading; + Task::future(async move { client.liked_albums().await }).map(Message::AlbumsLoaded) + } + Tab::Artists => { + self.library.artists = Loadable::Loading; + Task::future(async move { client.liked_artists().await }).map(Message::ArtistsLoaded) + } + Tab::Playlists => { + self.library.playlists = Loadable::Loading; + Task::future(async move { client.library_playlists().await }).map(Message::PlaylistsLoaded) + } + Tab::Clips => { + self.library.clips = Loadable::Loading; + Task::future(async move { client.liked_clips().await }).map(Message::ClipsLoaded) + } + } + } + + pub fn view(&self) -> Element<'_, Message> { + let t = theme::tokens(&self.theme); + let page = match &self.session { + Session::Restoring => screens::connecting(t, tr("Checking your sign-in…")), + Session::Connecting { .. } => screens::connecting(t, tr("Signing in…")), + Session::Unreachable => screens::unreachable(t), + Session::SignedOut(sign_in) => sign_in.view(t).map(Message::SignIn), + Session::SignedIn { account, .. } => return self.shell(t, account), + }; + container(page).width(Fill).height(Fill).style(theme::app).into() + } + + fn shell<'a>(&'a self, t: &'static theme::Tokens, account: &'a Account) -> Element<'a, Message> { + let route = self.nav.current(); + let env = Env { + t, + covers: &self.covers, + liked: &self.library.liked, + likes: &self.likes, + playing: self.player.track().map(|tr| tr.id.as_str()), + me: account.uid, + }; + + let page = scrollable(screens::view(screens::Ctx { + env, + route, + search: &self.search, + me: account, + library: &self.library, + pages: &self.pages, + discover: &self.discover, + genre_playlists: &self.genre_playlists, + player: &self.player, + wave: &self.wave, + wave_phase: self.wave_phase, + settings: &self.settings, + })) + .height(Fill) + .style(theme::scroll); + + // Suggestions float over the page, lined up under the search field. + let page: Element<'a, Message> = match self.search.suggestions() { + Some(list) => stack![ + page, + container(search::suggestions(t, list)) + .padding(iced::Padding::default().left(theme::space::GUTTER + 44.0)), + ] + .into(), + None => page.into(), + }; + + let content = column![topbar::view(t, self.nav.can_go_back(), &self.search.text), page] + .width(Fill) + .height(Fill); + + let mut body = row![ + sidebar::view(t, route, account, self.library.playlists.get(), &self.covers), + vline(), + content, + ] + .height(Fill); + + if let Some(panel) = self.drawer { + let lyrics = self.player.track().and_then(|tr| self.lyrics.get(&tr.id)); + body = body.push(vline()).push(drawer::view(t, panel, &self.player, &self.covers, lyrics)); + } + + let window = column![ + body, + hline(), + container(player_bar::view( + t, + &self.player, + self.player.track().is_some_and(|tr| self.library.liked.contains(&tr.id)), + self.drawer, + &self.covers, + )) + .height(shell::PLAYER) + .style(theme::panel), + ]; + + let mut layers = stack![container(window).width(Fill).height(Fill).style(theme::app)]; + if let Some((text, _)) = &self.toast { + layers = layers.push(sheet::toast(t, text)); + } + if let Some(open) = &self.sheet { + let track_id = match open { + Sheet::Track { track, .. } => Some(track.id.as_str()), + _ => None, + }; + let own: &[PlaylistSummary] = self.library.playlists.get().map_or(&[], |p| p.own.as_slice()); + layers = layers.push(sheet::overlay( + t, + open, + sheet::Ctx { + playing: track_id.is_some() && self.player.track().map(|tr| tr.id.as_str()) == track_id, + liked: track_id.is_some_and(|id| self.library.liked.contains(id)), + disliked: track_id.is_some_and(|id| self.likes.disliked_tracks.contains(id)), + own_playlists: own, + }, + )); + } + layers.into() + } + + /// Runs the player's requests against the API. + fn run(&self, effects: Vec) -> Task { + let Some(client) = self.client() else { return Task::none() }; + Task::batch(effects.into_iter().map(|effect| match effect { + Effect::Fetch { generation, track_id } => { + let client = client.clone(); + let quality = self.settings.quality; + Task::future(async move { fetch_audio(&client, &track_id, quality).await }) + .map(move |result| Message::Player(player::Msg::Fetched { generation, result })) + } + Effect::Prefetch { track_id } => { + let client = client.clone(); + let quality = self.settings.quality; + Task::future(async move { + let result = fetch_audio(&client, &track_id, quality).await; + (track_id, result) + }) + .map(|(track_id, result)| Message::Player(player::Msg::Prefetched { track_id, result })) + } + Effect::SignedOut => Task::done(Message::SignOut), + Effect::WaveFetch { station, session_id, queue } => { + let client = client.clone(); + // My Wave's settings ride along as seeds when a session starts. + let settings = (station == MY_WAVE).then(|| self.wave.shown()).flatten(); + Task::future(async move { + let result = match session_id { + Some(id) => client.wave_more(&id, &queue).await, + None => client.wave_start(&station, settings).await, + }; + Message::Player(player::Msg::WaveBatch { station, result }) + }) + } + // Feedback and reports are fire-and-forget: a lost one only blunts recommendations. + Effect::WaveFeedback { session_id, event, batch_id } => { + let client = client.clone(); + Task::future(async move { + if let Err(e) = client.wave_feedback(&session_id, &event, batch_id.as_deref()).await { + eprintln!("wave feedback {event:?} (batch {batch_id:?}): {e}"); + } + }) + .discard() + } + Effect::Report(report) => { + let client = client.clone(); + Task::future(async move { + if let Err(e) = client.report_play(&report).await { + eprintln!("play report: {e}"); + } + }) + .discard() + } + })) + } +} + +async fn fetch_audio(client: &YmClient, track_id: &str, quality: Quality) -> Result { + let stream = match quality { + Quality::Lossless => client.lossless_stream(track_id).await?, + _ => client.stream(track_id, quality.max_kbps()).await?, + }; + let bytes = client.fetch(&stream).await?; + Ok(Audio { stream, bytes }) +} + +/// `MUSYX_TRACE=1` logs every message except the frequent background ones. +/// Returns whether it logged, so the caller can add the resulting player state. +fn trace(message: &Message) -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("MUSYX_TRACE").is_some()) { + return false; + } + let noisy = matches!( + message, + Message::WaveTick + | Message::CoversTick + | Message::ToastTick + | Message::CoverWanted(_) + | Message::CoverLoaded(..) + | Message::Player(player::Msg::Engine(player::engine::Event::Position { .. })) + ); + if noisy { + return false; + } + let text = match message { + Message::PlayTracks { tracks, start, shuffle } => { + format!("PlayTracks {{ {} tracks, start: {start}, shuffle: {shuffle} }}", tracks.len()) + } + other => format!("{other:?}").chars().take(160).collect(), + }; + eprintln!("trace: {text}"); + true +} + +fn restore() -> Task { + Task::future(session::restore()).map(Message::Restored) +} + +/// Save first so a crash right after sign-in doesn't lose it, then check the token. +fn connect(credentials: Credentials) -> Task { + Task::future(async move { + if let Err(e) = session::save(credentials.clone()).await { + eprintln!("keychain: {e}"); + } + YmClient::connect(&credentials, crate::i18n::lang().content()).await + }) + .map(Message::Connected) +} + +fn vline<'a>() -> Element<'a, Message> { + container(space()).width(1).height(Fill).style(theme::divider).into() +} + +fn hline<'a>() -> Element<'a, Message> { + container(space()).width(Fill).height(1).style(theme::divider).into() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A signed-in app with no network behind it; tasks returned by `update` are dropped. + fn signed_in() -> App { + let (mut app, _) = App::new(); + // The saved setting and the machine's language mustn't change what tests read. + crate::i18n::set(crate::i18n::Lang::En); + app.session = Session::SignedIn { + client: YmClient::unauthenticated().unwrap(), + account: Account { uid: 1, login: "t".into(), name: "T".into(), has_plus: true, subscription_end: None }, + }; + app + } + + fn track(id: &str) -> Track { + Track::from_json(&format!(r#"{{"id":"{id}","title":"T{id}","durationMs":100000}}"#)).unwrap() + } + + fn upcoming(app: &App) -> Vec { + app.player.queue().map(|q| q.upcoming().map(|(_, t)| t.id.clone()).collect()).unwrap_or_default() + } + + #[test] + fn play_next_from_the_menu_lands_after_the_current_track() { + let mut app = signed_in(); + let tracks: Arc<[Track]> = vec![track("a"), track("b"), track("c")].into(); + let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false }); + let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("n"), playlist: None, choosing: false })); + let _ = app.update(Message::PlayNext(track("n"))); + assert!(app.sheet.is_none()); + assert_eq!(upcoming(&app), ["n", "b", "c"]); + let _ = app.update(Message::Player(player::Msg::Next)); + assert_eq!(app.player.track().unwrap().id, "n"); + } + + #[test] + fn next_track_from_the_playing_tracks_menu_skips() { + let mut app = signed_in(); + let tracks: Arc<[Track]> = vec![track("a"), track("b")].into(); + let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false }); + let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("a"), playlist: None, choosing: false })); + let messages = click_in_window(&app, "Next track"); + assert_eq!(messages, ["SkipFromMenu"]); + let _ = app.update(Message::SkipFromMenu); + assert!(app.sheet.is_none()); + assert_eq!(app.player.track().unwrap().id, "b"); + } + + #[test] + fn play_next_on_the_playing_track_says_so() { + let mut app = signed_in(); + let tracks: Arc<[Track]> = vec![track("a"), track("b")].into(); + let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false }); + let _ = app.update(Message::PlayNext(track("a"))); + assert_eq!(upcoming(&app), ["b"]); + assert!(app.toast.as_ref().is_some_and(|(t, _)| t.contains("already playing"))); + } + + /// Clicks `label` in the whole window with a track menu open; returns the messages. + fn click_in_window(app: &App, label: &str) -> Vec { + let mut ui = iced_test::simulator(app.view()); + ui.click(label).unwrap_or_else(|e| panic!("can't click {label}: {e:?}")); + ui.into_messages().map(|m| format!("{m:?}").chars().take(48).collect()).collect() + } + + #[test] + fn menu_clicks_do_not_fall_through_to_the_rows_beneath() { + let mut app = signed_in(); + let id = PlaylistId { owner: 1, kind: 1002 }; + let tracks: Arc<[Track]> = (0..30).map(|i| track(&i.to_string())).collect(); + let info = ym_api::PlaylistPage { + playlist: ym_api::PlaylistSummary::for_tests(id, "Дорога"), + description: None, + tracks: Vec::new(), + }; + app.pages.insert(Route::Playlist(id), Loadable::Loaded(crate::screens::detail::Page::Playlist { info, tracks: tracks.clone() })); + app.nav = Navigator::new(Route::Playlist(id)); + let _ = app.update(Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: false }); + let _ = app.update(Message::OpenSheet(Sheet::Track { track: tracks[5].clone(), playlist: Some((id, 5, 30)), choosing: false })); + for label in ["Play next", "Add to queue", "Move up"] { + let messages = click_in_window(&app, label); + assert!( + !messages.iter().any(|m| m.starts_with("PlayTracks")), + "{label} leaked to a row: {messages:?}" + ); + } + } + + fn clip(id: i64, title: &str) -> Clip { + Clip::from_json(&format!(r#"{{"clipId":{id},"title":"{title}","duration":263,"artists":[{{"id":3,"name":"КИНО"}}]}}"#)) + .unwrap() + } + + #[test] + fn liked_clips_open_from_collection_and_likes_update_the_list() { + let mut app = signed_in(); + app.nav = Navigator::new(Route::Collection); + app.library.tab = Tab::Clips; + app.library.clips = Loadable::Loaded(vec![clip(1, "Звезда")]); + app.likes.clips.insert(1); + let messages = click_in_window(&app, "Звезда"); + assert!(messages.first().is_some_and(|m| m.starts_with("OpenClip(")), "{messages:?}"); + + let _ = app.update(Message::LikeClip(clip(2, "Кукушка"), true)); + assert!(app.likes.clips.contains(&2)); + let ids = |app: &App| app.library.clips.get().unwrap().iter().map(|c| c.id).collect::>(); + assert_eq!(ids(&app), [2, 1]); + let _ = app.update(Message::LikeClip(clip(1, "Звезда"), false)); + assert_eq!(ids(&app), [2]); + assert!(!app.likes.clips.contains(&1)); + } + + #[test] + fn similar_tracks_replace_the_queue_and_say_so() { + let mut app = signed_in(); + let _ = app.update(Message::PlayTracks { tracks: vec![track("a"), track("b")].into(), start: 0, shuffle: false }); + let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("a"), playlist: None, choosing: false })); + let _ = app.update(Message::PlaySimilar(track("a"))); + assert!(app.sheet.is_none()); + let _ = app.update(Message::SimilarLoaded(track("a"), Ok(vec![track("s1"), track("s2")]))); + assert_eq!(app.player.track().unwrap().id, "s1"); + assert_eq!(upcoming(&app), ["s2"]); + assert!(app.toast.as_ref().is_some_and(|(t, _)| t.starts_with("Playing 2 tracks like"))); + let _ = app.update(Message::SimilarLoaded(track("b"), Ok(vec![]))); + assert_eq!(app.player.track().unwrap().id, "s1", "an empty answer leaves playback alone"); + } + + #[test] + fn recently_played_shows_on_home_and_survives_a_failed_reload() { + let mut app = signed_in(); + let _ = app.update(Message::RecentLoaded(Ok(vec![track("r1"), track("r2")]))); + let _ = app.update(Message::LoadRecent); + let _ = app.update(Message::RecentLoaded(Err(Error::Network("offline".into())))); + assert_eq!(app.discover.recent.get().map(|r| r.len()), Some(2)); + let messages = click_in_window(&app, "Tr2"); + assert!(messages.first().is_some_and(|m| m.starts_with("PlayTracks")), "{messages:?}"); + } + + #[test] + fn menu_clicks_reach_their_items_over_the_full_window() { + let mut app = signed_in(); + let tracks: Arc<[Track]> = vec![track("a"), track("b")].into(); + let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false }); + for toast in [false, true] { + if toast { + app.toast("Added to Liked tracks"); + } + let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("n"), playlist: None, choosing: false })); + for label in ["Play next", "Add to queue", "Add to Liked tracks"] { + let messages = click_in_window(&app, label); + assert!( + messages.first().is_some_and(|m| !m.starts_with("CloseSheet")), + "{label} (toast: {toast}) produced {messages:?}" + ); + } + } + } +} diff --git a/reference/musyx/src/app/edit.rs b/reference/musyx/src/app/edit.rs new file mode 100644 index 0000000..75f8e40 --- /dev/null +++ b/reference/musyx/src/app/edit.rs @@ -0,0 +1,297 @@ +//! Changing things: likes, dislikes, playlist edits, plus lyrics and the +//! server-side queue. Every change is shown at once and undone if Yandex refuses. + +use crate::i18n::{tr, trf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use iced::Task; +use ym_api::{Error, PlaylistId}; + +use super::{App, Message}; +use crate::player; +use crate::route::Route; +use crate::screens::Loadable; +use crate::screens::collection::Liked; +use crate::widgets::sheet::Sheet; + +/// How long a status message stays up. +const TOAST: Duration = Duration::from_secs(4); + +/// What to reload after an edit lands. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refresh { + Playlist(PlaylistId), + Playlists, + Liked, + LikedIds, +} + +/// The outcome of a change sent to Yandex. +#[derive(Debug, Clone)] +pub struct Edited { + pub result: Result<(), Error>, + /// Shown when it worked. + pub done: String, + /// Shown when it didn't. + pub failed: String, + pub refresh: Vec, +} + +impl App { + pub(super) fn toast(&mut self, text: impl Into) { + self.toast = Some((text.into(), Instant::now())); + } + + /// Sends a change, then reports and refreshes through [`Message::Edited`]. + fn send_edit(&self, change: F, done: String, failed: String, refresh: Vec) -> Task + where + F: std::future::Future> + Send + 'static, + { + Task::future(change).map(move |result| { + Message::Edited(Box::new(Edited { result, done: done.clone(), failed: failed.clone(), refresh: refresh.clone() })) + }) + } + + pub(super) fn update_edit(&mut self, message: Message) -> Task { + let Some(client) = self.client().cloned() else { return Task::none() }; + match message { + Message::LikeTrack(track, on) => { + self.library.liked = self.library.liked.with(&track, on); + if on { + self.likes.disliked_tracks.remove(&track.id); + } + let id = track.full_id(); + let c = client.clone(); + self.send_edit( + async move { c.set_track_liked(&id, on).await }, + if on { tr("Added to Liked tracks") } else { tr("Removed from Liked tracks") }.into(), + tr("Couldn't change the like. Try again.").into(), + vec![], + ) + } + Message::DislikeTrack(track, on) => { + if on { + self.likes.disliked_tracks.insert(track.id.clone()); + self.library.liked = self.library.liked.with(&track, false); + } else { + self.likes.disliked_tracks.remove(&track.id); + } + // Not hearing it again starts now. + let skip = if on && self.player.track().is_some_and(|t| t.id == track.id) { + self.update(Message::Player(player::Msg::Next)) + } else { + Task::none() + }; + let id = track.full_id(); + let c = client.clone(); + Task::batch([ + skip, + self.send_edit( + async move { c.set_track_disliked(&id, on).await }, + if on { tr("You won't be recommended this track") } else { tr("Recommendations for this track restored") }.into(), + tr("Couldn't change that. Try again.").into(), + vec![], + ), + ]) + } + Message::LikeAlbum(id, on) => { + toggle(&mut self.likes.albums, id, on); + self.library.albums = Loadable::NotLoaded; + self.send_edit( + async move { client.set_album_liked(id, on).await }, + if on { tr("Album added to your collection") } else { tr("Album removed from your collection") }.into(), + tr("Couldn't change the like. Try again.").into(), + vec![Refresh::LikedIds], + ) + } + Message::LikeArtist(id, on) => { + toggle(&mut self.likes.artists, id, on); + self.library.artists = Loadable::NotLoaded; + self.send_edit( + async move { client.set_artist_liked(id, on).await }, + if on { tr("Artist added to your collection") } else { tr("Artist removed from your collection") }.into(), + tr("Couldn't change the like. Try again.").into(), + vec![Refresh::LikedIds], + ) + } + Message::LikePlaylist(id, on) => { + toggle(&mut self.likes.playlists, id, on); + self.send_edit( + async move { client.set_playlist_liked(id, on).await }, + if on { tr("Playlist added to your collection") } else { tr("Playlist removed from your collection") }.into(), + tr("Couldn't change the like. Try again.").into(), + vec![Refresh::Playlists, Refresh::LikedIds], + ) + } + Message::LikeClip(clip, on) => { + toggle(&mut self.likes.clips, clip.id, on); + if let Loadable::Loaded(clips) = &mut self.library.clips { + clips.retain(|c| c.id != clip.id); + if on { + clips.insert(0, clip.clone()); + } + } + self.send_edit( + async move { client.set_clip_liked(clip.id, on).await }, + if on { tr("Clip added to your collection") } else { tr("Clip removed from your collection") }.into(), + tr("Couldn't change the like. Try again.").into(), + vec![], + ) + } + Message::AddToPlaylist(id, track) => { + self.sheet = None; + let title = self.playlist_title(id); + self.send_edit( + async move { client.add_to_playlist(id, &track).await }, + trf("Added to “{}”", &[&title]), + trf("Couldn't add to “{}”. Try again.", &[&title]), + vec![Refresh::Playlist(id), Refresh::Playlists], + ) + } + Message::CreatePlaylist => { + let Some(Sheet::NewPlaylist { name, add }) = self.sheet.take() else { return Task::none() }; + let name = name.trim().to_owned(); + if name.is_empty() { + return Task::none(); + } + let done = match &add { + Some(_) => trf("Created “{}” with the track", &[&name]), + None => trf("Created “{}”", &[&name]), + }; + self.send_edit( + async move { + let created = client.create_playlist(&name, false).await?; + if let Some(track) = add { + client.add_to_playlist(created.id, &track).await?; + } + Ok(()) + }, + done, + tr("Couldn't create the playlist. Try again.").into(), + vec![Refresh::Playlists], + ) + } + Message::RenamePlaylist => { + let Some(Sheet::Rename { id, name }) = self.sheet.take() else { return Task::none() }; + let name = name.trim().to_owned(); + if name.is_empty() { + return Task::none(); + } + let done = trf("Renamed to “{}”", &[&name]); + self.send_edit( + async move { client.rename_playlist(id, &name).await }, + done, + tr("Couldn't rename the playlist. Try again.").into(), + vec![Refresh::Playlist(id), Refresh::Playlists], + ) + } + Message::SetPlaylistPublic(id, public) => self.send_edit( + async move { client.set_playlist_public(id, public).await }, + if public { tr("Anyone with the link can now see this playlist") } else { tr("Only you can see this playlist now") }.into(), + tr("Couldn't change who can see it. Try again.").into(), + vec![Refresh::Playlist(id), Refresh::Playlists], + ), + Message::DeletePlaylist(id) => { + self.sheet = None; + let title = self.playlist_title(id); + if self.nav.current() == Route::Playlist(id) { + self.nav.back(); + } + self.pages.remove(&Route::Playlist(id)); + self.send_edit( + async move { client.delete_playlist(id).await }, + trf("Deleted “{}”", &[&title]), + trf("Couldn't delete “{}”. Try again.", &[&title]), + vec![Refresh::Playlists], + ) + } + Message::RemoveFromPlaylist(id, index) => { + self.sheet = None; + self.send_edit( + async move { client.remove_from_playlist(id, index).await }, + tr("Removed from the playlist").into(), + tr("Couldn't remove the track. Try again.").into(), + vec![Refresh::Playlist(id), Refresh::Playlists], + ) + } + Message::MovePlaylistTrack { id, track, from, to } => { + self.sheet = None; + self.send_edit( + async move { client.move_in_playlist(id, &track, from, to).await }, + tr("Moved").into(), + tr("Couldn't move the track. Try again.").into(), + vec![Refresh::Playlist(id)], + ) + } + Message::Edited(edited) => { + let Edited { result, done, failed, refresh } = *edited; + match result { + Ok(()) => { + self.toast(done); + Task::batch(refresh.into_iter().map(|r| self.refresh(r))) + } + Err(e) => { + if let Some(task) = self.failed("edit", &e) { + return task; + } + self.toast(failed); + // The optimistic change may be wrong now; re-read the truth. + Task::batch([self.refresh(Refresh::Liked), self.refresh(Refresh::LikedIds)]) + } + } + } + _ => Task::none(), + } + } + + fn playlist_title(&self, id: PlaylistId) -> String { + self.library + .playlists + .get() + .and_then(|p| p.own.iter().chain(&p.liked).find(|pl| pl.id == id)) + .map_or_else(|| tr("the playlist").to_owned(), |p| p.title.clone()) + } + + pub(super) fn refresh(&mut self, what: Refresh) -> Task { + match what { + Refresh::Playlist(id) => { + let route = Route::Playlist(id); + self.pages.remove(&route); + if self.nav.current() == route { self.on_enter(route) } else { Task::none() } + } + Refresh::Playlists => self.update(Message::LoadLibrary(crate::screens::collection::Tab::Playlists)), + Refresh::Liked => { + self.library.liked = Liked::NotLoaded; + self.update(Message::LoadLiked) + } + Refresh::LikedIds => self.update(Message::LoadLikedIds), + } + } + + /// Lyrics for the playing track, fetched once per track while the panel is open. + pub(super) fn want_lyrics(&mut self) -> Task { + let (Some(client), Some(track)) = (self.client().cloned(), self.player.track()) else { return Task::none() }; + if self.drawer != Some(crate::widgets::drawer::Panel::Lyrics) || self.lyrics.contains_key(&track.id) { + return Task::none(); + } + let id = track.id.clone(); + self.lyrics.insert(id.clone(), Loadable::Loading); + Task::future(async move { + let result = client.lyrics(&id).await.map(|l| l.map(Arc::new)); + Message::LyricsLoaded(id, result) + }) + } + + pub(super) fn toast_expired(&self) -> bool { + self.toast.as_ref().is_some_and(|(_, at)| at.elapsed() >= TOAST) + } +} + +fn toggle(set: &mut std::collections::HashSet, item: T, on: bool) { + if on { + set.insert(item); + } else { + set.remove(&item); + } +} diff --git a/reference/musyx/src/covers.rs b/reference/musyx/src/covers.rs new file mode 100644 index 0000000..fd4307d --- /dev/null +++ b/reference/musyx/src/covers.rs @@ -0,0 +1,194 @@ +//! Cover art: fetched when a cover scrolls into view, kept in memory for the +//! session and on disk across sessions. +//! +//! Views never wait for images. A missing cover renders its placeholder inside +//! a `sensor`, and showing it sends [`Message::CoverWanted`]. + +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; +use std::sync::Arc; + +use iced::widget::{container, image, sensor, space}; +use iced::{Element, Task}; +use tokio::sync::Semaphore; +use ym_api::YmClient; + +use crate::app::Message; +use crate::ui::theme; + +/// Pixel sizes requested from Yandex. Rows and the player bar use `SMALL`, +/// cards and page headers `LARGE`; both cover 2× displays. +pub const SMALL: u32 = 100; +pub const LARGE: u32 = 400; + +/// Downloads in flight at once. +const PARALLEL: usize = 8; + +pub struct Covers { + images: HashMap, + pending: HashSet, + failed: HashSet, + /// Bumped (debounced) when images arrive, so cached lists rebuild. + version: u64, + dirty: bool, + dir: Option, + gate: Arc, +} + +impl Default for Covers { + fn default() -> Self { + let dir = directories::ProjectDirs::from("", "", "Musyx").map(|d| d.cache_dir().join("covers")); + Self { + images: HashMap::new(), + pending: HashSet::new(), + failed: HashSet::new(), + version: 0, + dirty: false, + dir, + gate: Arc::new(Semaphore::new(PARALLEL)), + } + } +} + +impl Covers { + pub fn get(&self, url: &str) -> Option { + self.images.get(url).cloned() + } + + pub fn version(&self) -> u64 { + self.version + } + + /// Whether arrivals are waiting to be shown; the app ticks [`Covers::flush`] meanwhile. + pub fn dirty(&self) -> bool { + self.dirty + } + + pub fn flush(&mut self) { + if self.dirty { + self.version += 1; + self.dirty = false; + } + } + + /// Starts fetching `url` unless it is known, in flight, or failed before. + pub fn want(&mut self, url: String, client: &YmClient) -> Task { + if self.images.contains_key(&url) || self.pending.contains(&url) || self.failed.contains(&url) { + return Task::none(); + } + self.pending.insert(url.clone()); + let (client, dir, gate) = (client.clone(), self.dir.clone(), self.gate.clone()); + Task::future(async move { + let bytes = load(&client, &url, dir, &gate).await; + Message::CoverLoaded(url, bytes) + }) + } + + /// Deletes the on-disk cache and forgets failures; images in memory stay for this session. + pub fn clear_disk(&mut self) -> Task> { + self.failed.clear(); + let Some(dir) = self.dir.clone() else { return Task::done(Ok(())) }; + Task::future(async move { + match tokio::fs::remove_dir_all(&dir).await { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.to_string()), + } + }) + } + + pub fn loaded(&mut self, url: String, bytes: Option>) { + self.pending.remove(&url); + match bytes { + Some(bytes) => { + self.images.insert(url, image::Handle::from_bytes(bytes.to_vec())); + self.dirty = true; + } + None => { + self.failed.insert(url); + } + } + } +} + +async fn load(client: &YmClient, url: &str, dir: Option, gate: &Semaphore) -> Option> { + let path = dir.as_ref().map(|d| d.join(file_name(url))); + if let Some(path) = &path + && let Ok(bytes) = tokio::fs::read(path).await + { + return Some(bytes.into()); + } + + let _permit = gate.acquire().await.ok()?; + let bytes = match client.image(url).await { + Ok(bytes) if !bytes.is_empty() => bytes, + Ok(_) => return None, + Err(e) => { + eprintln!("cover {url}: {e}"); + return None; + } + }; + if let (Some(dir), Some(path)) = (&dir, &path) { + // A failed cache write only costs a re-download next time. + let _ = tokio::fs::create_dir_all(dir).await; + let _ = tokio::fs::write(path, &bytes).await; + } + Some(bytes.into()) +} + +/// A stable, filesystem-safe name for a URL (64-bit FNV-1a). +fn file_name(url: &str) -> String { + let hash = url.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)); + format!("{hash:016x}.img") +} + +/// A square cover: the image when cached, otherwise placeholder art that asks +/// for the image once it is (nearly) on screen. +pub fn view( + covers: &Covers, + url: Option, + hues: (f32, f32), + size: f32, + corner: f32, +) -> Element<'static, Message> { + if let Some(handle) = url.as_deref().and_then(|u| covers.get(u)) { + return image(handle).width(size).height(size).border_radius(corner).into(); + } + let placeholder = container(space()).width(size).height(size).style(theme::cover(hues.0, hues.1, corner)); + match url { + Some(url) => sensor(placeholder) + .on_show(move |_| Message::CoverWanted(url.clone())) + .anticipate(300) + .into(), + None => placeholder.into(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn file_names_are_stable_and_distinct() { + let a = file_name("https://avatars.yandex.net/get-music-content/1/100x100"); + assert_eq!(a, file_name("https://avatars.yandex.net/get-music-content/1/100x100")); + assert_ne!(a, file_name("https://avatars.yandex.net/get-music-content/1/400x400")); + assert!(a.ends_with(".img") && a.len() == 20); + } + + #[test] + fn arrivals_bump_version_only_on_flush() { + let mut covers = Covers { dir: None, ..Covers::default() }; + covers.pending.insert("u".into()); + covers.loaded("u".into(), Some(Arc::from(vec![1u8, 2, 3]))); + assert!(covers.dirty()); + assert_eq!(covers.version(), 0); + covers.flush(); + assert_eq!(covers.version(), 1); + assert!(covers.get("u").is_some()); + covers.loaded("bad".into(), None); + assert!(covers.failed.contains("bad")); + covers.flush(); + assert_eq!(covers.version(), 1, "a failure changes nothing on screen"); + } +} diff --git a/reference/musyx/src/i18n.rs b/reference/musyx/src/i18n.rs new file mode 100644 index 0000000..245981e --- /dev/null +++ b/reference/musyx/src/i18n.rs @@ -0,0 +1,198 @@ +//! Interface language. Strings are written in English where they're used and +//! looked up here; Russian falls back to English for anything missing (a test +//! scans the sources so nothing is). + +use std::fmt::Display; + +mod ru; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +pub enum Lang { + #[default] + En, + Ru, +} + +impl Lang { + /// From a BCP 47 tag such as `ru-RU` or `en-US`. + pub fn from_tag(tag: &str) -> Lang { + let primary = tag.split(['-', '_']).next().unwrap_or_default(); + if primary.eq_ignore_ascii_case("ru") { Lang::Ru } else { Lang::En } + } + + /// The first language the system prefers. + pub fn system() -> Lang { + sys_locale::get_locale().map_or(Lang::En, |tag| Lang::from_tag(&tag)) + } + + /// What Yandex should write its own titles in (genres, Home blocks, station names). + pub fn content(self) -> ym_api::ContentLanguage { + match self { + Lang::En => ym_api::ContentLanguage::English, + Lang::Ru => ym_api::ContentLanguage::Russian, + } + } +} + +// The app's state lives on the main thread, but tests run in parallel threads, +// so there each thread keeps its own language. +#[cfg(not(test))] +static RUSSIAN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +#[cfg(test)] +thread_local! { + static RUSSIAN: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +pub fn set(lang: Lang) { + #[cfg(not(test))] + RUSSIAN.store(lang == Lang::Ru, std::sync::atomic::Ordering::Relaxed); + #[cfg(test)] + RUSSIAN.set(lang == Lang::Ru); +} + +pub fn lang() -> Lang { + #[cfg(not(test))] + let russian = RUSSIAN.load(std::sync::atomic::Ordering::Relaxed); + #[cfg(test)] + let russian = RUSSIAN.get(); + if russian { Lang::Ru } else { Lang::En } +} + +/// `english` in the interface language. +pub fn tr(english: &str) -> &str { + match lang() { + Lang::En => english, + Lang::Ru => ru::get(english).unwrap_or(english), + } +} + +/// [`tr`] with each `{}` in the template filled from `args`, in order. +pub fn trf(template: &str, args: &[&dyn Display]) -> String { + let mut out = String::with_capacity(template.len() + 16); + let mut args = args.iter(); + let mut pieces = tr(template).split("{}"); + out.push_str(pieces.next().unwrap_or_default()); + for piece in pieces { + if let Some(arg) = args.next() { + out.push_str(&arg.to_string()); + } + out.push_str(piece); + } + out +} + +/// The word that goes with `n`: `en` is [one, other], `ru` is [one, few, many]. +pub fn plural<'a>(n: u64, en: [&'a str; 2], ru: [&'a str; 3]) -> &'a str { + match lang() { + Lang::En => en[usize::from(n != 1)], + Lang::Ru => ru[ru_form(n)], + } +} + +/// "1 track" / "5 tracks", "1 трек" / "3 трека" / "5 треков". +pub fn count(n: u64, en: [&str; 2], ru: [&str; 3]) -> String { + format!("{n} {}", plural(n, en, ru)) +} + +/// Russian plural form: 0 for 1, 21, 101…; 1 for 2–4, 22–24…; 2 for the rest. +fn ru_form(n: u64) -> usize { + match (n % 10, n % 100) { + (1, r) if r != 11 => 0, + (2..=4, r) if !(12..=14).contains(&r) => 1, + _ => 2, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn russian_lookups_fall_back_to_english() { + set(Lang::Ru); + assert_eq!(tr("Settings"), "Настройки"); + assert_eq!(tr("not a key"), "not a key"); + assert_eq!(trf("Added “{}” to the queue", &[&"Хочешь?"]), "«Хочешь?» добавлен в очередь"); + set(Lang::En); + assert_eq!(tr("Settings"), "Settings"); + assert_eq!(trf("Added “{}” to the queue", &[&"Hm"]), "Added “Hm” to the queue"); + } + + #[test] + fn plural_forms() { + let forms = ([("track"), "tracks"], ["трек", "трека", "треков"]); + set(Lang::Ru); + let ru: Vec = [1, 2, 5, 11, 12, 21, 22, 25, 101, 111].map(|n| count(n, forms.0, forms.1)).into(); + assert_eq!(ru, ["1 трек", "2 трека", "5 треков", "11 треков", "12 треков", "21 трек", "22 трека", "25 треков", "101 трек", "111 треков"]); + set(Lang::En); + assert_eq!(count(1, forms.0, forms.1), "1 track"); + assert_eq!(count(0, forms.0, forms.1), "0 tracks"); + } + + #[test] + fn system_tags() { + assert_eq!(Lang::from_tag("ru-RU"), Lang::Ru); + assert_eq!(Lang::from_tag("ru"), Lang::Ru); + assert_eq!(Lang::from_tag("en-US"), Lang::En); + assert_eq!(Lang::from_tag("kk_KZ"), Lang::En); + } + + /// Every `tr("…")` and `trf("…"` literal in the sources has a Russian entry, + /// and so does every label that reaches `tr` from ym-api. + #[test] + fn every_string_has_a_russian_translation() { + fn walk(dir: &std::path::Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).unwrap().flatten() { + let path = entry.path(); + if path.is_dir() { + walk(&path, out); + } else if path.extension().is_some_and(|e| e == "rs") { + out.push(path); + } + } + } + let mut files = Vec::new(); + walk(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut files); + let mut missing = Vec::new(); + let mut seen = 0; + // This file's own examples aren't interface strings. + for file in files.into_iter().filter(|f| !f.ends_with("i18n.rs")) { + let source = std::fs::read_to_string(&file).unwrap(); + // The scan reads a literal up to its closing quote, so it can't follow a + // string continued with a backslash; keep interface strings on one line. + let name = file.file_name().unwrap().to_string_lossy().into_owned(); + let code = source.split("#[cfg(test)]").next().unwrap_or_default(); + for (n, line) in code.lines().enumerate() { + if line.trim_end().ends_with('\\') && line.contains('"') { + missing.push(format!("{name}:{}: string continues on the next line", n + 1)); + } + } + for call in ["tr(\"", "trf(\""] { + for (at, _) in source.match_indices(call) { + // Skip `ustr(`, `attr(` and the like. + if source[..at].ends_with(|c: char| c.is_alphanumeric() || c == '_') { + continue; + } + let rest = &source[at + call.len()..]; + let end = rest.find('"').unwrap(); + let key = rest[..end].replace("\\n", "\n"); + seen += 1; + if ru::get(&key).is_none() { + missing.push(format!("{}: {key}", file.file_name().unwrap().to_string_lossy())); + } + } + } + } + use ym_api::{AlbumKind, Character, Language, Mood, SearchKind}; + let labels = Mood::ALL.iter().map(|m| m.label()) + .chain(Character::ALL.iter().map(|c| c.label())) + .chain(Language::ALL.iter().map(|l| l.label())) + .chain(SearchKind::ALL.iter().map(|k| k.label())) + .chain(AlbumKind::ALL.iter().map(|k| k.label())); + missing.extend(labels.filter(|l| ru::get(l).is_none()).map(|l| format!("ym-api label: {l}"))); + missing.sort(); + missing.dedup(); + assert!(seen > 200, "found only {seen} strings; is the scan broken?"); + assert!(missing.is_empty(), "{} strings have no Russian:\n{}", missing.len(), missing.join("\n")); + } +} diff --git a/reference/musyx/src/i18n/ru.rs b/reference/musyx/src/i18n/ru.rs new file mode 100644 index 0000000..c426ec0 --- /dev/null +++ b/reference/musyx/src/i18n/ru.rs @@ -0,0 +1,361 @@ +//! Russian strings, keyed by the English text in the code. Terms follow the +//! Yandex Music apps ("Моя волна", "Мне нравится", "Чарт"). + +pub fn get(english: &str) -> Option<&'static str> { + Some(match english { + // Navigation and pages + "Home" => "Главная", + "My Wave" => "Моя волна", + "Search" => "Поиск", + "Collection" => "Коллекция", + "Podcasts" => "Подкасты", + "Settings" => "Настройки", + "Album" => "Альбом", + "Artist" => "Исполнитель", + "Playlist" => "Плейлист", + "Chart" => "Чарт", + "Genre" => "Жанр", + "Browse" => "Обзор", + "Search artists, tracks, podcasts" => "Исполнители, треки, подкасты", + "Playlists" => "Плейлисты", + "Playlists you make or like show up here." => "Здесь появятся ваши плейлисты и те, что вам понравились.", + "Loading playlists…" => "Загружаем плейлисты…", + "Plus subscription" => "Подписка Плюс", + "No Plus: 30-second previews" => "Без Плюса: фрагменты по 30 секунд", + + // Home, chart, genres, podcasts + "Recently played" => "Вы недавно слушали", + "Made for you" => "Собрано для вас", + "Show all" => "Показать все", + "Show all {}" => "Показать все {}", + "New releases" => "Новые релизы", + "New playlists" => "Новые плейлисты", + "Loading your picks…" => "Подбираем музыку для вас…", + "The most played tracks on Yandex Music today" => "Самые популярные треки Яндекс Музыки сегодня", + "The chart is empty right now." => "Чарт сейчас пуст.", + "Loading the chart…" => "Загружаем чарт…", + "Genres" => "Жанры", + "Loading genres…" => "Загружаем жанры…", + "This genre isn't available any more." => "Этот жанр больше недоступен.", + "Play radio" => "Включить радио", + "No playlists in this genre yet." => "В этом жанре пока нет плейлистов.", + "Podcasts and books" => "Подкасты и книги", + "Yours" => "Ваши", + "Featured" => "Рекомендуем", + "Loading podcasts…" => "Загружаем подкасты…", + + // Loading and failures; the {} is an object in the accusative + "Loading {}…" => "Загружаем {}…", + "Loading…" => "Загрузка…", + "Couldn't load {}. Check your connection and try again." => { + "Не удалось загрузить {}. Проверьте подключение и попробуйте ещё раз." + } + "Couldn't load {}. Try again in a moment." => "Не удалось загрузить {}. Попробуйте чуть позже.", + "Try again" => "Повторить", + "your albums" => "ваши альбомы", + "your artists" => "ваших исполнителей", + "your clips" => "ваши клипы", + "your home page" => "главную страницу", + "your liked tracks" => "ваши любимые треки", + "your playlists" => "ваши плейлисты", + "your station settings" => "настройки волны", + "genres" => "жанры", + "podcasts" => "подкасты", + "stations" => "станции", + "the album" => "альбом", + "the artist" => "исполнителя", + "the chart" => "чарт", + "the playlist" => "плейлист", + "the playlists" => "плейлисты", + "the results" => "результаты", + + // Collection + "Liked tracks" => "Мне нравится", + "Albums" => "Альбомы", + "Artists" => "Исполнители", + "Clips" => "Клипы", + "Your playlists" => "Ваши плейлисты", + "Liked playlists" => "Понравившиеся плейлисты", + "Play" => "Слушать", + "Shuffle" => "Вперемешку", + "Loading your liked tracks…" => "Загружаем ваши любимые треки…", + "No liked albums yet. Like an album and it lands here." => { + "Понравившихся альбомов пока нет. Отметьте альбом сердечком, и он появится здесь." + } + "No liked artists yet. Like an artist and they land here." => { + "Понравившихся исполнителей пока нет. Отметьте исполнителя сердечком, и он появится здесь." + } + "No liked clips yet. Like a clip on an artist's page and it lands here." => { + "Понравившихся клипов пока нет. Отметьте клип на странице исполнителя, и он появится здесь." + } + "No liked tracks yet. Tap the heart on any track and it lands here." => { + "Любимых треков пока нет. Нажмите на сердечко у любого трека, и он появится здесь." + } + "No playlists yet. Playlists you make or like show up here." => { + "Плейлистов пока нет. Здесь появятся ваши плейлисты и те, что вам понравились." + } + + // Album, artist and playlist pages + "Loading the album…" => "Загружаем альбом…", + "Loading the artist…" => "Загружаем исполнителя…", + "Loading the playlist…" => "Загружаем плейлист…", + "This album isn't available on Yandex Music any more." => "Этого альбома больше нет в Яндекс Музыке.", + "This artist isn't available on Yandex Music any more." => "Этого исполнителя больше нет в Яндекс Музыке.", + "This playlist isn't available on Yandex Music any more." => "Этого плейлиста больше нет в Яндекс Музыке.", + "Artist · {}" => "Исполнитель · {}", + "Popular tracks" => "Популярные треки", + "Appears on" => "Участвует в", + "Similar artists" => "Похожие исполнители", + "Playlist · {}" => "Плейлист · {}", + "Public" => "Открытый", + "Private" => "Закрытый", + "Rename" => "Переименовать", + "Make private" => "Сделать закрытым", + "Make public" => "Сделать открытым", + "Delete" => "Удалить", + "This playlist is empty." => "В этом плейлисте пока пусто.", + "Single" => "Сингл", + "Compilation" => "Сборник", + "Podcast" => "Подкаст", + "Audiobook" => "Аудиокнига", + + // Search + "All" => "Всё", + "Tracks" => "Треки", + "Results for “{}”" => "Результаты по запросу «{}»", + "Nothing found for “{}”. Check the spelling or try fewer words." => { + "По запросу «{}» ничего не нашлось. Проверьте написание или сократите запрос." + } + "Searching…" => "Ищем…", + "Showing results for “{}”" => "Показаны результаты по запросу «{}»", + "Show more" => "Показать ещё", + "Track · {}" => "Трек · {}", + "Top result" => "Лучшее совпадение", + + // My Wave + "Tuned to: {} mood, {} tracks, {} language." => "Настроено: настроение — {}, характер — {}, язык — {}.", + "An endless stream picked from what you play, like and skip." => { + "Бесконечный поток музыки, который подстраивается под то, что вы слушаете, лайкаете и пропускаете." + } + "Pause" => "Пауза", + "Resume" => "Продолжить", + "Play My Wave" => "Слушать Мою волну", + "Mood" => "Настроение", + "Character" => "Характер", + "Language" => "Язык", + "Any" => "Не важно", + "Energetic" => "Бодрое", + "Cheerful" => "Весёлое", + "Calm" => "Спокойное", + "Sad" => "Грустное", + "Favourite" => "Любимое", + "Unfamiliar" => "Незнакомое", + "Popular" => "Популярное", + "Russian" => "Русский", + "Foreign" => "Иностранный", + "Loading your settings…" => "Загружаем настройки…", + "No other stations suggested right now." => "Других станций сейчас не предлагается.", + "Loading stations…" => "Загружаем станции…", + "Stations" => "Станции", + + // Settings + "Streaming quality" => "Качество звука", + "Lossless" => "Без потерь", + "Best" => "Лучшее", + "Balanced" => "Оптимальное", + "Data saver" => "Экономия трафика", + "FLAC when Yandex offers it for your subscription and region, otherwise the best it allows. About 3–5 times the data of MP3, and tracks take longer to start." => { + "FLAC, если Яндекс даёт его для вашей подписки и региона, иначе лучшее из доступного. Трафика в 3–5 раз больше, чем у MP3, и треки дольше запускаются." + } + "Highest MP3 bitrate Yandex offers, up to 320 kbps." => "Самый высокий битрейт MP3, который даёт Яндекс, до 320 кбит/с.", + "Up to 192 kbps. About 40% less data." => "До 192 кбит/с. Примерно на 40% меньше трафика.", + "Up to 128 kbps, for slow or metered connections." => "До 128 кбит/с, для медленного или платного интернета.", + "Streaming quality: {}. Applies from the next track." => "Качество звука: {}. Применится со следующего трека.", + "Appearance" => "Оформление", + "Match system" => "Как в системе", + "Light" => "Светлое", + "Dark" => "Тёмное", + "Storage" => "Хранилище", + "Covers are kept on disk so pages open instantly next time. Clearing them frees the space; they download again as you browse." => { + "Обложки хранятся на диске, чтобы страницы открывались мгновенно. Очистка освободит место, а обложки снова загрузятся по мере просмотра." + } + "Clear cover cache" => "Очистить кеш обложек", + "Cover cache cleared" => "Кеш обложек очищен", + "Couldn't clear the cover cache." => "Не удалось очистить кеш обложек.", + "Couldn't save your settings. They'll apply until Musyx quits." => { + "Не удалось сохранить настройки. Они будут действовать, пока Musyx открыт." + } + "Musyx {} · unofficial Yandex Music client" => "Musyx {} · неофициальный клиент Яндекс Музыки", + + // Account + "Yandex Plus" => "Яндекс Плюс", + "Yandex Plus until {}" => "Яндекс Плюс до {}", + "No Plus subscription. Tracks play as 30-second previews." => { + "Нет подписки Плюс. Треки играют фрагментами по 30 секунд." + } + "Sign out" => "Выйти", + "Can't reach Yandex Music" => "Яндекс Музыка недоступна", + "You're still signed in. Check your internet connection, then try again." => { + "Вы по-прежнему в аккаунте. Проверьте подключение к интернету и попробуйте ещё раз." + } + "Checking your sign-in…" => "Проверяем вход…", + "Signing in…" => "Входим…", + + // Sign-in + "Musyx plays your Yandex Music library, My Wave and playlists. You confirm sign-in on Yandex's own page, so your password never passes through this app." => { + "Musyx играет вашу коллекцию Яндекс Музыки, Мою волну и плейлисты. Вход подтверждается на странице самого Яндекса, поэтому пароль никогда не проходит через это приложение." + } + "Musyx is an unofficial client and isn't affiliated with Yandex. Your sign-in token is kept in the system keychain." => { + "Musyx — неофициальный клиент, не связанный с Яндексом. Токен входа хранится в системной связке ключей." + } + "Sign in with your Yandex account" => "Войдите с аккаунтом Яндекса", + "Get sign-in code" => "Получить код для входа", + "Getting a code…" => "Получаем код…", + "Copy code" => "Скопировать код", + "Copied" => "Скопировано", + "Waiting for confirmation · code expires in {}" => "Ждём подтверждения · код действует ещё {}", + "Cancel" => "Отмена", + "Open {}" => "Откройте {}", + "On this computer or your phone. You can also scan the QR code." => { + "На этом компьютере или на телефоне. Можно и отсканировать QR-код." + } + "Open in browser" => "Открыть в браузере", + "Enter this code" => "Введите этот код", + "Come back here" => "Вернитесь сюда", + "Musyx signs you in as soon as you allow access." => "Musyx войдёт, как только вы разрешите доступ.", + "Hide token sign-in" => "Скрыть вход по токену", + "Sign in with an existing token instead" => "Войти с готовым токеном", + "Paste OAuth token" => "Вставьте OAuth-токен", + "Sign in" => "Войти", + "Scan to open the sign-in page" => "Отсканируйте, чтобы открыть страницу входа", + "A QR code appears with your sign-in code" => "QR-код появится вместе с кодом для входа", + "Couldn't open your browser. Go to {} yourself." => "Не удалось открыть браузер. Откройте {} сами.", + "Yandex didn't accept that token. Check it and paste it again." => { + "Яндекс не принял этот токен. Проверьте его и вставьте ещё раз." + } + "The code expired before it was confirmed. Get a new code to try again." => { + "Срок действия кода истёк до подтверждения. Получите новый код и попробуйте снова." + } + "Access was declined on Yandex's page. Get a new code if that was a mistake." => { + "Доступ отклонён на странице Яндекса. Если это ошибка, получите новый код." + } + "Can't reach Yandex. Check your connection and try again." => { + "Яндекс недоступен. Проверьте подключение и попробуйте ещё раз." + } + "Yandex didn't accept the sign-in. Get a new code to try again." => { + "Яндекс не принял вход. Получите новый код и попробуйте снова." + } + "Yandex sent an unexpected answer. Try again in a moment." => { + "Яндекс прислал неожиданный ответ. Попробуйте чуть позже." + } + + // Player bar, queue and lyrics + "Can't play" => "Не удаётся воспроизвести", + "Nothing playing" => "Ничего не играет", + "Pick a track to start" => "Выберите трек", + "Preview" => "Фрагмент", + "Queue" => "Очередь", + "Lyrics" => "Текст", + "Now playing" => "Сейчас играет", + "Nothing after this" => "Дальше ничего нет", + "Next up · {}" => "Далее · {}", + "and {} more" => "и ещё {}", + "Nothing queued yet. Tracks you play, and the ones lined up after them, show up here." => { + "Очередь пока пуста. Здесь появятся треки, которые вы включите, и те, что за ними." + } + "Play a track to see its lyrics." => "Включите трек, чтобы увидеть его текст.", + "Yandex Music has no lyrics for this track." => "У Яндекс Музыки нет текста этого трека.", + "Couldn't load the lyrics. Check your connection and try again." => { + "Не удалось загрузить текст. Проверьте подключение и попробуйте ещё раз." + } + "Loading lyrics…" => "Загружаем текст…", + "Written by {}" => "Авторы: {}", + "No sound output found. Connect speakers or headphones and playback picks up." => { + "Не найдено устройство вывода звука. Подключите колонки или наушники, и воспроизведение продолжится." + } + "Couldn't load more of this station. Check your connection and try again." => { + "Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз." + } + "Several tracks in a row couldn't be played. Check your connection and try again." => { + "Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз." + } + "Couldn't play “{}”, so it was skipped." => "Не удалось воспроизвести «{}», трек пропущен.", + "Title" => "Название", + + // Track menu + "Next track" => "Следующий трек", + "Previous track" => "Предыдущий трек", + "Play next" => "Играть следующим", + "Add to queue" => "Добавить в очередь", + "Add to Liked tracks" => "Добавить в «Мне нравится»", + "Remove from Liked tracks" => "Убрать из «Мне нравится»", + "Add to playlist…" => "Добавить в плейлист…", + "Add to playlist" => "Добавить в плейлист", + "Play similar tracks" => "Слушать похожие", + "Go to album" => "Перейти к альбому", + "Go to artist" => "Перейти к исполнителю", + "Don't recommend this track" => "Не рекомендовать этот трек", + "Recommend this track again" => "Снова рекомендовать этот трек", + "Move up" => "Переместить выше", + "Move down" => "Переместить ниже", + "Remove from this playlist" => "Удалить из этого плейлиста", + "New playlist…" => "Новый плейлист…", + "New playlist" => "Новый плейлист", + "Rename playlist" => "Переименовать плейлист", + "Playlist name" => "Название плейлиста", + "Create" => "Создать", + "The track goes in once it's created." => "Трек добавится, как только плейлист будет создан.", + "Only you can see it until you make it public." => "Его видите только вы, пока не сделаете его открытым.", + "Delete “{}”?" => "Удалить «{}»?", + "The playlist and its track order go away for good. The tracks stay in Yandex Music." => { + "Плейлист и порядок треков удалятся навсегда. Сами треки останутся в Яндекс Музыке." + } + + // Toasts + "“{}” is already playing" => "«{}» уже играет", + "“{}” plays next" => "«{}» зазвучит следующим", + "Added “{}” to the queue" => "«{}» добавлен в очередь", + "Finding tracks like “{}”…" => "Ищем треки в духе «{}»…", + "Yandex has no similar tracks for “{}”" => "У Яндекса нет похожих треков для «{}»", + "Playing {} like “{}”" => "Играем {} в духе «{}»", + "Couldn't find similar tracks. Try again." => "Не удалось найти похожие треки. Попробуйте ещё раз.", + "Opening “{}” in your browser" => "Открываем «{}» в браузере", + "Couldn't open your browser." => "Не удалось открыть браузер.", + "Added to Liked tracks" => "Добавлено в «Мне нравится»", + "Removed from Liked tracks" => "Убрано из «Мне нравится»", + "Couldn't change the like. Try again." => "Не удалось изменить отметку. Попробуйте ещё раз.", + "You won't be recommended this track" => "Этот трек больше не будет попадаться в рекомендациях", + "Recommendations for this track restored" => "Трек снова может попадаться в рекомендациях", + "Couldn't change that. Try again." => "Не удалось это изменить. Попробуйте ещё раз.", + "Album added to your collection" => "Альбом добавлен в коллекцию", + "Album removed from your collection" => "Альбом убран из коллекции", + "Artist added to your collection" => "Исполнитель добавлен в коллекцию", + "Artist removed from your collection" => "Исполнитель убран из коллекции", + "Playlist added to your collection" => "Плейлист добавлен в коллекцию", + "Playlist removed from your collection" => "Плейлист убран из коллекции", + "Clip added to your collection" => "Клип добавлен в коллекцию", + "Clip removed from your collection" => "Клип убран из коллекции", + "Added to “{}”" => "Добавлено в «{}»", + "Couldn't add to “{}”. Try again." => "Не удалось добавить в «{}». Попробуйте ещё раз.", + "Created “{}”" => "Плейлист «{}» создан", + "Created “{}” with the track" => "Плейлист «{}» создан, трек добавлен", + "Couldn't create the playlist. Try again." => "Не удалось создать плейлист. Попробуйте ещё раз.", + "Renamed to “{}”" => "Плейлист переименован в «{}»", + "Couldn't rename the playlist. Try again." => "Не удалось переименовать плейлист. Попробуйте ещё раз.", + "Anyone with the link can now see this playlist" => "Теперь плейлист видят все, у кого есть ссылка", + "Only you can see this playlist now" => "Теперь плейлист видите только вы", + "Couldn't change who can see it. Try again." => "Не удалось изменить доступ. Попробуйте ещё раз.", + "Deleted “{}”" => "Плейлист «{}» удалён", + "Couldn't delete “{}”. Try again." => "Не удалось удалить «{}». Попробуйте ещё раз.", + "Removed from the playlist" => "Удалено из плейлиста", + "Couldn't remove the track. Try again." => "Не удалось удалить трек. Попробуйте ещё раз.", + "Moved" => "Перемещено", + "Couldn't move the track. Try again." => "Не удалось переместить трек. Попробуйте ещё раз.", + + // Units + "{} h {} min" => "{} ч {} мин", + "{} min" => "{} мин", + + _ => return None, + }) +} diff --git a/reference/musyx/src/main.rs b/reference/musyx/src/main.rs new file mode 100644 index 0000000..a7c8628 --- /dev/null +++ b/reference/musyx/src/main.rs @@ -0,0 +1,46 @@ +mod app; +mod covers; +mod i18n; +mod media; +mod menubar; +mod player; +mod route; +mod screens; +mod session; +mod store; +#[cfg(feature = "snapshot")] +mod snapshot; +mod ui; +mod widgets; + +use iced::{Size, window}; + +use app::App; +use ui::theme; + +/// The Linux application id: the window's Wayland app id / X11 class and the `.desktop` name. +#[cfg(target_os = "linux")] +const APP_ID: &str = "it.panov.musyx.desktop"; + +fn main() -> iced::Result { + let app = iced::application(App::new, App::update, App::view) + .title(App::title) + .theme(App::theme) + .subscription(App::subscription) + .default_font(theme::BODY) + .window(window::Settings { + size: Size::new(1280.0, 800.0), + min_size: Some(Size::new(960.0, 620.0)), + icon: window::icon::from_file_data(include_bytes!("../assets/icon/musyx.png"), None).ok(), + // Matches the installed `it.panov.musyx.desktop.desktop`, so the shell shows its name and icon. + #[cfg(target_os = "linux")] + platform_specific: window::settings::PlatformSpecific { + application_id: APP_ID.to_owned(), + ..Default::default() + }, + ..window::Settings::default() + }) + .centered(); + + theme::FONTS.into_iter().fold(app, |app, font| app.font(font)).run() +} diff --git a/reference/musyx/src/media.rs b/reference/musyx/src/media.rs new file mode 100644 index 0000000..605f700 --- /dev/null +++ b/reference/musyx/src/media.rs @@ -0,0 +1,167 @@ +//! Media keys and the system's Now Playing widget (macOS Control Center, +//! Windows media overlay, Linux MPRIS), through `souvlaki`. + +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +use iced::Subscription; +use iced::futures::{SinkExt, Stream}; +use souvlaki::{MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, MediaPosition, PlatformConfig}; +use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; +use ym_api::Track; + +use crate::covers; +use crate::player::Status; + +/// What the media keys asked for, in player terms. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Command { + Play, + Pause, + Toggle, + Next, + Previous, + SeekTo(Duration), + SeekBy { forward: bool, by: Duration }, +} + +/// Without an amount, a seek key jumps this far. +const SEEK_STEP: Duration = Duration::from_secs(10); + +impl Command { + fn from_event(event: MediaControlEvent) -> Option { + use souvlaki::SeekDirection::Forward; + Some(match event { + MediaControlEvent::Play => Command::Play, + MediaControlEvent::Pause | MediaControlEvent::Stop => Command::Pause, + MediaControlEvent::Toggle => Command::Toggle, + MediaControlEvent::Next => Command::Next, + MediaControlEvent::Previous => Command::Previous, + MediaControlEvent::SetPosition(MediaPosition(at)) => Command::SeekTo(at), + MediaControlEvent::Seek(dir) => Command::SeekBy { forward: dir == Forward, by: SEEK_STEP }, + MediaControlEvent::SeekBy(dir, by) => Command::SeekBy { forward: dir == Forward, by }, + _ => return None, + }) + } +} + +/// The OS calls back on its own thread; this hands commands to the subscription. +static INBOX: Mutex>> = Mutex::new(None); +static OUTBOX: OnceLock> = OnceLock::new(); + +/// Queues a command as if a media key sent it (the menu bar mini player uses this). +pub fn send(command: Command) { + if let Some(tx) = OUTBOX.get() { + let _ = tx.send(command); + } +} + +/// Owns the OS integration. Created on the main thread at startup. +pub struct Media { + controls: Option, + /// What was last published, so unchanged state isn't sent again. + shown: Option<(String, Status)>, +} + +impl Media { + pub fn new() -> Self { + let (tx, rx): (UnboundedSender, _) = unbounded_channel(); + if OUTBOX.set(tx).is_ok() + && let Ok(mut inbox) = INBOX.lock() + { + *inbox = Some(rx); + } + let controls = MediaControls::new(PlatformConfig { display_name: "Musyx", dbus_name: "musyx", hwnd: None }) + .and_then(|mut c| { + c.attach(|event| { + if let Some(command) = Command::from_event(event) { + send(command); + } + })?; + Ok(c) + }); + match controls { + Ok(c) => Self { controls: Some(c), shown: None }, + Err(e) => { + eprintln!("media controls unavailable: {e:?}"); + Self { controls: None, shown: None } + } + } + } + + /// Publishes the track and play state; `force` resends the position after a seek. + pub fn update(&mut self, track: Option<&Track>, status: Status, position: Duration, force: bool) { + let Some(controls) = &mut self.controls else { return }; + let Some(track) = track else { + if self.shown.take().is_some() { + let _ = controls.set_playback(MediaPlayback::Stopped); + } + return; + }; + let new_track = self.shown.as_ref().is_none_or(|(id, _)| *id != track.id); + let new_status = self.shown.as_ref().is_none_or(|(_, s)| *s != status); + if !new_track && !new_status && !force { + return; + } + if new_track { + let title = track.full_title(); + let artist = track.artist_line(); + let album = track.album.as_ref().map(|a| a.title.clone()); + let cover = track.cover_url(covers::LARGE); + let _ = controls.set_metadata(MediaMetadata { + title: Some(&title), + artist: Some(&artist), + album: album.as_deref(), + cover_url: cover.as_deref(), + duration: Some(track.duration), + }); + } + let progress = Some(MediaPosition(position)); + let _ = controls.set_playback(match status { + Status::Playing | Status::Loading => MediaPlayback::Playing { progress }, + Status::Paused | Status::Ended => MediaPlayback::Paused { progress }, + }); + self.shown = Some((track.id.clone(), status)); + } +} + +pub fn subscription() -> Subscription { + Subscription::run(commands) +} + +fn commands() -> impl Stream { + iced::stream::channel(16, async |mut output| { + let inbox = INBOX.lock().ok().and_then(|mut i| i.take()); + let Some(mut inbox) = inbox else { + // Already taken by an earlier run: stay pending rather than ending the subscription. + std::future::pending::<()>().await; + return; + }; + while let Some(command) = inbox.recv().await { + if output.send(command).await.is_err() { + break; + } + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use souvlaki::SeekDirection; + + #[test] + fn os_events_map_to_player_commands() { + assert_eq!(Command::from_event(MediaControlEvent::Toggle), Some(Command::Toggle)); + assert_eq!(Command::from_event(MediaControlEvent::Stop), Some(Command::Pause)); + assert_eq!( + Command::from_event(MediaControlEvent::SetPosition(MediaPosition(Duration::from_secs(42)))), + Some(Command::SeekTo(Duration::from_secs(42))) + ); + assert_eq!( + Command::from_event(MediaControlEvent::Seek(SeekDirection::Backward)), + Some(Command::SeekBy { forward: false, by: SEEK_STEP }) + ); + assert_eq!(Command::from_event(MediaControlEvent::Raise), None); + } +} diff --git a/reference/musyx/src/menubar.rs b/reference/musyx/src/menubar.rs new file mode 100644 index 0000000..23fc1b7 --- /dev/null +++ b/reference/musyx/src/menubar.rs @@ -0,0 +1,298 @@ +//! A monochrome mini player in the macOS menu bar, shown while the window is +//! minimised: previous, play/pause and next, then the track. Clicking the track +//! brings the window back. The glyphs are template SF Symbols and the text uses +//! the label colour, so the menu bar tints both to match itself. + +use ym_api::Track; + +use crate::player::Status; + +/// What the menu bar shows, so unchanged state isn't redrawn on every tick. +#[derive(Debug, Clone, PartialEq, Eq)] +struct NowPlaying { + title: String, + artist: String, + playing: bool, +} + +impl NowPlaying { + fn new(track: Option<&Track>, status: Status) -> Option { + track.map(|t| Self { + title: t.full_title(), + artist: t.artist_line(), + playing: matches!(status, Status::Playing | Status::Loading), + }) + } + + #[cfg(any(target_os = "macos", test))] + fn line(&self) -> String { + if self.artist.is_empty() { self.title.clone() } else { format!("{} — {}", self.title, self.artist) } + } +} + +/// The app's handle on the mini player. Created on the main thread at startup. +pub struct MiniPlayer { + shown: Option, +} + +impl MiniPlayer { + pub fn new() -> Self { + #[cfg(target_os = "macos")] + mac::install(); + Self { shown: None } + } + + /// Hands the mini player the current track and play state. + pub fn update(&mut self, track: Option<&Track>, status: Status) { + let now = NowPlaying::new(track, status); + if now == self.shown { + return; + } + #[cfg(target_os = "macos")] + mac::set_now_playing(now.clone()); + self.shown = now; + } +} + +#[cfg(target_os = "macos")] +mod mac { + use std::cell::RefCell; + use std::ptr::NonNull; + + use block2::RcBlock; + use objc2::rc::Retained; + use objc2::runtime::{AnyObject, NSObjectProtocol, ProtocolObject, Sel}; + use objc2::{MainThreadMarker, MainThreadOnly, define_class, msg_send, sel}; + use objc2_app_kit::{ + NSApplication, NSButton, NSCellImagePosition, NSFont, NSFontWeightRegular, NSImage, + NSImageSymbolConfiguration, NSLineBreakMode, NSStatusBar, NSStatusItem, NSTextField, + NSVariableStatusItemLength, NSWindowDidDeminiaturizeNotification, NSWindowDidMiniaturizeNotification, + }; + use objc2_foundation::{NSNotification, NSNotificationCenter, NSObject, NSPoint, NSRect, NSSize, NSString}; + + use super::NowPlaying; + use crate::i18n::tr; + use crate::media::{self, Command}; + + /// Width of each transport button, in points. + const KEY: f64 = 22.0; + /// Space at the ends and between the buttons and the text. + const PAD: f64 = 4.0; + /// Longer titles are cut with an ellipsis. + const MAX_TEXT: f64 = 220.0; + + #[derive(Default)] + struct State { + now: Option, + minimised: bool, + bar: Option, + /// Kept so the window notifications keep arriving. + observers: Vec>>, + } + + thread_local! { + static STATE: RefCell = RefCell::default(); + } + + /// Watches the window being minimised and restored. Off the main thread + /// (in tests) there's no menu bar, so this does nothing. + pub fn install() { + if MainThreadMarker::new().is_none() { + return; + } + let center = NSNotificationCenter::defaultCenter(); + // SAFETY: the notification names are AppKit constants, read on the main thread. + let names = unsafe { [(NSWindowDidMiniaturizeNotification, true), (NSWindowDidDeminiaturizeNotification, false)] }; + let observers = names.map(|(name, minimised)| { + let block = RcBlock::new(move |_: NonNull| { + STATE.with_borrow_mut(|s| { + s.minimised = minimised; + sync(s); + }); + }); + // SAFETY: with no queue, AppKit runs the block on the thread that posts, + // which for window notifications is the main thread. + unsafe { center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block) } + }); + STATE.with_borrow_mut(|s| s.observers.extend(observers)); + } + + pub fn set_now_playing(now: Option) { + STATE.with_borrow_mut(|s| { + s.now = now; + sync(s); + }); + } + + /// Adds, refreshes or removes the status item to match the state. + fn sync(state: &mut State) { + let Some(mtm) = MainThreadMarker::new() else { return }; + let now = state.now.as_ref().filter(|_| state.minimised); + match (now, &state.bar) { + (None, Some(_)) => { + if let Some(bar) = state.bar.take() { + NSStatusBar::systemStatusBar().removeStatusItem(&bar.item); + } + } + (Some(now), None) => state.bar = Bar::new(mtm).inspect(|bar| bar.show(now)), + (Some(now), Some(bar)) => bar.show(now), + (None, None) => {} + } + } + + struct Bar { + item: Retained, + keys: [Retained; 3], + label: Retained, + /// Receives the clicks; the buttons hold it only weakly. + _target: Retained, + } + + impl Bar { + fn new(mtm: MainThreadMarker) -> Option { + let item = NSStatusBar::systemStatusBar().statusItemWithLength(NSVariableStatusItemLength); + let button = item.button(mtm)?; + let target = Target::new(mtm); + let receiver: &AnyObject = ⌖ + // SAFETY: `Target` implements every action named here and outlives the buttons. + unsafe { + button.setTarget(Some(receiver)); + button.setAction(Some(sel!(restore:))); + } + let keys = [ + key("backward.fill", tr("Previous track"), sel!(previous:), receiver, mtm), + key("play.fill", tr("Play"), sel!(toggle:), receiver, mtm), + key("forward.fill", tr("Next track"), sel!(next:), receiver, mtm), + ]; + let label = NSTextField::labelWithString(&NSString::new(), mtm); + label.setFont(Some(&NSFont::menuBarFontOfSize(0.0))); + label.setLineBreakMode(NSLineBreakMode::ByTruncatingTail); + for key in &keys { + button.addSubview(key); + } + button.addSubview(&label); + Some(Self { item, keys, label, _target: target }) + } + + fn show(&self, now: &NowPlaying) { + let (symbol, description) = if now.playing { ("pause.fill", tr("Pause")) } else { ("play.fill", tr("Play")) }; + if let Some(image) = symbol_image(symbol, description) { + self.keys[1].setImage(Some(&image)); + } + let line = NSString::from_str(&now.line()); + self.label.setStringValue(&line); + self.label.sizeToFit(); + + let height = NSStatusBar::systemStatusBar().thickness(); + let mut x = PAD; + for key in &self.keys { + key.setFrame(NSRect::new(NSPoint::new(x, 0.0), NSSize::new(KEY, height))); + x += KEY; + } + x += PAD; + let text = self.label.frame().size; + let width = text.width.min(MAX_TEXT).ceil(); + self.label.setFrame(NSRect::new( + NSPoint::new(x, ((height - text.height) / 2.0).round()), + NSSize::new(width, text.height), + )); + self.item.setLength(x + width + PAD + 2.0); + if let Some(button) = self.item.button(MainThreadMarker::from(&*self.label)) { + button.setToolTip(Some(&line)); + } + } + } + + /// A borderless transport button showing one template SF Symbol. + fn key(symbol: &str, description: &str, action: Sel, target: &AnyObject, mtm: MainThreadMarker) -> Retained { + let button = NSButton::new(mtm); + if let Some(image) = symbol_image(symbol, description) { + button.setImage(Some(&image)); + } + button.setBordered(false); + button.setImagePosition(NSCellImagePosition::ImageOnly); + button.setToolTip(Some(&NSString::from_str(description))); + // SAFETY: `target` is the `Target` that implements `action`, kept alive by `Bar`. + unsafe { + button.setTarget(Some(target)); + button.setAction(Some(action)); + } + button + } + + fn symbol_image(symbol: &str, description: &str) -> Option> { + let image = NSImage::imageWithSystemSymbolName_accessibilityDescription( + &NSString::from_str(symbol), + Some(&NSString::from_str(description)), + )?; + // SAFETY: an AppKit constant. + let weight = unsafe { NSFontWeightRegular }; + let config = NSImageSymbolConfiguration::configurationWithPointSize_weight(12.0, weight); + let image = image.imageWithSymbolConfiguration(&config).unwrap_or(image); + image.setTemplate(true); + Some(image) + } + + /// Deminiaturises the app's windows and brings it to the front. + fn restore(mtm: MainThreadMarker) { + let app = NSApplication::sharedApplication(mtm); + for window in app.windows() { + if window.isMiniaturized() { + window.deminiaturize(None); + } + } + #[allow(deprecated)] // `activate` needs macOS 14. + app.activateIgnoringOtherApps(true); + } + + define_class!( + // SAFETY: NSObject has no subclassing requirements, and `Target` has no `Drop`. + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[name = "MusyxMiniPlayerTarget"] + struct Target; + + impl Target { + #[unsafe(method(previous:))] + fn previous(&self, _sender: Option<&AnyObject>) { + media::send(Command::Previous); + } + + #[unsafe(method(toggle:))] + fn toggle(&self, _sender: Option<&AnyObject>) { + media::send(Command::Toggle); + } + + #[unsafe(method(next:))] + fn next(&self, _sender: Option<&AnyObject>) { + media::send(Command::Next); + } + + #[unsafe(method(restore:))] + fn restore(&self, _sender: Option<&AnyObject>) { + restore(self.mtm()); + } + } + ); + + impl Target { + fn new(mtm: MainThreadMarker) -> Retained { + let this = Self::alloc(mtm).set_ivars(()); + // SAFETY: plain NSObject initialisation. + unsafe { msg_send![super(this), init] } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn line_joins_title_and_artist() { + let now = NowPlaying { title: "Song".into(), artist: "Band".into(), playing: true }; + assert_eq!(now.line(), "Song — Band"); + let now = NowPlaying { artist: String::new(), ..now }; + assert_eq!(now.line(), "Song"); + } +} diff --git a/reference/musyx/src/player/engine.rs b/reference/musyx/src/player/engine.rs new file mode 100644 index 0000000..569214b --- /dev/null +++ b/reference/musyx/src/player/engine.rs @@ -0,0 +1,335 @@ +//! The audio thread. It owns the output device and a rodio `Player`, takes +//! [`Command`]s over a channel and reports [`Event`]s through an iced subscription. +//! +//! Everything here is about one loaded item at a time; the queue and fetching +//! live in the UI state. Each load carries a `generation` so stale events from a +//! previous track can be told apart. + +use std::io::Cursor; +use std::sync::Arc; +use std::sync::mpsc::{self, RecvTimeoutError}; +use std::time::{Duration, Instant}; + +use iced::Subscription; +use iced::futures::{SinkExt, Stream}; +use rodio::{Decoder, DeviceSinkBuilder, MixerDeviceSink, Player, Source}; + +/// How often position is reported while playing. +const TICK: Duration = Duration::from_millis(250); + +pub enum Command { + Load { generation: u64, bytes: Arc<[u8]>, hint: String, play: bool }, + Play, + Pause, + Seek(Duration), + Volume(f32), + Stop, + /// The output device failed or changed; sent by the audio stream's error callback. + Reopen, +} + +/// A cheap handle the UI keeps to send commands. +#[derive(Clone)] +pub struct Handle(mpsc::Sender); + +impl std::fmt::Debug for Handle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("engine::Handle") + } +} + +impl Handle { + pub fn send(&self, command: Command) { + // The thread only stops with the subscription, i.e. when the app exits. + let _ = self.0.send(command); + } +} + +#[derive(Debug, Clone)] +pub enum Event { + Ready(Handle), + Loaded { generation: u64, duration: Option }, + Position { generation: u64, position: Duration }, + Ended { generation: u64 }, + /// The bytes didn't decode (corrupt download, unsupported codec). + DecodeFailed { generation: u64, reason: String }, + /// No output device, or it went away. Musyx keeps trying to reopen one. + NoOutput(String), + /// Sound is going to a device again after [`Event::NoOutput`]. + OutputReady, +} + +pub fn subscription() -> Subscription { + Subscription::run(events) +} + +fn events() -> impl Stream { + iced::stream::channel(64, async |mut output| { + let (commands, inbox) = mpsc::channel(); + let (events, mut outbox) = tokio::sync::mpsc::unbounded_channel(); + let own = commands.clone(); + std::thread::Builder::new() + .name("musyx-audio".into()) + .spawn(move || run(inbox, own, events)) + .expect("spawn audio thread"); + + let _ = output.send(Event::Ready(Handle(commands))).await; + while let Some(event) = outbox.recv().await { + if output.send(event).await.is_err() { + break; + } + } + }) +} + +/// Opens the system's default output device. +/// +/// rodio's own `open_default_sink` asks for a 50 ms buffer (2048 frames at +/// 44.1 kHz), which Bluetooth headphones that cap at 1024 frames reject, and its +/// fallback then filters out every macOS device. So pick the buffer here, +/// clamped to what the device says it supports. +fn open_output(on_error: impl FnMut(rodio::cpal::Error) + Send + Clone + 'static) -> Result { + use rodio::cpal::traits::{DeviceTrait, HostTrait}; + use rodio::cpal::{BufferSize, SupportedBufferSize}; + + let device = rodio::cpal::default_host() + .default_output_device() + .ok_or_else(|| "no default output device".to_owned())?; + let config = device.default_output_config().map_err(|e| e.to_string())?; + let buffer = match config.buffer_size() { + SupportedBufferSize::Range { min, max } => { + BufferSize::Fixed(buffer_frames(config.sample_rate(), *min, *max)) + } + SupportedBufferSize::Unknown => BufferSize::Default, + }; + DeviceSinkBuilder::default() + .with_device(device) + .with_supported_config(&config) + .with_buffer_size(buffer) + .with_error_callback(on_error) + .open_stream() + .or_else(|first| DeviceSinkBuilder::open_default_sink().map_err(|_| first.to_string())) +} + +/// About 50 ms of audio, rounded to a power of two, within the device's limits. +fn buffer_frames(sample_rate: u32, min: u32, max: u32) -> u32 { + (sample_rate / 20).next_power_of_two().clamp(min, max.max(min)) +} + +/// An open device and the player feeding it. The sink must outlive the player: +/// dropping it silences everything. +struct Output { + _sink: MixerDeviceSink, + player: Player, +} + +/// The track loaded now, kept so it can be reloaded on a new device. +struct Current { + generation: u64, + bytes: Arc<[u8]>, + hint: String, +} + +/// Wait after a device change before reopening; macOS needs a moment to settle. +const SETTLE: Duration = Duration::from_millis(400); +/// How often to look for a device when there is none. +const RETRY: Duration = Duration::from_secs(3); + +fn open(commands: &mpsc::Sender) -> Result { + let tx = commands.clone(); + let on_error = move |e: rodio::cpal::Error| { + use rodio::cpal::ErrorKind; + // Underruns are momentary glitches; only a lost or switched device needs a new stream. + if matches!(e.kind(), ErrorKind::DeviceChanged | ErrorKind::DeviceNotAvailable) { + let _ = tx.send(Command::Reopen); + } else if !matches!(e.kind(), ErrorKind::Xrun) { + eprintln!("audio stream error: {e}"); + } + }; + let mut sink = open_output(on_error)?; + sink.log_on_drop(false); + let player = Player::connect_new(sink.mixer()); + Ok(Output { _sink: sink, player }) +} + +fn decode(current: &Current) -> Result>>, String> { + let len = current.bytes.len() as u64; + Decoder::builder() + .with_data(Cursor::new(current.bytes.clone())) + .with_byte_len(len) + .with_hint(¤t.hint) + .with_seekable(true) + .with_gapless(true) + .build() + .map_err(|e| e.to_string()) +} + +fn run(inbox: mpsc::Receiver, commands: mpsc::Sender, events: tokio::sync::mpsc::UnboundedSender) { + let emit = |e: Event| { + let _ = events.send(e); + }; + + let mut output = match open(&commands) { + Ok(o) => Some(o), + Err(e) => { + emit(Event::NoOutput(e)); + None + } + }; + let mut volume = 1.0_f32; + let mut playing = false; + let mut current: Option = None; + let mut ended_sent = false; + let mut last_reported = None; + let mut last_attempt = Instant::now(); + + loop { + match inbox.recv_timeout(TICK) { + Ok(Command::Load { generation, bytes, hint, play }) => { + let next = Current { generation, bytes, hint }; + match decode(&next) { + Ok(source) => { + let duration = source.total_duration(); + if let Some(o) = &output { + o.player.clear(); + o.player.append(source); + if play { + o.player.play(); + } + } + playing = play; + current = Some(next); + ended_sent = false; + last_reported = None; + emit(Event::Loaded { generation, duration }); + } + Err(reason) => { + current = None; + emit(Event::DecodeFailed { generation, reason }); + } + } + } + Ok(Command::Play) => { + playing = true; + if let Some(o) = &output { + o.player.play(); + } + } + Ok(Command::Pause) => { + playing = false; + if let Some(o) = &output { + o.player.pause(); + } + } + Ok(Command::Seek(to)) => { + if let (Some(o), Some(c)) = (&output, ¤t) + // A failed seek leaves playback where it was; the next tick reports that. + && o.player.try_seek(to).is_ok() + { + emit(Event::Position { generation: c.generation, position: o.player.get_pos() }); + } + } + Ok(Command::Volume(v)) => { + volume = v.clamp(0.0, 1.0); + if let Some(o) = &output { + o.player.set_volume(volume); + } + } + Ok(Command::Stop) => { + if let Some(o) = &output { + o.player.clear(); + } + current = None; + playing = false; + } + Ok(Command::Reopen) => { + // Several errors arrive per change; one reopen covers them all. + while let Ok(Command::Reopen) = inbox.try_recv() {} + if last_attempt.elapsed() >= SETTLE { + std::thread::sleep(SETTLE); + while let Ok(Command::Reopen) = inbox.try_recv() {} + output = reopen(output.take(), &commands, ¤t, volume, playing, &emit); + last_attempt = Instant::now(); + } + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => break, + } + + // No device yet: look again now and then (headphones plugged in later). + if output.is_none() && last_attempt.elapsed() >= RETRY { + last_attempt = Instant::now(); + output = reopen(None, &commands, ¤t, volume, playing, &emit); + } + + let (Some(o), Some(c)) = (&output, ¤t) else { continue }; + if o.player.empty() { + if !ended_sent { + ended_sent = true; + emit(Event::Ended { generation: c.generation }); + } + } else if !o.player.is_paused() { + let position = o.player.get_pos(); + // Whole-tick resolution is plenty for a progress bar. + let bucket = position.as_millis() / TICK.as_millis(); + if last_reported != Some(bucket) { + last_reported = Some(bucket); + emit(Event::Position { generation: c.generation, position }); + } + } + } +} + +/// Opens the current default device and puts the loaded track back where it was. +fn reopen( + old: Option, + commands: &mpsc::Sender, + current: &Option, + volume: f32, + playing: bool, + emit: &impl Fn(Event), +) -> Option { + let position = old.as_ref().map(|o| o.player.get_pos()); + let had_output = old.is_some(); + drop(old); + let output = match open(commands) { + Ok(o) => o, + Err(e) => { + if had_output { + emit(Event::NoOutput(e)); + } + return None; + } + }; + output.player.set_volume(volume); + if let Some(c) = current + && let Ok(source) = decode(c) + { + output.player.append(source); + if let Some(at) = position { + let _ = output.player.try_seek(at); + } + if playing { + output.player.play(); + } else { + output.player.pause(); + } + } + if !had_output { + emit(Event::OutputReady); + } + Some(output) +} + +#[cfg(test)] +mod tests { + use super::buffer_frames; + + #[test] + fn buffer_fits_bluetooth_limits() { + assert_eq!(buffer_frames(44_100, 14, 1024), 1024); + assert_eq!(buffer_frames(48_000, 15, 4096), 4096); + assert_eq!(buffer_frames(8_000, 512, 4096), 512); + assert_eq!(buffer_frames(44_100, 100, 50), 100, "a bogus range still yields the minimum"); + } +} diff --git a/reference/musyx/src/player/mod.rs b/reference/musyx/src/player/mod.rs new file mode 100644 index 0000000..7653938 --- /dev/null +++ b/reference/musyx/src/player/mod.rs @@ -0,0 +1,944 @@ +//! 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 +//! module stays free of the API client and can be tested on its own. + +pub mod engine; +pub mod queue; + +use crate::i18n::{tr, trf}; +use std::sync::Arc; +use std::time::Duration; + +use ym_api::{Error, PlayReport, Stream, Track, WaveBatch, WaveEvent}; + +use engine::{Command, Event}; +pub use queue::{Queue, Repeat}; + +/// Give up after this many unplayable tracks in a row instead of skipping forever. +const MAX_SKIPS: u8 = 3; +/// "Previous" restarts the current track once it has played this long. +const RESTART_AFTER: Duration = Duration::from_secs(3); +/// Ask a station for more once this few tracks are left. +const WAVE_LOW_WATER: usize = 2; +/// Recent tracks sent with a request for more, so the station knows the context. +const WAVE_CONTEXT: usize = 5; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Status { + Loading, + Playing, + Paused, + /// The queue ran out with repeat off. Play starts the last track again. + Ended, +} + +/// Audio for one track, ready to hand to the engine. +#[derive(Debug, Clone)] +pub struct Audio { + pub stream: Stream, + pub bytes: Arc<[u8]>, +} + +#[derive(Debug, Clone)] +pub enum Msg { + Engine(Event), + /// Replace the queue. `shuffle` sets shuffle first; with it on, `start` is ignored. + Play { tracks: Arc<[Track]>, start: usize, shuffle: Option }, + Toggle, + Next, + Previous, + ToggleShuffle, + CycleRepeat, + /// The seek bar is being dragged; only the bar moves. + SeekPreview(f32), + SeekCommit, + SetVolume(f32), + ToggleMute, + JumpTo(usize), + Fetched { generation: u64, result: Result }, + Prefetched { track_id: String, result: Result }, + /// Start a station (`type:tag`). + PlayWave { station: String }, + WaveBatch { station: String, result: Result }, + /// The station's settings changed: replace what's queued after the current track. + WaveRestart, + /// Queue a track right after the current one (or play it if nothing is queued). + PlayNext(Track), + /// Queue a track at the end. + Append(Track), + Seek(Duration), +} + +/// Work the app has to do on the player's behalf. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Effect { + Fetch { generation: u64, track_id: String }, + Prefetch { track_id: String }, + /// The token stopped working mid-session. + SignedOut, + /// Start a session (`session_id: None`) or continue one; `queue` is recent `full_id`s. + WaveFetch { station: String, session_id: Option, queue: Vec }, + WaveFeedback { session_id: String, event: WaveEvent, batch_id: Option }, + Report(PlayReport), +} + +/// A station being played, endlessly topped up. +#[derive(Debug, Clone)] +struct Wave { + station: String, + /// Set by the first batch; feedback can't be sent before it. + session_id: Option, + /// The batch each queued track came in; feedback must name the track's own batch. + batches: std::collections::HashMap, + fetching: bool, + /// The queue ran out before the next batch came; advance when it does. + waiting: bool, +} + +pub struct Player { + engine: Option, + queue: Option>, + pub repeat: Repeat, + shuffle: bool, + pub volume: f32, + pub muted: bool, + generation: u64, + status: Status, + position: Duration, + duration: Duration, + current: Option