feat: add the Kotlin Multiplatform AudioManager client
CI / test (push) Successful in 2m0s
CI / build (push) Successful in 13m27s

A shared Compose Multiplatform client for Android, desktop and web on the
native mood-first API.

- Bearer login with persisted, restorable sessions.
- Mood grid and full editor (create, settings, seeds, delete).
- Server-driven radio sessions with automatic started/completed/skipped
  events and prefetching.
- Add to current mood or choose another mood from the player.
- Library search, original MP3 downloads, offline playback of downloads.
- Offline cache of moods, songs and the last sync revision.
- Platform audio: Media3 on Android, MP3SPI on desktop, HTML audio on web.
- Platform storage: filesystem on Android/desktop, localStorage on web.
- Desktop tests for API parsing, errors and cache persistence.
- Gitea CI image with Android SDK 35, build pipeline and tagged releases.
This commit is contained in:
TapTap committed 2026-11-14 18:24:06 +00:00
commit 3281e46104
40 files changed
+7021

No files matched your search

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:label="AudioManager"
android:supportsRtl="true"
android:theme="@android:style/Theme.Material.NoActionBar"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden|uiMode"
android:exported="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,76 @@
package win.taptap.musicmanager.client
import android.content.Context
import android.net.Uri
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import java.io.File
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.playback.AudioPlayer
class AndroidAudioPlayer(context: Context) : AudioPlayer {
private val player = ExoPlayer.Builder(context).build().apply {
setAudioAttributes(
AudioAttributes.Builder()
.setUsage(C.USAGE_MEDIA)
.setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
.build(),
true,
)
addListener(object : Player.Listener {
override fun onPlaybackStateChanged(playbackState: Int) {
if (playbackState == Player.STATE_ENDED) finished = true
}
})
}
private var finished = false
override fun play(source: String, song: Song, local: Boolean) {
finished = false
val uri = if (local) Uri.fromFile(File(source)) else Uri.parse(source)
player.setMediaItem(MediaItem.fromUri(uri))
player.prepare()
player.play()
}
override fun pause() {
player.pause()
}
override fun resume() {
player.play()
}
override fun stop() {
player.stop()
player.clearMediaItems()
finished = false
}
override fun isPlaying(): Boolean = player.isPlaying
override fun isFinished(): Boolean = finished
override fun positionSeconds(): Double =
player.currentPosition.coerceAtLeast(0L) / 1000.0
override fun durationSeconds(): Double {
val duration = player.duration
return if (duration > 0) duration / 1000.0 else 0.0
}
override val canSeek: Boolean = true
override fun seekTo(seconds: Double) {
player.seekTo((seconds * 1000).toLong().coerceAtLeast(0L))
}
override fun release() {
player.release()
}
}
@@ -0,0 +1,27 @@
package win.taptap.musicmanager.client
import android.content.Context
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.Composable
import win.taptap.musicmanager.client.ui.App
object AndroidContextHolder {
lateinit var context: Context
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: android.os.Bundle?) {
super.onCreate(savedInstanceState)
AndroidContextHolder.context = applicationContext
enableEdgeToEdge()
setContent { App() }
}
}
@Composable
actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) {
BackHandler(enabled = enabled, onBack = onBack)
}
@@ -0,0 +1,70 @@
package win.taptap.musicmanager.client
import android.content.Context
import android.graphics.BitmapFactory
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.okhttp.OkHttp
import java.io.File
import win.taptap.musicmanager.client.data.AppStorage
import win.taptap.musicmanager.client.playback.AudioPlayer
actual fun platformEngine(): HttpClientEngine = OkHttp.create()
actual val platformName: String = "android"
actual fun defaultServerUrl(): String = "http://10.0.2.2:8080"
actual fun platformStorage(): AppStorage = AndroidStorage(AndroidContextHolder.context)
actual fun createAudioPlayer(): AudioPlayer = AndroidAudioPlayer(AndroidContextHolder.context)
class AndroidStorage(context: Context) : AppStorage {
private val root = File(context.filesDir, "audiomanager").apply { mkdirs() }
private val downloads = File(root, "downloads").apply { mkdirs() }
override fun read(name: String): String? {
val file = File(root, name)
return if (file.isFile) file.readText() else null
}
override fun write(name: String, text: String) {
root.mkdirs()
File(root, name).writeText(text)
}
override fun delete(name: String) {
File(root, name).delete()
}
override fun saveDownload(songId: String, bytes: ByteArray): String? {
downloads.mkdirs()
val file = File(downloads, "${safeName(songId)}.mp3")
file.writeBytes(bytes)
return file.absolutePath
}
override fun downloadPath(songId: String): String? =
File(downloads, "${safeName(songId)}.mp3").takeIf { it.isFile }?.absolutePath
override fun listDownloads(): Map<String, Long> =
downloads.listFiles()
?.filter { it.isFile && it.extension == "mp3" }
?.associate { it.nameWithoutExtension to it.length() }
?: emptyMap()
override fun deleteDownload(songId: String) {
File(downloads, "${safeName(songId)}.mp3").delete()
}
override fun storageUsedBytes(): Long =
downloads.listFiles()?.sumOf { it.length() } ?: 0L
private fun safeName(songId: String): String =
songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("")
}
actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap()
@@ -0,0 +1,18 @@
package win.taptap.musicmanager.client
import androidx.compose.ui.graphics.ImageBitmap
import io.ktor.client.engine.HttpClientEngine
import win.taptap.musicmanager.client.data.AppStorage
import win.taptap.musicmanager.client.playback.AudioPlayer
expect val platformName: String
expect fun defaultServerUrl(): String
expect fun platformEngine(): HttpClientEngine
expect fun platformStorage(): AppStorage
expect fun createAudioPlayer(): AudioPlayer
expect fun decodeImage(bytes: ByteArray): ImageBitmap?
@@ -0,0 +1,6 @@
package win.taptap.musicmanager.client
import androidx.compose.runtime.Composable
@Composable
expect fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit)
@@ -0,0 +1,264 @@
package win.taptap.musicmanager.client.api
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.delete
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.patch
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsBytes
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.http.encodeURLParameter
import io.ktor.http.isSuccess
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engine) {
expectSuccess = false
install(ContentNegotiation) {
json(
Json {
ignoreUnknownKeys = true
encodeDefaults = true
explicitNulls = false
},
)
}
install(HttpTimeout) {
requestTimeoutMillis = 30_000
socketTimeoutMillis = 60_000
}
}
/**
* Native API client. Media URLs carry the token in the query string because
* Android's Media3, desktop playback and HTML audio all fetch them directly.
*/
class ApiClient(private val http: HttpClient) {
var baseUrl: String = ""
private set
var token: String? = null
private set
private val coverCache = mutableMapOf<String, ByteArray?>()
suspend fun login(
serverUrl: String,
username: String,
password: String,
deviceName: String,
platform: String,
): LoginResponse {
baseUrl = normalize(serverUrl)
val response = http.post("$baseUrl/api/v1/auth/login") {
contentType(ContentType.Application.Json)
setBody(LoginRequest(username.trim(), password, deviceName, platform))
}
val body = parse<LoginResponse>(response)
token = body.token
return body
}
fun restore(serverUrl: String, existingToken: String) {
baseUrl = normalize(serverUrl)
token = existingToken
}
fun clear() {
token = null
coverCache.clear()
}
suspend fun me(): User = get("/me")
suspend fun logout() {
requestNoContent { http.post(url("/auth/logout")) { auth() } }
clear()
}
suspend fun moods(): List<Mood> = get<MoodsResponse>("/moods").moods
suspend fun mood(id: String): MoodDetail = get("/moods/$id")
suspend fun createMood(request: CreateMoodRequest): MoodDetail =
parse(
http.post(url("/moods")) {
auth()
contentType(ContentType.Application.Json)
setBody(request)
},
)
suspend fun updateMood(id: String, request: UpdateMoodRequest): MoodDetail =
parse(
http.patch(url("/moods/$id")) {
auth()
contentType(ContentType.Application.Json)
setBody(request)
},
)
suspend fun deleteMood(id: String) {
requestNoContent { http.delete(url("/moods/$id")) { auth() } }
}
suspend fun addSeed(moodId: String, songId: String): AddToMoodResponse =
parse(
http.post(url("/moods/$moodId/seeds")) {
auth()
contentType(ContentType.Application.Json)
setBody(AddSeedRequest(songId))
},
)
suspend fun removeSeed(moodId: String, songId: String) {
requestNoContent { http.delete(url("/moods/$moodId/seeds/$songId")) { auth() } }
}
suspend fun preview(moodId: String, limit: Int = 20): List<Song> =
get<SearchResponse>("/moods/$moodId/preview?limit=$limit").songs
suspend fun search(query: String, limit: Int = 50): List<Song> =
get<SearchResponse>("/library/search?q=${query.encodeURLParameter()}&limit=$limit").songs
suspend fun library(
cursor: String? = null,
since: String? = null,
limit: Int = 500,
scope: String = "all",
): LibraryPage {
val query = buildString {
append("?limit=$limit&scope=$scope")
cursor?.let { append("&cursor=${it.encodeURLParameter()}") }
since?.let { append("&since=${it.encodeURLParameter()}") }
}
return get("/library/songs$query")
}
suspend fun startSession(moodId: String, limit: Int = 12): Session =
parse(
http.post(url("/moods/$moodId/sessions")) {
auth()
contentType(ContentType.Application.Json)
setBody(StartSessionRequest(limit))
},
)
suspend fun nextTracks(sessionId: String, limit: Int = 12): List<Song> =
parse<TracksResponse>(
http.post(url("/sessions/$sessionId/next")) {
auth()
contentType(ContentType.Application.Json)
setBody(NextTracksRequest(limit))
},
).songs
suspend fun reportEvents(sessionId: String, events: List<PlaybackEvent>) {
if (events.isEmpty()) return
runCatching {
http.post(url("/sessions/$sessionId/events")) {
auth()
contentType(ContentType.Application.Json)
setBody(PlaybackEventsRequest(events))
}
}
}
suspend fun addToMood(sessionId: String, songId: String, moodId: String?): AddToMoodResponse =
parse(
http.post(url("/sessions/$sessionId/add-to-mood")) {
auth()
contentType(ContentType.Application.Json)
setBody(AddToMoodRequest(songId, moodId))
},
)
suspend fun closeSession(id: String) {
runCatching { requestNoContent { http.delete(url("/sessions/$id")) { auth() } } }
}
suspend fun devices(): List<Device> = get("/auth/devices")
suspend fun scanStatus(): ScanStatus = get("/scan")
suspend fun startScan(): ScanStatus =
parse(
http.post(url("/scan")) {
auth()
},
)
suspend fun cover(albumId: String, size: Int = 320): ByteArray? {
val key = "$albumId:$size"
if (coverCache.containsKey(key)) return coverCache[key]
val bytes = runCatching {
http.get("$baseUrl/api/v1/covers/$albumId?size=$size&token=${token.orEmpty().encodeURLParameter()}")
.bodyAsBytes()
}.getOrNull()
val result = bytes?.takeIf { it.isNotEmpty() }
coverCache[key] = result
return result
}
suspend fun download(songId: String): ByteArray =
http.get("$baseUrl/api/v1/songs/$songId/stream") {
auth()
url.parameters.append("download", "true")
}.bodyAsBytes()
fun streamUrl(songId: String): String =
"$baseUrl/api/v1/songs/$songId/stream?token=${token.orEmpty().encodeURLParameter()}"
fun coverUrl(albumId: String, size: Int = 320): String =
"$baseUrl/api/v1/covers/$albumId?size=$size&token=${token.orEmpty().encodeURLParameter()}"
private suspend inline fun <reified T> get(path: String): T =
parse(http.get(url(path)) { auth() })
private fun HttpRequestBuilder.auth() {
token?.let { header(HttpHeaders.Authorization, "Bearer $it") }
}
private fun url(path: String): String = "$baseUrl/api/v1$path"
private suspend inline fun <reified T> parse(response: HttpResponse): T {
if (response.status.isSuccess()) return response.body()
throw error(response)
}
private suspend fun requestNoContent(block: suspend () -> HttpResponse) {
val response = block()
if (response.status == HttpStatusCode.NoContent || response.status.isSuccess()) return
throw error(response)
}
private suspend fun error(response: HttpResponse): ApiException {
val body = runCatching { response.body<ApiErrorBody>() }.getOrNull()
return ApiException(
status = response.status.value,
code = body?.error?.code ?: "http_${response.status.value}",
message = body?.error?.message ?: "Request failed (${response.status.value})",
)
}
private fun normalize(serverUrl: String): String {
var value = serverUrl.trim().trimEnd('/')
if (value.isEmpty()) value = "http://localhost:8080"
if (!value.startsWith("http://") && !value.startsWith("https://")) {
value = "http://$value"
}
return value
}
}
@@ -0,0 +1,204 @@
package win.taptap.musicmanager.client.api
import kotlinx.serialization.Serializable
@Serializable
data class ApiErrorBody(val error: ApiError)
@Serializable
data class ApiError(val code: String, val message: String)
class ApiException(val status: Int, val code: String, override val message: String) :
RuntimeException(message)
@Serializable
data class LoginRequest(
val username: String,
val password: String,
val deviceName: String,
val platform: String,
)
@Serializable
data class User(
val name: String,
val admin: Boolean,
val musicFolders: List<Int> = emptyList(),
val longformFolders: List<Int> = emptyList(),
)
@Serializable
data class LoginResponse(
val token: String,
val expiresAt: String,
val user: User,
)
@Serializable
data class Song(
val id: String,
val title: String,
val artist: String,
val album: String,
val albumId: String,
val trackNumber: Int? = null,
val discNumber: Int = 1,
val year: Int? = null,
val duration: Int,
val bitRate: Int,
val size: Long,
val suffix: String,
val genres: List<String> = emptyList(),
val folderId: Int,
val relativePath: String,
val updatedAt: String,
)
@Serializable
data class Mood(
val id: String,
val name: String,
val description: String? = null,
val query: String? = null,
val genres: List<String> = emptyList(),
val targetSize: Int,
val refreshHours: Int,
val ytEnabled: Boolean,
val lastDiscoveryAt: String? = null,
val createdAt: String,
val changedAt: String,
val lastError: String? = null,
val seedCount: Int,
val newRecommendations: Int = 0,
)
@Serializable
data class Seed(
val song: Song,
val origin: String,
val addedAt: String,
)
@Serializable
data class Recommendation(
val videoId: String,
val title: String,
val artist: String,
val album: String? = null,
val duration: Int? = null,
val thumbnail: String? = null,
val state: String,
val matchedSong: Song? = null,
val timesAdded: Int = 0,
val firstSeen: String,
val lastSeen: String,
)
@Serializable
data class MoodDetail(
val mood: Mood,
val seeds: List<Seed> = emptyList(),
val recommendations: List<Recommendation> = emptyList(),
)
@Serializable
data class MoodsResponse(val moods: List<Mood>)
@Serializable
data class LibraryPage(
val songs: List<Song> = emptyList(),
val deletedSongIds: List<String> = emptyList(),
val revision: String,
val nextCursor: String? = null,
val nextSince: String? = null,
)
@Serializable
data class SearchResponse(val songs: List<Song> = emptyList())
@Serializable
data class Session(
val id: String,
val moodId: String,
val moodName: String,
val startedAt: String,
val closedAt: String? = null,
val queue: List<Song> = emptyList(),
)
@Serializable
data class TracksResponse(val songs: List<Song> = emptyList())
@Serializable
data class StartSessionRequest(val limit: Int)
@Serializable
data class NextTracksRequest(
val limit: Int,
val excludeSongIds: List<String> = emptyList(),
)
@Serializable
data class PlaybackEvent(
val songId: String,
val type: String,
val positionSeconds: Int? = null,
)
@Serializable
data class PlaybackEventsRequest(val events: List<PlaybackEvent>)
@Serializable
data class PlaybackEventsResponse(val accepted: Int)
@Serializable
data class AddToMoodRequest(val songId: String, val moodId: String? = null)
@Serializable
data class AddToMoodResponse(val mood: Mood, val added: Boolean)
@Serializable
data class AddSeedRequest(val songId: String, val origin: String = "manual")
@Serializable
data class CreateMoodRequest(
val name: String,
val description: String? = null,
val query: String? = null,
val genres: List<String> = emptyList(),
val targetSize: Int = 30,
val refreshHours: Int = 24,
val ytEnabled: Boolean = true,
val seedSongIds: List<String> = emptyList(),
)
@Serializable
data class UpdateMoodRequest(
val name: String? = null,
val description: String? = null,
val clearDescription: Boolean = false,
val query: String? = null,
val clearQuery: Boolean = false,
val genres: List<String>? = null,
val targetSize: Int? = null,
val refreshHours: Int? = null,
val ytEnabled: Boolean? = null,
)
@Serializable
data class ScanStatus(
val scanning: Boolean,
val count: Long,
val error: String? = null,
)
@Serializable
data class Device(
val id: String,
val deviceName: String,
val platform: String,
val createdAt: String,
val lastUsedAt: String,
val expiresAt: String,
val current: Boolean = false,
)
@@ -0,0 +1,16 @@
package win.taptap.musicmanager.client.data
/** Platform persistence for the session, the offline library and downloaded MP3s. */
interface AppStorage {
fun read(name: String): String?
fun write(name: String, text: String)
fun delete(name: String)
/** Returns a platform-specific handle for playback, or null when unsupported. */
fun saveDownload(songId: String, bytes: ByteArray): String?
fun downloadPath(songId: String): String?
fun listDownloads(): Map<String, Long>
fun deleteDownload(songId: String)
fun storageUsedBytes(): Long
}
@@ -0,0 +1,61 @@
package win.taptap.musicmanager.client.data
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.api.MoodDetail
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.api.User
@Serializable
data class SessionState(
val serverUrl: String,
val token: String,
val user: User,
)
@Serializable
data class CachedState(
val serverUrl: String = "",
val userName: String = "",
val revision: String? = null,
val songs: List<Song> = emptyList(),
val moods: List<Mood> = emptyList(),
val moodDetails: List<MoodDetail> = emptyList(),
)
class LibraryCache(private val storage: AppStorage) {
private val json = Json {
ignoreUnknownKeys = true
encodeDefaults = true
explicitNulls = false
}
fun loadSession(): SessionState? =
storage.read(SESSION_FILE)?.let {
runCatching { json.decodeFromString<SessionState>(it) }.getOrNull()
}
fun saveSession(session: SessionState?) {
if (session == null) storage.delete(SESSION_FILE) else storage.write(SESSION_FILE, json.encodeToString(session))
}
fun load(): CachedState =
storage.read(CACHE_FILE)?.let {
runCatching { json.decodeFromString<CachedState>(it) }.getOrNull()
} ?: CachedState()
fun save(state: CachedState) {
storage.write(CACHE_FILE, json.encodeToString(state))
}
fun clear() {
storage.delete(CACHE_FILE)
}
private companion object {
const val SESSION_FILE = "session.json"
const val CACHE_FILE = "library.json"
}
}
@@ -0,0 +1,24 @@
package win.taptap.musicmanager.client.playback
import win.taptap.musicmanager.client.api.Song
/**
* Minimal audio abstraction shared by all targets.
*
* `source` is either an HTTP URL (tokenized stream) or a local file handle. The
* store polls [isFinished] because some backends have no callback support.
*/
interface AudioPlayer {
fun play(source: String, song: Song, local: Boolean)
fun pause()
fun resume()
fun stop()
fun isPlaying(): Boolean
fun isFinished(): Boolean
fun positionSeconds(): Double
fun durationSeconds(): Double
val canSeek: Boolean
fun seekTo(seconds: Double)
fun release()
}
@@ -0,0 +1,777 @@
package win.taptap.musicmanager.client.store
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlin.random.Random
import win.taptap.musicmanager.client.api.ApiClient
import win.taptap.musicmanager.client.createAudioPlayer
import win.taptap.musicmanager.client.platformEngine
import win.taptap.musicmanager.client.platformName
import win.taptap.musicmanager.client.platformStorage
import win.taptap.musicmanager.client.api.ApiException
import win.taptap.musicmanager.client.api.CreateMoodRequest
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.api.MoodDetail
import win.taptap.musicmanager.client.api.PlaybackEvent
import win.taptap.musicmanager.client.api.Session
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.api.UpdateMoodRequest
import win.taptap.musicmanager.client.api.configuredHttpClient
import win.taptap.musicmanager.client.data.CachedState
import win.taptap.musicmanager.client.data.LibraryCache
import win.taptap.musicmanager.client.data.SessionState
import win.taptap.musicmanager.client.playback.AudioPlayer
import win.taptap.musicmanager.client.platformName
enum class Screen { Moods, MoodDetail, Library, Settings }
data class AppState(
val booting: Boolean = true,
val authenticated: Boolean = false,
val offline: Boolean = false,
val user: win.taptap.musicmanager.client.api.User? = null,
val serverUrl: String = "",
val screen: Screen = Screen.Moods,
val moods: List<Mood> = emptyList(),
val selectedMood: MoodDetail? = null,
val preview: List<Song> = emptyList(),
val session: Session? = null,
val queue: List<Song> = emptyList(),
val current: Song? = null,
val playing: Boolean = false,
val positionSeconds: Double = 0.0,
val durationSeconds: Double = 0.0,
val downloads: Set<String> = emptySet(),
val downloading: Set<String> = emptySet(),
val library: List<Song> = emptyList(),
val searchResults: List<Song> = emptyList(),
val searching: Boolean = false,
val loading: Boolean = false,
val saving: Boolean = false,
val message: String? = null,
val messageIsError: Boolean = false,
val messageId: Long = 0,
)
/**
* Single source of truth for the shared UI. Plain Kotlin so the same store runs
* on Android, desktop and Wasm.
*/
class AppStore(
private val scope: CoroutineScope,
private val api: ApiClient = ApiClient(configuredHttpClient(platformEngine())),
private val storage: win.taptap.musicmanager.client.data.AppStorage = platformStorage(),
private val player: AudioPlayer = createAudioPlayer(),
private val cache: LibraryCache = LibraryCache(storage),
) {
private val _state = MutableStateFlow(AppState())
val state: StateFlow<AppState> = _state.asStateFlow()
private var pollJob: Job? = null
private var advancing = false
private var fetching = false
private var finishing = false
init {
bootstrap()
}
fun bootstrap() {
scope.launch {
val session = cache.loadSession()
val cached = cache.load()
_state.update {
it.copy(
booting = false,
downloads = storage.listDownloads().keys,
moods = cached.moods,
library = cached.songs.sortedLibrary(),
selectedMood = cached.moodDetails.firstOrNull(),
)
}
if (session == null) return@launch
api.restore(session.serverUrl, session.token)
_state.update {
it.copy(
authenticated = true,
user = session.user,
serverUrl = session.serverUrl,
)
}
refreshAll(silent = true)
}
}
fun login(serverUrl: String, username: String, password: String) {
scope.launch {
_state.update { it.copy(loading = true) }
try {
val response = api.login(
serverUrl = serverUrl,
username = username,
password = password,
deviceName = "$platformName device",
platform = platformName,
)
cache.saveSession(SessionState(api.baseUrl, response.token, response.user))
_state.update {
it.copy(
authenticated = true,
user = response.user,
serverUrl = api.baseUrl,
loading = false,
)
}
refreshAll()
} catch (t: Throwable) {
_state.update {
it.copy(loading = false, message = t.friendlyMessage(), messageIsError = true, messageId = it.messageId + 1)
}
}
}
}
fun logout() {
scope.launch {
runCatching { api.logout() }
cache.saveSession(null)
cache.clear()
stopPlayback()
_state.value = AppState(
booting = false,
serverUrl = _state.value.serverUrl,
downloads = storage.listDownloads().keys,
)
}
}
fun refreshAll(silent: Boolean = false) {
scope.launch {
if (!silent) _state.update { it.copy(loading = true) }
try {
val moods = api.moods()
val cached = cache.load()
var songs = cached.songs.associateBy { it.id }.toMutableMap()
var revision = cached.revision
if (revision == null) {
var cursor: String? = null
do {
val page = api.library(cursor = cursor, since = null, limit = 500)
page.songs.forEach { songs[it.id] = it }
cursor = page.nextCursor
revision = page.revision
} while (cursor != null)
} else {
var since: String? = revision
while (since != null) {
val page = api.library(cursor = null, since = since, limit = 500)
page.songs.forEach { songs[it.id] = it }
page.deletedSongIds.forEach { songs.remove(it) }
revision = page.revision
since = page.nextSince
}
}
val details = cached.moodDetails.filter { detail -> moods.any { it.id == detail.mood.id } }
cache.save(
CachedState(
serverUrl = _state.value.serverUrl,
userName = _state.value.user?.name.orEmpty(),
revision = revision,
songs = songs.values.toList(),
moods = moods,
moodDetails = details,
),
)
_state.update {
it.copy(
loading = false,
offline = false,
moods = moods,
library = songs.values.sortedLibrary(),
)
}
} catch (t: Throwable) {
if (t is ApiException && t.status == 401) {
logout()
return@launch
}
_state.update {
it.copy(
loading = false,
offline = true,
message = "Offline mode: ${t.friendlyMessage()}",
messageIsError = true,
messageId = it.messageId + 1,
)
}
}
}
}
fun openMoods() {
_state.update { it.copy(screen = Screen.Moods) }
}
fun openMood(id: String) {
scope.launch {
_state.update { it.copy(loading = true, screen = Screen.MoodDetail) }
try {
val detail = api.mood(id)
val preview = runCatching { api.preview(id, 20) }.getOrDefault(emptyList())
cacheDetail(detail)
_state.update { it.copy(loading = false, selectedMood = detail, preview = preview) }
} catch (t: Throwable) {
val cached = cache.load().moodDetails.firstOrNull { it.mood.id == id }
_state.update {
it.copy(
loading = false,
selectedMood = cached ?: it.selectedMood,
message = if (cached == null) t.friendlyMessage() else "Showing cached mood",
messageIsError = cached == null,
messageId = it.messageId + 1,
)
}
}
}
}
fun openLibrary() {
_state.update { it.copy(screen = Screen.Library) }
}
fun openSettings() {
_state.update { it.copy(screen = Screen.Settings) }
}
fun createMood(
name: String,
description: String?,
genres: List<String>,
query: String?,
targetSize: Int,
refreshHours: Int,
ytEnabled: Boolean,
) {
scope.launch {
_state.update { it.copy(saving = true) }
try {
val detail = api.createMood(
CreateMoodRequest(
name = name,
description = description?.takeIf { it.isNotBlank() },
query = query?.takeIf { it.isNotBlank() },
genres = genres,
targetSize = targetSize,
refreshHours = refreshHours,
ytEnabled = ytEnabled,
),
)
cacheDetail(detail)
_state.update {
it.copy(
saving = false,
selectedMood = detail,
screen = Screen.MoodDetail,
moods = it.moods + detail.mood,
message = "Mood created",
messageIsError = false,
messageId = it.messageId + 1,
)
}
} catch (t: Throwable) {
_state.update { it.copy(saving = false, message = t.friendlyMessage(), messageIsError = true, messageId = it.messageId + 1) }
}
}
}
fun saveMood(
detail: MoodDetail,
name: String,
description: String?,
genres: List<String>,
query: String?,
targetSize: Int,
refreshHours: Int,
ytEnabled: Boolean,
) {
scope.launch {
_state.update { it.copy(saving = true) }
try {
val updated = api.updateMood(
detail.mood.id,
UpdateMoodRequest(
name = name,
description = description ?: "",
clearDescription = description.isNullOrBlank(),
query = query ?: "",
clearQuery = query.isNullOrBlank(),
genres = genres,
targetSize = targetSize,
refreshHours = refreshHours,
ytEnabled = ytEnabled,
),
)
cacheDetail(updated)
_state.update {
it.copy(
saving = false,
selectedMood = updated,
moods = it.moods.map { mood -> if (mood.id == updated.mood.id) updated.mood else mood },
message = "Saved",
messageIsError = false,
messageId = it.messageId + 1,
)
}
} catch (t: Throwable) {
_state.update { it.copy(saving = false, message = t.friendlyMessage(), messageIsError = true, messageId = it.messageId + 1) }
}
}
}
fun deleteMood(id: String) {
scope.launch {
try {
api.deleteMood(id)
_state.update {
it.copy(
screen = Screen.Moods,
selectedMood = null,
moods = it.moods.filterNot { mood -> mood.id == id },
message = "Mood deleted",
messageIsError = false,
messageId = it.messageId + 1,
)
}
} catch (t: Throwable) {
message(t)
}
}
}
fun addSeed(moodId: String, songId: String) {
scope.launch {
try {
api.addSeed(moodId, songId)
val detail = api.mood(moodId)
cacheDetail(detail)
_state.update {
it.copy(
selectedMood = detail,
moods = it.moods.map { mood -> if (mood.id == moodId) detail.mood else mood },
message = "Seed added",
messageIsError = false,
messageId = it.messageId + 1,
)
}
} catch (t: Throwable) {
message(t)
}
}
}
fun removeSeed(moodId: String, songId: String) {
scope.launch {
try {
api.removeSeed(moodId, songId)
val detail = api.mood(moodId)
cacheDetail(detail)
_state.update {
it.copy(
selectedMood = detail,
moods = it.moods.map { mood -> if (mood.id == moodId) detail.mood else mood },
message = "Seed removed",
messageIsError = false,
messageId = it.messageId + 1,
)
}
} catch (t: Throwable) {
message(t)
}
}
}
fun search(query: String) {
if (query.isBlank()) {
_state.update { it.copy(searchResults = emptyList()) }
return
}
scope.launch {
_state.update { it.copy(searching = true) }
try {
val songs = api.search(query, 60)
_state.update { it.copy(searching = false, searchResults = songs) }
} catch (t: Throwable) {
_state.update { it.copy(searching = false, searchResults = emptyList()) }
message(t)
}
}
}
fun playMood(moodId: String) {
scope.launch {
val state = _state.value
try {
val session = api.startSession(moodId, 12)
_state.update {
it.copy(
session = session,
queue = session.queue,
offline = false,
screen = Screen.MoodDetail,
)
}
playNext()
} catch (t: Throwable) {
val fallback = state.library.filter { it.id in state.downloads }
if (fallback.isNotEmpty()) {
_state.update {
it.copy(
session = null,
queue = fallback.shuffled(Random.Default),
offline = true,
message = "Server unreachable, playing downloads",
messageIsError = true,
messageId = it.messageId + 1,
)
}
playNext()
} else {
message(t)
}
}
}
}
fun playSong(song: Song) {
scope.launch {
_state.value.session?.let { api.closeSession(it.id) }
_state.update {
it.copy(
session = null,
queue = emptyList(),
current = song,
playing = true,
positionSeconds = 0.0,
durationSeconds = song.duration.toDouble(),
)
}
startSong(song)
}
}
fun togglePlayPause() {
val state = _state.value
if (state.current == null) return
if (state.playing) {
player.pause()
_state.update { it.copy(playing = false) }
} else {
player.resume()
_state.update { it.copy(playing = true) }
startPolling()
}
}
fun skip() {
val state = _state.value
state.current?.let { report("skipped", it.id) }
playNext()
}
fun seekTo(seconds: Double) {
if (!player.canSeek) return
player.seekTo(seconds)
_state.update { it.copy(positionSeconds = seconds) }
}
fun addCurrentToMood(targetMoodId: String?) {
val state = _state.value
val song = state.current ?: return
val session = state.session
scope.launch {
try {
val response = if (targetMoodId != null) {
api.addSeed(targetMoodId, song.id)
} else if (session != null) {
api.addToMood(session.id, song.id, null)
} else {
_state.update {
it.copy(
message = "Start a mood before adding tracks",
messageIsError = true,
messageId = it.messageId + 1,
)
}
return@launch
}
val updatedMoods = state.moods.map { mood ->
if (mood.id == response.mood.id) response.mood else mood
}
val selected = state.selectedMood?.let { detail ->
if (detail.mood.id == response.mood.id) {
detail.copy(mood = response.mood)
} else {
detail
}
}
_state.update {
it.copy(
moods = updatedMoods,
selectedMood = selected,
message = if (response.added) {
"Added to ${response.mood.name}"
} else {
"Already in ${response.mood.name}"
},
messageIsError = false,
messageId = it.messageId + 1,
)
}
if (selected != null) cacheDetail(selected)
} catch (t: Throwable) {
message(t)
}
}
}
fun toggleDownload(song: Song) {
val state = _state.value
if (song.id in state.downloads) {
storage.deleteDownload(song.id)
_state.update {
it.copy(
downloads = storage.listDownloads().keys,
message = "Download removed",
messageIsError = false,
messageId = it.messageId + 1,
)
}
return
}
scope.launch {
_state.update { it.copy(downloading = it.downloading + song.id) }
try {
val bytes = api.download(song.id)
val path = storage.saveDownload(song.id, bytes)
if (path == null) {
_state.update {
it.copy(
downloading = it.downloading - song.id,
message = "Downloads are not available on this platform",
messageIsError = true,
messageId = it.messageId + 1,
)
}
} else {
_state.update {
it.copy(
downloading = it.downloading - song.id,
downloads = storage.listDownloads().keys,
message = "Downloaded ${song.title}",
messageIsError = false,
messageId = it.messageId + 1,
)
}
}
} catch (t: Throwable) {
_state.update { it.copy(downloading = it.downloading - song.id) }
message(t)
}
}
}
fun clearDownloads() {
storage.listDownloads().keys.forEach(storage::deleteDownload)
_state.update {
it.copy(
downloads = emptySet(),
message = "Downloads cleared",
messageIsError = false,
messageId = it.messageId + 1,
)
}
}
fun scanLibrary() {
scope.launch {
try {
api.startScan()
_state.update {
it.copy(message = "Library scan started", messageIsError = false, messageId = it.messageId + 1)
}
} catch (t: Throwable) {
message(t)
}
}
}
suspend fun cover(albumId: String): ByteArray? = api.cover(albumId, 320)
fun storageBytes(): Long = storage.storageUsedBytes()
fun canSeek(): Boolean = player.canSeek
fun clearMessage() {
_state.update { it.copy(message = null) }
}
fun dismissOffline() {
_state.update { it.copy(offline = false) }
}
fun release() {
pollJob?.cancel()
player.release()
}
private fun playNext() {
if (advancing) return
val state = _state.value
if (state.queue.isEmpty()) {
val session = state.session
if (session == null) {
_state.update { it.copy(playing = false) }
return
}
advancing = true
scope.launch {
try {
val more = api.nextTracks(session.id, 12)
_state.update { it.copy(queue = it.queue + more) }
} catch (t: Throwable) {
message(t)
} finally {
advancing = false
}
if (_state.value.queue.isNotEmpty()) playNext() else _state.update { it.copy(playing = false) }
}
return
}
val song = state.queue.first()
_state.update {
it.copy(
queue = it.queue.drop(1),
current = song,
playing = true,
positionSeconds = 0.0,
durationSeconds = song.duration.toDouble(),
)
}
startSong(song)
report("started", song.id)
if (_state.value.queue.size < 3) prefetch()
}
private fun prefetch() {
val session = _state.value.session ?: return
if (fetching) return
fetching = true
scope.launch {
try {
val more = api.nextTracks(session.id, 12)
_state.update { it.copy(queue = it.queue + more) }
} catch (_: Throwable) {
// The queue still has tracks; a later request will retry.
} finally {
fetching = false
}
}
}
private fun startSong(song: Song) {
val localPath = storage.downloadPath(song.id)
finishing = false
player.play(localPath ?: api.streamUrl(song.id), song, localPath != null)
startPolling()
}
private fun startPolling() {
pollJob?.cancel()
pollJob = scope.launch {
while (isActive && _state.value.current != null) {
delay(400)
val state = _state.value
val position = player.positionSeconds()
val duration = player.durationSeconds().takeIf { it > 0 } ?: state.durationSeconds
_state.update {
it.copy(
positionSeconds = position.coerceAtLeast(0.0),
durationSeconds = duration,
playing = player.isPlaying(),
)
}
if (player.isFinished()) {
if (!finishing) {
finishing = true
report("completed", state.current?.id)
playNext()
}
break
}
if (state.current == null) break
}
}
}
private fun report(type: String, songId: String?) {
val session = _state.value.session ?: return
if (songId == null) return
scope.launch {
api.reportEvents(
session.id,
listOf(
PlaybackEvent(
songId = songId,
type = type,
positionSeconds = _state.value.positionSeconds.toInt(),
),
),
)
}
}
private fun stopPlayback() {
pollJob?.cancel()
player.stop()
_state.update { it.copy(current = null, playing = false, queue = emptyList(), session = null) }
}
private fun cacheDetail(detail: MoodDetail) {
val cached = cache.load()
val details = cached.moodDetails.filterNot { it.mood.id == detail.mood.id } + detail
cache.save(cached.copy(moodDetails = details, moods = cached.moods))
}
private fun message(t: Throwable) {
_state.update {
it.copy(
message = t.friendlyMessage(),
messageIsError = true,
messageId = it.messageId + 1,
)
}
}
}
private fun Throwable.friendlyMessage(): String = when (this) {
is ApiException -> message
else -> message ?: "Something went wrong"
}
private fun Collection<Song>.sortedLibrary(): List<Song> =
sortedWith(compareBy({ it.artist.lowercase() }, { it.album.lowercase() }, { it.trackNumber ?: 0 }))
@@ -0,0 +1,217 @@
package win.taptap.musicmanager.client.ui
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.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material.icons.rounded.LibraryMusic
import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import win.taptap.musicmanager.client.PlatformBackHandler
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.Screen
@Composable
fun App() {
val scope = rememberCoroutineScope()
val store = remember { AppStore(scope) }
val state by store.state.collectAsState()
AudioManagerTheme {
Surface(color = MaterialTheme.colorScheme.background, modifier = Modifier.fillMaxSize()) {
when {
state.booting -> Splash()
!state.authenticated -> LoginScreen(state, store)
else -> MainScreen(state, store)
}
}
}
DisposableEffect(Unit) {
onDispose { store.release() }
}
}
@Composable
private fun Splash() {
Box(
modifier = Modifier
.fillMaxSize()
.background(
Brush.radialGradient(
listOf(Color(0xFF1B2540), MaterialTheme.colorScheme.background),
),
),
contentAlignment = Alignment.Center,
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
"Audio",
fontSize = 34.sp,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onBackground,
)
Text(
"Manager",
fontSize = 34.sp,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary,
)
CircularProgressIndicator(modifier = Modifier.padding(top = 24.dp).size(26.dp))
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun MainScreen(state: AppState, store: AppStore) {
val snackbar = remember { SnackbarHostState() }
var confirmDelete by remember { mutableStateOf(false) }
LaunchedEffect(state.messageId) {
val message = state.message
if (message != null) {
snackbar.showSnackbar(message)
store.clearMessage()
}
}
PlatformBackHandler(enabled = state.screen != Screen.Moods) {
store.openMoods()
}
Scaffold(
containerColor = MaterialTheme.colorScheme.background,
snackbarHost = { SnackbarHost(snackbar) },
topBar = {
TopAppBar(
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.background,
),
navigationIcon = {
if (state.screen != Screen.Moods) {
IconButton(onClick = { store.openMoods() }) {
Icon(Icons.Rounded.ArrowBack, contentDescription = "Back")
}
}
},
title = {
Column {
val title = when (state.screen) {
Screen.Moods -> "Moods"
Screen.MoodDetail -> state.selectedMood?.mood?.name ?: "Mood"
Screen.Library -> "Library & downloads"
Screen.Settings -> "Settings"
}
Text(title, fontWeight = FontWeight.SemiBold)
if (state.offline) {
Text(
"Offline mode",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.tertiary,
)
}
}
},
actions = {
when (state.screen) {
Screen.Moods -> {
IconButton(onClick = { store.refreshAll() }) {
Icon(Icons.Rounded.Refresh, contentDescription = "Refresh")
}
IconButton(onClick = { store.openLibrary() }) {
Icon(Icons.Rounded.LibraryMusic, contentDescription = "Library")
}
IconButton(onClick = { store.openSettings() }) {
Icon(Icons.Rounded.Settings, contentDescription = "Settings")
}
}
Screen.MoodDetail -> {
IconButton(onClick = { confirmDelete = true }) {
Icon(Icons.Rounded.Delete, contentDescription = "Delete mood")
}
}
Screen.Library -> {
IconButton(onClick = { store.openSettings() }) {
Icon(Icons.Rounded.Settings, contentDescription = "Settings")
}
}
Screen.Settings -> Unit
}
},
)
},
bottomBar = {
if (state.current != null) {
PlayerBar(state, store)
}
},
) { padding ->
Box(Modifier.fillMaxSize().padding(padding)) {
when (state.screen) {
Screen.Moods -> MoodsScreen(state, store)
Screen.MoodDetail -> MoodDetailScreen(state, store)
Screen.Library -> LibraryScreen(state, store)
Screen.Settings -> SettingsScreen(state, store)
}
}
}
if (confirmDelete) {
val name = state.selectedMood?.mood?.name ?: "this mood"
AlertDialog(
onDismissRequest = { confirmDelete = false },
title = { Text("Delete mood?") },
text = { Text("\"$name\" and its seeds will be removed. Downloads stay on this device.") },
confirmButton = {
TextButton(
onClick = {
confirmDelete = false
state.selectedMood?.let { store.deleteMood(it.mood.id) }
},
) { Text("Delete", color = MaterialTheme.colorScheme.error) }
},
dismissButton = {
TextButton(onClick = { confirmDelete = false }) { Text("Cancel") }
},
)
}
}
@@ -0,0 +1,275 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.MusicNote
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import kotlin.math.abs
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.decodeImage
import win.taptap.musicmanager.client.store.AppStore
@Composable
fun Cover(
store: AppStore,
albumId: String?,
modifier: Modifier = Modifier,
size: Int = 320,
) {
var bitmap by remember(albumId, size) { mutableStateOf<ImageBitmap?>(null) }
LaunchedEffect(albumId, size) {
if (albumId == null) return@LaunchedEffect
val bytes = store.cover(albumId)
bitmap = bytes?.let { data -> runCatching { decodeImage(data) }.getOrNull() }
}
Box(
modifier = modifier
.clip(RoundedCornerShape(12.dp))
.background(
Brush.linearGradient(
listOf(Color(0xFF28344A), Color(0xFF1A2230)),
),
),
contentAlignment = Alignment.Center,
) {
val image = bitmap
if (image != null) {
Image(
bitmap = image,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
)
} else {
Icon(
Icons.Rounded.MusicNote,
contentDescription = null,
tint = Color(0xFF5E6C84),
modifier = Modifier.size(28.dp),
)
}
}
}
@Composable
fun EmptyState(title: String, subtitle: String? = null, modifier: Modifier = Modifier) {
Column(
modifier = modifier
.fillMaxWidth()
.padding(vertical = 42.dp, horizontal = 20.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
Icon(
Icons.Rounded.MusicNote,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(36.dp),
)
Text(title, style = MaterialTheme.typography.titleMedium)
if (subtitle != null) {
Text(
subtitle,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
fun SectionTitle(text: String, trailing: @Composable (() -> Unit)? = null) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text.uppercase(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.SemiBold,
)
Spacer(Modifier.weight(1f))
trailing?.invoke()
}
}
@Composable
fun SongRow(
store: AppStore,
song: win.taptap.musicmanager.client.api.Song,
onPlay: () -> Unit,
trailing: (@Composable () -> Unit)? = null,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onPlay)
.padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Cover(store, song.albumId, Modifier.size(44.dp), size = 96)
Column(Modifier.weight(1f)) {
Text(
song.title,
style = MaterialTheme.typography.bodyLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
"${song.artist} · ${song.album}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
trailing?.invoke()
}
}
@Composable
fun MoodGradient(name: String): Brush {
val palettes = listOf(
Color(0xFF3B5BDB) to Color(0xFF7048E8),
Color(0xFF0B7285) to Color(0xFF2B8A3E),
Color(0xFF9C36B5) to Color(0xFFC2255C),
Color(0xFFE8590C) to Color(0xFFF08C00),
Color(0xFF1864AB) to Color(0xFF1098AD),
Color(0xFF5F3DC4) to Color(0xFF862E9C),
)
val palette = palettes[abs(name.hashCode()) % palettes.size]
return Brush.linearGradient(listOf(palette.first, palette.second))
}
fun formatDuration(seconds: Int): String {
if (seconds <= 0) return "0:00"
val minutes = seconds / 60
val rest = seconds % 60
return "$minutes:${rest.toString().padStart(2, '0')}"
}
fun formatBytes(bytes: Long): String = when {
bytes >= 1_073_741_824 -> "${(bytes / 1_073_741_824.0).round(1)} GB"
bytes >= 1_048_576 -> "${(bytes / 1_048_576.0).round(1)} MB"
bytes >= 1024 -> "${(bytes / 1024.0).round(0)} KB"
else -> "$bytes B"
}
private fun Double.round(decimals: Int): String {
var value = this
var factor = 1.0
repeat(decimals) { factor *= 10 }
value = kotlin.math.round(value * factor) / factor
val whole = value.toLong()
if (decimals == 0) return whole.toString()
val fraction = kotlin.math.round((value - whole) * factor).toLong()
return "$whole.${fraction.toString().padStart(decimals, '0')}"
}
@Composable
fun MoodPickerDialog(
moods: List<Mood>,
currentMoodId: String?,
onDismiss: () -> Unit,
onSelect: (Mood) -> Unit,
) {
Dialog(onDismissRequest = onDismiss) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 6.dp,
modifier = Modifier.fillMaxWidth().heightIn(max = 520.dp),
) {
Column {
Text(
"Add to mood",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(20.dp),
)
HorizontalDivider()
LazyColumn(Modifier.fillMaxWidth()) {
items(moods, key = { it.id }) { mood ->
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { onSelect(mood) }
.padding(horizontal = 20.dp, vertical = 14.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(mood.name, style = MaterialTheme.typography.bodyLarge)
Text(
if (mood.id == currentMoodId) "Current mood" else "${mood.seedCount} seeds",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (mood.id == currentMoodId) {
Text("Playing", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.secondary)
}
}
}
if (moods.isEmpty()) {
item {
Text(
"No moods yet. Create one first.",
modifier = Modifier.padding(20.dp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
HorizontalDivider()
TextButton(
onClick = onDismiss,
modifier = Modifier.align(Alignment.End).padding(8.dp),
) {
Text("Cancel")
}
}
}
}
}
@@ -0,0 +1,155 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.CheckCircle
import androidx.compose.material.icons.rounded.DeleteOutline
import androidx.compose.material.icons.rounded.Download
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.platformName
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
@Composable
fun LibraryScreen(state: AppState, store: AppStore) {
var query by remember { mutableStateOf("") }
val supported = platformName != "web"
val downloadedSongs = state.library.filter { it.id in state.downloads }
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
item {
OutlinedTextField(
value = query,
onValueChange = { query = it },
singleLine = true,
label = { Text("Search library") },
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
trailingIcon = {
if (state.searching) {
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
}
},
modifier = Modifier.fillMaxWidth(),
)
}
if (state.searchResults.isNotEmpty()) {
item {
SectionTitle("Search results") {
Text(
"${state.searchResults.size}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
items(state.searchResults, key = { "search-${it.id}" }) { song ->
LibrarySongRow(song, state, store, supported)
}
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
}
item {
SectionTitle("Downloads") {
Text(
"${state.downloads.size} tracks · ${formatBytes(store.storageBytes())}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (!supported) {
item {
Text(
"The browser plays from the server and lets the browser manage its cache. Install the Android or desktop app for offline downloads.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else if (downloadedSongs.isEmpty()) {
item {
Text(
"No downloads yet. Search for a song and press the download icon.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else {
items(downloadedSongs, key = { "download-${it.id}" }) { song ->
LibrarySongRow(song, state, store, supported)
}
item {
Text(
"Offline playback uses these files when the server is unreachable.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 8.dp),
)
}
}
}
}
@Composable
private fun LibrarySongRow(song: Song, state: AppState, store: AppStore, supported: Boolean) {
SongRow(store = store, song = song, onPlay = { store.playSong(song) }) {
if (supported) {
when {
song.id in state.downloading -> CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
song.id in state.downloads -> {
IconButton(onClick = { store.toggleDownload(song) }) {
Icon(Icons.Rounded.DeleteOutline, contentDescription = "Delete download")
}
}
else -> {
IconButton(onClick = { store.toggleDownload(song) }) {
Icon(Icons.Rounded.Download, contentDescription = "Download")
}
}
}
}
if (song.id in state.downloads) {
Icon(
Icons.Rounded.CheckCircle,
contentDescription = "Downloaded",
tint = MaterialTheme.colorScheme.secondary,
modifier = Modifier.size(18.dp),
)
}
IconButton(onClick = { store.playSong(song) }) {
Icon(Icons.Rounded.PlayArrow, contentDescription = "Play")
}
}
}
@@ -0,0 +1,155 @@
package win.taptap.musicmanager.client.ui
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.Spacer
import androidx.compose.foundation.layout.fillMaxSize
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.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import win.taptap.musicmanager.client.defaultServerUrl
import win.taptap.musicmanager.client.platformName
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
@Composable
fun LoginScreen(state: AppState, store: AppStore) {
var server by remember { mutableStateOf(state.serverUrl.ifBlank { defaultServerUrl() }) }
var username by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
fun submit() {
if (username.isBlank() || password.isBlank()) return
store.login(server, username, password)
}
Box(
modifier = Modifier
.fillMaxSize()
.background(
Brush.radialGradient(
listOf(Color(0xFF1B2540), MaterialTheme.colorScheme.background),
radius = 1600f,
),
),
contentAlignment = Alignment.Center,
) {
Surface(
shape = RoundedCornerShape(22.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 8.dp,
modifier = Modifier.padding(24.dp).widthIn(max = 420.dp),
) {
Column(
modifier = Modifier.padding(26.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
Row {
Text(
"Audio",
fontSize = 30.sp,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onBackground,
)
Spacer(Modifier.width(6.dp))
Text(
"Manager",
fontSize = 30.sp,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary,
)
}
Text(
"Mood-based streaming. Sign in to your server.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(6.dp))
OutlinedTextField(
value = server,
onValueChange = { server = it },
label = { Text("Server URL") },
placeholder = { Text("https://music.example.com") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = username,
onValueChange = { username = it },
label = { Text("Username") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text("Password") },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { submit() }),
modifier = Modifier.fillMaxWidth(),
)
if (state.message != null && state.messageIsError) {
Text(
state.message,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
)
}
Button(
onClick = { submit() },
enabled = !state.loading && username.isNotBlank() && password.isNotBlank(),
modifier = Modifier.fillMaxWidth(),
) {
if (state.loading) {
CircularProgressIndicator(
modifier = Modifier.size(18.dp),
strokeWidth = 2.dp,
)
} else {
Text("Sign in")
}
}
Text(
"Platform: $platformName",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
@@ -0,0 +1,292 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.RemoveCircleOutline
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
@Composable
fun MoodDetailScreen(state: AppState, store: AppStore) {
val detail = state.selectedMood
if (state.loading && detail == null) {
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
CircularProgressIndicator()
}
return
}
if (detail == null) {
EmptyState("Mood not available", "It may have been deleted, or the server is offline.")
return
}
val mood = detail.mood
var seedQuery by remember { mutableStateOf("") }
var name by remember(mood.id, mood.changedAt) { mutableStateOf(mood.name) }
var description by remember(mood.id, mood.changedAt) { mutableStateOf(mood.description.orEmpty()) }
var genres by remember(mood.id, mood.changedAt) { mutableStateOf(mood.genres.joinToString(", ")) }
var query by remember(mood.id, mood.changedAt) { mutableStateOf(mood.query.orEmpty()) }
var target by remember(mood.id, mood.changedAt) { mutableStateOf(mood.targetSize.toString()) }
var hours by remember(mood.id, mood.changedAt) { mutableStateOf(mood.refreshHours.toString()) }
var yt by remember(mood.id, mood.changedAt) { mutableStateOf(mood.ytEnabled) }
val seedIds = detail.seeds.map { it.song.id }.toSet()
val searchResults = state.searchResults.filterNot { it.id in seedIds }
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
item {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text(
mood.description ?: "Server-driven radio",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Text("${mood.seedCount} seeds", style = MaterialTheme.typography.labelMedium)
Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant)
Text("${mood.targetSize} batch", style = MaterialTheme.typography.labelMedium)
Spacer(Modifier.weight(1f))
Button(onClick = { store.playMood(mood.id) }) {
Icon(Icons.Rounded.PlayArrow, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Play radio")
}
}
if (mood.lastError != null) {
Text(mood.lastError, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}
}
}
}
item {
SectionTitle("Seeds") {
Text(
"${detail.seeds.size}",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (detail.seeds.isEmpty()) {
item {
Text(
"No seeds yet. Add a few songs below; every seed is always part of the radio.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else {
items(detail.seeds, key = { it.song.id }) { seed ->
SongRow(
store = store,
song = seed.song,
onPlay = { store.playSong(seed.song) },
) {
Text(seed.origin, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
IconButton(onClick = { store.removeSeed(mood.id, seed.song.id) }) {
Icon(Icons.Rounded.RemoveCircleOutline, contentDescription = "Remove seed")
}
}
}
}
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Add songs")
}
item {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth(),
) {
OutlinedTextField(
value = seedQuery,
onValueChange = { seedQuery = it },
singleLine = true,
label = { Text("Search your music") },
modifier = Modifier.weight(1f),
)
OutlinedButton(onClick = { store.search(seedQuery) }, enabled = seedQuery.isNotBlank()) {
Text("Search")
}
}
}
if (state.searching) {
item { CircularProgressIndicator(Modifier.size(22.dp)) }
}
items(searchResults.take(12), key = { it.id }) { song ->
SongRow(store = store, song = song, onPlay = { store.playSong(song) }) {
IconButton(onClick = { store.addSeed(mood.id, song.id) }) {
Icon(Icons.Rounded.Add, contentDescription = "Add seed")
}
}
}
if (state.preview.isNotEmpty()) {
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Next batch")
}
items(state.preview, key = { "preview-${it.id}" }) { song ->
SongRow(store = store, song = song, onPlay = { store.playSong(song) }) {
Text(formatDuration(song.duration), style = MaterialTheme.typography.labelSmall)
}
}
}
if (detail.recommendations.isNotEmpty()) {
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Recommendations")
}
items(detail.recommendations, key = { it.videoId }) { recommendation ->
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(recommendation.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
recommendation.artist,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Text(recommendation.state, style = MaterialTheme.typography.labelSmall)
}
}
}
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Settings")
}
item {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = name,
onValueChange = { name = it },
label = { Text("Name") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = description,
onValueChange = { description = it },
label = { Text("Description") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = genres,
onValueChange = { genres = it },
label = { Text("Genres (comma separated)") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = query,
onValueChange = { query = it },
label = { Text("Free-text hint") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = target,
onValueChange = { target = it },
label = { Text("Batch size") },
singleLine = true,
modifier = Modifier.weight(1f),
)
OutlinedTextField(
value = hours,
onValueChange = { hours = it },
label = { Text("Refresh h") },
singleLine = true,
modifier = Modifier.weight(1f),
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text("YT Music discovery", Modifier.weight(1f))
Switch(checked = yt, onCheckedChange = { yt = it })
}
FilledTonalButton(
enabled = !state.saving && name.isNotBlank(),
onClick = {
store.saveMood(
detail = detail,
name = name.trim(),
description = description.trim().takeIf { it.isNotEmpty() },
genres = genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query = query.trim().takeIf { it.isNotEmpty() },
targetSize = target.toIntOrNull() ?: mood.targetSize,
refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
ytEnabled = yt,
)
},
modifier = Modifier.fillMaxWidth(),
) {
Text(if (state.saving) "Saving..." else "Save settings")
}
}
}
item { Spacer(Modifier.size(24.dp)) }
}
}
@@ -0,0 +1,271 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
@Composable
fun MoodsScreen(state: AppState, store: AppStore) {
var creating by remember { mutableStateOf(false) }
Column(Modifier.fillMaxSize()) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(
"Your moods",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.SemiBold,
)
Text(
"Radio is generated live and learns from what you finish or skip.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Button(onClick = { creating = true }) {
Icon(Icons.Rounded.Add, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("New mood")
}
}
if (state.loading && state.moods.isEmpty()) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator()
}
return@Column
}
if (state.moods.isEmpty()) {
EmptyState(
title = "No moods yet",
subtitle = "Create a mood, add a few seed songs, and press play. The server builds the rest.",
modifier = Modifier.fillMaxSize(),
)
} else {
LazyVerticalGrid(
columns = GridCells.Adaptive(250.dp),
contentPadding = PaddingValues(20.dp),
horizontalArrangement = Arrangement.spacedBy(14.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.fillMaxSize(),
) {
items(state.moods, key = { it.id }) { mood ->
MoodCard(
mood = mood,
onOpen = { store.openMood(mood.id) },
onPlay = { store.playMood(mood.id) },
)
}
}
}
}
if (creating) {
CreateMoodDialog(
saving = state.saving,
onDismiss = { creating = false },
onCreate = { name, description, genres, query, target, hours, yt ->
creating = false
store.createMood(name, description, genres, query, target, hours, yt)
},
)
}
}
@Composable
private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
Column(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(18.dp))
.background(MoodGradient(mood.name))
.clickable(onClick = onOpen)
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
mood.name,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = Color.White,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Text(
mood.description ?: mood.genres.joinToString(" · ").ifBlank { "Server-driven radio" },
style = MaterialTheme.typography.bodySmall,
color = Color.White.copy(alpha = 0.78f),
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.height(36.dp),
)
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
"${mood.seedCount} seeds",
style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.85f),
)
if (mood.newRecommendations > 0) {
Spacer(Modifier.width(8.dp))
Text(
"${mood.newRecommendations} picks",
style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.85f),
)
}
Spacer(Modifier.weight(1f))
FilledTonalButton(
onClick = onPlay,
colors = ButtonDefaults.filledTonalButtonColors(
containerColor = Color.White.copy(alpha = 0.16f),
contentColor = Color.White,
),
contentPadding = PaddingValues(horizontal = 14.dp, vertical = 8.dp),
) {
Icon(Icons.Rounded.PlayArrow, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(4.dp))
Text("Play")
}
}
}
}
@Composable
private fun CreateMoodDialog(
saving: Boolean,
onDismiss: () -> Unit,
onCreate: (String, String?, List<String>, String?, Int, Int, Boolean) -> Unit,
) {
var name by remember { mutableStateOf("") }
var description by remember { mutableStateOf("") }
var genres by remember { mutableStateOf("") }
var query by remember { mutableStateOf("") }
var target by remember { mutableStateOf("30") }
var hours by remember { mutableStateOf("24") }
var yt by remember { mutableStateOf(true) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("New mood") },
text = {
Column(
modifier = Modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
OutlinedTextField(
value = name,
onValueChange = { name = it },
label = { Text("Name") },
singleLine = true,
)
OutlinedTextField(
value = description,
onValueChange = { description = it },
label = { Text("Description") },
singleLine = true,
)
OutlinedTextField(
value = genres,
onValueChange = { genres = it },
label = { Text("Genres (comma separated)") },
singleLine = true,
)
OutlinedTextField(
value = query,
onValueChange = { query = it },
label = { Text("Free-text hint") },
singleLine = true,
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = target,
onValueChange = { target = it },
label = { Text("Batch size") },
singleLine = true,
modifier = Modifier.weight(1f),
)
OutlinedTextField(
value = hours,
onValueChange = { hours = it },
label = { Text("Refresh h") },
singleLine = true,
modifier = Modifier.weight(1f),
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text("YT Music discovery", Modifier.weight(1f))
Switch(checked = yt, onCheckedChange = { yt = it })
}
}
},
confirmButton = {
TextButton(
enabled = name.isNotBlank() && !saving,
onClick = {
onCreate(
name.trim(),
description.trim().takeIf { it.isNotEmpty() },
genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query.trim().takeIf { it.isNotEmpty() },
target.toIntOrNull() ?: 30,
hours.toIntOrNull() ?: 24,
yt,
)
},
) { Text("Create") }
},
dismissButton = {
TextButton(onClick = onDismiss) { Text("Cancel") }
},
)
}
@@ -0,0 +1,120 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.material.icons.Icons
import androidx.compose.material.icons.rounded.AddCircleOutline
import androidx.compose.material.icons.rounded.Pause
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.PlaylistAdd
import androidx.compose.material.icons.rounded.SkipNext
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
@Composable
fun PlayerBar(state: AppState, store: AppStore) {
val song = state.current ?: return
var picker by remember { mutableStateOf(false) }
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
Surface(
color = MaterialTheme.colorScheme.surfaceVariant,
tonalElevation = 8.dp,
) {
Column(Modifier.fillMaxWidth()) {
val progress = if (state.durationSeconds > 0) {
(state.positionSeconds / state.durationSeconds).toFloat().coerceIn(0f, 1f)
} else {
0f
}
Slider(
value = dragSeconds ?: progress,
onValueChange = { dragSeconds = it },
onValueChangeFinished = {
dragSeconds?.let { store.seekTo(it * state.durationSeconds) }
dragSeconds = null
},
enabled = store.canSeek(),
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),
)
Row(
modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 8.dp, bottom = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Cover(store, song.albumId, Modifier.size(48.dp), size = 160)
Column(Modifier.weight(1f)) {
Text(
song.title,
style = MaterialTheme.typography.bodyLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
song.artist,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
"${formatDuration(state.positionSeconds.toInt())} / ${formatDuration(state.durationSeconds.toInt())}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = { store.addCurrentToMood(null) }) {
Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood")
}
IconButton(onClick = { picker = true }) {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood")
}
IconButton(onClick = { store.skip() }) {
Icon(Icons.Rounded.SkipNext, contentDescription = "Skip")
}
IconButton(onClick = { store.togglePlayPause() }) {
Icon(
if (state.playing) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,
contentDescription = if (state.playing) "Pause" else "Play",
modifier = Modifier.size(30.dp),
)
}
}
}
}
if (picker) {
MoodPickerDialog(
moods = state.moods,
currentMoodId = state.session?.moodId,
onDismiss = { picker = false },
onSelect = { mood ->
picker = false
store.addCurrentToMood(mood.id)
},
)
}
}
@@ -0,0 +1,132 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.DeleteSweep
import androidx.compose.material.icons.rounded.Logout
import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material.icons.rounded.TravelExplore
import androidx.compose.material3.Button
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import win.taptap.musicmanager.client.platformName
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
@Composable
fun SettingsScreen(state: AppState, store: AppStore) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = androidx.compose.foundation.layout.PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
item {
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text("Account", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text(state.user?.name ?: "Unknown", style = MaterialTheme.typography.bodyLarge)
Text(
if (state.user?.admin == true) "Administrator" else "Listener",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
state.serverUrl,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
item {
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("Library", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text(
"${state.library.size} songs cached · ${state.downloads.size} downloaded · ${formatBytes(store.storageBytes())}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
FilledTonalButton(onClick = { store.refreshAll() }) {
Icon(Icons.Rounded.Refresh, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Sync")
}
if (state.user?.admin == true) {
OutlinedButton(onClick = { store.scanLibrary() }) {
Icon(Icons.Rounded.TravelExplore, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Scan")
}
}
}
if (state.downloads.isNotEmpty()) {
OutlinedButton(onClick = { store.clearDownloads() }) {
Icon(Icons.Rounded.DeleteSweep, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Clear downloads")
}
}
}
}
}
item {
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text(
"AudioManager 0.1.0 · $platformName",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
"Moods are radio: the server chooses the next batch and learns from skips and completions. Add a track to a mood with the two buttons in the player.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
item {
Button(onClick = { store.logout() }, modifier = Modifier.fillMaxWidth()) {
Icon(Icons.Rounded.Logout, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Sign out")
}
}
}
}
@@ -0,0 +1,37 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Typography
import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val DarkScheme = darkColorScheme(
primary = Color(0xFF8BA4FF),
onPrimary = Color(0xFF0B1020),
primaryContainer = Color(0xFF27345C),
onPrimaryContainer = Color(0xFFDCE4FF),
secondary = Color(0xFF5ED6AA),
onSecondary = Color(0xFF042018),
secondaryContainer = Color(0xFF17402F),
onSecondaryContainer = Color(0xFFB8F3DA),
tertiary = Color(0xFFF3B45E),
background = Color(0xFF0D1117),
onBackground = Color(0xFFE6EDF3),
surface = Color(0xFF151B24),
onSurface = Color(0xFFE6EDF3),
surfaceVariant = Color(0xFF202936),
onSurfaceVariant = Color(0xFFA7B4C5),
outline = Color(0xFF34404F),
error = Color(0xFFFF8A80),
onError = Color(0xFF2A0805),
)
@Composable
fun AudioManagerTheme(content: @Composable () -> Unit) {
MaterialTheme(
colorScheme = DarkScheme,
typography = Typography(),
content = content,
)
}
@@ -0,0 +1,114 @@
package win.taptap.musicmanager.client
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.engine.mock.respondError
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import win.taptap.musicmanager.client.api.ApiClient
import win.taptap.musicmanager.client.api.ApiException
import win.taptap.musicmanager.client.api.configuredHttpClient
import win.taptap.musicmanager.client.data.AppStorage
import win.taptap.musicmanager.client.data.CachedState
import win.taptap.musicmanager.client.data.LibraryCache
class ApiClientTest {
private val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json")
@Test
fun `login stores the token and parses moods`() = runTest {
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/auth/login" -> respond(
"""
{"token":"abc123","expiresAt":"2027-01-01T00:00:00Z",
"user":{"name":"alice","admin":true,"musicFolders":[1],"longformFolders":[10]}}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods" -> respond(
"""
{"moods":[{"id":"mo-1","name":"Focus","targetSize":30,"refreshHours":24,
"ytEnabled":true,"createdAt":"now","changedAt":"now","seedCount":2}]}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val client = ApiClient(configuredHttpClient(engine))
val login = client.login("music.example.com", "alice", "secret", "test", "test")
assertEquals("abc123", login.token)
assertEquals("http://music.example.com", client.baseUrl)
val moods = client.moods()
assertEquals(1, moods.size)
assertEquals("Focus", moods.first().name)
assertEquals(2, moods.first().seedCount)
}
@Test
fun `api errors surface the server message`() = runTest {
val engine = MockEngine {
respond(
"""{"error":{"code":"unauthorized","message":"Missing or invalid token"}}""",
HttpStatusCode.Unauthorized,
jsonHeaders,
)
}
val client = ApiClient(configuredHttpClient(engine))
val error = assertFailsWith<ApiException> { client.moods() }
assertEquals(401, error.status)
assertEquals("unauthorized", error.code)
}
@Test
fun `cache round-trips songs and moods`() = runTest {
val storage = MemoryStorage()
val cache = LibraryCache(storage)
assertNull(cache.loadSession())
cache.save(
CachedState(
serverUrl = "http://localhost:8080",
userName = "alice",
revision = "2026-11-14T00:00:00Z",
songs = emptyList(),
moods = emptyList(),
),
)
val loaded = cache.load()
assertEquals("2026-11-14T00:00:00Z", loaded.revision)
assertEquals("alice", loaded.userName)
}
private class MemoryStorage : AppStorage {
private val files = mutableMapOf<String, String>()
override fun read(name: String): String? = files[name]
override fun write(name: String, text: String) {
files[name] = text
}
override fun delete(name: String) {
files.remove(name)
}
override fun saveDownload(songId: String, bytes: ByteArray): String? = null
override fun downloadPath(songId: String): String? = null
override fun listDownloads(): Map<String, Long> = emptyMap()
override fun deleteDownload(songId: String) = Unit
override fun storageUsedBytes(): Long = 0
}
}
@@ -0,0 +1,126 @@
package win.taptap.musicmanager.client
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.net.URI
import javax.sound.sampled.AudioSystem
import javax.sound.sampled.SourceDataLine
import kotlin.concurrent.thread
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.playback.AudioPlayer
/**
* Desktop playback through the MP3SPI decoder and a PCM line. Pause/resume is a
* decoder loop gate, so no audio device is reopened. Seeking is not supported.
*/
class DesktopAudioPlayer : AudioPlayer {
private var input: InputStream? = null
private var line: SourceDataLine? = null
private var worker: Thread? = null
private val lock = Object()
@Volatile private var paused = false
@Volatile private var stopped = false
@Volatile private var finished = false
@Volatile private var framesRead = 0L
private var frameSize = 4
private var frameRate = 44_100f
private var duration = 0.0
override fun play(source: String, song: Song, local: Boolean) {
stop()
finished = false
paused = false
stopped = false
framesRead = 0
duration = song.duration.toDouble()
val raw = if (local) FileInputStream(File(source)) else URI(source).toURL().openStream()
val buffered = BufferedInputStream(raw, 128 * 1024)
input = buffered
val audio = AudioSystem.getAudioInputStream(buffered)
frameSize = audio.format.frameSize.takeIf { it > 0 } ?: 4
frameRate = audio.format.frameRate.takeIf { it > 0 } ?: 44_100f
val info = javax.sound.sampled.DataLine.Info(SourceDataLine::class.java, audio.format)
val dataLine = AudioSystem.getLine(info) as SourceDataLine
dataLine.open(audio.format)
dataLine.start()
line = dataLine
worker = thread(isDaemon = true, name = "audiomanager-player") {
val buffer = ByteArray(16 * 1024)
try {
while (!stopped) {
synchronized(lock) {
while (paused && !stopped) lock.wait()
}
if (stopped) break
val read = audio.read(buffer)
if (read < 0) {
finished = true
break
}
dataLine.write(buffer, 0, read)
framesRead += read.toLong()
}
dataLine.drain()
} catch (_: Throwable) {
// Stopping closes the stream; that is expected.
} finally {
runCatching { dataLine.close() }
runCatching { audio.close() }
runCatching { buffered.close() }
}
}
}
override fun pause() {
paused = true
}
override fun resume() {
synchronized(lock) {
paused = false
lock.notifyAll()
}
}
override fun stop() {
stopped = true
paused = false
synchronized(lock) { lock.notifyAll() }
runCatching { line?.stop() }
runCatching { line?.flush() }
worker?.interrupt()
runCatching { worker?.join(400) }
runCatching { input?.close() }
line = null
input = null
worker = null
}
override fun isPlaying(): Boolean =
!paused && !finished && worker?.isAlive == true
override fun isFinished(): Boolean = finished
override fun positionSeconds(): Double {
val seconds = framesRead.toDouble() / frameSize / frameRate
return seconds.coerceIn(0.0, duration.takeIf { it > 0 } ?: seconds)
}
override fun durationSeconds(): Double = duration
override val canSeek: Boolean = false
override fun seekTo(seconds: Double) = Unit
override fun release() {
stop()
}
}
@@ -0,0 +1,24 @@
package win.taptap.musicmanager.client
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import win.taptap.musicmanager.client.ui.App
fun main() = application {
Window(
onCloseRequest = ::exitApplication,
title = "AudioManager",
state = rememberWindowState(size = DpSize(1100.dp, 820.dp)),
) {
App()
}
}
@Composable
actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) {
// Desktop navigation is explicit; no system back gesture.
}
@@ -0,0 +1,70 @@
package win.taptap.musicmanager.client
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.toComposeImageBitmap
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.cio.CIO
import java.io.File
import win.taptap.musicmanager.client.data.AppStorage
import win.taptap.musicmanager.client.playback.AudioPlayer
actual fun platformEngine(): HttpClientEngine = CIO.create()
actual val platformName: String = "desktop"
actual fun defaultServerUrl(): String = "http://localhost:8080"
actual fun platformStorage(): AppStorage = DesktopStorage()
actual fun createAudioPlayer(): AudioPlayer = DesktopAudioPlayer()
class DesktopStorage : AppStorage {
private val root: File = run {
val base = System.getenv("XDG_DATA_HOME")?.takeIf { it.isNotBlank() }
?: (System.getProperty("user.home") + "/.local/share")
File(base, "AudioManager").apply { mkdirs() }
}
private val downloads = File(root, "downloads").apply { mkdirs() }
override fun read(name: String): String? =
File(root, name).takeIf { it.isFile }?.readText()
override fun write(name: String, text: String) {
root.mkdirs()
File(root, name).writeText(text)
}
override fun delete(name: String) {
File(root, name).delete()
}
override fun saveDownload(songId: String, bytes: ByteArray): String? {
downloads.mkdirs()
val file = File(downloads, "${safeName(songId)}.mp3")
file.writeBytes(bytes)
return file.absolutePath
}
override fun downloadPath(songId: String): String? =
File(downloads, "${safeName(songId)}.mp3").takeIf { it.isFile }?.absolutePath
override fun listDownloads(): Map<String, Long> =
downloads.listFiles()
?.filter { it.isFile && it.extension == "mp3" }
?.associate { it.nameWithoutExtension to it.length() }
?: emptyMap()
override fun deleteDownload(songId: String) {
File(downloads, "${safeName(songId)}.mp3").delete()
}
override fun storageUsedBytes(): Long =
downloads.listFiles()?.sumOf { it.length() } ?: 0L
private fun safeName(songId: String): String =
songId.map { if (it.isLetterOrDigit() || it == '-' || it == '_') it else '_' }.joinToString("")
}
actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull()
@@ -0,0 +1,43 @@
package win.taptap.musicmanager.client
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.toComposeImageBitmap
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.js.Js
import kotlinx.browser.window
import org.w3c.dom.Storage
import win.taptap.musicmanager.client.data.AppStorage
import win.taptap.musicmanager.client.playback.AudioPlayer
actual fun platformEngine(): HttpClientEngine = Js.create()
actual val platformName: String = "web"
actual fun defaultServerUrl(): String = window.location.origin
actual fun platformStorage(): AppStorage = WebStorage()
actual fun createAudioPlayer(): AudioPlayer = WebAudioPlayer()
class WebStorage : AppStorage {
private val storage: Storage get() = window.localStorage
override fun read(name: String): String? = storage.getItem("am:$name")
override fun write(name: String, text: String) = storage.setItem("am:$name", text)
override fun delete(name: String) = storage.removeItem("am:$name")
override fun saveDownload(songId: String, bytes: ByteArray): String? = null
override fun downloadPath(songId: String): String? = null
override fun listDownloads(): Map<String, Long> = emptyMap()
override fun deleteDownload(songId: String) = Unit
override fun storageUsedBytes(): Long = 0L
}
@Composable
actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) {
// Browser back is not intercepted.
}
actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull()
@@ -0,0 +1,52 @@
package win.taptap.musicmanager.client
import kotlinx.browser.document
import org.w3c.dom.HTMLAudioElement
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.playback.AudioPlayer
class WebAudioPlayer : AudioPlayer {
private val audio: HTMLAudioElement =
(document.createElement("audio") as HTMLAudioElement).apply {
preload = "auto"
}
override fun play(source: String, song: Song, local: Boolean) {
audio.src = source
audio.play()
}
override fun pause() {
audio.pause()
}
override fun resume() {
audio.play()
}
override fun stop() {
audio.pause()
audio.removeAttribute("src")
audio.load()
}
override fun isPlaying(): Boolean = !audio.paused && !audio.ended
override fun isFinished(): Boolean = audio.ended
override fun positionSeconds(): Double = audio.currentTime.takeIf { it.isFinite() } ?: 0.0
override fun durationSeconds(): Double =
audio.duration.takeIf { it.isFinite() && it > 0 } ?: 0.0
override val canSeek: Boolean = true
override fun seekTo(seconds: Double) {
audio.currentTime = seconds
}
override fun release() {
stop()
}
}
@@ -0,0 +1,13 @@
package win.taptap.musicmanager.client
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.window.ComposeViewport
import kotlinx.browser.document
import win.taptap.musicmanager.client.ui.App
@OptIn(ExperimentalComposeUiApi::class)
fun main() {
ComposeViewport(document.body!!) {
App()
}
}
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AudioManager</title>
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
background: #0d1117;
overflow: hidden;
}
#composeApp {
width: 100%;
height: 100%;
}
canvas { outline: none; }
</style>
</head>
<body>
<script type="application/javascript" src="composeApp.js"></script>
</body>
</html>