14 Commits
Author SHA1 Message Date
TapTap 4d5a97cdac fix: make finish-this-track win over prefetched audio
CI / build (push) Successful in 4m4s
CI / play (push) Successful in 3m24s
Stop half a second before the boundary so ExoPlayer cannot start the next item,
report the final completed event, and show offline download progress in mood
settings. Version 0.4.2.
2026-11-19 17:11:41 +00:00
TapTap 8e737fae2e fix: mirror a live service timeline after the UI is recreated
CI / build (push) Successful in 3m59s
CI / play (push) Successful in 3m27s
The media service can keep playing after the task is swiped. A new UI now
adopts its queue, index and position instead of showing a stale paused state.
Notification artwork also uses cached offline covers. Version 0.4.1.
2026-11-19 16:58:20 +00:00
TapTap 8cf77f156d fix: avoid duplicate playback events at the end of the timeline
CI / play (push) Successful in 3m38s
CI / build (push) Successful in 3m55s
Also prefer the freshest mood detail during offline sync and reset the skip
suppression after a previous that only restarted the track.
2026-11-19 16:41:41 +00:00
TapTap 1e3dac4e47 feat: service-owned queue, full player, audio consistency and mood settings
CI / build (push) Successful in 2m40s
CI / play (push) Skipped
- Android Media3 service owns a real timeline: gapless playback, notification
  and headset next/back, 2 s previous rule, queue survives task swipes
- per-track loudness gain via an Android PCM processor and desktop mixer
- optional 0-8 s fade between tracks; full-screen player with quality info
- per-mood offline switch auto-syncs songs on Wi-Fi, three at a time
- dedicated mood settings screen with delete at the bottom
- one-tap add-to-mood in the player; sleep timer can finish the current track
- version 0.4.0
2026-11-19 16:38:21 +00:00
TapTap 8d7f6a0ccb fix: re-run search immediately when the mood source changes
CI / build (push) Successful in 3m54s
CI / play (push) Successful in 3m29s
The explicit source switch cancelled the debounced search and then waited
another 300 ms for no reason. It now searches right away, which also makes the
test deterministic.
2026-11-18 19:48:09 +00:00
TapTap 4048262fc5 feat: remove the Up next preview section
CI / build (push) Successful in 2m22s
CI / play (push) Skipped
The preview duplicated what the radio does and is not the real queue. Mood
detail now only loads songs and recommendations, so opening a mood makes one
fewer request.

Also drop the Wasm warm-up from the CI image recipe: the target is local-only.
Version 0.3.3.
2026-11-18 19:39:51 +00:00
TapTap 14e5b9d982 ci: drop the Wasm build from the pipeline
CI / build (push) Successful in 2m57s
CI / play (push) Skipped
It is CPU-bound and dominates the runtime. The target stays available for
local builds with :composeApp:wasmJsBrowserDistribution.
2026-11-18 19:26:04 +00:00
TapTap e28e95fa2b fix: notification skip/back drive the app queue
CI / build (push) Successful in 14m12s
CI / play (push) Successful in 3m20s
- advertise next/previous on a ForwardingPlayer so the notification and
  Android Auto show the buttons, and route them to the mood queue
- rename the preview section to 'Up next' with a clearer subtitle
- version 0.3.2
2026-11-18 19:14:05 +00:00
TapTap 2478505dba test: make the search download status assertion timing independent
CI / build (push) Successful in 13m58s
CI / play (push) Successful in 3m18s
2026-11-17 16:57:07 +00:00
TapTap 957ee3eb4b feat: inline search download status and headset transport
CI / build (push) Successful in 5m35s
CI / play (push) Skipped
- mood detail carries the server's download jobs
- search rows show Downloading… / Added / Failed, so the keyboard cannot hide it
- headset and Bluetooth next/previous drive the app queue; previous keeps the
  after-two-seconds restart rule
- 'Next batch' now explains what the preview is
- version 0.3.1
2026-11-17 16:43:21 +00:00
TapTap cfab559e5e fix: keep the dragged queue row opaque
CI / build (push) Successful in 11m56s
CI / play (push) Successful in 3m16s
2026-11-17 08:55:38 +00:00
TapTap a63ee62673 feat: drag-to-reorder queue and a compact mobile player
CI / build (push) Successful in 4m51s
CI / play (push) Skipped
- long-press and drag queue rows, with auto-scroll near the edges
- pin the now-playing row above the upcoming queue
- move add-to-mood actions into an overflow menu so the title and
  artist get the full width on narrow phones
2026-11-17 08:54:23 +00:00
TapTap 3b40726edb feat: choose Deezer or YouTube Music per mood
CI / build (push) Successful in 3m35s
CI / play (push) Skipped
- models carry source and externalId instead of videoId
- AppCache v3 discards the old shape
- source selector in the create dialog, mood settings and search screen
- switching source patches the mood and re-runs the search
- client requests ten catalog results with a 60s timeout
2026-11-17 07:32:40 +00:00
TapTap 96ab25a91d feat: search YouTube Music and poll for the first recommendation batch
CI / build (push) Successful in 12m2s
CI / play (push) Successful in 3m18s
- label and document the YouTube Music search source
- allow up to 60s for a search and request ten results
- keep refreshing a new mood until its first recommendations arrive
2026-11-16 18:38:58 +00:00
32 changed files with 2910 additions and 658 deletions

No files matched your search

