Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6c1dae3c3 | ||
|
|
b1ccfc9ee1 | ||
|
|
4d5a97cdac | ||
|
|
8e737fae2e | ||
|
|
8cf77f156d | ||
|
|
1e3dac4e47 |
No files matched your search
@@ -37,9 +37,8 @@ a server-driven radio session and songs are added from Deezer or YouTube Music.
|
||||
same mood session.
|
||||
- Playback events are reported automatically (`started`, `completed`, `skipped`)
|
||||
so the server learns.
|
||||
- Two add-to-mood actions in the player:
|
||||
- **Add to current mood** (the mood of the active radio session)
|
||||
- **Choose another mood** (picker)
|
||||
- **Add to mood is one tap** in the bottom player and the full-screen player.
|
||||
Choosing a different mood stays in the overflow/picker.
|
||||
- A queue sheet from the player: the current track is pinned, upcoming tracks
|
||||
can be reordered by **long-press and drag** or removed. Changes are persisted
|
||||
locally.
|
||||
@@ -48,15 +47,27 @@ a server-driven radio session and songs are added from Deezer or YouTube Music.
|
||||
- **Headset/Bluetooth next and previous** and the media notification's skip /
|
||||
back buttons use the same queue rules as the in-app controls; they no longer
|
||||
seek inside the single ExoPlayer item.
|
||||
- The bottom player keeps the cover and title/artist readable on narrow phones;
|
||||
add-to-mood actions moved into the overflow menu.
|
||||
- The bottom player keeps the cover and title/artist readable on narrow phones.
|
||||
Tapping it opens the **full-screen player**: large artwork, scrubber, transport,
|
||||
add-to-mood, queue, sleep timer and Up next.
|
||||
- **Audio consistency**: the server measures every track's integrated loudness
|
||||
with ffmpeg and stores a gain (target `-16 LUFS`); the app applies it per
|
||||
track. The player shows the source and bitrate, and settings explain when the
|
||||
Deezer ARL is limited to 128 kbps.
|
||||
- **Gapless playback** on Android with an optional 0–8 s fade between tracks.
|
||||
- **Scrubbing**: the progress slider can be dragged on every platform. Android and
|
||||
web seek natively; desktop restarts the decoder at the requested position.
|
||||
- **Mood settings**: name, description, discovery hint, genres, collection share,
|
||||
active recommendation count (0–30), and refresh interval.
|
||||
- **Mood settings** live on their own screen: name, description, discovery hint,
|
||||
genres, source, collection share, recommendations, refresh interval, a
|
||||
**Keep this mood offline** switch, and Delete at the bottom.
|
||||
- **Downloads** screen for device-side copies: play, delete, clear, storage
|
||||
usage.
|
||||
- **Sleep timer** (15/30/45/60/90 minutes) that pauses playback. On Android the
|
||||
- **Diagnostics**: warnings, errors and crashes are kept in a 500-entry local
|
||||
ring buffer and uploaded in batches (tokens and passwords are redacted). The
|
||||
full-screen Settings screen shows the queue, last upload and a Send now action;
|
||||
`scripts/logs.sh` on the server prints or clears stored entries.
|
||||
- **Sleep timer** (15/30/45/60/90 minutes or **finish this track**) that pauses
|
||||
playback. On Android the
|
||||
pause is scheduled inside the media service, so it still fires when the app is
|
||||
backgrounded or the task is swiped away.
|
||||
- Mood cache: moods and details are stored locally so the app opens instantly
|
||||
@@ -72,7 +83,7 @@ a server-driven radio session and songs are added from Deezer or YouTube Music.
|
||||
|
||||
## Screens
|
||||
|
||||
`Moods | Mood Detail | Search | Downloads | Settings`
|
||||
`Moods | Mood Detail | Mood settings | Search | Downloads | Settings | Now playing`
|
||||
|
||||
- **Moods** — grid with song and pick counts, create, global search.
|
||||
- **Mood Detail** — songs, add music, recommendations, next batch, settings.
|
||||
@@ -80,7 +91,8 @@ a server-driven radio session and songs are added from Deezer or YouTube Music.
|
||||
downloaded badges and an inline Downloading… / Added / Failed status per
|
||||
result, so the keyboard never hides the feedback.
|
||||
- **Downloads** — offline files and storage usage.
|
||||
- **Settings** — account, server URL, offline storage, sign out.
|
||||
- **Settings** — account, server URL, audio (normalization, crossfade, source
|
||||
quality), offline storage and auto-synced moods, sign out.
|
||||
|
||||
There is no Library tab, no Longform tab and no global shuffle.
|
||||
|
||||
@@ -200,7 +212,7 @@ Tagged builds (`v*`) publish to internal testing from CI. The Gitea secrets are:
|
||||
| `ANDROID_KEY_PASSWORD` | key password |
|
||||
| `PLAY_SERVICE_ACCOUNT_JSON` | contents of the service account JSON |
|
||||
|
||||
Then `git tag v0.3.3 && git push --tags` builds, signs and uploads the bundle.
|
||||
Then `git tag v0.4.3 && git push --tags` builds, signs and uploads the bundle.
|
||||
Gradle Play Publisher asks Play for the next free `versionCode`
|
||||
(`ResolutionStrategy.AUTO`), so only the tag/version name needs to change.
|
||||
|
||||
@@ -264,9 +276,11 @@ scripts/build-ci-image.sh 3
|
||||
|
||||
## Known limitations
|
||||
|
||||
- The media notification exposes play/pause and seeking. Queue actions (skip,
|
||||
add to mood) stay in the app because the mood session and its events belong to
|
||||
the server.
|
||||
- The media notification exposes play/pause, skip and back from the timeline.
|
||||
Adding to a mood stays in the app because the session and its events belong to
|
||||
the server. The queue lives in the Android media service, but the *next batch*
|
||||
still comes from the app process; if the process is killed, the known queue
|
||||
keeps working but nothing more is fetched.
|
||||
- Desktop playback supports seeking by reopening the decoder at the requested
|
||||
position. MP3s are decoded to 16-bit PCM before the line is opened, because
|
||||
Java Sound has no line for the compressed format.
|
||||
|
||||
@@ -41,7 +41,7 @@ val hasUploadKey = uploadKeyStore?.exists() == true &&
|
||||
val appVersionCode = (System.getenv("VERSION_CODE") ?: localProperties.getProperty("VERSION_CODE") ?: "1").toInt()
|
||||
val appVersionName = System.getenv("VERSION_NAME")
|
||||
?: localProperties.getProperty("VERSION_NAME")
|
||||
?: "0.3.3"
|
||||
?: "0.4.3"
|
||||
|
||||
kotlin {
|
||||
androidTarget {
|
||||
@@ -78,6 +78,7 @@ kotlin {
|
||||
implementation("io.ktor:ktor-client-content-negotiation:3.1.2")
|
||||
implementation("io.ktor:ktor-serialization-kotlinx-json:3.1.2")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.2")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.2")
|
||||
}
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
<application
|
||||
android:name=".AudioManagerApplication"
|
||||
android:allowBackup="true"
|
||||
android:label="AudioManager"
|
||||
android:supportsRtl="true"
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package win.taptap.musicmanager.client
|
||||
|
||||
import android.app.Application
|
||||
import win.taptap.musicmanager.client.logging.AppLog
|
||||
|
||||
/**
|
||||
* Initializes diagnostics before the activity exists and records the one case
|
||||
* the in-app logger cannot: an uncaught exception. The line is persisted
|
||||
* synchronously and uploaded on the next launch.
|
||||
*/
|
||||
class AudioManagerApplication : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
AndroidContextHolder.context = applicationContext
|
||||
AppLog.init(platformStorage())
|
||||
|
||||
val previous = Thread.getDefaultUncaughtExceptionHandler()
|
||||
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
|
||||
runCatching {
|
||||
AppLog.error("crash", "Uncaught exception on ${thread.name}", error)
|
||||
AppLog.flushNow()
|
||||
}
|
||||
previous?.uncaughtException(thread, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package win.taptap.musicmanager.client
|
||||
|
||||
import android.content.Context
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.audio.AudioProcessor
|
||||
import androidx.media3.common.audio.AudioProcessor.AudioFormat
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.exoplayer.DefaultRenderersFactory
|
||||
import androidx.media3.exoplayer.audio.AudioSink
|
||||
import androidx.media3.exoplayer.audio.DefaultAudioSink
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import kotlin.math.pow
|
||||
|
||||
/**
|
||||
* Applies the server's per-track loudness gain to 16-bit PCM.
|
||||
*
|
||||
* ExoPlayer's own volume is limited to 0..1, so it can only attenuate. Measuring
|
||||
* tracks against -16 LUFS needs small positive gains on quiet recordings too;
|
||||
* scaling the PCM samples supports both directions while leaving the hardware
|
||||
* volume untouched.
|
||||
*/
|
||||
@UnstableApi
|
||||
class GainAudioProcessor : AudioProcessor {
|
||||
|
||||
@Volatile
|
||||
var gain: Float = 1f
|
||||
|
||||
private var inputFormat: AudioFormat = AudioFormat.NOT_SET
|
||||
private var outputFormat: AudioFormat = AudioFormat.NOT_SET
|
||||
private var buffer: ByteBuffer = AudioProcessor.EMPTY_BUFFER
|
||||
private var endOfStream = false
|
||||
|
||||
override fun configure(inputAudioFormat: AudioFormat): AudioFormat {
|
||||
if (inputAudioFormat.encoding != C.ENCODING_PCM_16BIT) {
|
||||
// Float output or compressed passthrough: leave the samples alone.
|
||||
inputFormat = AudioFormat.NOT_SET
|
||||
outputFormat = AudioFormat.NOT_SET
|
||||
return AudioFormat.NOT_SET
|
||||
}
|
||||
inputFormat = inputAudioFormat
|
||||
outputFormat = inputAudioFormat
|
||||
return outputFormat
|
||||
}
|
||||
|
||||
override fun isActive(): Boolean = inputFormat != AudioFormat.NOT_SET
|
||||
|
||||
override fun queueInput(inputBuffer: ByteBuffer) {
|
||||
val value = gain
|
||||
val output = ByteBuffer.allocateDirect(inputBuffer.remaining())
|
||||
.order(ByteOrder.nativeOrder())
|
||||
while (inputBuffer.remaining() >= 2) {
|
||||
val sample = inputBuffer.short.toInt()
|
||||
val scaled = (sample * value).toInt()
|
||||
.coerceIn(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt())
|
||||
output.putShort(scaled.toShort())
|
||||
}
|
||||
output.flip()
|
||||
buffer = output
|
||||
}
|
||||
|
||||
override fun queueEndOfStream() {
|
||||
endOfStream = true
|
||||
}
|
||||
|
||||
override fun getOutput(): ByteBuffer = buffer
|
||||
|
||||
override fun isEnded(): Boolean = endOfStream && !buffer.hasRemaining()
|
||||
|
||||
override fun flush() {
|
||||
buffer = AudioProcessor.EMPTY_BUFFER
|
||||
endOfStream = false
|
||||
}
|
||||
|
||||
override fun reset() {
|
||||
buffer = AudioProcessor.EMPTY_BUFFER
|
||||
endOfStream = false
|
||||
inputFormat = AudioFormat.NOT_SET
|
||||
outputFormat = AudioFormat.NOT_SET
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun fromDb(db: Double): Float =
|
||||
10.0.pow(db / 20.0).toFloat().coerceIn(0f, 4f)
|
||||
}
|
||||
}
|
||||
|
||||
/** Wires the gain processor into ExoPlayer's audio sink. */
|
||||
@UnstableApi
|
||||
class GainRenderersFactory(
|
||||
context: Context,
|
||||
private val gainProcessor: GainAudioProcessor,
|
||||
) : DefaultRenderersFactory(context) {
|
||||
|
||||
override fun buildAudioSink(
|
||||
context: Context,
|
||||
enableFloatOutput: Boolean,
|
||||
enableAudioTrackPlaybackParams: Boolean,
|
||||
): AudioSink = DefaultAudioSink.Builder(context)
|
||||
.setAudioProcessors(arrayOf(gainProcessor))
|
||||
// The processor works on 16-bit PCM; forcing float output would bypass it.
|
||||
.setEnableFloatOutput(false)
|
||||
.setEnableAudioTrackPlaybackParams(enableAudioTrackPlaybackParams)
|
||||
.build()
|
||||
}
|
||||
+89
-40
@@ -10,8 +10,8 @@ import androidx.media3.common.MediaMetadata
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.session.MediaController
|
||||
import androidx.media3.session.SessionToken
|
||||
import win.taptap.musicmanager.client.api.Song
|
||||
import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||
import win.taptap.musicmanager.client.playback.PlaybackTrack
|
||||
|
||||
/**
|
||||
* Client side of [PlaybackService]. The controller is created asynchronously;
|
||||
@@ -55,42 +55,55 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
|
||||
)
|
||||
}
|
||||
|
||||
override fun play(
|
||||
source: String,
|
||||
song: Song,
|
||||
local: Boolean,
|
||||
artworkUri: String?,
|
||||
artworkBytes: ByteArray?,
|
||||
) {
|
||||
override fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double) {
|
||||
if (tracks.isEmpty()) return
|
||||
finished = false
|
||||
withController { controller ->
|
||||
val uri = if (local) Uri.fromFile(java.io.File(source)) else Uri.parse(source)
|
||||
val metadata = MediaMetadata.Builder()
|
||||
.setTitle(song.title)
|
||||
.setArtist(song.artist)
|
||||
.setAlbumTitle(song.album)
|
||||
.apply {
|
||||
if (artworkBytes != null && artworkBytes.isNotEmpty()) {
|
||||
setArtworkData(
|
||||
artworkBytes,
|
||||
MediaMetadata.PICTURE_TYPE_FRONT_COVER,
|
||||
)
|
||||
} else {
|
||||
setArtworkUri(artworkUri?.let(Uri::parse))
|
||||
val items = tracks.map(::mediaItem)
|
||||
val index = startIndex.coerceIn(tracks.indices)
|
||||
val positionMs = (startAtSeconds * 1_000).toLong().coerceAtLeast(0L)
|
||||
withController { current ->
|
||||
current.setMediaItems(items, index, positionMs)
|
||||
current.prepare()
|
||||
current.play()
|
||||
}
|
||||
}
|
||||
.build()
|
||||
val item = MediaItem.Builder()
|
||||
.setUri(uri)
|
||||
.setMimeType("audio/mpeg")
|
||||
.setMediaMetadata(metadata)
|
||||
.build()
|
||||
|
||||
controller.setMediaItem(item)
|
||||
controller.prepare()
|
||||
controller.play()
|
||||
override fun appendToQueue(tracks: List<PlaybackTrack>) {
|
||||
if (tracks.isEmpty()) return
|
||||
val items = tracks.map(::mediaItem)
|
||||
withController { current -> current.addMediaItems(items) }
|
||||
}
|
||||
|
||||
override fun moveInQueue(fromIndex: Int, toIndex: Int) {
|
||||
withController { current -> current.moveMediaItem(fromIndex, toIndex) }
|
||||
}
|
||||
|
||||
override fun removeAt(index: Int) {
|
||||
withController { current -> current.removeMediaItem(index) }
|
||||
}
|
||||
|
||||
override fun playIndex(index: Int, startAtSeconds: Double) {
|
||||
finished = false
|
||||
val positionMs = (startAtSeconds * 1_000).toLong().coerceAtLeast(0L)
|
||||
withController { current ->
|
||||
if (index in 0 until current.mediaItemCount) {
|
||||
current.seekTo(index, positionMs)
|
||||
current.play()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun skipToNext() {
|
||||
withController { current -> current.seekToNextMediaItem() }
|
||||
}
|
||||
|
||||
override fun skipToPrevious(restartAfterSeconds: Double) {
|
||||
withController { current -> current.seekToPreviousMediaItem() }
|
||||
}
|
||||
|
||||
override fun currentIndex(): Int = controller?.currentMediaItemIndex ?: 0
|
||||
|
||||
override fun queueSize(): Int = controller?.mediaItemCount ?: 0
|
||||
|
||||
override fun pause() {
|
||||
withController { it.pause() }
|
||||
@@ -126,19 +139,26 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
|
||||
withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) }
|
||||
}
|
||||
|
||||
override fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) {
|
||||
PlaybackCommands.onNext = onNext
|
||||
PlaybackCommands.onPrevious = onPrevious
|
||||
override val supportsCrossfade: Boolean = true
|
||||
|
||||
override fun setCrossfadeSeconds(seconds: Int) {
|
||||
val args = Bundle().apply { putInt(CROSSFADE_SECONDS, seconds.coerceAtLeast(0)) }
|
||||
withController { current ->
|
||||
runCatching { current.sendCustomCommand(CROSSFADE_COMMAND, args) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun scheduleSleepTimer(seconds: Long?): Boolean {
|
||||
val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) }
|
||||
val send: (MediaController) -> Boolean = { current ->
|
||||
runCatching { current.sendCustomCommand(SLEEP_TIMER_COMMAND, args) }.isSuccess
|
||||
val send: (MediaController) -> Unit = { current ->
|
||||
runCatching { current.sendCustomCommand(SLEEP_TIMER_COMMAND, args) }
|
||||
}
|
||||
val current = controller
|
||||
if (current != null && connected) return send(current)
|
||||
synchronized(pending) { pending.addLast { controller -> send(controller) } }
|
||||
if (current != null && connected) {
|
||||
send(current)
|
||||
return true
|
||||
}
|
||||
synchronized(pending) { pending.addLast(send) }
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -150,13 +170,42 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
|
||||
synchronized(pending) { pending.clear() }
|
||||
}
|
||||
|
||||
private fun mediaItem(track: PlaybackTrack): MediaItem {
|
||||
val uri = if (track.local) {
|
||||
Uri.fromFile(java.io.File(track.source))
|
||||
} else {
|
||||
Uri.parse(track.source)
|
||||
}
|
||||
val metadata = MediaMetadata.Builder()
|
||||
.setTitle(track.song.title)
|
||||
.setArtist(track.song.artist)
|
||||
.setAlbumTitle(track.song.album)
|
||||
.setExtras(
|
||||
Bundle().apply { putDouble(GAIN_DB_KEY, track.gainDb ?: 0.0) },
|
||||
)
|
||||
.apply {
|
||||
val bytes = track.artworkBytes
|
||||
if (bytes != null && bytes.isNotEmpty()) {
|
||||
setArtworkData(bytes, MediaMetadata.PICTURE_TYPE_FRONT_COVER)
|
||||
} else if (!track.artworkUri.isNullOrBlank()) {
|
||||
setArtworkUri(Uri.parse(track.artworkUri))
|
||||
}
|
||||
}
|
||||
.build()
|
||||
return MediaItem.Builder()
|
||||
.setUri(uri)
|
||||
.setMimeType("audio/mpeg")
|
||||
.setMediaMetadata(metadata)
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun withController(block: (MediaController) -> Unit) {
|
||||
val current = controller
|
||||
if (current != null && connected) {
|
||||
block(current)
|
||||
} else {
|
||||
// The first playback request can be followed immediately by a seek
|
||||
// (long-form resume). Keep every action, not only the last one.
|
||||
// The first playback request can be followed immediately by a seek.
|
||||
// Keep every action, not only the last one.
|
||||
synchronized(pending) { pending.addLast(block) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package win.taptap.musicmanager.client
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
@@ -21,6 +23,15 @@ actual fun platformStorage(): AppStorage = AndroidStorage(AndroidContextHolder.c
|
||||
|
||||
actual fun createAudioPlayer(): AudioPlayer = MediaControllerAudioPlayer(AndroidContextHolder.context)
|
||||
|
||||
actual fun isUnmeteredNetwork(): Boolean {
|
||||
val manager = AndroidContextHolder.context
|
||||
.getSystemService(ConnectivityManager::class.java) ?: return true
|
||||
val network = manager.activeNetwork ?: return false
|
||||
val capabilities = manager.getNetworkCapabilities(network) ?: return false
|
||||
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
|
||||
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
|
||||
}
|
||||
|
||||
class AndroidStorage(context: Context) : AppStorage {
|
||||
|
||||
private val root = File(context.filesDir, "audiomanager").apply { mkdirs() }
|
||||
@@ -124,3 +135,7 @@ class AndroidStorage(context: Context) : AppStorage {
|
||||
|
||||
actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap()
|
||||
|
||||
private val LOG_LOCK = Any()
|
||||
|
||||
internal actual fun <T> withLogLock(block: () -> T): T = synchronized(LOG_LOCK) { block() }
|
||||
@@ -1,27 +0,0 @@
|
||||
package win.taptap.musicmanager.client
|
||||
|
||||
/**
|
||||
* Bridge between the media session in [PlaybackService] and the queue that
|
||||
* lives in the app's store. Media3 sends headset/Bluetooth next and previous
|
||||
* here instead of seeking the single-item ExoPlayer.
|
||||
*/
|
||||
internal object PlaybackCommands {
|
||||
@Volatile
|
||||
var onNext: (() -> Unit)? = null
|
||||
|
||||
@Volatile
|
||||
var onPrevious: (() -> Unit)? = null
|
||||
|
||||
/** Returns false when no store is attached, so the default handling applies. */
|
||||
fun next(): Boolean {
|
||||
val handler = onNext ?: return false
|
||||
handler()
|
||||
return true
|
||||
}
|
||||
|
||||
fun previous(): Boolean {
|
||||
val handler = onPrevious ?: return false
|
||||
handler()
|
||||
return true
|
||||
}
|
||||
}
|
||||
+107
-71
@@ -5,11 +5,10 @@ import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.KeyEvent
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.media3.common.AudioAttributes
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.ForwardingPlayer
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.session.MediaSession
|
||||
@@ -24,12 +23,22 @@ internal const val SLEEP_TIMER_ACTION = "win.taptap.musicmanager.client.SLEEP_TI
|
||||
internal const val SLEEP_TIMER_SECONDS = "seconds"
|
||||
internal val SLEEP_TIMER_COMMAND = SessionCommand(SLEEP_TIMER_ACTION, Bundle.EMPTY)
|
||||
|
||||
/** Custom session command that sets the crossfade/fade length. */
|
||||
internal const val CROSSFADE_ACTION = "win.taptap.musicmanager.client.CROSSFADE"
|
||||
internal const val CROSSFADE_SECONDS = "seconds"
|
||||
internal val CROSSFADE_COMMAND = SessionCommand(CROSSFADE_ACTION, Bundle.EMPTY)
|
||||
|
||||
/** MediaItem metadata key carrying the server-measured gain in dB. */
|
||||
internal const val GAIN_DB_KEY = "gainDb"
|
||||
|
||||
/**
|
||||
* Hosts playback in a foreground service so audio continues when the activity
|
||||
* is backgrounded, the screen is off, or the task is swiped away.
|
||||
*
|
||||
* Media3 publishes the media notification and exposes the session to lock-screen
|
||||
* controls, Bluetooth/headset buttons and Android Auto.
|
||||
* The queue lives here as a Media3 timeline. That lets the notification,
|
||||
* headset buttons and Android Auto advance tracks even when the UI process is
|
||||
* gone, and makes gapless playback possible because ExoPlayer prepares the next
|
||||
* item ahead of time.
|
||||
*/
|
||||
class PlaybackService : MediaSessionService() {
|
||||
|
||||
@@ -37,10 +46,42 @@ class PlaybackService : MediaSessionService() {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val sleepTimer = Runnable { mediaSession?.player?.pause() }
|
||||
|
||||
@Volatile private var crossfadeSeconds = 0
|
||||
@Volatile private var fade = 1f
|
||||
private val gainProcessor = GainAudioProcessor()
|
||||
private var player: ExoPlayer? = null
|
||||
|
||||
private val fadeLoop = object : Runnable {
|
||||
override fun run() {
|
||||
val exo = player ?: return
|
||||
if (!exo.isPlaying) {
|
||||
handler.postDelayed(this, FADE_TICK_MS)
|
||||
return
|
||||
}
|
||||
val fadeMs = crossfadeSeconds * 1_000L
|
||||
if (fadeMs > 0) {
|
||||
val position = exo.currentPosition.coerceAtLeast(0L)
|
||||
val duration = exo.duration
|
||||
val fadeOut = if (duration > 0) {
|
||||
((duration - position).toFloat() / fadeMs).coerceIn(0f, 1f)
|
||||
} else {
|
||||
1f
|
||||
}
|
||||
val fadeIn = (position.toFloat() / fadeMs).coerceIn(0f, 1f)
|
||||
fade = minOf(fadeOut, fadeIn)
|
||||
} else {
|
||||
fade = 1f
|
||||
}
|
||||
exo.volume = fade.coerceIn(0f, 1f)
|
||||
handler.postDelayed(this, FADE_TICK_MS)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
val exoPlayer = ExoPlayer.Builder(this)
|
||||
.setRenderersFactory(GainRenderersFactory(this, gainProcessor))
|
||||
.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(C.USAGE_MEDIA)
|
||||
@@ -53,44 +94,47 @@ class PlaybackService : MediaSessionService() {
|
||||
.apply {
|
||||
setWakeMode(C.WAKE_MODE_NETWORK)
|
||||
}
|
||||
player = exoPlayer
|
||||
|
||||
// ExoPlayer holds one item at a time; the queue lives in the app. Advertise
|
||||
// next/previous so the notification and Android Auto show the buttons and
|
||||
// route them to the queue instead of seeking inside the single item.
|
||||
val player = object : ForwardingPlayer(exoPlayer) {
|
||||
override fun getAvailableCommands(): Player.Commands =
|
||||
super.getAvailableCommands().buildUpon()
|
||||
.addAll(
|
||||
Player.COMMAND_SEEK_TO_NEXT,
|
||||
Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM,
|
||||
Player.COMMAND_SEEK_TO_PREVIOUS,
|
||||
Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM,
|
||||
)
|
||||
.build()
|
||||
|
||||
override fun isCommandAvailable(command: Int): Boolean =
|
||||
command == Player.COMMAND_SEEK_TO_NEXT ||
|
||||
command == Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM ||
|
||||
command == Player.COMMAND_SEEK_TO_PREVIOUS ||
|
||||
command == Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM ||
|
||||
super.isCommandAvailable(command)
|
||||
|
||||
override fun seekToNext() {
|
||||
if (!PlaybackCommands.next()) super.seekToNext()
|
||||
}
|
||||
|
||||
override fun seekToNextMediaItem() {
|
||||
if (!PlaybackCommands.next()) super.seekToNextMediaItem()
|
||||
}
|
||||
|
||||
// Media3's notification/next/previous map onto the real timeline. The
|
||||
// only custom rule is Android's usual previous behaviour: after two
|
||||
// seconds of playback it restarts the current item.
|
||||
val sessionPlayer = object : ForwardingPlayer(exoPlayer) {
|
||||
override fun seekToPrevious() {
|
||||
if (!PlaybackCommands.previous()) super.seekToPrevious()
|
||||
if (exoPlayer.currentPosition > PREVIOUS_RESTART_MS) {
|
||||
exoPlayer.seekTo(0)
|
||||
} else if (exoPlayer.hasPreviousMediaItem()) {
|
||||
exoPlayer.seekToPreviousMediaItem()
|
||||
} else {
|
||||
exoPlayer.seekTo(0)
|
||||
}
|
||||
}
|
||||
|
||||
override fun seekToPreviousMediaItem() {
|
||||
if (!PlaybackCommands.previous()) super.seekToPreviousMediaItem()
|
||||
if (exoPlayer.currentPosition > PREVIOUS_RESTART_MS) {
|
||||
exoPlayer.seekTo(0)
|
||||
} else if (exoPlayer.hasPreviousMediaItem()) {
|
||||
exoPlayer.seekToPreviousMediaItem()
|
||||
} else {
|
||||
exoPlayer.seekTo(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
exoPlayer.addListener(
|
||||
object : Player.Listener {
|
||||
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
|
||||
gainProcessor.gain = gainOf(mediaItem)
|
||||
fade = if (crossfadeSeconds > 0) 0f else 1f
|
||||
exoPlayer.volume = fade.coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
override fun onIsPlayingChanged(isPlaying: Boolean) {
|
||||
handler.removeCallbacks(fadeLoop)
|
||||
if (isPlaying) handler.post(fadeLoop)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
val sessionActivity = PendingIntent.getActivity(
|
||||
this,
|
||||
@@ -99,7 +143,7 @@ class PlaybackService : MediaSessionService() {
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
mediaSession = MediaSession.Builder(this, player)
|
||||
mediaSession = MediaSession.Builder(this, sessionPlayer)
|
||||
.setSessionActivity(sessionActivity)
|
||||
.setCallback(object : MediaSession.Callback {
|
||||
override fun onConnect(
|
||||
@@ -109,64 +153,49 @@ class PlaybackService : MediaSessionService() {
|
||||
val commands = MediaSession.ConnectionResult.DEFAULT_SESSION_AND_LIBRARY_COMMANDS
|
||||
.buildUpon()
|
||||
.add(SLEEP_TIMER_COMMAND)
|
||||
.add(CROSSFADE_COMMAND)
|
||||
.build()
|
||||
return MediaSession.ConnectionResult.AcceptedResultBuilder(session)
|
||||
.setAvailableSessionCommands(commands)
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* A headset skip must move the app's queue, not seek the one
|
||||
* item ExoPlayer holds. Returning true consumes the event.
|
||||
*/
|
||||
override fun onMediaButtonEvent(
|
||||
session: MediaSession,
|
||||
controllerInfo: MediaSession.ControllerInfo,
|
||||
intent: Intent,
|
||||
): Boolean {
|
||||
if (intent.action != Intent.ACTION_MEDIA_BUTTON) return false
|
||||
val event = IntentCompat.getParcelableExtra(
|
||||
intent,
|
||||
Intent.EXTRA_KEY_EVENT,
|
||||
KeyEvent::class.java,
|
||||
) ?: return false
|
||||
return when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_MEDIA_NEXT -> when (event.action) {
|
||||
KeyEvent.ACTION_DOWN -> PlaybackCommands.next()
|
||||
KeyEvent.ACTION_UP -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> when (event.action) {
|
||||
KeyEvent.ACTION_DOWN -> PlaybackCommands.previous()
|
||||
KeyEvent.ACTION_UP -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCustomCommand(
|
||||
session: MediaSession,
|
||||
controller: MediaSession.ControllerInfo,
|
||||
customCommand: SessionCommand,
|
||||
args: Bundle,
|
||||
): ListenableFuture<SessionResult> {
|
||||
if (customCommand.customAction != SLEEP_TIMER_ACTION) {
|
||||
return super.onCustomCommand(session, controller, customCommand, args)
|
||||
}
|
||||
when (customCommand.customAction) {
|
||||
SLEEP_TIMER_ACTION -> {
|
||||
handler.removeCallbacks(sleepTimer)
|
||||
val seconds = args.getLong(SLEEP_TIMER_SECONDS, 0L)
|
||||
if (seconds > 0) {
|
||||
handler.postDelayed(sleepTimer, seconds * 1_000)
|
||||
}
|
||||
}
|
||||
|
||||
CROSSFADE_ACTION -> {
|
||||
crossfadeSeconds = args.getInt(CROSSFADE_SECONDS, 0).coerceAtLeast(0)
|
||||
fade = if (crossfadeSeconds > 0) 0f else 1f
|
||||
exoPlayer.volume = fade.coerceIn(0f, 1f)
|
||||
handler.removeCallbacks(fadeLoop)
|
||||
if (exoPlayer.isPlaying) handler.post(fadeLoop)
|
||||
}
|
||||
|
||||
else -> return super.onCustomCommand(session, controller, customCommand, args)
|
||||
}
|
||||
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
|
||||
}
|
||||
})
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun gainOf(item: MediaItem?): Float {
|
||||
val db = item?.mediaMetadata?.extras?.getDouble(GAIN_DB_KEY, 0.0) ?: 0.0
|
||||
return GainAudioProcessor.fromDb(db)
|
||||
}
|
||||
|
||||
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? =
|
||||
mediaSession
|
||||
|
||||
@@ -179,11 +208,18 @@ class PlaybackService : MediaSessionService() {
|
||||
|
||||
override fun onDestroy() {
|
||||
handler.removeCallbacks(sleepTimer)
|
||||
handler.removeCallbacks(fadeLoop)
|
||||
mediaSession?.run {
|
||||
player.release()
|
||||
release()
|
||||
}
|
||||
mediaSession = null
|
||||
player = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val PREVIOUS_RESTART_MS = 2_000L
|
||||
const val FADE_TICK_MS = 100L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package win.taptap.musicmanager.client
|
||||
|
||||
/** One place for the version shown in Settings and sent with diagnostics. */
|
||||
const val APP_VERSION = "0.4.3"
|
||||
@@ -16,3 +16,15 @@ expect fun platformStorage(): AppStorage
|
||||
expect fun createAudioPlayer(): AudioPlayer
|
||||
|
||||
expect fun decodeImage(bytes: ByteArray): ImageBitmap?
|
||||
|
||||
/**
|
||||
* True when bulk downloads may run. Android checks for an unmetered network;
|
||||
* desktop and web have no metered flag and return true.
|
||||
*/
|
||||
expect fun isUnmeteredNetwork(): Boolean
|
||||
|
||||
/**
|
||||
* Serializes the shared log buffer. Android and desktop have real threads;
|
||||
* Wasm is single-threaded and runs the block directly.
|
||||
*/
|
||||
internal expect fun <T> withLogLock(block: () -> T): T
|
||||
@@ -0,0 +1,6 @@
|
||||
package win.taptap.musicmanager.client
|
||||
|
||||
import kotlinx.datetime.Clock
|
||||
|
||||
/** Epoch milliseconds, shared by the log buffer, settings and the uploader. */
|
||||
fun currentTimeMillis(): Long = Clock.System.now().toEpochMilliseconds()
|
||||
@@ -25,6 +25,7 @@ import io.ktor.http.isSuccess
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import io.ktor.utils.io.ByteReadChannel
|
||||
import kotlinx.serialization.json.Json
|
||||
import win.taptap.musicmanager.client.logging.AppLog
|
||||
|
||||
fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engine) {
|
||||
expectSuccess = false
|
||||
@@ -184,6 +185,18 @@ class ApiClient(private val http: HttpClient) {
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun info(): ServerInfo = get("/info")
|
||||
|
||||
/** Uploads a diagnostics batch; returns how many entries the server kept. */
|
||||
suspend fun uploadLogs(batch: ClientLogBatch): Int =
|
||||
parse<ClientLogsAccepted>(
|
||||
http.post(url("/logs")) {
|
||||
auth()
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(batch)
|
||||
},
|
||||
).accepted
|
||||
|
||||
suspend fun search(
|
||||
query: String,
|
||||
limit: Int = 10,
|
||||
@@ -343,11 +356,24 @@ class ApiClient(private val http: HttpClient) {
|
||||
}
|
||||
|
||||
private suspend fun error(response: HttpResponse): ApiException {
|
||||
val status = response.status.value
|
||||
val requestId = response.headers["X-Request-Id"]
|
||||
// Path only: query strings can carry the media token.
|
||||
val method = response.call.request.method.value
|
||||
val path = response.call.request.url.encodedPath
|
||||
if (status >= 500) {
|
||||
AppLog.warn(
|
||||
"api",
|
||||
"$method $path failed with $status" +
|
||||
(requestId?.let { " (request $it)" } ?: ""),
|
||||
)
|
||||
}
|
||||
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})",
|
||||
status = status,
|
||||
code = body?.error?.code ?: "http_$status",
|
||||
message = body?.error?.message ?: "Request failed ($status)",
|
||||
requestId = requestId,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,8 +8,13 @@ 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)
|
||||
class ApiException(
|
||||
val status: Int,
|
||||
val code: String,
|
||||
override val message: String,
|
||||
/** Server request id from `X-Request-Id`, when the response carried one. */
|
||||
val requestId: String? = null,
|
||||
) : RuntimeException(message)
|
||||
|
||||
@Serializable
|
||||
data class LoginRequest(
|
||||
@@ -45,10 +50,43 @@ data class Song(
|
||||
val size: Long = 0,
|
||||
val suffix: String = "mp3",
|
||||
val thumbnail: String? = null,
|
||||
/** Server-measured loudness and the gain to apply; null when not analyzed. */
|
||||
val loudnessLufs: Double? = null,
|
||||
val gainDb: Double? = null,
|
||||
) {
|
||||
val subtitle: String get() = album?.takeIf { it.isNotBlank() } ?: artist
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class ClientLogEntry(
|
||||
val timestamp: Long = 0,
|
||||
val level: String,
|
||||
val tag: String,
|
||||
val message: String,
|
||||
val detail: String? = null,
|
||||
val sessionId: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ClientLogBatch(
|
||||
val deviceId: String,
|
||||
val platform: String,
|
||||
val appVersion: String,
|
||||
val entries: List<ClientLogEntry>,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ClientLogsAccepted(val accepted: Int)
|
||||
|
||||
@Serializable
|
||||
data class ServerInfo(
|
||||
val defaultSource: String = "deezer",
|
||||
val deezerQuality: Int = 0,
|
||||
val loudnessEnabled: Boolean = false,
|
||||
val loudnessTargetLufs: Double = -16.0,
|
||||
val clientLogRetentionDays: Int = 14,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Mood(
|
||||
val id: String,
|
||||
|
||||
@@ -32,6 +32,20 @@ data class CachedState(
|
||||
}
|
||||
}
|
||||
|
||||
/** Client-only preferences that are not part of the server profile. */
|
||||
@Serializable
|
||||
data class ClientSettings(
|
||||
/** Moods kept downloaded on this device and auto-synced. */
|
||||
val offlineMoods: Set<String> = emptySet(),
|
||||
val normalizationEnabled: Boolean = true,
|
||||
/** 0 = gapless; other values are fade lengths in seconds. */
|
||||
val crossfadeSeconds: Int = 0,
|
||||
/** Upload warnings and errors to the server for later debugging. */
|
||||
val diagnosticsEnabled: Boolean = true,
|
||||
/** Stable random id so the server can group one device's batches. */
|
||||
val deviceId: String = "",
|
||||
)
|
||||
|
||||
/** The queue survives a restart so the next launch can resume where it stopped. */
|
||||
@Serializable
|
||||
data class PlaybackSnapshot(
|
||||
@@ -70,6 +84,15 @@ class AppCache(private val storage: AppStorage) {
|
||||
write(CACHE_FILE, json.encodeToString(state))
|
||||
}
|
||||
|
||||
fun loadSettings(): ClientSettings =
|
||||
read(SETTINGS_FILE)?.let {
|
||||
runCatching { json.decodeFromString<ClientSettings>(it) }.getOrNull()
|
||||
} ?: ClientSettings()
|
||||
|
||||
fun saveSettings(settings: ClientSettings) {
|
||||
write(SETTINGS_FILE, json.encodeToString(settings))
|
||||
}
|
||||
|
||||
fun loadPlayback(): PlaybackSnapshot? =
|
||||
read(PLAYBACK_FILE)?.let {
|
||||
runCatching { json.decodeFromString<PlaybackSnapshot>(it) }.getOrNull()
|
||||
@@ -86,6 +109,7 @@ class AppCache(private val storage: AppStorage) {
|
||||
fun clear() {
|
||||
delete(CACHE_FILE)
|
||||
delete(PLAYBACK_FILE)
|
||||
delete(SETTINGS_FILE)
|
||||
}
|
||||
|
||||
// Web storage can be blocked (Safari private mode) or full. Cache failure
|
||||
@@ -102,5 +126,6 @@ class AppCache(private val storage: AppStorage) {
|
||||
const val SESSION_FILE = "session.json"
|
||||
const val CACHE_FILE = "mood-cache.json"
|
||||
const val PLAYBACK_FILE = "playback.json"
|
||||
const val SETTINGS_FILE = "settings.json"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package win.taptap.musicmanager.client.logging
|
||||
|
||||
import kotlin.random.Random
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import win.taptap.musicmanager.client.APP_VERSION
|
||||
import win.taptap.musicmanager.client.currentTimeMillis
|
||||
import win.taptap.musicmanager.client.data.AppStorage
|
||||
import win.taptap.musicmanager.client.platformName
|
||||
import win.taptap.musicmanager.client.withLogLock
|
||||
|
||||
enum class LogLevel(val label: String, val severity: Int) {
|
||||
DEBUG("debug", 0),
|
||||
INFO("info", 1),
|
||||
WARN("warn", 2),
|
||||
ERROR("error", 3),
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class LogRecord(
|
||||
val id: Long,
|
||||
val timestamp: Long,
|
||||
val level: String,
|
||||
val tag: String,
|
||||
val message: String,
|
||||
val detail: String? = null,
|
||||
val sessionId: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class StoredLogs(
|
||||
val nextId: Long = 1,
|
||||
val owner: String? = null,
|
||||
val entries: List<LogRecord> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Small, persistent diagnostics buffer.
|
||||
*
|
||||
* The buffer is a ring: info and above (debug is opt-in) is kept up to
|
||||
* [MAX_ENTRIES], persisted after a short debounce, and flushed immediately for
|
||||
* warnings and errors so a crash cannot lose the line that explains it. Bearing
|
||||
* tokens, passwords and ARLs are redacted before anything is written or sent.
|
||||
*
|
||||
* Logging must never break playback: every storage operation is best-effort.
|
||||
*/
|
||||
object AppLog {
|
||||
|
||||
const val FILE = "logs.json"
|
||||
const val MAX_ENTRIES = 500
|
||||
|
||||
private const val MAX_MESSAGE = 2_000
|
||||
private const val MAX_DETAIL = 8_000
|
||||
private const val MAX_TAG = 48
|
||||
private const val FLUSH_DELAY_MS = 1_500L
|
||||
|
||||
private val json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
encodeDefaults = true
|
||||
explicitNulls = false
|
||||
}
|
||||
|
||||
private val bearer = Regex("""(?i)\b(bearer\s+)[A-Za-z0-9._~+/=-]{8,}""")
|
||||
private val authorization = Regex("""(?i)\b(authorization\s*:\s*)[^\r\n]+""")
|
||||
private val querySecret = Regex(
|
||||
"""(?i)(\b(?:token|access_token|password|passwd|arl|key)=)[^&\s"'<>]+""",
|
||||
)
|
||||
private val jsonSecret = Regex(
|
||||
"""(?i)("(?:token|access_token|password|arl|key)"\s*:\s*")[^"]*(")""",
|
||||
)
|
||||
|
||||
private var storage: AppStorage? = null
|
||||
private var scope: CoroutineScope? = null
|
||||
private var flushJob: Job? = null
|
||||
private var entries = mutableListOf<LogRecord>()
|
||||
private var nextId = 1L
|
||||
private var owner: String? = null
|
||||
private var collecting = true
|
||||
private var minimum = LogLevel.INFO
|
||||
private var sessionId = newSessionId()
|
||||
|
||||
/** Safe to call more than once; the first storage wins. */
|
||||
fun attach(storage: AppStorage, scope: CoroutineScope) {
|
||||
if (this.storage == null) {
|
||||
init(storage)
|
||||
}
|
||||
this.scope = scope
|
||||
}
|
||||
|
||||
fun init(storage: AppStorage) {
|
||||
withLogLock {
|
||||
this.storage = storage
|
||||
val stored = runCatching {
|
||||
storage.read(FILE)?.let { json.decodeFromString<StoredLogs>(it) }
|
||||
}.getOrNull()
|
||||
entries = stored?.entries?.toMutableList() ?: mutableListOf()
|
||||
nextId = maxOf(
|
||||
stored?.nextId ?: 1L,
|
||||
(entries.maxOfOrNull { it.id } ?: 0L) + 1,
|
||||
)
|
||||
owner = stored?.owner
|
||||
}
|
||||
info("app", "Started AudioManager $APP_VERSION on $platformName")
|
||||
}
|
||||
|
||||
fun setCollecting(enabled: Boolean) {
|
||||
collecting = enabled
|
||||
}
|
||||
|
||||
fun setMinimumLevel(level: LogLevel) {
|
||||
minimum = level
|
||||
}
|
||||
|
||||
/** Clears the buffer when a different account signs in on this device. */
|
||||
fun setOwner(name: String?) {
|
||||
val clear = withLogLock {
|
||||
val changed = owner != null && name != null && owner != name
|
||||
if (changed) {
|
||||
entries.clear()
|
||||
nextId = 1
|
||||
}
|
||||
owner = name
|
||||
changed
|
||||
}
|
||||
if (clear) flushNow()
|
||||
}
|
||||
|
||||
fun ownerName(): String? = withLogLock { owner }
|
||||
|
||||
fun debug(tag: String, message: String, error: Throwable? = null) =
|
||||
log(LogLevel.DEBUG, tag, message, error)
|
||||
|
||||
fun info(tag: String, message: String, error: Throwable? = null) =
|
||||
log(LogLevel.INFO, tag, message, error)
|
||||
|
||||
fun warn(tag: String, message: String, error: Throwable? = null) =
|
||||
log(LogLevel.WARN, tag, message, error)
|
||||
|
||||
fun error(tag: String, message: String, error: Throwable? = null) =
|
||||
log(LogLevel.ERROR, tag, message, error)
|
||||
|
||||
/** Oldest entries first; the uploader takes a prefix and removes it on success. */
|
||||
fun pending(limit: Int = 100): List<LogRecord> =
|
||||
withLogLock { entries.take(limit.coerceAtLeast(1)) }
|
||||
|
||||
fun pendingCount(): Int = withLogLock { entries.size }
|
||||
|
||||
fun markUploaded(ids: Set<Long>) {
|
||||
if (ids.isEmpty()) return
|
||||
withLogLock { entries.removeAll { it.id in ids } }
|
||||
flushNow()
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
withLogLock {
|
||||
entries.clear()
|
||||
nextId = 1
|
||||
owner = null
|
||||
}
|
||||
runCatching { storage?.delete(FILE) }
|
||||
}
|
||||
|
||||
fun flushNow() {
|
||||
val target = storage ?: return
|
||||
val snapshot = withLogLock {
|
||||
StoredLogs(nextId = nextId, owner = owner, entries = entries.toList())
|
||||
}
|
||||
runCatching { target.write(FILE, json.encodeToString(snapshot)) }
|
||||
}
|
||||
|
||||
/** Removes tokens and passwords from a line; also used by tests. */
|
||||
fun redact(value: String): String = value
|
||||
.replace(bearer) { match -> match.groupValues[1] + "***" }
|
||||
.replace(authorization) { match -> match.groupValues[1] + "***" }
|
||||
.replace(querySecret) { match -> match.groupValues[1] + "***" }
|
||||
.replace(jsonSecret) { match -> match.groupValues[1] + "***" + match.groupValues[2] }
|
||||
|
||||
private fun log(level: LogLevel, tag: String, message: String, error: Throwable?) {
|
||||
if (!collecting || level.severity < minimum.severity) return
|
||||
|
||||
val cleanTag = redact(tag).trim().take(MAX_TAG).ifBlank { "app" }
|
||||
val cleanMessage = redact(message).trim().take(MAX_MESSAGE).ifBlank { "(empty)" }
|
||||
val cleanDetail = error
|
||||
?.let { redact(it.stackTraceToString()).take(MAX_DETAIL) }
|
||||
?.takeIf { it.isNotBlank() }
|
||||
|
||||
withLogLock {
|
||||
entries += LogRecord(
|
||||
id = nextId++,
|
||||
timestamp = currentTimeMillis(),
|
||||
level = level.label,
|
||||
tag = cleanTag,
|
||||
message = cleanMessage,
|
||||
detail = cleanDetail,
|
||||
sessionId = sessionId,
|
||||
)
|
||||
while (entries.size > MAX_ENTRIES) entries.removeAt(0)
|
||||
}
|
||||
|
||||
// Console output is redacted too: logcat and desktop stderr are just as
|
||||
// readable as the uploaded copy.
|
||||
println("${level.label.uppercase()}/$cleanTag: $cleanMessage")
|
||||
|
||||
if (level.severity >= LogLevel.WARN.severity) {
|
||||
flushNow()
|
||||
} else {
|
||||
scheduleFlush()
|
||||
}
|
||||
}
|
||||
|
||||
private fun scheduleFlush() {
|
||||
val parent = scope
|
||||
if (parent == null) {
|
||||
flushNow()
|
||||
return
|
||||
}
|
||||
if (flushJob?.isActive == true) return
|
||||
flushJob = parent.launch {
|
||||
delay(FLUSH_DELAY_MS)
|
||||
flushJob = null
|
||||
flushNow()
|
||||
}
|
||||
}
|
||||
|
||||
private fun newSessionId(): String = buildString {
|
||||
append("run-")
|
||||
repeat(2) { append(Random.nextInt().toUInt().toString(16).padStart(8, '0')) }
|
||||
}
|
||||
}
|
||||
+36
-19
@@ -2,20 +2,41 @@ package win.taptap.musicmanager.client.playback
|
||||
|
||||
import win.taptap.musicmanager.client.api.Song
|
||||
|
||||
/**
|
||||
* One entry in the playback timeline. The store resolves the stream or local
|
||||
* file and holds the metadata the service needs for the notification.
|
||||
*/
|
||||
data class PlaybackTrack(
|
||||
val song: Song,
|
||||
/** HTTP stream URL or a local file path. */
|
||||
val source: String,
|
||||
val local: Boolean,
|
||||
val artworkUri: String? = null,
|
||||
/** Cached cover for offline playback; avoids a network fetch in the notification. */
|
||||
val artworkBytes: ByteArray? = null,
|
||||
/** Server-measured gain; null leaves the track untouched. */
|
||||
val gainDb: Double? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* The timeline is owned by the player so Android's media service can keep
|
||||
* advancing tracks when the UI process is gone. The store mirrors
|
||||
* [currentIndex] and the song list it last supplied.
|
||||
*/
|
||||
interface AudioPlayer {
|
||||
fun play(
|
||||
source: String,
|
||||
song: Song,
|
||||
local: Boolean,
|
||||
artworkUri: String? = null,
|
||||
artworkBytes: ByteArray? = null,
|
||||
)
|
||||
/** Replaces the timeline and starts at [startIndex]. */
|
||||
fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double = 0.0)
|
||||
fun appendToQueue(tracks: List<PlaybackTrack>)
|
||||
fun moveInQueue(fromIndex: Int, toIndex: Int)
|
||||
fun removeAt(index: Int)
|
||||
fun playIndex(index: Int, startAtSeconds: Double = 0.0)
|
||||
fun skipToNext()
|
||||
fun skipToPrevious(restartAfterSeconds: Double = 2.0)
|
||||
fun currentIndex(): Int
|
||||
fun queueSize(): Int
|
||||
|
||||
fun pause()
|
||||
fun resume()
|
||||
fun stop()
|
||||
@@ -25,21 +46,17 @@ interface AudioPlayer {
|
||||
fun durationSeconds(): Double
|
||||
val canSeek: Boolean
|
||||
fun seekTo(seconds: Double)
|
||||
fun release()
|
||||
|
||||
/** Crossfade length in seconds; 0 means gapless. Platforms may ignore it. */
|
||||
fun setCrossfadeSeconds(seconds: Int) = Unit
|
||||
val supportsCrossfade: Boolean get() = false
|
||||
|
||||
/**
|
||||
* Pauses playback after [seconds], or cancels a pending timer with null.
|
||||
* Returns true when the platform scheduled the pause itself, so it still
|
||||
* fires when the UI is gone (Android background playback). Callers keep
|
||||
* their own countdown for the UI either way.
|
||||
* fires when the UI is gone (Android background playback).
|
||||
*/
|
||||
fun scheduleSleepTimer(seconds: Long?): Boolean = false
|
||||
|
||||
/**
|
||||
* Routes hardware transport buttons (headset/Bluetooth next and previous)
|
||||
* to the app's own queue. Android wires this to its MediaSession; other
|
||||
* platforms ignore it. Null clears the handlers.
|
||||
*/
|
||||
fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) = Unit
|
||||
fun release()
|
||||
}
|
||||
|
||||
+753
-200
File diff suppressed because it is too large.
Load diff
@@ -103,7 +103,6 @@ private fun Splash() {
|
||||
@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
|
||||
@@ -114,7 +113,7 @@ private fun MainScreen(state: AppState, store: AppStore) {
|
||||
}
|
||||
|
||||
PlatformBackHandler(enabled = state.screen != Screen.Moods) {
|
||||
store.openMoods()
|
||||
store.back()
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
@@ -127,7 +126,7 @@ private fun MainScreen(state: AppState, store: AppStore) {
|
||||
),
|
||||
navigationIcon = {
|
||||
if (state.screen != Screen.Moods) {
|
||||
IconButton(onClick = { store.openMoods() }) {
|
||||
IconButton(onClick = { store.back() }) {
|
||||
Icon(Icons.Rounded.ArrowBack, contentDescription = "Back")
|
||||
}
|
||||
}
|
||||
@@ -137,9 +136,11 @@ private fun MainScreen(state: AppState, store: AppStore) {
|
||||
val title = when (state.screen) {
|
||||
Screen.Moods -> "Moods"
|
||||
Screen.MoodDetail -> state.selectedMood?.mood?.name ?: "Mood"
|
||||
Screen.MoodSettings -> "Mood settings"
|
||||
Screen.Search -> "Add music"
|
||||
Screen.Downloads -> "Downloads"
|
||||
Screen.Settings -> "Settings"
|
||||
Screen.NowPlaying -> "Now playing"
|
||||
}
|
||||
Text(title, fontWeight = FontWeight.SemiBold)
|
||||
if (state.offline) {
|
||||
@@ -168,11 +169,11 @@ private fun MainScreen(state: AppState, store: AppStore) {
|
||||
}
|
||||
}
|
||||
Screen.MoodDetail -> {
|
||||
IconButton(onClick = { confirmDelete = true }) {
|
||||
Icon(Icons.Rounded.Delete, contentDescription = "Delete mood")
|
||||
IconButton(onClick = { store.openMoodSettings() }) {
|
||||
Icon(Icons.Rounded.Settings, contentDescription = "Mood settings")
|
||||
}
|
||||
}
|
||||
Screen.Search -> Unit
|
||||
Screen.MoodSettings, Screen.NowPlaying, Screen.Search -> Unit
|
||||
Screen.Downloads -> {
|
||||
IconButton(onClick = { store.openSettings() }) {
|
||||
Icon(Icons.Rounded.Settings, contentDescription = "Settings")
|
||||
@@ -184,7 +185,7 @@ private fun MainScreen(state: AppState, store: AppStore) {
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
if (state.current != null) {
|
||||
if (state.current != null && state.screen != Screen.NowPlaying) {
|
||||
PlayerBar(state, store)
|
||||
}
|
||||
},
|
||||
@@ -193,35 +194,12 @@ private fun MainScreen(state: AppState, store: AppStore) {
|
||||
when (state.screen) {
|
||||
Screen.Moods -> MoodsScreen(state, store)
|
||||
Screen.MoodDetail -> MoodDetailScreen(state, store)
|
||||
Screen.MoodSettings -> MoodSettingsScreen(state, store)
|
||||
Screen.Search -> SearchScreen(state, store)
|
||||
Screen.Downloads -> DownloadsScreen(state, store)
|
||||
Screen.Settings -> SettingsScreen(state, store)
|
||||
Screen.NowPlaying -> NowPlayingScreen(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 recommendation history will be removed. " +
|
||||
"Unused downloads are deleted from the server.",
|
||||
)
|
||||
},
|
||||
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") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
+7
-146
@@ -24,6 +24,7 @@ import androidx.compose.material.icons.rounded.PlayArrow
|
||||
import androidx.compose.material.icons.rounded.Refresh
|
||||
import androidx.compose.material.icons.rounded.RemoveCircleOutline
|
||||
import androidx.compose.material.icons.rounded.Search
|
||||
import androidx.compose.material.icons.rounded.Settings
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
@@ -78,15 +79,6 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
||||
}
|
||||
|
||||
val mood = detail.mood
|
||||
var name by remember(mood.id) { mutableStateOf(mood.name) }
|
||||
var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) }
|
||||
var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) }
|
||||
var query by remember(mood.id) { mutableStateOf(mood.query.orEmpty()) }
|
||||
var source by remember(mood.id) { mutableStateOf(mood.source) }
|
||||
var sourceMenu by remember { mutableStateOf(false) }
|
||||
var collectionPercent by remember(mood.id) { mutableStateOf(mood.collectionPercent.toFloat()) }
|
||||
var recommendations by remember(mood.id) { mutableStateOf(mood.recommendationCount.toFloat()) }
|
||||
var hours by remember(mood.id) { mutableStateOf(mood.refreshHours.toString()) }
|
||||
|
||||
val inFlight = mood.recommendationDownloading +
|
||||
detail.recommendations.count {
|
||||
@@ -183,6 +175,11 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Add music")
|
||||
}
|
||||
OutlinedButton(onClick = { store.openMoodSettings() }) {
|
||||
Icon(Icons.Rounded.Settings, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Settings")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,144 +229,8 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
||||
}
|
||||
}
|
||||
|
||||
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("Discovery hint") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Download source", style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
"Search, recommendations and downloads use this catalog.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Box {
|
||||
OutlinedButton(onClick = { sourceMenu = true }) {
|
||||
Text(sourceLabel(source))
|
||||
}
|
||||
DropdownMenu(
|
||||
expanded = sourceMenu,
|
||||
onDismissRequest = { sourceMenu = false },
|
||||
) {
|
||||
listOf("deezer", "youtube").forEach { option ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(sourceLabel(option)) },
|
||||
onClick = {
|
||||
sourceMenu = false
|
||||
source = option
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (source != mood.source) {
|
||||
Text(
|
||||
"Changing the source clears active recommendations and refills them.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.tertiary,
|
||||
)
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
"Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Slider(
|
||||
value = collectionPercent,
|
||||
onValueChange = { collectionPercent = it },
|
||||
valueRange = 0f..100f,
|
||||
steps = 9,
|
||||
)
|
||||
Text(
|
||||
"Each queue slot rolls this share; when one pool runs out the other fills in.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
"Active recommendations: ${recommendations.roundToInt()}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Slider(
|
||||
value = recommendations,
|
||||
onValueChange = { recommendations = it },
|
||||
valueRange = 0f..30f,
|
||||
steps = 29,
|
||||
)
|
||||
Text(
|
||||
"Downloaded picks that count as active slots (0 turns discovery off).",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
OutlinedTextField(
|
||||
value = hours,
|
||||
onValueChange = { hours = it },
|
||||
label = { Text("Refresh interval (hours)") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
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() },
|
||||
source = source,
|
||||
collectionPercent = collectionPercent.roundToInt(),
|
||||
recommendationCount = recommendations.roundToInt(),
|
||||
refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
|
||||
)
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(if (state.saving) "Saving..." else "Save settings")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item { Spacer(Modifier.size(24.dp)) }
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+354
@@ -0,0 +1,354 @@
|
||||
package win.taptap.musicmanager.client.ui
|
||||
|
||||
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.LazyColumn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Delete
|
||||
import androidx.compose.material.icons.rounded.DownloadDone
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Slider
|
||||
import androidx.compose.material3.Surface
|
||||
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.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlin.math.roundToInt
|
||||
import win.taptap.musicmanager.client.store.AppState
|
||||
import win.taptap.musicmanager.client.store.AppStore
|
||||
import win.taptap.musicmanager.client.store.sourceLabel
|
||||
|
||||
/**
|
||||
* Dedicated mood settings screen. Keeping the form out of the mood page makes
|
||||
* the collection the focus and gives destructive actions their own place at the
|
||||
* bottom instead of the top bar.
|
||||
*/
|
||||
@Composable
|
||||
fun MoodSettingsScreen(state: AppState, store: AppStore) {
|
||||
val detail = state.selectedMood
|
||||
if (detail == null) {
|
||||
EmptyState("Mood not available", "Open a mood first.")
|
||||
return
|
||||
}
|
||||
val mood = detail.mood
|
||||
var name by remember(mood.id) { mutableStateOf(mood.name) }
|
||||
var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) }
|
||||
var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) }
|
||||
var query by remember(mood.id) { mutableStateOf(mood.query.orEmpty()) }
|
||||
var source by remember(mood.id) { mutableStateOf(mood.source) }
|
||||
var sourceMenu by remember { mutableStateOf(false) }
|
||||
var collectionPercent by remember(mood.id) { mutableStateOf(mood.collectionPercent.toFloat()) }
|
||||
var recommendations by remember(mood.id) { mutableStateOf(mood.recommendationCount.toFloat()) }
|
||||
var hours by remember(mood.id) { mutableStateOf(mood.refreshHours.toString()) }
|
||||
var confirmDelete by remember { mutableStateOf(false) }
|
||||
val offline = mood.id in state.offlineMoods
|
||||
val offlineDownloaded = detail.songs.count { it.song.id in state.downloads }
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(20.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
item {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Text(
|
||||
mood.name,
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Text(
|
||||
"${mood.songCount} songs · ${mood.collectionPercent}% collection",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
SectionTitle("Details")
|
||||
}
|
||||
|
||||
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("Discovery hint") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
SectionTitle("Downloads")
|
||||
}
|
||||
|
||||
item {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Download source", style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
"Search, recommendations and downloads use this catalog.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Box {
|
||||
OutlinedButton(onClick = { sourceMenu = true }) {
|
||||
Text(sourceLabel(source))
|
||||
}
|
||||
DropdownMenu(
|
||||
expanded = sourceMenu,
|
||||
onDismissRequest = { sourceMenu = false },
|
||||
) {
|
||||
listOf("deezer", "youtube").forEach { option ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(sourceLabel(option)) },
|
||||
onClick = {
|
||||
sourceMenu = false
|
||||
source = option
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (source != mood.source) {
|
||||
Text(
|
||||
"Changing the source clears active recommendations and refills them.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.tertiary,
|
||||
)
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Rounded.DownloadDone,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Keep this mood offline", style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
Text(
|
||||
if (offline) {
|
||||
"$offlineDownloaded of ${detail.songs.size} downloaded · " +
|
||||
"new songs sync on Wi-Fi"
|
||||
} else {
|
||||
"Downloads every song and keeps new additions in sync on Wi-Fi."
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = offline,
|
||||
onCheckedChange = { store.setMoodOffline(mood.id, it) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
SectionTitle("Mixing")
|
||||
}
|
||||
|
||||
item {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
"Collection share: ${collectionPercent.roundToInt()}% · " +
|
||||
"${100 - collectionPercent.roundToInt()}% recommendations",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Slider(
|
||||
value = collectionPercent,
|
||||
onValueChange = { collectionPercent = it },
|
||||
valueRange = 0f..100f,
|
||||
steps = 9,
|
||||
)
|
||||
Text(
|
||||
"Each queue slot rolls this share; when one pool runs out the other fills in.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
"Active recommendations: ${recommendations.roundToInt()}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Slider(
|
||||
value = recommendations,
|
||||
onValueChange = { recommendations = it },
|
||||
valueRange = 0f..30f,
|
||||
steps = 29,
|
||||
)
|
||||
Text(
|
||||
"Downloaded picks that count as active slots (0 turns discovery off).",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
OutlinedTextField(
|
||||
value = hours,
|
||||
onValueChange = { hours = it },
|
||||
label = { Text("Refresh interval (hours)") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
|
||||
item {
|
||||
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() },
|
||||
source = source,
|
||||
collectionPercent = collectionPercent.roundToInt(),
|
||||
recommendationCount = recommendations.roundToInt(),
|
||||
refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
|
||||
)
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
if (state.saving) {
|
||||
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
Text(if (state.saving) "Saving..." else "Save settings")
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
HorizontalDivider()
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(
|
||||
"Deleting a mood removes it for everyone who can see it. Downloaded files " +
|
||||
"shared with other moods are kept.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Button(
|
||||
onClick = { confirmDelete = true },
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onErrorContainer,
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Icon(Icons.Rounded.Delete, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Delete mood")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (confirmDelete) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmDelete = false },
|
||||
title = { Text("Delete \"${mood.name}\"?") },
|
||||
text = {
|
||||
Text(
|
||||
"This cannot be undone. Downloaded tracks stay available to other moods " +
|
||||
"that still use them.",
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
confirmDelete = false
|
||||
store.deleteMood(mood.id)
|
||||
},
|
||||
) {
|
||||
Text("Delete", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { confirmDelete = false }) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
+353
@@ -0,0 +1,353 @@
|
||||
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.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Bedtime
|
||||
import androidx.compose.material.icons.rounded.DownloadDone
|
||||
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.QueueMusic
|
||||
import androidx.compose.material.icons.rounded.SkipNext
|
||||
import androidx.compose.material.icons.rounded.SkipPrevious
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
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.Slider
|
||||
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.store.AppState
|
||||
import win.taptap.musicmanager.client.store.AppStore
|
||||
import win.taptap.musicmanager.client.store.sourceLabel
|
||||
|
||||
/**
|
||||
* Full-screen player. The compact bar stays visible on other screens; tapping
|
||||
* it opens this view with large artwork, the timeline, transport, offline and
|
||||
* mood actions, and the upcoming queue.
|
||||
*/
|
||||
@Composable
|
||||
fun NowPlayingScreen(state: AppState, store: AppStore) {
|
||||
val song = state.current
|
||||
if (song == null) {
|
||||
EmptyState("Nothing playing", "Pick a mood and press play.", Modifier.fillMaxSize())
|
||||
return
|
||||
}
|
||||
|
||||
var sleepMenu by remember { mutableStateOf(false) }
|
||||
var queueOpen by remember { mutableStateOf(false) }
|
||||
var picker by remember { mutableStateOf(false) }
|
||||
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
|
||||
val progress = if (state.durationSeconds > 0) {
|
||||
(state.positionSeconds / state.durationSeconds).toFloat().coerceIn(0f, 1f)
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
val quality = buildString {
|
||||
append(sourceLabel(song.source))
|
||||
if (song.bitRate > 0) {
|
||||
append(" · ")
|
||||
append(song.bitRate)
|
||||
append(" kbps")
|
||||
}
|
||||
if (song.id in state.downloads) append(" · offline")
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
item {
|
||||
Cover(
|
||||
store = store,
|
||||
songId = song.id,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(1f)
|
||||
.padding(horizontal = 12.dp),
|
||||
size = 800,
|
||||
)
|
||||
}
|
||||
|
||||
item {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(
|
||||
song.title,
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.Bold,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
song.artist,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
quality,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Column {
|
||||
Slider(
|
||||
value = dragSeconds ?: progress,
|
||||
onValueChange = { dragSeconds = it },
|
||||
onValueChangeFinished = {
|
||||
dragSeconds?.let { fraction ->
|
||||
if (state.durationSeconds > 0) {
|
||||
store.seekTo(fraction * state.durationSeconds)
|
||||
}
|
||||
}
|
||||
dragSeconds = null
|
||||
},
|
||||
enabled = store.canSeek() && state.durationSeconds > 0,
|
||||
)
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
formatDuration(state.positionSeconds.toInt()),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
formatDuration(state.durationSeconds.toInt()),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceEvenly,
|
||||
) {
|
||||
IconButton(onClick = { store.previous() }, modifier = Modifier.size(52.dp)) {
|
||||
Icon(
|
||||
Icons.Rounded.SkipPrevious,
|
||||
contentDescription = "Previous",
|
||||
modifier = Modifier.size(36.dp),
|
||||
)
|
||||
}
|
||||
IconButton(onClick = { store.togglePlayPause() }, modifier = Modifier.size(76.dp)) {
|
||||
Icon(
|
||||
if (state.playing) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,
|
||||
contentDescription = if (state.playing) "Pause" else "Play",
|
||||
modifier = Modifier.size(52.dp),
|
||||
)
|
||||
}
|
||||
IconButton(onClick = { store.skip() }, modifier = Modifier.size(52.dp)) {
|
||||
Icon(
|
||||
Icons.Rounded.SkipNext,
|
||||
contentDescription = "Skip",
|
||||
modifier = Modifier.size(36.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
FilledTonalButton(
|
||||
onClick = {
|
||||
if (state.session != null) {
|
||||
store.addCurrentToMood(null)
|
||||
} else {
|
||||
picker = true
|
||||
}
|
||||
},
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Icon(Icons.Rounded.PlaylistAdd, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Add to mood")
|
||||
}
|
||||
IconButton(onClick = { queueOpen = true }) {
|
||||
Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue")
|
||||
}
|
||||
androidx.compose.foundation.layout.Box {
|
||||
IconButton(onClick = { sleepMenu = true }) {
|
||||
Icon(
|
||||
Icons.Rounded.Bedtime,
|
||||
contentDescription = "Sleep timer",
|
||||
tint = if (state.sleepTimerRemainingSeconds != null || state.sleepAtTrackEnd) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
}
|
||||
SleepTimerMenu(
|
||||
expanded = sleepMenu,
|
||||
onDismiss = { sleepMenu = false },
|
||||
state = state,
|
||||
store = store,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (state.sleepAtTrackEnd) {
|
||||
item {
|
||||
Text(
|
||||
"Sleep: stopping after this track",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
} else if (state.sleepTimerRemainingSeconds != null) {
|
||||
item {
|
||||
Text(
|
||||
"Sleep in ${formatDuration(state.sleepTimerRemainingSeconds.toInt())}",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (song.id in state.downloads) {
|
||||
item {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Rounded.DownloadDone,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
"Available without the server",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
HorizontalDivider()
|
||||
SectionTitle("Up next") {
|
||||
Text(
|
||||
"${state.queue.size}",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (state.queue.isEmpty()) {
|
||||
item {
|
||||
Text(
|
||||
"Nothing queued. The radio adds tracks automatically.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
itemsIndexed(
|
||||
state.queue.take(10),
|
||||
key = { _, item -> "np-${item.id}" },
|
||||
) { index, queued ->
|
||||
SongRow(
|
||||
store = store,
|
||||
song = queued,
|
||||
onPlay = { store.playFromQueue(index) },
|
||||
) {
|
||||
Text(
|
||||
formatDuration(queued.duration),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (queueOpen) QueueDialog(state, store) { queueOpen = false }
|
||||
if (picker) {
|
||||
MoodPickerDialog(
|
||||
moods = state.moods,
|
||||
currentMoodId = state.session?.moodId,
|
||||
onDismiss = { picker = false },
|
||||
onSelect = { mood ->
|
||||
picker = false
|
||||
store.addCurrentToMood(mood.id)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SleepTimerMenu(
|
||||
expanded: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
state: AppState,
|
||||
store: AppStore,
|
||||
) {
|
||||
DropdownMenu(expanded = expanded, onDismissRequest = onDismiss) {
|
||||
DropdownMenuItem(
|
||||
text = { Text("Finish this track") },
|
||||
onClick = {
|
||||
onDismiss()
|
||||
store.setSleepAfterTrack()
|
||||
},
|
||||
)
|
||||
listOf(15, 30, 45, 60, 90).forEach { minutes ->
|
||||
DropdownMenuItem(
|
||||
text = { Text("$minutes minutes") },
|
||||
onClick = {
|
||||
onDismiss()
|
||||
store.setSleepTimer(minutes)
|
||||
},
|
||||
)
|
||||
}
|
||||
if (state.sleepTimerRemainingSeconds != null || state.sleepAtTrackEnd) {
|
||||
HorizontalDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text("Turn off") },
|
||||
onClick = {
|
||||
onDismiss()
|
||||
store.setSleepTimer(null)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package win.taptap.musicmanager.client.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
|
||||
import androidx.compose.foundation.gestures.scrollBy
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -102,6 +103,17 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
||||
enabled = store.canSeek() && state.durationSeconds > 0,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (state.session != null) {
|
||||
store.addCurrentToMood(null)
|
||||
} else {
|
||||
picker = true
|
||||
}
|
||||
},
|
||||
) {
|
||||
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to mood")
|
||||
}
|
||||
IconButton(onClick = { queueOpen = true }) {
|
||||
Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue")
|
||||
}
|
||||
@@ -113,16 +125,6 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
||||
expanded = moreMenu,
|
||||
onDismissRequest = { moreMenu = false },
|
||||
) {
|
||||
DropdownMenuItem(
|
||||
text = { Text("Add to current mood") },
|
||||
leadingIcon = {
|
||||
Icon(Icons.Rounded.AddCircleOutline, contentDescription = null)
|
||||
},
|
||||
onClick = {
|
||||
moreMenu = false
|
||||
store.addCurrentToMood(null)
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text("Add to another mood") },
|
||||
leadingIcon = {
|
||||
@@ -140,38 +142,20 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
||||
Icon(
|
||||
Icons.Rounded.Bedtime,
|
||||
contentDescription = "Sleep timer",
|
||||
tint = if (sleepRemaining != null) {
|
||||
tint = if (sleepRemaining != null || state.sleepAtTrackEnd) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
}
|
||||
DropdownMenu(
|
||||
SleepTimerMenu(
|
||||
expanded = sleepMenu,
|
||||
onDismissRequest = { sleepMenu = false },
|
||||
) {
|
||||
listOf(15, 30, 45, 60, 90).forEach { minutes ->
|
||||
DropdownMenuItem(
|
||||
text = { Text("$minutes minutes") },
|
||||
onClick = {
|
||||
sleepMenu = false
|
||||
store.setSleepTimer(minutes)
|
||||
},
|
||||
onDismiss = { sleepMenu = false },
|
||||
state = state,
|
||||
store = store,
|
||||
)
|
||||
}
|
||||
if (sleepRemaining != null) {
|
||||
HorizontalDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text("Turn off") },
|
||||
onClick = {
|
||||
sleepMenu = false
|
||||
store.setSleepTimer(null)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
@@ -180,6 +164,13 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
||||
.padding(start = 12.dp, end = 8.dp, bottom = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.clickable(onClick = { store.openNowPlaying() }),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Cover(store, song.id, Modifier.size(48.dp), size = 160)
|
||||
Column(Modifier.weight(1f)) {
|
||||
@@ -201,7 +192,9 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
||||
append(formatDuration(state.positionSeconds.toInt()))
|
||||
append(" / ")
|
||||
append(formatDuration(state.durationSeconds.toInt()))
|
||||
if (sleepRemaining != null) {
|
||||
if (state.sleepAtTrackEnd) {
|
||||
append(" · sleep after track")
|
||||
} else if (sleepRemaining != null) {
|
||||
append(" · sleep ")
|
||||
append(formatDuration(sleepRemaining.toInt()))
|
||||
}
|
||||
@@ -212,6 +205,7 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
IconButton(
|
||||
onClick = { store.previous() },
|
||||
@@ -265,7 +259,7 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) {
|
||||
fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) {
|
||||
val listState = rememberLazyListState()
|
||||
var draggingIndex by remember { mutableStateOf<Int?>(null) }
|
||||
var dragPointerY by remember { mutableStateOf(0f) }
|
||||
|
||||
+164
-1
@@ -8,6 +8,7 @@ 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.shape.RoundedCornerShape
|
||||
@@ -16,17 +17,23 @@ import androidx.compose.material.icons.rounded.DeleteSweep
|
||||
import androidx.compose.material.icons.rounded.Logout
|
||||
import androidx.compose.material.icons.rounded.Refresh
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Slider
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
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 kotlin.math.roundToInt
|
||||
import win.taptap.musicmanager.client.APP_VERSION
|
||||
import win.taptap.musicmanager.client.currentTimeMillis
|
||||
import win.taptap.musicmanager.client.platformName
|
||||
import win.taptap.musicmanager.client.store.AppState
|
||||
import win.taptap.musicmanager.client.store.AppStore
|
||||
@@ -66,6 +73,78 @@ fun SettingsScreen(state: AppState, store: AppStore) {
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
val info = state.serverInfo
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text("Audio", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Loudness normalization", style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
when {
|
||||
info == null -> "The server does not report audio settings."
|
||||
info.loudnessEnabled ->
|
||||
"Server-measured gain per track, target ${info.loudnessTargetLufs} LUFS."
|
||||
else -> "Disabled on this server."
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = state.normalizationEnabled && info?.loudnessEnabled == true,
|
||||
onCheckedChange = { store.setNormalizationEnabled(it) },
|
||||
enabled = info?.loudnessEnabled == true,
|
||||
)
|
||||
}
|
||||
if (store.supportsCrossfade()) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
if (state.crossfadeSeconds == 0) {
|
||||
"Track transition: gapless"
|
||||
} else {
|
||||
"Track transition: ${state.crossfadeSeconds}s fade"
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Slider(
|
||||
value = state.crossfadeSeconds.toFloat(),
|
||||
onValueChange = { store.setCrossfadeSeconds(it.roundToInt()) },
|
||||
valueRange = 0f..8f,
|
||||
steps = 7,
|
||||
)
|
||||
}
|
||||
}
|
||||
info?.let {
|
||||
Text(
|
||||
buildString {
|
||||
append(if (it.defaultSource == "deezer") "Deezer" else "YouTube Music")
|
||||
append(" default · ")
|
||||
if (it.defaultSource == "deezer") {
|
||||
append(
|
||||
if (it.deezerQuality == 1) {
|
||||
"320 kbps downloads"
|
||||
} else {
|
||||
"128 kbps downloads (320 needs a Premium/HiFi ARL)"
|
||||
},
|
||||
)
|
||||
} else {
|
||||
append("best available audio")
|
||||
}
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
@@ -79,6 +158,17 @@ fun SettingsScreen(state: AppState, store: AppStore) {
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
if (state.offlineMoods.isEmpty()) {
|
||||
"No mood is kept offline."
|
||||
} else {
|
||||
"${state.offlineMoods.size} mood(s) auto-sync on Wi-Fi: " +
|
||||
state.moods.filter { it.id in state.offlineMoods }
|
||||
.joinToString(", ") { it.name }
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -98,6 +188,79 @@ fun SettingsScreen(state: AppState, store: AppStore) {
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
val retention = state.serverInfo?.clientLogRetentionDays ?: 14
|
||||
val lastUpload = state.lastLogUploadAt
|
||||
val uploadedText = when {
|
||||
lastUpload == null -> "never"
|
||||
currentTimeMillis() - lastUpload < 60_000 -> "just now"
|
||||
currentTimeMillis() - lastUpload < 3_600_000 ->
|
||||
"${(currentTimeMillis() - lastUpload) / 60_000} min ago"
|
||||
else -> "${(currentTimeMillis() - lastUpload) / 3_600_000} h ago"
|
||||
}
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text("Diagnostics", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Send logs to this server", style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
"Warnings, errors and crashes so a bug can be fixed later.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = state.diagnosticsEnabled,
|
||||
onCheckedChange = { store.setDiagnosticsEnabled(it) },
|
||||
)
|
||||
}
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
FilledTonalButton(
|
||||
onClick = { store.sendLogsNow() },
|
||||
enabled = state.pendingLogCount > 0 && !state.logUploading &&
|
||||
state.diagnosticsEnabled && state.logUploadSupported,
|
||||
) {
|
||||
if (state.logUploading) {
|
||||
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
Text("Send now")
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = { store.clearLocalLogs() },
|
||||
enabled = state.pendingLogCount > 0,
|
||||
) {
|
||||
Text("Clear local")
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"${state.pendingLogCount} entries waiting · last sent $uploadedText",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
if (state.logUploadSupported) {
|
||||
"Authorization headers, tokens and passwords are removed before upload. " +
|
||||
"The server keeps diagnostics for $retention days."
|
||||
} else {
|
||||
"This server does not accept diagnostics yet; entries stay on this device. " +
|
||||
"Restart or toggle this switch after updating the server."
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
@@ -107,7 +270,7 @@ fun SettingsScreen(state: AppState, store: AppStore) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||
Text(
|
||||
"AudioManager 0.3.3 · $platformName",
|
||||
"AudioManager $APP_VERSION · $platformName",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package win.taptap.musicmanager.client
|
||||
|
||||
import kotlin.test.AfterTest
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertTrue
|
||||
import win.taptap.musicmanager.client.logging.AppLog
|
||||
|
||||
class AppLogTest {
|
||||
|
||||
@AfterTest
|
||||
fun cleanUp() {
|
||||
AppLog.clear()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `redacts bearer tokens query parameters and json secrets`() {
|
||||
assertFalse(AppLog.redact("Authorization: Bearer abcdefgh123").contains("abcdefgh123"))
|
||||
assertTrue(AppLog.redact("Authorization: Bearer abcdefgh123").contains("***"))
|
||||
|
||||
val query = AppLog.redact("GET https://music/stream?token=abc123&size=320 failed")
|
||||
assertFalse(query.contains("abc123"))
|
||||
assertTrue(query.contains("token=***"))
|
||||
assertTrue(query.contains("size=320"))
|
||||
|
||||
val json = AppLog.redact("""{"password":"hunter2","keep":"me"}""")
|
||||
assertFalse(json.contains("hunter2"))
|
||||
assertTrue(json.contains("\"keep\":\"me\""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `keeps only the newest entries and persists across a reload`() {
|
||||
val storage = MemoryStorage()
|
||||
AppLog.init(storage)
|
||||
AppLog.clear()
|
||||
|
||||
repeat(AppLog.MAX_ENTRIES + 10) { index ->
|
||||
AppLog.warn("test", "line-$index")
|
||||
}
|
||||
|
||||
assertEquals(AppLog.MAX_ENTRIES, AppLog.pendingCount())
|
||||
assertEquals("line-10", AppLog.pending(1).single().message)
|
||||
|
||||
AppLog.init(storage)
|
||||
assertTrue(AppLog.pending(AppLog.MAX_ENTRIES).any { it.message == "line-509" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `uploaded entries are removed and the rest stays queued`() {
|
||||
AppLog.init(MemoryStorage())
|
||||
AppLog.clear()
|
||||
AppLog.warn("test", "first")
|
||||
AppLog.warn("test", "second")
|
||||
|
||||
val first = AppLog.pending(1)
|
||||
AppLog.markUploaded(first.map { it.id }.toSet())
|
||||
|
||||
assertEquals(1, AppLog.pendingCount())
|
||||
assertEquals("second", AppLog.pending().single().message)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ 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.content.TextContent
|
||||
import io.ktor.http.headersOf
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
@@ -29,6 +30,8 @@ import win.taptap.musicmanager.client.data.CachedState
|
||||
import win.taptap.musicmanager.client.data.PlaybackSnapshot
|
||||
import win.taptap.musicmanager.client.data.SessionState
|
||||
import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||
import win.taptap.musicmanager.client.logging.AppLog
|
||||
import win.taptap.musicmanager.client.playback.PlaybackTrack
|
||||
import win.taptap.musicmanager.client.store.AppStore
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
@@ -417,6 +420,169 @@ class AppStoreTest {
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `offline mood downloads its songs and remembers the setting`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/info" -> respond(
|
||||
"""{"defaultSource":"deezer","deezerQuality":0,
|
||||
"loudnessEnabled":true,"loudnessTargetLufs":-16}""",
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/moods/mo-1" -> respond(detailJson(listOf("a")), HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/songs/a/stream" -> respond(
|
||||
byteArrayOf(1, 2, 3, 4),
|
||||
HttpStatusCode.OK,
|
||||
headersOf(HttpHeaders.ContentType, "audio/mpeg"),
|
||||
)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
runCurrent()
|
||||
store.openMood("mo-1")
|
||||
awaitState { store.state.value.selectedMood != null }
|
||||
|
||||
store.setMoodOffline("mo-1", true)
|
||||
awaitState("offline download") { "a" in store.state.value.downloads }
|
||||
|
||||
assertEquals(setOf("mo-1"), store.state.value.offlineMoods)
|
||||
assertEquals(setOf("mo-1"), cache.loadSettings().offlineMoods)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `finish this track pauses at the end of the current song`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
runCurrent()
|
||||
|
||||
store.playSong(song("a", duration = 180))
|
||||
awaitState { store.state.value.current?.id == "a" }
|
||||
|
||||
player.position = 177.0
|
||||
advanceTimeBy(500)
|
||||
runCurrent()
|
||||
store.setSleepAfterTrack()
|
||||
assertTrue(store.state.value.sleepAtTrackEnd)
|
||||
|
||||
advanceTimeBy(3_500)
|
||||
runCurrent()
|
||||
|
||||
assertFalse(store.state.value.playing)
|
||||
assertFalse(store.state.value.sleepAtTrackEnd)
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `finish this track does not start the prefetched next song`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
cache.savePlayback(
|
||||
PlaybackSnapshot(
|
||||
current = song("a", duration = 180),
|
||||
queue = listOf(song("b", duration = 180)),
|
||||
),
|
||||
)
|
||||
val player = FakePlayer()
|
||||
val store = store(storage, cache, player)
|
||||
runCurrent()
|
||||
store.togglePlayPause()
|
||||
awaitState { store.state.value.playing }
|
||||
|
||||
store.setSleepAfterTrack()
|
||||
player.finish()
|
||||
advanceTimeBy(600)
|
||||
runCurrent()
|
||||
|
||||
assertFalse(store.state.value.playing)
|
||||
assertEquals("a", store.state.value.current?.id)
|
||||
assertEquals(listOf("b"), store.state.value.queue.map { it.id })
|
||||
store.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `diagnostics upload after authentication and are removed locally`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
AppLog.clear()
|
||||
AppLog.init(storage)
|
||||
AppLog.clear()
|
||||
AppLog.warn("test", "playback stalled", RuntimeException("Bearer super-secret-token"))
|
||||
|
||||
var uploads = 0
|
||||
var body: String? = null
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/info" -> respond(
|
||||
"""{"defaultSource":"deezer","deezerQuality":0,"loudnessEnabled":true,
|
||||
"loudnessTargetLufs":-16.0,"clientLogRetentionDays":14}""",
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/logs" -> {
|
||||
uploads += 1
|
||||
body = (request.body as TextContent).text
|
||||
respond("""{"accepted":1}""", HttpStatusCode.OK, jsonHeaders)
|
||||
}
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
awaitState("diagnostics upload") { uploads == 1 }
|
||||
awaitState("log queue drained") { store.state.value.pendingLogCount == 0 }
|
||||
|
||||
assertTrue(body!!.contains("playback stalled"))
|
||||
assertFalse(body!!.contains("super-secret-token"))
|
||||
assertTrue(body!!.contains("***"))
|
||||
assertEquals(0, AppLog.pendingCount())
|
||||
store.release()
|
||||
AppLog.clear()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an older server disables uploads but keeps the local entries`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
val cache = AppCache(storage)
|
||||
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
|
||||
AppLog.clear()
|
||||
AppLog.init(storage)
|
||||
AppLog.clear()
|
||||
AppLog.warn("test", "keep this line")
|
||||
|
||||
val engine = MockEngine { request ->
|
||||
when (request.url.encodedPath) {
|
||||
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
|
||||
"/api/v1/info" -> respond(
|
||||
"""{"defaultSource":"deezer","deezerQuality":0,"loudnessEnabled":true,"loudnessTargetLufs":-16.0}""",
|
||||
HttpStatusCode.OK,
|
||||
jsonHeaders,
|
||||
)
|
||||
"/api/v1/moods" -> respond("""{"moods":[]}""", HttpStatusCode.OK, jsonHeaders)
|
||||
else -> respondError(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
val store = store(storage, cache, FakePlayer(), engine)
|
||||
awaitState("diagnostics unsupported") { !store.state.value.logUploadSupported }
|
||||
|
||||
assertTrue(store.state.value.pendingLogCount > 0)
|
||||
assertTrue(AppLog.pending().any { it.message == "keep this line" })
|
||||
store.release()
|
||||
AppLog.clear()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `logout clears the session and the mood cache`() = runTest {
|
||||
val storage = MemoryStorage()
|
||||
@@ -529,22 +695,6 @@ class AppStoreTest {
|
||||
)
|
||||
|
||||
private class FakePlayer : AudioPlayer {
|
||||
private var onNext: (() -> Unit)? = null
|
||||
private var onPrevious: (() -> Unit)? = null
|
||||
|
||||
fun pressNext() {
|
||||
onNext?.invoke()
|
||||
}
|
||||
|
||||
fun pressPrevious() {
|
||||
onPrevious?.invoke()
|
||||
}
|
||||
|
||||
override fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) {
|
||||
this.onNext = onNext
|
||||
this.onPrevious = onPrevious
|
||||
}
|
||||
|
||||
val played = mutableListOf<String>()
|
||||
val seeks = mutableListOf<Double>()
|
||||
var paused = false
|
||||
@@ -552,25 +702,79 @@ class AppStoreTest {
|
||||
private var playing = false
|
||||
var position = 0.0
|
||||
private var finished = false
|
||||
private var tracks: List<PlaybackTrack> = emptyList()
|
||||
private var index = 0
|
||||
|
||||
fun finish() {
|
||||
finished = true
|
||||
fun pressNext() {
|
||||
skipToNext()
|
||||
}
|
||||
|
||||
override fun play(
|
||||
source: String,
|
||||
song: Song,
|
||||
local: Boolean,
|
||||
artworkUri: String?,
|
||||
artworkBytes: ByteArray?,
|
||||
) {
|
||||
played += song.id
|
||||
fun pressPrevious() {
|
||||
skipToPrevious(2.0)
|
||||
}
|
||||
|
||||
override fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double) {
|
||||
this.tracks = tracks
|
||||
index = startIndex.coerceIn(tracks.indices)
|
||||
startCurrent(startAtSeconds)
|
||||
}
|
||||
|
||||
override fun appendToQueue(tracks: List<PlaybackTrack>) {
|
||||
this.tracks = this.tracks + tracks
|
||||
}
|
||||
|
||||
override fun moveInQueue(fromIndex: Int, toIndex: Int) {
|
||||
if (fromIndex !in tracks.indices || toIndex !in tracks.indices) return
|
||||
val moved = tracks.toMutableList()
|
||||
val item = moved.removeAt(fromIndex)
|
||||
moved.add(toIndex, item)
|
||||
tracks = moved
|
||||
if (index == fromIndex) index = toIndex
|
||||
}
|
||||
|
||||
override fun removeAt(index: Int) {
|
||||
if (index !in tracks.indices) return
|
||||
tracks = tracks.filterIndexed { i, _ -> i != index }
|
||||
if (index < this.index) this.index = (this.index - 1).coerceAtLeast(0)
|
||||
}
|
||||
|
||||
override fun playIndex(index: Int, startAtSeconds: Double) {
|
||||
if (index !in tracks.indices) return
|
||||
this.index = index
|
||||
startCurrent(startAtSeconds)
|
||||
}
|
||||
|
||||
private fun startCurrent(startAtSeconds: Double) {
|
||||
val track = tracks.getOrNull(index) ?: return
|
||||
played += track.song.id
|
||||
playing = true
|
||||
paused = false
|
||||
position = 0.0
|
||||
position = startAtSeconds
|
||||
seeks += startAtSeconds
|
||||
finished = false
|
||||
}
|
||||
|
||||
override fun skipToNext() {
|
||||
if (index + 1 < tracks.size) {
|
||||
playIndex(index + 1, 0.0)
|
||||
} else {
|
||||
finished = true
|
||||
playing = false
|
||||
}
|
||||
}
|
||||
|
||||
override fun skipToPrevious(restartAfterSeconds: Double) {
|
||||
if (position > restartAfterSeconds || index == 0) {
|
||||
seekTo(0.0)
|
||||
} else {
|
||||
playIndex(index - 1, 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
override fun currentIndex(): Int = index
|
||||
|
||||
override fun queueSize(): Int = tracks.size
|
||||
|
||||
override fun pause() {
|
||||
playing = false
|
||||
paused = true
|
||||
@@ -588,12 +792,21 @@ class AppStoreTest {
|
||||
override fun isPlaying(): Boolean = playing
|
||||
override fun isFinished(): Boolean = finished
|
||||
override fun positionSeconds(): Double = position
|
||||
override fun durationSeconds(): Double = 0.0
|
||||
override fun durationSeconds(): Double =
|
||||
tracks.getOrNull(index)?.song?.duration?.toDouble() ?: 0.0
|
||||
|
||||
override val canSeek: Boolean = true
|
||||
|
||||
override fun seekTo(seconds: Double) {
|
||||
position = seconds
|
||||
seeks += seconds
|
||||
}
|
||||
|
||||
fun finish() {
|
||||
finished = true
|
||||
playing = false
|
||||
}
|
||||
|
||||
override fun release() {
|
||||
playing = false
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package win.taptap.musicmanager.client
|
||||
|
||||
import io.ktor.utils.io.readAvailable
|
||||
import win.taptap.musicmanager.client.data.AppStorage
|
||||
|
||||
/** In-memory [AppStorage] for store and cache tests. */
|
||||
internal class MemoryStorage : AppStorage {
|
||||
private val files = mutableMapOf<String, String>()
|
||||
private val artwork = mutableMapOf<String, ByteArray>()
|
||||
private val downloads = mutableMapOf<String, ByteArray>()
|
||||
|
||||
override fun read(name: String): String? = files[name]
|
||||
|
||||
@@ -17,16 +19,40 @@ internal class MemoryStorage : AppStorage {
|
||||
files.remove(name)
|
||||
}
|
||||
|
||||
override fun saveDownload(songId: String, bytes: ByteArray): String? = null
|
||||
override fun downloadPath(songId: String): String? = null
|
||||
override fun saveDownload(songId: String, bytes: ByteArray): String? {
|
||||
downloads[songId] = bytes
|
||||
return "memory://$songId.mp3"
|
||||
}
|
||||
|
||||
override suspend fun saveDownloadStream(
|
||||
songId: String,
|
||||
source: io.ktor.utils.io.ByteReadChannel,
|
||||
): String? {
|
||||
val bytes = ArrayList<Byte>()
|
||||
val buffer = ByteArray(8 * 1024)
|
||||
while (true) {
|
||||
val read = source.readAvailable(buffer)
|
||||
if (read < 0) break
|
||||
for (i in 0 until read) bytes += buffer[i]
|
||||
}
|
||||
downloads[songId] = bytes.toByteArray()
|
||||
return "memory://$songId.mp3"
|
||||
}
|
||||
|
||||
override fun downloadPath(songId: String): String? =
|
||||
downloads[songId]?.let { "memory://$songId.mp3" }
|
||||
override fun saveArtwork(songId: String, bytes: ByteArray): String? {
|
||||
artwork[songId] = bytes
|
||||
return "memory://$songId.jpg"
|
||||
}
|
||||
override fun artworkBytes(songId: String): ByteArray? = artwork[songId]
|
||||
override fun listDownloads(): Map<String, Long> = emptyMap()
|
||||
override fun listDownloads(): Map<String, Long> =
|
||||
downloads.mapValues { it.value.size.toLong() }
|
||||
|
||||
override fun deleteDownload(songId: String) {
|
||||
artwork.remove(songId)
|
||||
downloads.remove(songId)
|
||||
}
|
||||
override fun storageUsedBytes(): Long = 0
|
||||
|
||||
override fun storageUsedBytes(): Long = downloads.values.sumOf { it.size.toLong() }
|
||||
}
|
||||
+86
-27
@@ -8,23 +8,24 @@ import java.net.URI
|
||||
import javax.sound.sampled.AudioFormat
|
||||
import javax.sound.sampled.AudioInputStream
|
||||
import javax.sound.sampled.AudioSystem
|
||||
import javax.sound.sampled.FloatControl
|
||||
import javax.sound.sampled.SourceDataLine
|
||||
import kotlin.concurrent.thread
|
||||
import win.taptap.musicmanager.client.api.Song
|
||||
import kotlin.math.pow
|
||||
import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||
import win.taptap.musicmanager.client.playback.PlaybackTrack
|
||||
|
||||
/**
|
||||
* Desktop playback through the MP3SPI decoder and a PCM line. Pause/resume is a
|
||||
* decoder loop gate, so no audio device is reopened.
|
||||
*
|
||||
* The queue is kept here so the store can use the same timeline operations as
|
||||
* Android. Desktop has no media service, so the store advances to the next item
|
||||
* when the decoder reaches the end.
|
||||
*
|
||||
* Seeking restarts the decoder at the requested position. Remote streams ask
|
||||
* the server to transcode from that offset (`timeOffset`); local files skip the
|
||||
* decoded PCM frames. Both keep the reported position aligned with the song.
|
||||
*
|
||||
* Java Sound cannot open a line for the compressed MP3 format itself; the
|
||||
* decoded stream has to be converted to PCM_SIGNED first. Opening the encoded
|
||||
* format fails with "No line matching interface SourceDataLine supporting
|
||||
* format MPEG1L3 ...".
|
||||
*/
|
||||
class DesktopAudioPlayer : AudioPlayer {
|
||||
|
||||
@@ -34,10 +35,10 @@ class DesktopAudioPlayer : AudioPlayer {
|
||||
private var worker: Thread? = null
|
||||
private val lock = Object()
|
||||
|
||||
private var currentSource: String? = null
|
||||
private var currentSong: Song? = null
|
||||
private var currentLocal = false
|
||||
private var currentArtwork: String? = null
|
||||
private var tracks: List<PlaybackTrack> = emptyList()
|
||||
private var index = 0
|
||||
private var currentTrack: PlaybackTrack? = null
|
||||
private var gain = 1f
|
||||
|
||||
@Volatile private var paused = false
|
||||
@Volatile private var stopped = false
|
||||
@@ -48,29 +49,78 @@ class DesktopAudioPlayer : AudioPlayer {
|
||||
private var frameRate = 44_100f
|
||||
private var duration = 0.0
|
||||
|
||||
override fun play(
|
||||
source: String,
|
||||
song: Song,
|
||||
local: Boolean,
|
||||
artworkUri: String?,
|
||||
artworkBytes: ByteArray?,
|
||||
) {
|
||||
currentSource = source
|
||||
currentSong = song
|
||||
currentLocal = local
|
||||
currentArtwork = artworkUri
|
||||
start(source, song, local, startAtSeconds = 0.0)
|
||||
override fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double) {
|
||||
if (tracks.isEmpty()) return
|
||||
this.tracks = tracks
|
||||
index = startIndex.coerceIn(tracks.indices)
|
||||
playIndex(index, startAtSeconds)
|
||||
}
|
||||
|
||||
private fun start(source: String, song: Song, local: Boolean, startAtSeconds: Double) {
|
||||
override fun appendToQueue(tracks: List<PlaybackTrack>) {
|
||||
this.tracks = this.tracks + tracks
|
||||
}
|
||||
|
||||
override fun moveInQueue(fromIndex: Int, toIndex: Int) {
|
||||
if (fromIndex !in tracks.indices || toIndex !in tracks.indices || fromIndex == toIndex) return
|
||||
val moved = tracks.toMutableList()
|
||||
val item = moved.removeAt(fromIndex)
|
||||
moved.add(toIndex, item)
|
||||
tracks = moved
|
||||
if (index == fromIndex) {
|
||||
index = toIndex
|
||||
} else if (fromIndex < index && toIndex >= index) {
|
||||
index -= 1
|
||||
} else if (fromIndex > index && toIndex <= index) {
|
||||
index += 1
|
||||
}
|
||||
}
|
||||
|
||||
override fun removeAt(index: Int) {
|
||||
if (index !in tracks.indices) return
|
||||
tracks = tracks.filterIndexed { i, _ -> i != index }
|
||||
if (index < this.index) this.index = (this.index - 1).coerceAtLeast(0)
|
||||
}
|
||||
|
||||
override fun playIndex(index: Int, startAtSeconds: Double) {
|
||||
val track = tracks.getOrNull(index) ?: return
|
||||
this.index = index
|
||||
currentTrack = track
|
||||
gain = track.gainDb?.let { 10.0.pow(it / 20.0).toFloat() }?.coerceIn(0f, 4f) ?: 1f
|
||||
start(track, startAtSeconds)
|
||||
}
|
||||
|
||||
override fun skipToNext() {
|
||||
if (index + 1 < tracks.size) {
|
||||
playIndex(index + 1)
|
||||
} else {
|
||||
finished = true
|
||||
stop()
|
||||
}
|
||||
}
|
||||
|
||||
override fun skipToPrevious(restartAfterSeconds: Double) {
|
||||
if (positionSeconds() > restartAfterSeconds || index == 0) {
|
||||
seekTo(0.0)
|
||||
} else {
|
||||
playIndex(index - 1)
|
||||
}
|
||||
}
|
||||
|
||||
override fun currentIndex(): Int = index
|
||||
|
||||
override fun queueSize(): Int = tracks.size
|
||||
|
||||
private fun start(track: PlaybackTrack, startAtSeconds: Double) {
|
||||
stop()
|
||||
finished = false
|
||||
paused = false
|
||||
stopped = false
|
||||
framesRead = 0
|
||||
baseSeconds = startAtSeconds.coerceAtLeast(0.0)
|
||||
duration = song.duration.toDouble()
|
||||
duration = track.song.duration.toDouble()
|
||||
|
||||
val source = track.source
|
||||
val local = track.local
|
||||
val requestSource = if (!local && startAtSeconds > 0) {
|
||||
withTimeOffset(source, startAtSeconds)
|
||||
} else {
|
||||
@@ -102,6 +152,7 @@ class DesktopAudioPlayer : AudioPlayer {
|
||||
val info = javax.sound.sampled.DataLine.Info(SourceDataLine::class.java, audio.format)
|
||||
val dataLine = AudioSystem.getLine(info) as SourceDataLine
|
||||
dataLine.open(audio.format)
|
||||
applyGain(dataLine)
|
||||
dataLine.start()
|
||||
line = dataLine
|
||||
|
||||
@@ -133,6 +184,14 @@ class DesktopAudioPlayer : AudioPlayer {
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyGain(dataLine: SourceDataLine) {
|
||||
val control = runCatching {
|
||||
dataLine.getControl(FloatControl.Type.MASTER_GAIN) as FloatControl
|
||||
}.getOrNull() ?: return
|
||||
val db = 20.0 * kotlin.math.log10(gain.coerceAtLeast(0.0001f).toDouble())
|
||||
control.value = db.coerceIn(control.minimum.toDouble(), control.maximum.toDouble()).toFloat()
|
||||
}
|
||||
|
||||
private fun skipPcm(audio: AudioInputStream, seconds: Double) {
|
||||
var remaining = (seconds * frameRate * frameSize).toLong().coerceAtLeast(0L)
|
||||
val buffer = ByteArray(16 * 1024)
|
||||
@@ -192,15 +251,15 @@ class DesktopAudioPlayer : AudioPlayer {
|
||||
override val canSeek: Boolean = true
|
||||
|
||||
override fun seekTo(seconds: Double) {
|
||||
val source = currentSource ?: return
|
||||
val song = currentSong ?: return
|
||||
val track = currentTrack ?: return
|
||||
val wasPaused = paused
|
||||
start(source, song, currentLocal, seconds.coerceAtLeast(0.0))
|
||||
start(track, seconds.coerceAtLeast(0.0))
|
||||
if (wasPaused) pause()
|
||||
}
|
||||
|
||||
override fun release() {
|
||||
stop()
|
||||
tracks = emptyList()
|
||||
}
|
||||
|
||||
/** Adds the server's `timeOffset` parameter, replacing an earlier one. */
|
||||
|
||||
@@ -6,9 +6,18 @@ 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.logging.AppLog
|
||||
import win.taptap.musicmanager.client.ui.App
|
||||
|
||||
fun main() = application {
|
||||
fun main() {
|
||||
AppLog.init(platformStorage())
|
||||
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
|
||||
runCatching {
|
||||
AppLog.error("crash", "Uncaught exception on ${thread.name}", error)
|
||||
AppLog.flushNow()
|
||||
}
|
||||
}
|
||||
application {
|
||||
Window(
|
||||
onCloseRequest = ::exitApplication,
|
||||
title = "AudioManager",
|
||||
@@ -16,6 +25,7 @@ fun main() = application {
|
||||
) {
|
||||
App()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -124,3 +124,9 @@ class DesktopStorage : AppStorage {
|
||||
|
||||
actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
|
||||
runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull()
|
||||
|
||||
actual fun isUnmeteredNetwork(): Boolean = true
|
||||
|
||||
private val LOG_LOCK = Any()
|
||||
|
||||
internal actual fun <T> withLogLock(block: () -> T): T = synchronized(LOG_LOCK) { block() }
|
||||
@@ -47,3 +47,7 @@ actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) {
|
||||
|
||||
actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
|
||||
runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull()
|
||||
|
||||
actual fun isUnmeteredNetwork(): Boolean = true
|
||||
|
||||
internal actual fun <T> withLogLock(block: () -> T): T = block()
|
||||
@@ -1,10 +1,15 @@
|
||||
package win.taptap.musicmanager.client
|
||||
|
||||
import kotlinx.browser.document
|
||||
import kotlin.math.pow
|
||||
import org.w3c.dom.HTMLAudioElement
|
||||
import win.taptap.musicmanager.client.api.Song
|
||||
import kotlinx.browser.document
|
||||
import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||
import win.taptap.musicmanager.client.playback.PlaybackTrack
|
||||
|
||||
/**
|
||||
* Browser playback. The queue lives here like on the other targets; the store
|
||||
* advances at the end because HTMLAudioElement has one source at a time.
|
||||
*/
|
||||
class WebAudioPlayer : AudioPlayer {
|
||||
|
||||
private val audio: HTMLAudioElement =
|
||||
@@ -12,17 +17,72 @@ class WebAudioPlayer : AudioPlayer {
|
||||
preload = "auto"
|
||||
}
|
||||
|
||||
override fun play(
|
||||
source: String,
|
||||
song: Song,
|
||||
local: Boolean,
|
||||
artworkUri: String?,
|
||||
artworkBytes: ByteArray?,
|
||||
) {
|
||||
audio.src = source
|
||||
private var tracks: List<PlaybackTrack> = emptyList()
|
||||
private var index = 0
|
||||
private var gain = 1.0
|
||||
|
||||
override fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double) {
|
||||
if (tracks.isEmpty()) return
|
||||
this.tracks = tracks
|
||||
index = startIndex.coerceIn(tracks.indices)
|
||||
playIndex(index, startAtSeconds)
|
||||
}
|
||||
|
||||
override fun appendToQueue(tracks: List<PlaybackTrack>) {
|
||||
this.tracks = this.tracks + tracks
|
||||
}
|
||||
|
||||
override fun moveInQueue(fromIndex: Int, toIndex: Int) {
|
||||
if (fromIndex !in tracks.indices || toIndex !in tracks.indices || fromIndex == toIndex) return
|
||||
val moved = tracks.toMutableList()
|
||||
val item = moved.removeAt(fromIndex)
|
||||
moved.add(toIndex, item)
|
||||
tracks = moved
|
||||
if (index == fromIndex) {
|
||||
index = toIndex
|
||||
} else if (fromIndex < index && toIndex >= index) {
|
||||
index -= 1
|
||||
} else if (fromIndex > index && toIndex <= index) {
|
||||
index += 1
|
||||
}
|
||||
}
|
||||
|
||||
override fun removeAt(index: Int) {
|
||||
if (index !in tracks.indices) return
|
||||
tracks = tracks.filterIndexed { i, _ -> i != index }
|
||||
if (index < this.index) this.index = (this.index - 1).coerceAtLeast(0)
|
||||
}
|
||||
|
||||
override fun playIndex(index: Int, startAtSeconds: Double) {
|
||||
val track = tracks.getOrNull(index) ?: return
|
||||
this.index = index
|
||||
gain = track.gainDb?.let { 10.0.pow(it / 20.0) }?.coerceIn(0.0, 1.0) ?: 1.0
|
||||
audio.volume = gain
|
||||
audio.src = track.source
|
||||
if (startAtSeconds > 0) audio.currentTime = startAtSeconds
|
||||
audio.play()
|
||||
}
|
||||
|
||||
override fun skipToNext() {
|
||||
if (index + 1 < tracks.size) {
|
||||
playIndex(index + 1)
|
||||
} else {
|
||||
audio.pause()
|
||||
}
|
||||
}
|
||||
|
||||
override fun skipToPrevious(restartAfterSeconds: Double) {
|
||||
if (positionSeconds() > restartAfterSeconds || index == 0) {
|
||||
seekTo(0.0)
|
||||
} else {
|
||||
playIndex(index - 1)
|
||||
}
|
||||
}
|
||||
|
||||
override fun currentIndex(): Int = index
|
||||
|
||||
override fun queueSize(): Int = tracks.size
|
||||
|
||||
override fun pause() {
|
||||
audio.pause()
|
||||
}
|
||||
@@ -54,5 +114,6 @@ class WebAudioPlayer : AudioPlayer {
|
||||
|
||||
override fun release() {
|
||||
stop()
|
||||
tracks = emptyList()
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,12 @@ 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.logging.AppLog
|
||||
import win.taptap.musicmanager.client.ui.App
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
fun main() {
|
||||
AppLog.init(platformStorage())
|
||||
ComposeViewport(document.body!!) {
|
||||
App()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user