Playback: - Persist the playhead in the playback snapshot and resume from it; restored longform progress is no longer overwritten with 0 on first play. - Previous compares elapsed playtime since the track start, so resuming at 1:00:00 and pressing previous goes back instead of restarting the book. - Auto-advance no longer overwrites completed=true with false, longform PUTs are serialized, and playing rows/search results resume saved positions. - Pause cancels the 400 ms poll; seek errors are reported instead of crashing. Sync and state: - First-sync snapshots keep the first page revision; cached revisions are only trusted for the same server/user. - Refresh re-reads /me, merges local and server longform progress by timestamp, replays newer local positions, and keeps cached longform after deltas. - Logout cancels refresh jobs, suppresses late progress writes, clears after playback teardown, and closes the HTTP client on release. - Failed/racing mood opens clear the previous mood; stale responses cannot replace a newer selection. Mood drafts survive background refreshes. Downloads and storage: - Stream downloads to a .part file and atomically rename on Android/desktop, with a download-specific timeout and no whole-file buffering. - Cache writes are best-effort and atomic; blocked/full web storage no longer leaves the app on the splash screen or blocks playback. - Artwork failures do not fail audio downloads; failed downloads refresh the download index. - Android queues sleep-timer commands before the controller connects. UI: - Music search is wired, debounced and kept separate from mood search. - Player bar respects navigation-bar insets and hides music-only mood actions for longform. Mood gradient handles Int.MIN_VALUE.
This commit is contained in:
1 parent
14bebced10
commit
43bd9629d3
17 files changed
+766
-145
No files matched your search
@@ -16,6 +16,7 @@ import io.ktor.client.request.put
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.client.statement.HttpResponse
|
||||
import io.ktor.client.statement.bodyAsBytes
|
||||
import io.ktor.client.statement.bodyAsChannel
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpHeaders
|
||||
import io.ktor.http.HttpStatusCode
|
||||
@@ -23,6 +24,7 @@ import io.ktor.http.contentType
|
||||
import io.ktor.http.encodeURLParameter
|
||||
import io.ktor.http.isSuccess
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import io.ktor.utils.io.ByteReadChannel
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
fun configuredHttpClient(engine: HttpClientEngine): HttpClient = HttpClient(engine) {
|
||||
@@ -85,6 +87,10 @@ class ApiClient(private val http: HttpClient) {
|
||||
imageCache.clear()
|
||||
}
|
||||
|
||||
fun close() {
|
||||
http.close()
|
||||
}
|
||||
|
||||
suspend fun me(): User = get("/me")
|
||||
|
||||
suspend fun logout() {
|
||||
@@ -173,11 +179,13 @@ class ApiClient(private val http: HttpClient) {
|
||||
since: String? = null,
|
||||
limit: Int = 500,
|
||||
scope: String = "all",
|
||||
revision: String? = null,
|
||||
): LibraryPage {
|
||||
val query = buildString {
|
||||
append("?limit=$limit&scope=$scope")
|
||||
cursor?.let { append("&cursor=${it.encodeURLParameter()}") }
|
||||
since?.let { append("&since=${it.encodeURLParameter()}") }
|
||||
revision?.let { append("&revision=${it.encodeURLParameter()}") }
|
||||
}
|
||||
return get("/library/songs$query")
|
||||
}
|
||||
@@ -266,25 +274,61 @@ class ApiClient(private val http: HttpClient) {
|
||||
}
|
||||
}.getOrNull()
|
||||
if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear()
|
||||
coverCache[key] = result
|
||||
// Do not cache failures: a cover can appear after the scanner indexes a
|
||||
// newly downloaded track, and the UI should pick it up without a restart.
|
||||
if (result != null) coverCache[key] = result
|
||||
return result
|
||||
}
|
||||
|
||||
/** Remote artwork such as YT thumbnails, cached for the app's lifetime. */
|
||||
suspend fun image(url: String): ByteArray? {
|
||||
if (imageCache.containsKey(url)) return imageCache[url]
|
||||
val bytes = runCatching { http.get(url).bodyAsBytes() }.getOrNull()
|
||||
val result = bytes?.takeIf { it.isNotEmpty() }
|
||||
val result = runCatching {
|
||||
val response = http.get(url)
|
||||
if (response.status.isSuccess()) {
|
||||
response.bodyAsBytes().takeIf { it.isNotEmpty() }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}.getOrNull()
|
||||
if (imageCache.size > MAX_CACHED_IMAGES) imageCache.clear()
|
||||
imageCache[url] = result
|
||||
if (result != null) imageCache[url] = result
|
||||
return result
|
||||
}
|
||||
|
||||
suspend fun download(songId: String): ByteArray =
|
||||
http.get("$baseUrl/api/v1/songs/$songId/stream") {
|
||||
suspend fun download(songId: String): ByteArray {
|
||||
val response = downloadResponse(songId)
|
||||
return response.bodyAsBytes().takeIf { it.isNotEmpty() }
|
||||
?: throw ApiException(
|
||||
status = response.status.value,
|
||||
code = "empty_download",
|
||||
message = "The server returned an empty audio file",
|
||||
)
|
||||
}
|
||||
|
||||
/** Streams an audio download into [sink] instead of buffering it in RAM. */
|
||||
suspend fun downloadTo(
|
||||
songId: String,
|
||||
sink: suspend (ByteReadChannel) -> String?,
|
||||
): String? {
|
||||
val response = downloadResponse(songId)
|
||||
return sink(response.bodyAsChannel())
|
||||
}
|
||||
|
||||
private suspend fun downloadResponse(songId: String): HttpResponse {
|
||||
val response = http.get("$baseUrl/api/v1/songs/$songId/stream") {
|
||||
auth()
|
||||
url.parameters.append("download", "true")
|
||||
}.bodyAsBytes()
|
||||
// A long audiobook must not be cancelled by the default 30s total
|
||||
// request timeout.
|
||||
timeout {
|
||||
requestTimeoutMillis = 6 * 60 * 60 * 1000
|
||||
socketTimeoutMillis = 60_000
|
||||
}
|
||||
}
|
||||
if (!response.status.isSuccess()) throw error(response)
|
||||
return response
|
||||
}
|
||||
|
||||
fun streamUrl(songId: String): String =
|
||||
"$baseUrl/api/v1/songs/$songId/stream?token=${token.orEmpty().encodeURLParameter()}"
|
||||
|
||||
@@ -10,6 +10,9 @@ interface AppStorage {
|
||||
fun saveDownload(songId: String, bytes: ByteArray): String?
|
||||
fun downloadPath(songId: String): String?
|
||||
|
||||
/** Streams a download to disk and returns the final playback path. */
|
||||
suspend fun saveDownloadStream(songId: String, source: io.ktor.utils.io.ByteReadChannel): String? = null
|
||||
|
||||
/** Stores the cover next to the audio file so offline playback keeps artwork. */
|
||||
fun saveArtwork(songId: String, bytes: ByteArray): String?
|
||||
fun artworkBytes(songId: String): ByteArray?
|
||||
|
||||
+23
-12
@@ -34,6 +34,7 @@ data class PlaybackSnapshot(
|
||||
val queue: List<Song> = emptyList(),
|
||||
val current: Song? = null,
|
||||
val history: List<Song> = emptyList(),
|
||||
val positionSeconds: Double = 0.0,
|
||||
)
|
||||
|
||||
class LibraryCache(private val storage: AppStorage) {
|
||||
@@ -45,49 +46,59 @@ class LibraryCache(private val storage: AppStorage) {
|
||||
}
|
||||
|
||||
fun loadSession(): SessionState? =
|
||||
storage.read(SESSION_FILE)?.let {
|
||||
read(SESSION_FILE)?.let {
|
||||
runCatching { json.decodeFromString<SessionState>(it) }.getOrNull()
|
||||
}
|
||||
|
||||
fun saveSession(session: SessionState?) {
|
||||
if (session == null) storage.delete(SESSION_FILE) else storage.write(SESSION_FILE, json.encodeToString(session))
|
||||
if (session == null) delete(SESSION_FILE) else write(SESSION_FILE, json.encodeToString(session))
|
||||
}
|
||||
|
||||
fun load(): CachedState =
|
||||
storage.read(CACHE_FILE)?.let {
|
||||
read(CACHE_FILE)?.let {
|
||||
runCatching { json.decodeFromString<CachedState>(it) }.getOrNull()
|
||||
} ?: CachedState()
|
||||
|
||||
fun save(state: CachedState) {
|
||||
storage.write(CACHE_FILE, json.encodeToString(state))
|
||||
write(CACHE_FILE, json.encodeToString(state))
|
||||
}
|
||||
|
||||
fun loadPlayback(): PlaybackSnapshot? =
|
||||
storage.read(PLAYBACK_FILE)?.let {
|
||||
read(PLAYBACK_FILE)?.let {
|
||||
runCatching { json.decodeFromString<PlaybackSnapshot>(it) }.getOrNull()
|
||||
}
|
||||
|
||||
fun savePlayback(snapshot: PlaybackSnapshot?) {
|
||||
if (snapshot == null || (snapshot.current == null && snapshot.queue.isEmpty())) {
|
||||
storage.delete(PLAYBACK_FILE)
|
||||
delete(PLAYBACK_FILE)
|
||||
} else {
|
||||
storage.write(PLAYBACK_FILE, json.encodeToString(snapshot))
|
||||
write(PLAYBACK_FILE, json.encodeToString(snapshot))
|
||||
}
|
||||
}
|
||||
|
||||
fun loadProgress(): List<LongformProgress> =
|
||||
storage.read(PROGRESS_FILE)?.let {
|
||||
read(PROGRESS_FILE)?.let {
|
||||
runCatching { json.decodeFromString<List<LongformProgress>>(it) }.getOrNull()
|
||||
} ?: emptyList()
|
||||
|
||||
fun saveProgress(progress: List<LongformProgress>) {
|
||||
storage.write(PROGRESS_FILE, json.encodeToString(progress))
|
||||
write(PROGRESS_FILE, json.encodeToString(progress))
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
storage.delete(CACHE_FILE)
|
||||
storage.delete(PLAYBACK_FILE)
|
||||
storage.delete(PROGRESS_FILE)
|
||||
delete(CACHE_FILE)
|
||||
delete(PLAYBACK_FILE)
|
||||
delete(PROGRESS_FILE)
|
||||
}
|
||||
|
||||
// Web storage can be blocked (Safari private mode) or full. Cache failure
|
||||
// must never prevent the app from reaching the login screen or playing.
|
||||
private fun read(name: String): String? = runCatching { storage.read(name) }.getOrNull()
|
||||
private fun write(name: String, text: String) {
|
||||
runCatching { storage.write(name, text) }
|
||||
}
|
||||
private fun delete(name: String) {
|
||||
runCatching { storage.delete(name) }
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
||||
+288
-86
@@ -1,10 +1,13 @@
|
||||
package win.taptap.musicmanager.client.store
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -60,7 +63,10 @@ data class AppState(
|
||||
val longform: List<Song> = emptyList(),
|
||||
val longformResults: List<Song> = emptyList(),
|
||||
val longformProgress: Map<String, LongformProgress> = emptyMap(),
|
||||
/** Results for the mood seed picker. */
|
||||
val searchResults: List<Song> = emptyList(),
|
||||
/** Results for the Music library tab, kept separate from mood search. */
|
||||
val musicResults: List<Song> = emptyList(),
|
||||
val searching: Boolean = false,
|
||||
val loading: Boolean = false,
|
||||
val saving: Boolean = false,
|
||||
@@ -85,13 +91,21 @@ class AppStore(
|
||||
val state: StateFlow<AppState> = _state.asStateFlow()
|
||||
|
||||
private var pollJob: Job? = null
|
||||
private var refreshJob: Job? = null
|
||||
private var sleepJob: Job? = null
|
||||
private var musicSearchJob: Job? = null
|
||||
private var longformSearchJob: Job? = null
|
||||
private var reconnectJob: Job? = null
|
||||
private var playbackStarted = false
|
||||
private var advancing = false
|
||||
private var fetching = false
|
||||
private var finishing = false
|
||||
private var pollTicks = 0
|
||||
private var trackStartOffset = 0.0
|
||||
private var dataGeneration = 0
|
||||
private var moodRequestGeneration = 0
|
||||
private var loggingOut = false
|
||||
private val progressSaveMutex = Mutex()
|
||||
|
||||
init {
|
||||
bootstrap()
|
||||
@@ -103,6 +117,12 @@ class AppStore(
|
||||
val cached = cache.load()
|
||||
val playback = cache.loadPlayback()
|
||||
val progress = cache.loadProgress()
|
||||
val progressById = progress.associateBy { entry -> entry.songId }
|
||||
val restoredSong = playback?.current
|
||||
val restoredPosition = playback?.positionSeconds?.takeIf { it > 0.0 }
|
||||
?: restoredSong?.let { progressById[it.id]?.positionSeconds?.toDouble() }
|
||||
?: 0.0
|
||||
trackStartOffset = restoredPosition
|
||||
_state.update {
|
||||
it.copy(
|
||||
booting = false,
|
||||
@@ -110,13 +130,14 @@ class AppStore(
|
||||
moods = cached.moods,
|
||||
library = cached.songs.sortedLibrary(),
|
||||
longform = cached.longform.sortedLibrary(),
|
||||
longformProgress = progress.associateBy { entry -> entry.songId },
|
||||
longformProgress = progressById,
|
||||
selectedMood = cached.moodDetails.firstOrNull(),
|
||||
session = playback?.session,
|
||||
queue = playback?.queue.orEmpty(),
|
||||
current = playback?.current,
|
||||
current = restoredSong,
|
||||
history = playback?.history.orEmpty(),
|
||||
durationSeconds = playback?.current?.duration?.toDouble() ?: 0.0,
|
||||
positionSeconds = restoredPosition,
|
||||
durationSeconds = restoredSong?.duration?.toDouble() ?: 0.0,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -145,13 +166,18 @@ class AppStore(
|
||||
deviceName = "$platformName device",
|
||||
platform = platformName,
|
||||
)
|
||||
cache.saveSession(SessionState(api.baseUrl, response.token, response.user))
|
||||
dataGeneration += 1
|
||||
runCatching {
|
||||
cache.saveSession(SessionState(api.baseUrl, response.token, response.user))
|
||||
}
|
||||
loggingOut = false
|
||||
_state.update {
|
||||
it.copy(
|
||||
authenticated = true,
|
||||
user = response.user,
|
||||
serverUrl = api.baseUrl,
|
||||
loading = false,
|
||||
message = null,
|
||||
)
|
||||
}
|
||||
refreshAll()
|
||||
@@ -164,11 +190,17 @@ class AppStore(
|
||||
}
|
||||
|
||||
fun logout() {
|
||||
dataGeneration += 1
|
||||
loggingOut = true
|
||||
scope.launch {
|
||||
musicSearchJob?.cancel()
|
||||
longformSearchJob?.cancel()
|
||||
refreshJob?.cancel()
|
||||
stopPlayback()
|
||||
runCatching { api.logout() }
|
||||
api.clear()
|
||||
cache.saveSession(null)
|
||||
cache.clear()
|
||||
stopPlayback()
|
||||
_state.value = AppState(
|
||||
booting = false,
|
||||
serverUrl = _state.value.serverUrl,
|
||||
@@ -178,14 +210,31 @@ class AppStore(
|
||||
}
|
||||
|
||||
fun refreshAll(silent: Boolean = false) {
|
||||
scope.launch { refreshAllNow(silent) }
|
||||
refreshJob?.cancel()
|
||||
refreshJob = scope.launch { refreshAllNow(silent) }
|
||||
}
|
||||
|
||||
private suspend fun refreshAllNow(silent: Boolean) {
|
||||
if (!silent) _state.update { it.copy(loading = true) }
|
||||
val generation = dataGeneration
|
||||
try {
|
||||
// Folder assignments can change server-side after login. Re-read the
|
||||
// user so the music/longform split does not keep using stale folders.
|
||||
val me = try {
|
||||
api.me()
|
||||
} catch (t: ApiException) {
|
||||
if (t.status == 401) throw t
|
||||
null
|
||||
}
|
||||
val currentUser = me ?: _state.value.user
|
||||
if (me != null) {
|
||||
cache.loadSession()?.let { session -> cache.saveSession(session.copy(user = me)) }
|
||||
}
|
||||
val moods = api.moods()
|
||||
val cached = cache.load()
|
||||
val loaded = cache.load()
|
||||
val cacheMatches = loaded.serverUrl == _state.value.serverUrl &&
|
||||
(loaded.userName.isEmpty() || loaded.userName == currentUser?.name.orEmpty())
|
||||
val cached = if (cacheMatches) loaded else CachedState()
|
||||
// Both halves of the cache must feed the delta sync; otherwise the
|
||||
// long-form list disappears as soon as the first delta arrives.
|
||||
var songs = (cached.songs + cached.longform)
|
||||
@@ -194,9 +243,18 @@ class AppStore(
|
||||
var revision = cached.revision
|
||||
|
||||
if (revision == null) {
|
||||
// Keep the first page's timestamp across the whole snapshot, so
|
||||
// songs inserted between pages are fetched by the next delta.
|
||||
var snapshotRevision: String? = null
|
||||
var cursor: String? = null
|
||||
do {
|
||||
val page = api.library(cursor = cursor, since = null, limit = 500)
|
||||
val page = api.library(
|
||||
cursor = cursor,
|
||||
since = null,
|
||||
limit = 500,
|
||||
revision = snapshotRevision,
|
||||
)
|
||||
if (snapshotRevision == null) snapshotRevision = page.revision
|
||||
page.songs.forEach { songs[it.id] = it }
|
||||
cursor = page.nextCursor
|
||||
revision = page.revision
|
||||
@@ -213,37 +271,67 @@ class AppStore(
|
||||
}
|
||||
|
||||
val details = cached.moodDetails.filter { detail -> moods.any { it.id == detail.mood.id } }
|
||||
val longformFolders = longformFolders()
|
||||
val longformFolders = currentUser?.longformFolders?.toSet().orEmpty()
|
||||
val allSongs = songs.values.toList()
|
||||
val longformSongs = allSongs.filter { it.folderId in longformFolders }
|
||||
val musicSongs = allSongs.filterNot { it.folderId in longformFolders }
|
||||
val serverProgress = runCatching { api.longformProgress() }.getOrNull()
|
||||
|
||||
cache.save(
|
||||
CachedState(
|
||||
serverUrl = _state.value.serverUrl,
|
||||
userName = _state.value.user?.name.orEmpty(),
|
||||
revision = revision,
|
||||
songs = musicSongs,
|
||||
longform = longformSongs,
|
||||
moods = moods,
|
||||
moodDetails = details,
|
||||
),
|
||||
)
|
||||
serverProgress?.let { items ->
|
||||
cache.saveProgress(items.map { it.toProgress() })
|
||||
if (generation != dataGeneration) return
|
||||
runCatching {
|
||||
cache.save(
|
||||
CachedState(
|
||||
serverUrl = _state.value.serverUrl,
|
||||
userName = currentUser?.name.orEmpty(),
|
||||
revision = revision,
|
||||
songs = musicSongs,
|
||||
longform = longformSongs,
|
||||
moods = moods,
|
||||
moodDetails = details,
|
||||
),
|
||||
)
|
||||
}
|
||||
// Progress saved while offline must not be replaced by a stale
|
||||
// server copy. Keep whichever entry was updated last.
|
||||
val localProgress = _state.value.longformProgress
|
||||
val mergedProgress = localProgress.toMutableMap()
|
||||
serverProgress?.forEach { item ->
|
||||
val remote = item.toProgress()
|
||||
val existing = mergedProgress[remote.songId]
|
||||
if (existing == null || remote.updatedAt >= existing.updatedAt) {
|
||||
mergedProgress[remote.songId] = remote
|
||||
}
|
||||
}
|
||||
if (generation != dataGeneration) return
|
||||
if (serverProgress != null) {
|
||||
cache.saveProgress(mergedProgress.values.toList())
|
||||
// Replay local positions that are newer than the server copy
|
||||
// (typically written while offline).
|
||||
mergedProgress.forEach { (songId, local) ->
|
||||
val remote = serverProgress.firstOrNull { it.song.id == songId }
|
||||
if (remote == null || local.updatedAt > remote.updatedAt) {
|
||||
runCatching {
|
||||
api.saveLongformProgress(
|
||||
songId,
|
||||
local.positionSeconds,
|
||||
local.durationSeconds,
|
||||
local.completed,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (generation != dataGeneration) return
|
||||
_state.update {
|
||||
it.copy(
|
||||
loading = false,
|
||||
offline = false,
|
||||
user = currentUser,
|
||||
moods = moods,
|
||||
library = musicSongs.sortedLibrary(),
|
||||
longform = longformSongs.sortedLibrary(),
|
||||
longformProgress = serverProgress
|
||||
?.associate { item -> item.song.id to item.toProgress() }
|
||||
?: it.longformProgress,
|
||||
longformProgress = if (serverProgress != null) mergedProgress else it.longformProgress,
|
||||
)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
@@ -265,23 +353,37 @@ class AppStore(
|
||||
}
|
||||
|
||||
fun openMoods() {
|
||||
moodRequestGeneration += 1
|
||||
_state.update { it.copy(screen = Screen.Moods) }
|
||||
}
|
||||
|
||||
fun openMood(id: String) {
|
||||
scope.launch {
|
||||
_state.update { it.copy(loading = true, screen = Screen.MoodDetail) }
|
||||
val request = ++moodRequestGeneration
|
||||
_state.update {
|
||||
it.copy(
|
||||
loading = true,
|
||||
screen = Screen.MoodDetail,
|
||||
selectedMood = null,
|
||||
preview = emptyList(),
|
||||
searchResults = emptyList(),
|
||||
)
|
||||
}
|
||||
try {
|
||||
val detail = api.mood(id)
|
||||
val preview = runCatching { api.preview(id, 20) }.getOrDefault(emptyList())
|
||||
if (request != moodRequestGeneration) return@launch
|
||||
cacheDetail(detail)
|
||||
_state.update { it.copy(loading = false, selectedMood = detail, preview = preview) }
|
||||
} catch (t: Throwable) {
|
||||
if (request != moodRequestGeneration) return@launch
|
||||
val cached = cache.load().moodDetails.firstOrNull { it.mood.id == id }
|
||||
_state.update {
|
||||
it.copy(
|
||||
loading = false,
|
||||
selectedMood = cached ?: it.selectedMood,
|
||||
// Never leave a different mood editable under the new title.
|
||||
selectedMood = cached,
|
||||
preview = emptyList(),
|
||||
message = if (cached == null) t.friendlyMessage() else "Showing cached mood",
|
||||
messageIsError = cached == null,
|
||||
messageId = it.messageId + 1,
|
||||
@@ -295,7 +397,9 @@ class AppStore(
|
||||
fun refreshSelectedMood() {
|
||||
val moodId = _state.value.selectedMood?.mood?.id ?: return
|
||||
scope.launch {
|
||||
runCatching { api.mood(moodId) }.onSuccess { applyMoodDetail(it) }
|
||||
runCatching { api.mood(moodId) }.onSuccess { detail ->
|
||||
if (_state.value.selectedMood?.mood?.id == moodId) applyMoodDetail(detail)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -379,12 +483,10 @@ class AppStore(
|
||||
seedPercent = seedPercent,
|
||||
),
|
||||
)
|
||||
cacheDetail(updated)
|
||||
applyMoodDetail(updated)
|
||||
_state.update {
|
||||
it.copy(
|
||||
saving = false,
|
||||
selectedMood = updated,
|
||||
moods = it.moods.map { mood -> if (mood.id == updated.mood.id) updated.mood else mood },
|
||||
message = "Saved",
|
||||
messageIsError = false,
|
||||
messageId = it.messageId + 1,
|
||||
@@ -421,11 +523,9 @@ class AppStore(
|
||||
try {
|
||||
api.addSeed(moodId, songId)
|
||||
val detail = api.mood(moodId)
|
||||
cacheDetail(detail)
|
||||
applyMoodDetail(detail)
|
||||
_state.update {
|
||||
it.copy(
|
||||
selectedMood = detail,
|
||||
moods = it.moods.map { mood -> if (mood.id == moodId) detail.mood else mood },
|
||||
message = "Seed added",
|
||||
messageIsError = false,
|
||||
messageId = it.messageId + 1,
|
||||
@@ -442,11 +542,9 @@ class AppStore(
|
||||
try {
|
||||
api.removeSeed(moodId, songId)
|
||||
val detail = api.mood(moodId)
|
||||
cacheDetail(detail)
|
||||
applyMoodDetail(detail)
|
||||
_state.update {
|
||||
it.copy(
|
||||
selectedMood = detail,
|
||||
moods = it.moods.map { mood -> if (mood.id == moodId) detail.mood else mood },
|
||||
message = "Seed removed",
|
||||
messageIsError = false,
|
||||
messageId = it.messageId + 1,
|
||||
@@ -475,19 +573,48 @@ class AppStore(
|
||||
}
|
||||
}
|
||||
|
||||
fun searchMusic(query: String) {
|
||||
musicSearchJob?.cancel()
|
||||
if (query.isBlank()) {
|
||||
_state.update { it.copy(musicResults = emptyList()) }
|
||||
return
|
||||
}
|
||||
musicSearchJob = scope.launch {
|
||||
delay(SEARCH_DEBOUNCE_MS)
|
||||
_state.update { it.copy(searching = true) }
|
||||
try {
|
||||
val songs = api.search(query, 60, scope = "music")
|
||||
_state.update { it.copy(musicResults = songs) }
|
||||
} catch (t: CancellationException) {
|
||||
throw t
|
||||
} catch (t: Throwable) {
|
||||
_state.update { it.copy(musicResults = emptyList()) }
|
||||
message(t)
|
||||
} finally {
|
||||
_state.update { it.copy(searching = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun searchLongform(query: String) {
|
||||
longformSearchJob?.cancel()
|
||||
if (query.isBlank()) {
|
||||
_state.update { it.copy(longformResults = emptyList()) }
|
||||
return
|
||||
}
|
||||
scope.launch {
|
||||
longformSearchJob = scope.launch {
|
||||
delay(SEARCH_DEBOUNCE_MS)
|
||||
_state.update { it.copy(searching = true) }
|
||||
try {
|
||||
val songs = api.search(query, 60, scope = "longform")
|
||||
_state.update { it.copy(searching = false, longformResults = songs) }
|
||||
_state.update { it.copy(longformResults = songs) }
|
||||
} catch (t: CancellationException) {
|
||||
throw t
|
||||
} catch (t: Throwable) {
|
||||
_state.update { it.copy(searching = false, longformResults = emptyList()) }
|
||||
_state.update { it.copy(longformResults = emptyList()) }
|
||||
message(t)
|
||||
} finally {
|
||||
_state.update { it.copy(searching = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -521,8 +648,10 @@ class AppStore(
|
||||
)
|
||||
}
|
||||
playNext()
|
||||
scheduleReconnect()
|
||||
} else {
|
||||
message(t)
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -530,6 +659,7 @@ class AppStore(
|
||||
|
||||
fun playSong(song: Song) {
|
||||
scope.launch {
|
||||
reportCurrentProgress(completed = false)
|
||||
_state.value.session?.let { api.closeSession(it.id) }
|
||||
_state.update {
|
||||
it.copy(
|
||||
@@ -595,9 +725,11 @@ class AppStore(
|
||||
}
|
||||
}
|
||||
|
||||
fun playLongformSong(song: Song, startAtSeconds: Double = 0.0) {
|
||||
fun playLongformSong(song: Song, startAtSeconds: Double? = null) {
|
||||
scope.launch {
|
||||
reportCurrentProgress(completed = false)
|
||||
_state.value.session?.let { runCatching { api.closeSession(it.id) } }
|
||||
val startAt = startAtSeconds ?: savedPosition(song)
|
||||
_state.update {
|
||||
it.copy(
|
||||
session = null,
|
||||
@@ -605,20 +737,25 @@ class AppStore(
|
||||
current = song,
|
||||
history = pushHistory(it.history, it.current),
|
||||
playing = true,
|
||||
positionSeconds = startAtSeconds,
|
||||
positionSeconds = startAt,
|
||||
durationSeconds = song.duration.toDouble(),
|
||||
)
|
||||
}
|
||||
persistPlayback()
|
||||
startSong(song, startAtSeconds)
|
||||
startSong(song, startAt)
|
||||
}
|
||||
}
|
||||
|
||||
fun resumeLongform(songId: String) {
|
||||
val state = _state.value
|
||||
val song = state.longform.firstOrNull { it.id == songId } ?: return
|
||||
val startAt = state.longformProgress[songId]?.positionSeconds?.toDouble() ?: 0.0
|
||||
playLongformSong(song, startAt)
|
||||
playLongformSong(song, savedPosition(song))
|
||||
}
|
||||
|
||||
private fun savedPosition(song: Song): Double {
|
||||
if (song.folderId !in longformFolders()) return 0.0
|
||||
val progress = _state.value.longformProgress[song.id] ?: return 0.0
|
||||
return if (progress.completed) 0.0 else progress.positionSeconds.toDouble().coerceAtLeast(0.0)
|
||||
}
|
||||
|
||||
fun moveInQueue(fromIndex: Int, toIndex: Int) {
|
||||
@@ -675,6 +812,9 @@ class AppStore(
|
||||
if (!isActive) return@launch
|
||||
val wasPlaying = _state.value.playing
|
||||
player.pause()
|
||||
pollJob?.cancel()
|
||||
reportCurrentProgress(completed = false)
|
||||
persistPlayback()
|
||||
_state.update {
|
||||
it.copy(
|
||||
playing = false,
|
||||
@@ -751,14 +891,26 @@ class AppStore(
|
||||
val song = state.current ?: return
|
||||
if (state.playing) {
|
||||
player.pause()
|
||||
pollJob?.cancel()
|
||||
_state.update { it.copy(playing = false) }
|
||||
reportCurrentProgress(completed = false)
|
||||
persistPlayback()
|
||||
} else if (!playbackStarted || player.isFinished()) {
|
||||
// Restored queue or finished track: start it from the beginning.
|
||||
_state.update {
|
||||
it.copy(playing = true, positionSeconds = 0.0, durationSeconds = song.duration.toDouble())
|
||||
val finished = player.isFinished()
|
||||
val duration = state.durationSeconds.takeIf { it > 0 } ?: song.duration.toDouble()
|
||||
val startAt = if (finished || (duration > 0 && state.positionSeconds >= duration - 1.0)) {
|
||||
0.0
|
||||
} else {
|
||||
state.positionSeconds.coerceAtLeast(0.0)
|
||||
}
|
||||
startSong(song)
|
||||
_state.update {
|
||||
it.copy(
|
||||
playing = true,
|
||||
positionSeconds = startAt,
|
||||
durationSeconds = duration,
|
||||
)
|
||||
}
|
||||
startSong(song, startAt)
|
||||
} else {
|
||||
player.resume()
|
||||
_state.update { it.copy(playing = true) }
|
||||
@@ -768,7 +920,7 @@ class AppStore(
|
||||
|
||||
fun skip() {
|
||||
val state = _state.value
|
||||
state.current?.let { report("skipped", it.id) }
|
||||
state.current?.let { report("skipped", it.id, state.positionSeconds.toInt()) }
|
||||
playNext()
|
||||
}
|
||||
|
||||
@@ -780,7 +932,8 @@ class AppStore(
|
||||
fun previous() {
|
||||
val state = _state.value
|
||||
val song = state.current ?: return
|
||||
if (state.positionSeconds > 2.0) {
|
||||
val elapsed = (state.positionSeconds - trackStartOffset).coerceAtLeast(0.0)
|
||||
if (elapsed > 2.0) {
|
||||
restartCurrent(song)
|
||||
return
|
||||
}
|
||||
@@ -791,6 +944,7 @@ class AppStore(
|
||||
return
|
||||
}
|
||||
|
||||
val targetStart = savedPosition(target)
|
||||
reportCurrentProgress(completed = false)
|
||||
_state.update {
|
||||
it.copy(
|
||||
@@ -798,18 +952,20 @@ class AppStore(
|
||||
queue = listOf(song) + it.queue,
|
||||
current = target,
|
||||
playing = true,
|
||||
positionSeconds = 0.0,
|
||||
positionSeconds = targetStart,
|
||||
durationSeconds = target.duration.toDouble(),
|
||||
)
|
||||
}
|
||||
persistPlayback()
|
||||
startSong(target)
|
||||
report("started", target.id)
|
||||
startSong(target, targetStart)
|
||||
report("started", target.id, 0)
|
||||
}
|
||||
|
||||
private fun restartCurrent(song: Song) {
|
||||
trackStartOffset = 0.0
|
||||
if (player.canSeek) {
|
||||
player.seekTo(0.0)
|
||||
runCatching { player.seekTo(0.0) }
|
||||
.onFailure { message(it) }
|
||||
_state.update { it.copy(positionSeconds = 0.0) }
|
||||
} else {
|
||||
_state.update { it.copy(playing = true, positionSeconds = 0.0) }
|
||||
@@ -821,9 +977,15 @@ class AppStore(
|
||||
|
||||
fun seekTo(seconds: Double) {
|
||||
if (!player.canSeek) return
|
||||
player.seekTo(seconds)
|
||||
_state.update { it.copy(positionSeconds = seconds) }
|
||||
reportCurrentProgress(completed = false)
|
||||
val target = seconds.coerceAtLeast(0.0)
|
||||
try {
|
||||
player.seekTo(target)
|
||||
_state.update { it.copy(positionSeconds = target) }
|
||||
reportCurrentProgress(completed = false)
|
||||
persistPlayback()
|
||||
} catch (t: Throwable) {
|
||||
message(t)
|
||||
}
|
||||
}
|
||||
|
||||
fun addCurrentToMood(targetMoodId: String?) {
|
||||
@@ -850,14 +1012,14 @@ class AppStore(
|
||||
val updatedMoods = state.moods.map { mood ->
|
||||
if (mood.id == response.mood.id) response.mood else mood
|
||||
}
|
||||
val selected = state.selectedMood?.let { detail ->
|
||||
if (detail.mood.id == response.mood.id) {
|
||||
detail.copy(mood = response.mood)
|
||||
} else {
|
||||
detail
|
||||
}
|
||||
}
|
||||
_state.update {
|
||||
val selected = it.selectedMood?.let { detail ->
|
||||
if (detail.mood.id == response.mood.id) {
|
||||
detail.copy(mood = response.mood)
|
||||
} else {
|
||||
detail
|
||||
}
|
||||
}
|
||||
it.copy(
|
||||
moods = updatedMoods,
|
||||
selectedMood = selected,
|
||||
@@ -870,7 +1032,7 @@ class AppStore(
|
||||
messageId = it.messageId + 1,
|
||||
)
|
||||
}
|
||||
if (selected != null) cacheDetail(selected)
|
||||
_state.value.selectedMood?.let { cacheDetail(it) }
|
||||
} catch (t: Throwable) {
|
||||
message(t)
|
||||
}
|
||||
@@ -892,18 +1054,24 @@ class AppStore(
|
||||
return
|
||||
}
|
||||
|
||||
val generation = dataGeneration
|
||||
scope.launch {
|
||||
_state.update { it.copy(downloading = it.downloading + song.id) }
|
||||
var lastError: Throwable? = null
|
||||
repeat(DOWNLOAD_ATTEMPTS) { attempt ->
|
||||
try {
|
||||
val bytes = api.download(song.id)
|
||||
val path = storage.saveDownload(song.id, bytes)
|
||||
val path = api.downloadTo(song.id) { channel ->
|
||||
storage.saveDownloadStream(song.id, channel)
|
||||
}
|
||||
if (path != null) {
|
||||
runCatching { api.cover(song.albumId, 320) }
|
||||
.getOrNull()
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
?.let { storage.saveArtwork(song.id, it) }
|
||||
?.let { artwork -> runCatching { storage.saveArtwork(song.id, artwork) } }
|
||||
}
|
||||
if (generation != dataGeneration) {
|
||||
storage.deleteDownload(song.id)
|
||||
return@launch
|
||||
}
|
||||
if (path == null) {
|
||||
_state.update {
|
||||
@@ -933,7 +1101,12 @@ class AppStore(
|
||||
}
|
||||
}
|
||||
}
|
||||
_state.update { it.copy(downloading = it.downloading - song.id) }
|
||||
_state.update {
|
||||
it.copy(
|
||||
downloading = it.downloading - song.id,
|
||||
downloads = storage.listDownloads().keys,
|
||||
)
|
||||
}
|
||||
message(lastError ?: IllegalStateException("Download failed"))
|
||||
}
|
||||
}
|
||||
@@ -983,9 +1156,13 @@ class AppStore(
|
||||
fun release() {
|
||||
persistPlayback()
|
||||
pollJob?.cancel()
|
||||
refreshJob?.cancel()
|
||||
sleepJob?.cancel()
|
||||
reconnectJob?.cancel()
|
||||
musicSearchJob?.cancel()
|
||||
longformSearchJob?.cancel()
|
||||
player.release()
|
||||
api.close()
|
||||
}
|
||||
|
||||
private fun playNext() {
|
||||
@@ -998,22 +1175,28 @@ class AppStore(
|
||||
return
|
||||
}
|
||||
advancing = true
|
||||
val sessionId = session.id
|
||||
scope.launch {
|
||||
try {
|
||||
val more = api.nextTracks(session.id, 12)
|
||||
_state.update { it.copy(queue = it.queue + more) }
|
||||
val more = api.nextTracks(sessionId, 12)
|
||||
if (_state.value.session?.id == sessionId) {
|
||||
_state.update { it.copy(queue = it.queue + more) }
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
message(t)
|
||||
} finally {
|
||||
advancing = false
|
||||
}
|
||||
if (_state.value.session?.id != sessionId) return@launch
|
||||
if (_state.value.queue.isNotEmpty()) playNext() else _state.update { it.copy(playing = false) }
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
val song = state.queue.first()
|
||||
reportCurrentProgress(completed = false)
|
||||
// On natural completion the poll already saved completed=true for the
|
||||
// outgoing track; do not immediately overwrite it with false.
|
||||
if (!finishing) reportCurrentProgress(completed = false)
|
||||
_state.update {
|
||||
it.copy(
|
||||
queue = it.queue.drop(1),
|
||||
@@ -1026,7 +1209,7 @@ class AppStore(
|
||||
}
|
||||
persistPlayback()
|
||||
startSong(song)
|
||||
report("started", song.id)
|
||||
report("started", song.id, 0)
|
||||
if (_state.value.queue.size < 3) prefetch()
|
||||
}
|
||||
|
||||
@@ -1034,10 +1217,13 @@ class AppStore(
|
||||
val session = _state.value.session ?: return
|
||||
if (fetching) return
|
||||
fetching = true
|
||||
val sessionId = session.id
|
||||
scope.launch {
|
||||
try {
|
||||
val more = api.nextTracks(session.id, 12)
|
||||
_state.update { it.copy(queue = it.queue + more) }
|
||||
val more = api.nextTracks(sessionId, 12)
|
||||
if (_state.value.session?.id == sessionId) {
|
||||
_state.update { it.copy(queue = it.queue + more) }
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
// The queue still has tracks; a later request will retry.
|
||||
} finally {
|
||||
@@ -1050,6 +1236,7 @@ class AppStore(
|
||||
val localPath = storage.downloadPath(song.id)
|
||||
finishing = false
|
||||
pollTicks = 0
|
||||
trackStartOffset = startAtSeconds
|
||||
try {
|
||||
player.play(
|
||||
source = localPath ?: api.streamUrl(song.id),
|
||||
@@ -1094,14 +1281,16 @@ class AppStore(
|
||||
pollTicks += 1
|
||||
if (pollTicks >= PROGRESS_POLL_TICKS) {
|
||||
pollTicks = 0
|
||||
reportCurrentProgress(completed = false)
|
||||
// Pause/seek/track changes report explicitly; avoid
|
||||
// rewriting the same position every few seconds while paused.
|
||||
if (player.isPlaying()) reportCurrentProgress(completed = false)
|
||||
}
|
||||
|
||||
if (player.isFinished()) {
|
||||
if (!finishing) {
|
||||
finishing = true
|
||||
reportCurrentProgress(completed = true)
|
||||
report("completed", state.current?.id)
|
||||
report("completed", state.current?.id, state.positionSeconds.toInt())
|
||||
playNext()
|
||||
}
|
||||
break
|
||||
@@ -1111,7 +1300,7 @@ class AppStore(
|
||||
}
|
||||
}
|
||||
|
||||
private fun report(type: String, songId: String?) {
|
||||
private fun report(type: String, songId: String?, positionSeconds: Int) {
|
||||
val session = _state.value.session ?: return
|
||||
if (songId == null) return
|
||||
scope.launch {
|
||||
@@ -1121,7 +1310,7 @@ class AppStore(
|
||||
PlaybackEvent(
|
||||
songId = songId,
|
||||
type = type,
|
||||
positionSeconds = _state.value.positionSeconds.toInt(),
|
||||
positionSeconds = positionSeconds,
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -1151,16 +1340,22 @@ class AppStore(
|
||||
}
|
||||
|
||||
private fun cacheDetail(detail: MoodDetail) {
|
||||
val cached = cache.load()
|
||||
val details = cached.moodDetails.filterNot { it.mood.id == detail.mood.id } + detail
|
||||
cache.save(cached.copy(moodDetails = details, moods = cached.moods))
|
||||
runCatching {
|
||||
val cached = cache.load()
|
||||
val details = cached.moodDetails.filterNot { it.mood.id == detail.mood.id } + detail
|
||||
cache.save(cached.copy(moodDetails = details, moods = cached.moods))
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyMoodDetail(detail: MoodDetail) {
|
||||
cacheDetail(detail)
|
||||
_state.update { state ->
|
||||
state.copy(
|
||||
selectedMood = detail,
|
||||
selectedMood = if (state.selectedMood?.mood?.id == detail.mood.id) {
|
||||
detail
|
||||
} else {
|
||||
state.selectedMood
|
||||
},
|
||||
moods = state.moods.map { mood -> if (mood.id == detail.mood.id) detail.mood else mood },
|
||||
)
|
||||
}
|
||||
@@ -1168,14 +1363,17 @@ class AppStore(
|
||||
|
||||
private fun persistPlayback() {
|
||||
val state = _state.value
|
||||
cache.savePlayback(
|
||||
runCatching {
|
||||
cache.savePlayback(
|
||||
PlaybackSnapshot(
|
||||
session = state.session,
|
||||
queue = state.queue,
|
||||
current = state.current,
|
||||
history = state.history,
|
||||
positionSeconds = state.positionSeconds,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Retries the library sync with exponential backoff while offline. */
|
||||
@@ -1200,6 +1398,7 @@ class AppStore(
|
||||
_state.value.user?.longformFolders?.toSet().orEmpty()
|
||||
|
||||
private fun reportCurrentProgress(completed: Boolean) {
|
||||
if (loggingOut) return
|
||||
val state = _state.value
|
||||
val song = state.current ?: return
|
||||
if (song.folderId !in longformFolders()) return
|
||||
@@ -1225,7 +1424,9 @@ class AppStore(
|
||||
_state.update { it.copy(longformProgress = it.longformProgress + (songId to entry)) }
|
||||
cache.saveProgress(_state.value.longformProgress.values.toList())
|
||||
scope.launch {
|
||||
runCatching { api.saveLongformProgress(songId, position, duration, completed) }
|
||||
progressSaveMutex.withLock {
|
||||
runCatching { api.saveLongformProgress(songId, position, duration, completed) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1253,6 +1454,7 @@ private const val RECONNECT_MAX_MS = 300_000L
|
||||
private const val DOWNLOAD_ATTEMPTS = 3
|
||||
private const val PROGRESS_POLL_TICKS = 12
|
||||
private const val MAX_HISTORY = 50
|
||||
private const val SEARCH_DEBOUNCE_MS = 300L
|
||||
|
||||
private fun LongformProgressItem.toProgress(): LongformProgress = LongformProgress(
|
||||
songId = song.id,
|
||||
|
||||
@@ -215,7 +215,7 @@ fun MoodGradient(name: String): Brush {
|
||||
Color(0xFF1864AB) to Color(0xFF1098AD),
|
||||
Color(0xFF5F3DC4) to Color(0xFF862E9C),
|
||||
)
|
||||
val palette = palettes[abs(name.hashCode()) % palettes.size]
|
||||
val palette = palettes[(name.hashCode() % palettes.size + palettes.size) % palettes.size]
|
||||
return Brush.linearGradient(listOf(palette.first, palette.second))
|
||||
}
|
||||
|
||||
|
||||
@@ -93,7 +93,10 @@ private fun MusicLibrary(state: AppState, store: AppStore) {
|
||||
item {
|
||||
OutlinedTextField(
|
||||
value = query,
|
||||
onValueChange = { query = it },
|
||||
onValueChange = {
|
||||
query = it
|
||||
store.searchMusic(it)
|
||||
},
|
||||
singleLine = true,
|
||||
label = { Text("Search music") },
|
||||
leadingIcon = { Icon(Icons.Rounded.Search, contentDescription = null) },
|
||||
@@ -141,17 +144,17 @@ private fun MusicLibrary(state: AppState, store: AppStore) {
|
||||
}
|
||||
}
|
||||
|
||||
if (state.searchResults.isNotEmpty()) {
|
||||
if (state.musicResults.isNotEmpty()) {
|
||||
item {
|
||||
SectionTitle("Search results") {
|
||||
Text(
|
||||
"${state.searchResults.size}",
|
||||
"${state.musicResults.size}",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
items(state.searchResults, key = { "search-${it.id}" }) { song ->
|
||||
items(state.musicResults, key = { "search-${it.id}" }) { song ->
|
||||
LibrarySongRow(song, state, store, supported)
|
||||
}
|
||||
item { HorizontalDivider(Modifier.padding(vertical = 14.dp)) }
|
||||
|
||||
+11
-9
@@ -69,22 +69,24 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
||||
|
||||
val mood = detail.mood
|
||||
var seedQuery by remember { mutableStateOf("") }
|
||||
var name by remember(mood.id, mood.changedAt) { mutableStateOf(mood.name) }
|
||||
var description by remember(mood.id, mood.changedAt) { mutableStateOf(mood.description.orEmpty()) }
|
||||
var genres by remember(mood.id, mood.changedAt) { mutableStateOf(mood.genres.joinToString(", ")) }
|
||||
var query by remember(mood.id, mood.changedAt) { mutableStateOf(mood.query.orEmpty()) }
|
||||
var target by remember(mood.id, mood.changedAt) { mutableStateOf(mood.targetSize.toString()) }
|
||||
var hours by remember(mood.id, mood.changedAt) { mutableStateOf(mood.refreshHours.toString()) }
|
||||
var yt by remember(mood.id, mood.changedAt) { mutableStateOf(mood.ytEnabled) }
|
||||
var seedPercent by remember(mood.id, mood.changedAt) { mutableStateOf(mood.seedPercent.toFloat()) }
|
||||
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 target by remember(mood.id) { mutableStateOf(mood.targetSize.toString()) }
|
||||
var hours by remember(mood.id) { mutableStateOf(mood.refreshHours.toString()) }
|
||||
var yt by remember(mood.id) { mutableStateOf(mood.ytEnabled) }
|
||||
var seedPercent by remember(mood.id) { mutableStateOf(mood.seedPercent.toFloat()) }
|
||||
|
||||
val pendingDownloads = detail.recommendations.count {
|
||||
it.download?.state == "queued" || it.download?.state == "downloading"
|
||||
}
|
||||
LaunchedEffect(detail.mood.id, pendingDownloads) {
|
||||
while (pendingDownloads > 0) {
|
||||
var polls = 0
|
||||
while (pendingDownloads > 0 && polls < 60) {
|
||||
kotlinx.coroutines.delay(10_000)
|
||||
store.refreshSelectedMood()
|
||||
polls += 1
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
@@ -56,10 +57,12 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
||||
var queueOpen by remember { mutableStateOf(false) }
|
||||
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
|
||||
val sleepRemaining = state.sleepTimerRemainingSeconds
|
||||
val isLongform = state.user?.longformFolders?.contains(song.folderId) == true
|
||||
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
tonalElevation = 8.dp,
|
||||
modifier = Modifier.navigationBarsPadding(),
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
val progress = if (state.durationSeconds > 0) {
|
||||
@@ -164,11 +167,13 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
||||
)
|
||||
}
|
||||
|
||||
IconButton(onClick = { store.addCurrentToMood(null) }) {
|
||||
Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood")
|
||||
}
|
||||
IconButton(onClick = { picker = true }) {
|
||||
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood")
|
||||
if (!isLongform) {
|
||||
IconButton(onClick = { store.addCurrentToMood(null) }) {
|
||||
Icon(Icons.Rounded.AddCircleOutline, contentDescription = "Add to current mood")
|
||||
}
|
||||
IconButton(onClick = { picker = true }) {
|
||||
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to another mood")
|
||||
}
|
||||
}
|
||||
IconButton(onClick = { store.previous() }) {
|
||||
Icon(Icons.Rounded.SkipPrevious, contentDescription = "Previous")
|
||||
|
||||
Reference in new issue
Block a user