+2 -5
View File
@@ -45,15 +45,13 @@ jobs:
:composeApp:desktopTest \
:composeApp:assembleDebug \
:composeApp:packageUberJarForCurrentOS \
:composeApp:wasmJsBrowserDistribution \
--console=plain
else
# The optimized Wasm build is CPU-bound and slow; main/PR builds
# only need to prove the web target compiles and bundles.
# The Wasm target is kept for local builds but is not part of CI:
# it is CPU-bound and dominates the pipeline runtime.
gradle \
:composeApp:desktopTest \
:composeApp:assembleDebug \
:composeApp:wasmJsBrowserDevelopmentExecutableDistribution \
--console=plain
fi
@@ -64,7 +62,6 @@ jobs:
cp composeApp/build/outputs/apk/debug/composeApp-debug.apk dist/AudioManager.apk
if [[ "$GITHUB_REF" == refs/tags/* ]]; then
cp composeApp/build/compose/jars/*.jar dist/AudioManager-desktop.jar
(cd composeApp/build/dist/wasmJs/productionExecutable && zip -qr "$GITHUB_WORKSPACE/dist/AudioManager-web.zip" .)
fi
- name: Publish release assets
+52 -27
View File
@@ -5,7 +5,7 @@ self-hosted music server.
The client and server are designed together. There is no OpenSubsonic
compatibility layer: the app speaks the native `/api/v1` API, where playback is
a server-driven radio session and songs are added by searching YouTube.
a server-driven radio session and songs are added from Deezer or YouTube Music.
## Targets
@@ -22,8 +22,9 @@ a server-driven radio session and songs are added by searching YouTube.
- **Moods** are the only content model. Each user sees only their own moods.
- **Songs** belong to the mood's permanent collection. A mood needs at least one
song before it can play.
- **Search YouTube** from inside a mood or globally with a mood picker. Tracks
over 10 minutes are hidden. Results that are already downloaded are marked and
- **Search Deezer or YouTube Music** from inside a mood or globally with a mood
picker. Each mood has a **Download source** selector; search, recommendations
and downloads follow it. Tracks over 10 minutes are hidden. Results that are already downloaded are marked and
add instantly; other videos are queued for server-side download.
- **Paste a YouTube URL** to add a specific video.
- **Recommendations** are downloaded automatically and play in the radio without
@@ -36,20 +37,33 @@ a server-driven radio session and songs are added by searching YouTube.
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)
- A queue sheet from the player: the current track plus every upcoming track,
with move up/down and remove. Changes are persisted locally.
- **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.
- **Previous** from the player: after two seconds of playback it restarts the
current track; before that it restores the last played track.
- **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.
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
- **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
@@ -65,13 +79,16 @@ a server-driven radio session and songs are added by searching YouTube.
## 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.
- **Search** — mood picker, YouTube search, paste URL, downloaded badges.
- **Search** — mood picker, source selector, catalog search, paste URL,
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.
@@ -124,7 +141,7 @@ gradle :composeApp:run
# Desktop fat jar
gradle :composeApp:packageUberJarForCurrentOS
# Web bundle
# Web bundle (local only, not built by CI)
gradle :composeApp:wasmJsBrowserDistribution
# composeApp/build/dist/wasmJs/productionExecutable
```
@@ -191,7 +208,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.2.0 && git push --tags` builds, signs and uploads the bundle.
Then `git tag v0.4.2 && 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.
@@ -204,7 +221,8 @@ it. It owns:
- **Mood sync** — GET `/moods` on login/refresh; details are fetched when a mood
is opened and cached.
- **Mood cache** — cached details power offline mood lists and downloads.
- **Search** — debounced remote YouTube search with the selected target mood.
- **Search** — debounced remote catalog search with the selected target mood and
its source.
- **Radio** — one session per mood, batches of 12, prefetch when the queue is
short, no repeats within a session.
- **Downloads** — stored under the platform app directory, keyed by the shared
@@ -240,11 +258,11 @@ radio and visible in the song list.
`gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android
SDK, Node, Yarn and a warmed Gradle dependency cache.
- **main / PR:** run `desktopTest`, build the Android APK and the *development*
Wasm bundle.
- **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm
bundle, attach the artifacts to the Gitea release, and publish the AAB to Play
internal testing.
- **main / PR:** run `desktopTest` and build the Android APK.
- **`v*` tag:** additionally build the desktop fat jar, attach the artifacts to
the Gitea release, and publish the AAB to Play internal testing.
- The Wasm target stays in the project for local builds but is **not** part of
CI; compiling it dominates the pipeline runtime.
Rebuild the CI image after changing `ci/Dockerfile` or dependency versions:
@@ -254,9 +272,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.
@@ -264,6 +284,11 @@ scripts/build-ci-image.sh 3
streams and caches metadata.
- Downloads store the 320 px cover next to the MP3 (`<songId>.jpg`), so the
in-app cover and the Android notification artwork survive without the server.
- Search and downloads depend on `yt-dlp` on the server. YouTube bot checks can
fail a search (`502`) or leave a recommendation in `failed` with Retry.
- Search and downloads depend on the server's catalogs. YouTube bot checks can
fail a YouTube Music search (`502`) or leave a recommendation in `failed`
with Retry. Music search resolves every result for its artist/album/duration,
so a YouTube Music search takes roughly 10–15 seconds for ten results;
Deezer search is much faster.
- Deezer downloads need `DEEZER_ARL` on the server. A Free ARL is limited to
128 kbps; Premium enables 320 kbps. The client never stores the ARL.
- No iOS target yet. The shared module is ready for one.
+4 -9
View File
@@ -43,21 +43,16 @@ RUN mkdir -p "$ANDROID_HOME/cmdline-tools" \
"build-tools;36.0.0" \
&& rm -rf "$ANDROID_HOME/.temp" "$ANDROID_HOME/.downloadIntermediates"
# Warm the Gradle dependency cache and the Kotlin/Wasm (node, yarn, binaryen)
# toolchain so CI jobs do not download them on every run. Rebuild this image
# when dependencies change.
# Warm the Gradle dependency cache and the common/Android/desktop compilers so
# CI jobs do not download them on every run. The Wasm toolchain is intentionally
# not warmed: Wasm is not part of the pipeline. Rebuild this image when
# dependencies change.
COPY . /warmup
WORKDIR /warmup
# Warm dependencies and the common/Android/desktop compilers here. The Wasm
# executable build is memory hungry and stays in the web job, but node and yarn
# are cached: Kotlin downloads them from GitHub, which has been flaky during CI.
RUN sed -i 's/kotlin.daemon.jvmargs=-Xmx3g/kotlin.daemon.jvmargs=-Xmx2g/' gradle.properties \
&& gradle --no-daemon --max-workers=2 \
:kotlinNodeJsSetup \
:kotlinYarnSetup \
:composeApp:desktopTest \
:composeApp:assembleDebug \
:composeApp:compileKotlinWasmJs \
--console=plain \
&& rm -rf /warmup
+1 -1
View File
@@ -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.2.0"
?: "0.4.2"
kotlin {
androidTarget {
@@ -2,6 +2,7 @@
<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" />
@@ -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()
}
@@ -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,14 +139,26 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) }
}
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
}
@@ -145,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() }
@@ -7,6 +7,9 @@ import android.os.Handler
import android.os.Looper
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
import androidx.media3.session.MediaSessionService
@@ -20,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() {
@@ -33,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 player = ExoPlayer.Builder(this)
val exoPlayer = ExoPlayer.Builder(this)
.setRenderersFactory(GainRenderersFactory(this, gainProcessor))
.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(C.USAGE_MEDIA)
@@ -49,6 +94,47 @@ class PlaybackService : MediaSessionService() {
.apply {
setWakeMode(C.WAKE_MODE_NETWORK)
}
player = exoPlayer
// 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 (exoPlayer.currentPosition > PREVIOUS_RESTART_MS) {
exoPlayer.seekTo(0)
} else if (exoPlayer.hasPreviousMediaItem()) {
exoPlayer.seekToPreviousMediaItem()
} else {
exoPlayer.seekTo(0)
}
}
override fun 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,
@@ -57,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(
@@ -67,6 +153,7 @@ 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)
@@ -79,20 +166,36 @@ class PlaybackService : MediaSessionService() {
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
@@ -105,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
}
}
@@ -16,3 +16,9 @@ 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
@@ -125,14 +125,22 @@ class ApiClient(private val http: HttpClient) {
suspend fun addSong(
moodId: String,
songId: String? = null,
videoId: String? = null,
source: String? = null,
externalId: String? = null,
url: String? = null,
): AddSongResponse =
parse(
http.post(url("/moods/$moodId/songs")) {
auth()
contentType(ContentType.Application.Json)
setBody(AddSongRequest(songId = songId, videoId = videoId, url = url))
setBody(
AddSongRequest(
songId = songId,
source = source,
externalId = externalId,
url = url,
),
)
},
)
@@ -155,33 +163,48 @@ class ApiClient(private val http: HttpClient) {
},
)
suspend fun addRecommendation(moodId: String, videoId: String): RecommendationDecision =
suspend fun addRecommendation(moodId: String, externalId: String): RecommendationDecision =
parse(
http.post(url("/moods/$moodId/recommendations/$videoId/add")) {
http.post(url("/moods/$moodId/recommendations/$externalId/add")) {
auth()
},
)
suspend fun rejectRecommendation(moodId: String, videoId: String): RecommendationDecision =
suspend fun rejectRecommendation(moodId: String, externalId: String): RecommendationDecision =
parse(
http.post(url("/moods/$moodId/recommendations/$videoId/reject")) {
http.post(url("/moods/$moodId/recommendations/$externalId/reject")) {
auth()
},
)
suspend fun retryRecommendation(moodId: String, videoId: String): MoodDetail =
suspend fun retryRecommendation(moodId: String, externalId: String): MoodDetail =
parse(
http.post(url("/moods/$moodId/recommendations/$videoId/retry")) {
http.post(url("/moods/$moodId/recommendations/$externalId/retry")) {
auth()
},
)
suspend fun preview(moodId: String, limit: Int = 20): List<Song> =
get<TracksResponse>("/moods/$moodId/preview?limit=$limit").songs
suspend fun info(): ServerInfo = get("/info")
suspend fun search(query: String, limit: Int = 20, moodId: String? = null): List<SearchResult> {
suspend fun search(
query: String,
limit: Int = 10,
source: String? = null,
moodId: String? = null,
): List<SearchResult> {
val sourceParam = source?.let { "&source=${it.encodeURLParameter()}" }.orEmpty()
val mood = moodId?.let { "&moodId=${it.encodeURLParameter()}" }.orEmpty()
return get<SearchResponse>("/search?q=${query.encodeURLParameter()}&limit=$limit$mood").results
return parse<SearchResponse>(
http.get(url("/search?q=${query.encodeURLParameter()}&limit=$limit$sourceParam$mood")) {
auth()
// yt-dlp resolves every YouTube Music hit to get artist, album
// and duration, so a search takes longer than a plain API call.
timeout {
requestTimeoutMillis = 60_000
socketTimeoutMillis = 60_000
}
},
).results
}
suspend fun startSession(moodId: String, limit: Int = 12): Session =
@@ -35,7 +35,8 @@ data class LoginResponse(
@Serializable
data class Song(
val id: String,
val videoId: String,
val source: String = "youtube",
val externalId: String,
val title: String,
val artist: String,
val album: String? = null,
@@ -44,10 +45,21 @@ 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 ServerInfo(
val defaultSource: String = "deezer",
val deezerQuality: Int = 0,
val loudnessEnabled: Boolean = false,
val loudnessTargetLufs: Double = -16.0,
)
@Serializable
data class Mood(
val id: String,
@@ -55,6 +67,7 @@ data class Mood(
val description: String? = null,
val query: String? = null,
val genres: List<String> = emptyList(),
val source: String = "youtube",
val collectionPercent: Int = 50,
val recommendationPercent: Int = 50,
val recommendationCount: Int = 10,
@@ -86,7 +99,8 @@ data class Download(
@Serializable
data class Recommendation(
val videoId: String,
val source: String = "youtube",
val externalId: String,
val title: String,
val artist: String,
val album: String? = null,
@@ -105,8 +119,22 @@ data class MoodDetail(
val mood: Mood,
val songs: List<MoodSong> = emptyList(),
val recommendations: List<Recommendation> = emptyList(),
val downloads: List<DownloadStatus> = emptyList(),
)
/** Server-side download state for one track, keyed by source and external id. */
@Serializable
data class DownloadStatus(
val source: String = "youtube",
val externalId: String,
val state: String,
val attempts: Int = 0,
val error: String? = null,
val songId: String? = null,
) {
val active: Boolean get() = state == "queued" || state == "downloading"
}
@Serializable
data class MoodsResponse(val moods: List<Mood> = emptyList())
@@ -121,7 +149,8 @@ data class RecommendationDecision(
@Serializable
data class SearchResult(
val videoId: String,
val source: String = "youtube",
val externalId: String,
val title: String,
val artist: String,
val album: String? = null,
@@ -180,7 +209,8 @@ data class AddToMoodResponse(val mood: Mood, val added: Boolean)
@Serializable
data class AddSongRequest(
val songId: String? = null,
val videoId: String? = null,
val source: String? = null,
val externalId: String? = null,
val url: String? = null,
)
@@ -197,6 +227,7 @@ data class CreateMoodRequest(
val description: String? = null,
val query: String? = null,
val genres: List<String> = emptyList(),
val source: String? = null,
val collectionPercent: Int = 50,
val recommendationCount: Int = 10,
val refreshHours: Int = 24,
@@ -210,6 +241,7 @@ data class UpdateMoodRequest(
val query: String? = null,
val clearQuery: Boolean = false,
val genres: List<String>? = null,
val source: String? = null,
val collectionPercent: Int? = null,
val recommendationCount: Int? = null,
val refreshHours: Int? = null,
@@ -16,8 +16,8 @@ data class SessionState(
)
/**
* Offline cache. Version 2 holds moods and their details only; the old
* mounted-library shape is discarded instead of silently mis-decoding.
* Offline cache. Version 3 adds the download source and the source-neutral
* external track id; older shapes are discarded instead of mis-decoding.
*/
@Serializable
data class CachedState(
@@ -28,10 +28,20 @@ data class CachedState(
val moodDetails: List<MoodDetail> = emptyList(),
) {
companion object {
const val CACHE_VERSION = 2
const val CACHE_VERSION = 3
}
}
/** 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,
)
/** The queue survives a restart so the next launch can resume where it stopped. */
@Serializable
data class PlaybackSnapshot(
@@ -70,6 +80,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 +105,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 +122,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"
}
}
@@ -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,14 +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
}
fun release()
}
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") }
},
)
}
}
@@ -113,7 +113,8 @@ fun DownloadsScreen(state: AppState, store: AppStore) {
store.toggleDownload(
win.taptap.musicmanager.client.api.Song(
id = id,
videoId = id,
source = "youtube",
externalId = id,
title = id,
artist = "",
duration = 0,
@@ -1,10 +1,12 @@
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.height
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
@@ -22,13 +24,17 @@ 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
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.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
@@ -50,6 +56,7 @@ import win.taptap.musicmanager.client.api.MoodSong
import win.taptap.musicmanager.client.api.Recommendation
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
@Composable
fun MoodDetailScreen(state: AppState, store: AppStore) {
@@ -72,21 +79,17 @@ 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 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 {
it.download?.state == "queued" || it.download?.state == "downloading"
}
LaunchedEffect(mood.id, inFlight) {
// A new mood gets its first batch from a background discovery run, which
// resolves the YouTube Music search. Keep refreshing until it lands.
val waitingForFirstBatch = mood.recommendationCount > 0 && detail.recommendations.isEmpty()
LaunchedEffect(mood.id, inFlight, waitingForFirstBatch) {
var polls = 0
while (inFlight > 0 && polls < 60) {
while ((inFlight > 0 || waitingForFirstBatch) && polls < 60) {
kotlinx.coroutines.delay(5_000)
store.refreshSelectedMood()
polls += 1
@@ -172,17 +175,10 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
Spacer(Modifier.width(6.dp))
Text("Add music")
}
}
}
if (state.preview.isNotEmpty()) {
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Next batch")
}
items(state.preview, key = { "preview-${it.id}" }) { song ->
SongRow(store, song, onPlay = { store.playSong(song) }) {
Text(formatDuration(song.duration), style = MaterialTheme.typography.labelSmall)
OutlinedButton(onClick = { store.openMoodSettings() }) {
Icon(Icons.Rounded.Settings, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Settings")
}
}
}
@@ -228,109 +224,13 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
)
}
} else {
items(detail.recommendations, key = { "rec-${it.videoId}" }) { recommendation ->
items(detail.recommendations, key = { "rec-${it.source}-${it.externalId}" }) { recommendation ->
RecommendationRow(recommendation, state.discovering, store)
}
}
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(),
)
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() },
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)) }
}
}
@@ -415,21 +315,21 @@ private fun RecommendationRow(
}
if (failed) {
IconButton(
onClick = { store.retryRecommendation(recommendation.videoId) },
onClick = { store.retryRecommendation(recommendation.externalId) },
enabled = !busy,
) {
Icon(Icons.Rounded.Refresh, contentDescription = "Retry download")
}
} else {
IconButton(
onClick = { store.addRecommendation(recommendation.videoId) },
onClick = { store.addRecommendation(recommendation.externalId) },
enabled = !busy,
) {
Icon(Icons.Rounded.Add, contentDescription = "Add to mood")
}
}
IconButton(
onClick = { store.rejectRecommendation(recommendation.videoId) },
onClick = { store.rejectRecommendation(recommendation.externalId) },
enabled = !busy,
) {
Icon(Icons.Rounded.Close, contentDescription = "Not interested")
@@ -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") }
},
)
}
}
@@ -27,9 +27,12 @@ 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.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.Text
@@ -50,6 +53,7 @@ import kotlin.math.roundToInt
import win.taptap.musicmanager.client.api.Mood
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
@Composable
fun MoodsScreen(state: AppState, store: AppStore) {
@@ -115,9 +119,18 @@ fun MoodsScreen(state: AppState, store: AppStore) {
CreateMoodDialog(
saving = state.saving,
onDismiss = { creating = false },
onCreate = { name, description, genres, query, collectionPercent, recommendations, hours ->
onCreate = { name, description, genres, query, source, collectionPercent, recommendations, hours ->
creating = false
store.createMood(name, description, genres, query, collectionPercent, recommendations, hours)
store.createMood(
name,
description,
genres,
query,
source,
collectionPercent,
recommendations,
hours,
)
},
)
}
@@ -165,6 +178,12 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
color = Color.White.copy(alpha = 0.85f),
)
}
Spacer(Modifier.width(8.dp))
Text(
sourceLabel(mood.source),
style = MaterialTheme.typography.labelMedium,
color = Color.White.copy(alpha = 0.7f),
)
Spacer(Modifier.weight(1f))
FilledTonalButton(
onClick = onPlay,
@@ -187,12 +206,14 @@ private fun MoodCard(mood: Mood, onOpen: () -> Unit, onPlay: () -> Unit) {
private fun CreateMoodDialog(
saving: Boolean,
onDismiss: () -> Unit,
onCreate: (String, String?, List<String>, String?, Int, Int, Int) -> Unit,
onCreate: (String, String?, List<String>, String?, String, Int, Int, Int) -> Unit,
) {
var name by remember { mutableStateOf("") }
var description by remember { mutableStateOf("") }
var genres by remember { mutableStateOf("") }
var query by remember { mutableStateOf("") }
var source by remember { mutableStateOf("deezer") }
var sourceMenu by remember { mutableStateOf(false) }
var collectionPercent by remember { mutableStateOf(50f) }
var recommendations by remember { mutableStateOf(10f) }
var hours by remember { mutableStateOf("24") }
@@ -229,6 +250,35 @@ private fun CreateMoodDialog(
label = { Text("Discovery hint") },
singleLine = true,
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"Download source",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.weight(1f),
)
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
},
)
}
}
}
}
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations",
@@ -270,6 +320,7 @@ private fun CreateMoodDialog(
description.trim().takeIf { it.isNotEmpty() },
genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query.trim().takeIf { it.isNotEmpty() },
source,
collectionPercent.roundToInt(),
recommendations.roundToInt(),
hours.toIntOrNull() ?: 24,
@@ -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,11 +1,16 @@
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
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
@@ -13,13 +18,14 @@ 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.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AddCircleOutline
import androidx.compose.material.icons.rounded.Bedtime
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.KeyboardArrowDown
import androidx.compose.material.icons.rounded.KeyboardArrowUp
import androidx.compose.material.icons.rounded.DragHandle
import androidx.compose.material.icons.rounded.MoreVert
import androidx.compose.material.icons.rounded.Pause
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.PlaylistAdd
@@ -37,23 +43,33 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.zIndex
import kotlinx.coroutines.delay
import kotlin.math.roundToInt
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
private val QUEUE_ROW_HEIGHT = 58.dp
@Composable
fun PlayerBar(state: AppState, store: AppStore) {
val song = state.current ?: return
var picker by remember { mutableStateOf(false) }
var sleepMenu by remember { mutableStateOf(false) }
var moreMenu by remember { mutableStateOf(false) }
var queueOpen by remember { mutableStateOf(false) }
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
val sleepRemaining = state.sleepTimerRemainingSeconds
@@ -87,50 +103,72 @@ 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")
}
Box {
IconButton(onClick = { moreMenu = true }) {
Icon(Icons.Rounded.MoreVert, contentDescription = "More actions")
}
DropdownMenu(
expanded = moreMenu,
onDismissRequest = { moreMenu = false },
) {
DropdownMenuItem(
text = { Text("Add to another mood") },
leadingIcon = {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = null)
},
onClick = {
moreMenu = false
picker = true
},
)
}
}
Box {
IconButton(onClick = { sleepMenu = true }) {
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(
modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 8.dp, bottom = 8.dp),
modifier = Modifier
.fillMaxWidth()
.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),
) {
@@ -154,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()))
}
@@ -165,26 +205,38 @@ fun PlayerBar(state: AppState, store: AppStore) {
overflow = TextOverflow.Ellipsis,
)
}
}
IconButton(onClick = { store.addCurrentToMood(null) }) {
Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood")
IconButton(
onClick = { store.previous() },
modifier = Modifier.size(40.dp),
) {
Icon(
Icons.Rounded.SkipPrevious,
contentDescription = "Previous",
modifier = Modifier.size(26.dp),
)
}
IconButton(onClick = { picker = true }) {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood")
}
IconButton(onClick = { store.previous() }) {
Icon(Icons.Rounded.SkipPrevious, contentDescription = "Previous")
}
IconButton(onClick = { store.skip() }) {
Icon(Icons.Rounded.SkipNext, contentDescription = "Skip")
}
IconButton(onClick = { store.togglePlayPause() }) {
IconButton(
onClick = { store.togglePlayPause() },
modifier = Modifier.size(48.dp),
) {
Icon(
if (state.playing) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,
contentDescription = if (state.playing) "Pause" else "Play",
modifier = Modifier.size(30.dp),
)
}
IconButton(
onClick = { store.skip() },
modifier = Modifier.size(40.dp),
) {
Icon(
Icons.Rounded.SkipNext,
contentDescription = "Skip",
modifier = Modifier.size(26.dp),
)
}
}
}
}
@@ -207,13 +259,44 @@ 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) }
var grabOffset by remember { mutableStateOf(0f) }
val edgePx = with(LocalDensity.current) { 48.dp.toPx() }
fun queueIndexAt(y: Float): Int? =
listState.layoutInfo.visibleItemsInfo
.firstOrNull { y >= it.offset && y < it.offset + it.size }
?.index
LaunchedEffect(draggingIndex) {
while (draggingIndex != null) {
val y = dragPointerY
val edge = edgePx
val viewport = listState.layoutInfo.viewportEndOffset.toFloat()
if (y < edge) {
listState.scrollBy(-18f)
} else if (y > viewport - edge) {
listState.scrollBy(18f)
}
val from = draggingIndex
val to = queueIndexAt(y)
if (from != null && to != null && to != from) {
store.moveInQueue(from, to)
draggingIndex = to
}
delay(16)
}
}
Dialog(onDismissRequest = onDismiss) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 6.dp,
modifier = Modifier.fillMaxWidth().heightIn(max = 600.dp),
modifier = Modifier.fillMaxWidth().heightIn(max = 620.dp),
) {
Column {
Row(
@@ -223,7 +306,11 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
Column(Modifier.weight(1f)) {
Text("Queue", style = MaterialTheme.typography.titleMedium)
Text(
"${state.queue.size} upcoming",
if (state.queue.isEmpty()) {
"Nothing queued"
} else {
"${state.queue.size} upcoming · long-press and drag to reorder"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -231,17 +318,23 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
TextButton(onClick = onDismiss) { Text("Close") }
}
HorizontalDivider()
LazyColumn(Modifier.fillMaxWidth().heightIn(max = 480.dp)) {
state.current?.let { song ->
item(key = "current") {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 10.dp),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Cover(store, song.id, Modifier.size(40.dp), size = 96)
Column(Modifier.weight(1f)) {
Text(song.title, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
song.title,
style = MaterialTheme.typography.bodyLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
"Now playing",
style = MaterialTheme.typography.labelSmall,
@@ -249,29 +342,86 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
)
}
}
}
HorizontalDivider()
}
if (state.queue.isEmpty()) {
item {
Text(
"Nothing queued. Start a mood to build a radio queue.",
modifier = Modifier.padding(20.dp),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
Box(
modifier = Modifier
.fillMaxWidth()
.pointerInput(Unit) {
detectDragGesturesAfterLongPress(
onDragStart = { offset ->
val index = queueIndexAt(offset.y)
val info = listState.layoutInfo.visibleItemsInfo
.firstOrNull { it.index == index }
if (index != null && info != null) {
draggingIndex = index
dragPointerY = offset.y
grabOffset = offset.y - info.offset
}
},
onDrag = { change, _ ->
change.consume()
dragPointerY = change.position.y
val from = draggingIndex
val to = queueIndexAt(change.position.y)
if (from != null && to != null && to != from) {
store.moveInQueue(from, to)
draggingIndex = to
}
},
onDragEnd = { draggingIndex = null },
onDragCancel = { draggingIndex = null },
)
},
) {
LazyColumn(
state = listState,
modifier = Modifier.fillMaxWidth().heightIn(max = 500.dp),
) {
itemsIndexed(state.queue, key = { _, song -> song.id }) { index, song ->
val isDragging = index == draggingIndex
val rowInfo = if (isDragging) {
listState.layoutInfo.visibleItemsInfo
.firstOrNull { it.index == index }
} else {
null
}
val translation = if (rowInfo != null) {
dragPointerY - rowInfo.offset - grabOffset
} else {
0f
}
itemsIndexed(state.queue, key = { index, _ -> "queue-$index" }) { index, song ->
Row(
modifier = Modifier.fillMaxWidth().padding(start = 20.dp, end = 8.dp, top = 6.dp, bottom = 6.dp),
modifier = Modifier
.fillMaxWidth()
.height(QUEUE_ROW_HEIGHT)
.background(MaterialTheme.colorScheme.surface)
.zIndex(if (isDragging) 1f else 0f)
.graphicsLayer {
translationY = translation
shadowElevation = if (isDragging) 8.dp.toPx() else 0f
}
.padding(start = 20.dp, end = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Cover(store, song.id, Modifier.size(36.dp), size = 96)
Column(Modifier.weight(1f)) {
Text(song.title, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
song.title,
style = MaterialTheme.typography.bodyMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
song.artist,
style = MaterialTheme.typography.labelSmall,
@@ -280,19 +430,19 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
overflow = TextOverflow.Ellipsis,
)
}
Icon(
Icons.Rounded.DragHandle,
contentDescription = "Drag to reorder",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(22.dp),
)
IconButton(
onClick = { store.moveInQueue(index, index - 1) },
enabled = index > 0,
onClick = {
val from = store.state.value.queue
.indexOfFirst { it.id == song.id }
if (from >= 0) store.removeFromQueue(from)
},
) {
Icon(Icons.Rounded.KeyboardArrowUp, contentDescription = "Move up")
}
IconButton(
onClick = { store.moveInQueue(index, index + 1) },
enabled = index < state.queue.lastIndex,
) {
Icon(Icons.Rounded.KeyboardArrowDown, contentDescription = "Move down")
}
IconButton(onClick = { store.removeFromQueue(index) }) {
Icon(Icons.Rounded.Close, contentDescription = "Remove from queue")
}
}
@@ -302,3 +452,5 @@ private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit)
}
}
}
}
}
@@ -44,9 +44,12 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import win.taptap.musicmanager.client.api.DownloadStatus
import win.taptap.musicmanager.client.api.SearchResult
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.downloadKey
import win.taptap.musicmanager.client.store.sourceLabel
@Composable
fun SearchScreen(state: AppState, store: AppStore) {
@@ -61,6 +64,7 @@ fun SearchScreen(state: AppState, store: AppStore) {
var url by remember { mutableStateOf("") }
var moodMenu by remember { mutableStateOf(false) }
var sourceMenu by remember { mutableStateOf(false) }
val target = state.moods.firstOrNull { it.id == state.searchTargetMoodId } ?: state.moods.first()
LazyColumn(
@@ -95,11 +99,41 @@ fun SearchScreen(state: AppState, store: AppStore) {
}
}
item {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Text("Download source", style = MaterialTheme.typography.bodyMedium)
Box {
OutlinedButton(onClick = { sourceMenu = true }) {
Text(sourceLabel(target.source))
Icon(Icons.Rounded.ArrowDropDown, contentDescription = null)
}
DropdownMenu(
expanded = sourceMenu,
onDismissRequest = { sourceMenu = false },
) {
listOf("deezer", "youtube").forEach { option ->
DropdownMenuItem(
text = { Text(sourceLabel(option)) },
onClick = {
sourceMenu = false
store.setMoodSource(target.id, option)
},
)
}
}
}
}
}
item {
OutlinedTextField(
value = state.searchQuery,
onValueChange = store::setSearchQuery,
label = { Text("Search YouTube") },
label = { Text("Search ${sourceLabel(target.source)}") },
singleLine = true,
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
modifier = Modifier.fillMaxWidth(),
@@ -115,7 +149,7 @@ fun SearchScreen(state: AppState, store: AppStore) {
OutlinedTextField(
value = url,
onValueChange = { url = it },
label = { Text("Paste a YouTube URL") },
label = { Text("Paste a YouTube or Deezer URL") },
singleLine = true,
leadingIcon = { Icon(Icons.Rounded.Link, contentDescription = null) },
modifier = Modifier.weight(1f),
@@ -137,7 +171,7 @@ fun SearchScreen(state: AppState, store: AppStore) {
Row(verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(10.dp))
Text("Searching YouTube…", style = MaterialTheme.typography.bodySmall)
Text("Searching YouTube Music…", style = MaterialTheme.typography.bodySmall)
}
}
}
@@ -152,8 +186,12 @@ fun SearchScreen(state: AppState, store: AppStore) {
}
}
items(state.searchResults, key = { it.videoId }) { result ->
SearchRow(result, store)
items(state.searchResults, key = { "${it.source}-${it.externalId}" }) { result ->
SearchRow(
result,
store,
download = state.searchDownloads[downloadKey(result.source, result.externalId)],
)
}
item { Spacer(Modifier.size(24.dp)) }
@@ -161,7 +199,9 @@ fun SearchScreen(state: AppState, store: AppStore) {
}
@Composable
private fun SearchRow(result: SearchResult, store: AppStore) {
private fun SearchRow(result: SearchResult, store: AppStore, download: DownloadStatus?) {
val pending = download?.active == true
val added = download?.state == "done"
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
@@ -186,8 +226,43 @@ private fun SearchRow(result: SearchResult, store: AppStore) {
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (result.inMood) {
Row(verticalAlignment = Alignment.CenterVertically) {
when {
pending -> Row(verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(Modifier.size(12.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(6.dp))
Text(
"Downloading…",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
added -> Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Rounded.Check,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(14.dp),
)
Spacer(Modifier.width(4.dp))
Text(
"Added to this mood",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
download?.state == "failed" -> Text(
"Download failed" +
(download.error?.takeIf { it.isNotBlank() }?.let { " — ${it}" } ?: "") +
". Tap + to retry.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.error,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
result.inMood -> Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Rounded.Check,
contentDescription = null,
@@ -201,8 +276,8 @@ private fun SearchRow(result: SearchResult, store: AppStore) {
color = MaterialTheme.colorScheme.primary,
)
}
} else if (result.downloaded) {
Row(verticalAlignment = Alignment.CenterVertically) {
result.downloaded -> Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Rounded.DownloadDone,
contentDescription = null,
@@ -220,8 +295,11 @@ private fun SearchRow(result: SearchResult, store: AppStore) {
}
IconButton(
onClick = { store.addSearchResult(result) },
enabled = !result.inMood,
enabled = !result.inMood && !pending && !added,
) {
if (pending) {
CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
} else {
Icon(
Icons.Rounded.Add,
contentDescription = "Add to ${result.title}",
@@ -229,3 +307,4 @@ private fun SearchRow(result: SearchResult, store: AppStore) {
}
}
}
}
@@ -20,13 +20,16 @@ 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.platformName
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
@@ -66,6 +69,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 +154,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,
@@ -107,7 +193,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.2.0 · $platformName",
"AudioManager 0.4.2 · $platformName",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -38,7 +38,7 @@ class ApiClientTest {
)
"/api/v1/moods" -> respond(
"""
{"moods":[{"id":"mo-1","name":"Focus","collectionPercent":60,
{"moods":[{"id":"mo-1","name":"Focus","source":"deezer","collectionPercent":60,
"recommendationPercent":40,"recommendationCount":10,"refreshHours":24,
"createdAt":"now","changedAt":"now","songCount":2,"recommendationReady":3}]}
""".trimIndent(),
@@ -68,10 +68,10 @@ class ApiClientTest {
"/api/v1/search" -> respond(
"""
{"results":[
{"videoId":"v1","title":"Fresh","artist":"Artist","duration":180,
"downloaded":false},
{"videoId":"v2","title":"Old","artist":"Artist","duration":200,
"songId":"sg-2","downloaded":true}
{"source":"deezer","externalId":"v1","title":"Fresh","artist":"Artist",
"duration":180,"downloaded":false},
{"source":"deezer","externalId":"v2","title":"Old","artist":"Artist",
"duration":200,"songId":"sg-2","downloaded":true}
]}
""".trimIndent(),
HttpStatusCode.OK,
@@ -98,8 +98,9 @@ class ApiClientTest {
assertNull(results[0].songId)
assertEquals("sg-2", results[1].songId)
assertTrue(results[1].downloaded)
assertEquals("v2", results[1].externalId)
val added = client.addSong("mo-1", videoId = "v1")
val added = client.addSong("mo-1", source = "deezer", externalId = "v1")
assertTrue(added.downloading)
assertEquals(1, added.detail.mood.songCount)
}
@@ -112,8 +113,8 @@ class ApiClientTest {
"""
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
"changedAt":"now","songCount":2},"songs":[],"recommendations":[]},
"recommendation":{"videoId":"v1","title":"Pick","artist":"Artist",
"state":"added"}}
"recommendation":{"source":"deezer","externalId":"v1","title":"Pick",
"artist":"Artist","state":"added"}}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
@@ -122,8 +123,8 @@ class ApiClientTest {
"""
{"detail":{"mood":{"id":"mo-1","name":"Focus","createdAt":"now",
"changedAt":"now","songCount":2},"songs":[],"recommendations":[]},
"recommendation":{"videoId":"v2","title":"Other","artist":"Artist",
"state":"rejected"}}
"recommendation":{"source":"deezer","externalId":"v2","title":"Other",
"artist":"Artist","state":"rejected"}}
""".trimIndent(),
HttpStatusCode.OK,
jsonHeaders,
@@ -223,6 +224,6 @@ class ApiClientTest {
storage.write("mood-cache.json", """{"version":1,"songs":[{"id":"old"}]}""")
val invalidated = cache.load()
assertTrue(invalidated.moods.isEmpty())
assertEquals(2, invalidated.version)
assertEquals(3, invalidated.version)
}
}
@@ -29,6 +29,7 @@ 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.playback.PlaybackTrack
import win.taptap.musicmanager.client.store.AppStore
@OptIn(ExperimentalCoroutinesApi::class)
@@ -45,7 +46,6 @@ class AppStoreTest {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", 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/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/sessions" -> respond(
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
"queue":[${songJson("a")}]}""",
@@ -82,7 +82,6 @@ class AppStoreTest {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
else -> respondError(HttpStatusCode.NotFound)
}
}
@@ -111,8 +110,8 @@ class AppStoreTest {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/search" -> respond(
"""{"results":[{"videoId":"v1","title":"Fresh","artist":"Artist",
"duration":180,"downloaded":false}]}""",
"""{"results":[{"source":"youtube","externalId":"v1","title":"Fresh",
"artist":"Artist","duration":180,"downloaded":false}]}""",
HttpStatusCode.OK,
jsonHeaders,
)
@@ -133,7 +132,7 @@ class AppStoreTest {
advanceTimeBy(350)
runCurrent()
awaitState { store.state.value.searchResults.isNotEmpty() }
assertEquals("v1", store.state.value.searchResults.single().videoId)
assertEquals("v1", store.state.value.searchResults.single().externalId)
store.addSearchResult(store.state.value.searchResults.single())
awaitState { store.state.value.message != null }
@@ -141,6 +140,56 @@ class AppStoreTest {
store.release()
}
@Test
fun `search shows the queued download status for a result`() = 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/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
// Any detail the app may race with reports the job as active.
"/api/v1/moods/mo-1" -> respond(
detailJson(emptyList(), downloads = listOf(downloadJson("downloading"))),
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/search" -> respond(
"""{"results":[{"source":"youtube","externalId":"v1","title":"Fresh",
"artist":"Artist","duration":180,"downloaded":false}]}""",
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/songs" -> respond(
"""{"detail":${detailJson(emptyList(), downloads = listOf(downloadJson("queued")) )},
"added":false,"downloading":true}""",
HttpStatusCode.Accepted,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, FakePlayer(), engine)
runCurrent()
awaitState { store.state.value.moods.isNotEmpty() }
store.openSearch("mo-1")
store.setSearchQuery("fresh")
advanceTimeBy(350)
runCurrent()
awaitState("search results") { store.state.value.searchResults.isNotEmpty() }
store.addSearchResult(store.state.value.searchResults.single())
awaitState("queued download") {
store.state.value.searchDownloads["youtube|v1"]?.active == true
}
val status = store.state.value.searchDownloads.getValue("youtube|v1")
assertTrue(status.state == "queued" || status.state == "downloading")
assertTrue(status.active)
store.release()
}
@Test
fun `adding a recommendation refreshes the selected mood`() = runTest {
val storage = MemoryStorage()
@@ -155,7 +204,6 @@ class AppStoreTest {
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/recommendations/v1/add" -> respond(
"""{"detail":${detailJson(listOf("a"))},
"recommendation":${recommendationJson(state = "added", songId = "a")}}""",
@@ -180,6 +228,56 @@ class AppStoreTest {
store.release()
}
@Test
fun `changing the mood source re-runs the search against the new catalog`() = 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)
request.url.encodedPath == "/api/v1/moods" ->
respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
request.method.value == "PATCH" && request.url.encodedPath == "/api/v1/moods/mo-1" ->
respond(detailJson(emptyList(), source = "deezer"), HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/moods/mo-1" ->
respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/search" -> {
val source = request.url.parameters["source"]
val body = if (source == "deezer") {
"""{"results":[{"source":"deezer","externalId":"67238732",
"title":"Instant Crush","artist":"Daft Punk","duration":337,
"downloaded":false}]}"""
} else {
"""{"results":[]}"""
}
respond(body, HttpStatusCode.OK, jsonHeaders)
}
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, FakePlayer(), engine)
runCurrent()
store.openMood("mo-1")
awaitState { store.state.value.selectedMood != null }
store.openSearch("mo-1")
store.setSearchQuery("daft")
advanceTimeBy(350)
runCurrent()
store.setMoodSource("mo-1", "deezer")
awaitState("mood source updated") {
store.state.value.moods.first { it.id == "mo-1" }.source == "deezer"
}
// The source change re-runs the search immediately, without debounce.
awaitState { store.state.value.searchResults.any { it.source == "deezer" } }
assertEquals("deezer", store.state.value.moods.first { it.id == "mo-1" }.source)
assertEquals("67238732", store.state.value.searchResults.single().externalId)
store.release()
}
@Test
fun `sleep timer pauses playback when it expires`() = runTest {
val storage = MemoryStorage()
@@ -247,7 +345,6 @@ class AppStoreTest {
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/sessions" -> respond(
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
"queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""",
@@ -275,6 +372,142 @@ class AppStoreTest {
store.release()
}
@Test
fun `headset next and previous follow the queue instead of seeking`() = runTest {
val storage = MemoryStorage()
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
val player = FakePlayer()
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(3)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(detailJson(listOf("a", "b", "c")), HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/sessions" -> respond(
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
"queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""",
HttpStatusCode.Created,
jsonHeaders,
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, player, engine)
runCurrent()
store.openMood("mo-1")
awaitState { store.state.value.selectedMood != null }
store.playMood("mo-1")
awaitState { store.state.value.current?.id == "a" }
// A headset next moves the app queue: a -> b, not a seek inside one item.
player.pressNext()
awaitState { store.state.value.current?.id == "b" }
assertEquals("b", store.state.value.current?.id)
// Within two seconds, previous restores the track that just finished.
player.pressPrevious()
awaitState { store.state.value.current?.id == "a" }
assertEquals("a", store.state.value.current?.id)
// After two seconds it restarts the current track instead.
store.seekTo(5.0)
player.pressPrevious()
runCurrent()
assertEquals("a", store.state.value.current?.id)
assertEquals(0.0, player.seeks.last())
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 `logout clears the session and the mood cache`() = runTest {
val storage = MemoryStorage()
@@ -307,43 +540,62 @@ class AppStoreTest {
store.release()
}
private suspend fun TestScope.awaitState(predicate: () -> Boolean) {
private suspend fun TestScope.awaitState(predicate: () -> Boolean) =
awaitState("state", predicate)
private suspend fun TestScope.awaitState(label: String, predicate: () -> Boolean) {
repeat(500) {
runCurrent()
if (predicate()) return
withContext(Dispatchers.Default) { delay(10) }
}
throw AssertionError("state did not settle")
throw AssertionError("$label did not settle")
}
private val jsonHeaders = headersOf(HttpHeaders.ContentType, "application/json")
private fun songJson(id: String) = """
{"id":"$id","videoId":"video-$id","title":"Song $id","artist":"Artist",
"album":"Album","duration":180,"bitRate":320,"size":1000,"suffix":"mp3"}
{"id":"$id","source":"youtube","externalId":"video-$id","title":"Song $id",
"artist":"Artist","album":"Album","duration":180,"bitRate":320,"size":1000,"suffix":"mp3"}
""".trimIndent()
private fun moodJson(songCount: Int) = """
{"id":"mo-1","name":"Focus","collectionPercent":50,"recommendationPercent":50,
"recommendationCount":10,"refreshHours":24,"createdAt":"2026-01-01T00:00:00Z",
"changedAt":"2026-01-01T00:00:00Z","songCount":$songCount}
private fun moodJson(songCount: Int, source: String = "youtube") = """
{"id":"mo-1","name":"Focus","source":"$source","collectionPercent":50,
"recommendationPercent":50,"recommendationCount":10,"refreshHours":24,
"createdAt":"2026-01-01T00:00:00Z","changedAt":"2026-01-01T00:00:00Z",
"songCount":$songCount}
""".trimIndent()
private fun recommendationJson(state: String = "new", songId: String? = null) = """
{"videoId":"v1","title":"Pick","artist":"Artist","duration":180,"state":"$state",
{"source":"youtube","externalId":"v1","title":"Pick","artist":"Artist",
"duration":180,"state":"$state",
${songId?.let { "\"song\":${songJson(it)}," } ?: ""}
"firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z"}
""".trimIndent()
private fun detailJson(songs: List<String>, recommendation: String? = null) = """
{"mood":${moodJson(songs.size)},
private fun detailJson(
songs: List<String>,
recommendation: String? = null,
source: String = "youtube",
downloads: List<String> = emptyList(),
) = """
{"mood":${moodJson(songs.size, source)},
"songs":[${songs.joinToString(",") { """{"song":${songJson(it)},"origin":"search","addedAt":"now"}""" }}],
"recommendations":${recommendation?.let { "[$it]" } ?: "[]"}}
"recommendations":${recommendation?.let { "[$it]" } ?: "[]"},
"downloads":[${downloads.joinToString(",")}]}
""".trimIndent()
private fun downloadJson(
state: String,
source: String = "youtube",
externalId: String = "v1",
) = """{"source":"$source","externalId":"$externalId","state":"$state",
"attempts":1,"songId":null}""".trimIndent()
private fun song(id: String, duration: Int = 180) = Song(
id = id,
videoId = "video-$id",
source = "youtube",
externalId = "video-$id",
title = "Song $id",
artist = "Artist",
album = "Album",
@@ -375,25 +627,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
@@ -411,12 +717,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() }
}
@@ -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. */
@@ -124,3 +124,5 @@ class DesktopStorage : AppStorage {
actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull()
actual fun isUnmeteredNetwork(): Boolean = true
@@ -47,3 +47,5 @@ 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
@@ -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()
}
}
+4 -4
View File
@@ -10,7 +10,7 @@ Read that first. This file only records the client-side consequences.
## What the client becomes
- Moods are the only content model. No Library, no Longform, no mounted music.
- All music is downloaded on the server from YouTube; the client searches and
- All music is downloaded on the server from Deezer or YouTube Music; the client searches and
adds songs to a mood.
- A mood has **songs** (collection) and **recommendations** (auto-downloaded,
playable in radio, not permanent until added).
@@ -25,7 +25,7 @@ Read that first. This file only records the client-side consequences.
- **MoodDetail**: songs, add music, recommendations (Add / Not interested /
Retry), next batch, mood settings (query, genres, collectionPercent,
recommendationCount 0–30, refreshHours).
- **Search**: remote YouTube search, results over 10 minutes hidden, add to the
- **Search**: remote Deezer/YouTube Music search, results over 10 minutes hidden, add to the
current or a chosen mood, already-downloaded/in-mood badges, paste URL.
- **Downloads**: device-side offline files, delete/clear, storage usage.
- **Settings**: server/account/devices/logout (no scan UI).
@@ -59,10 +59,10 @@ Implemented. Concretely:
- `AppCache` (version 2) stores moods and details only; old cache shapes are
discarded. Session and playback snapshots are kept.
- `AppStore` has `Moods | MoodDetail | Search | Downloads | Settings`, remote
search with a target mood, add/remove song, recommendation actions, offline
Deezer/YouTube Music search with a target mood and a per-mood source, add/remove song, recommendation actions, offline
playback from device downloads, and no longform/library paths.
- The UI has a dedicated Search screen (mood picker, paste URL, downloaded
badges) and a Downloads screen. Mood Detail shows songs, add music,
recommendation states and the new options. The player keeps queue editing,
recommendation states and the new options. The player keeps drag-to-reorder queue editing,
previous/seek and the sleep timer.
- Device downloads store covers by song id (`<songId>.jpg`).