The mood screen now shows recommendation cards with thumbnails, a refresh action, and accept/reject buttons. Accepting a library match adds it as a seed immediately; other accepted tracks are marked as queued for download. The player persists the session, queue and current track, restores them paused on the next launch and starts the track on the next tap. While offline the store retries the library sync with exponential backoff, downloads retry three times before failing, and covers plus YT thumbnails are cached for the app's lifetime.
This commit is contained in:
1 parent
2234192dc7
commit
dc719f3e1a
8 files changed
+582
-91
No files matched your search
@@ -5,6 +5,7 @@ import io.ktor.client.call.body
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
import io.ktor.client.plugins.HttpTimeout
|
||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.client.plugins.timeout
|
||||
import io.ktor.client.request.HttpRequestBuilder
|
||||
import io.ktor.client.request.delete
|
||||
import io.ktor.client.request.get
|
||||
@@ -53,6 +54,7 @@ class ApiClient(private val http: HttpClient) {
|
||||
private set
|
||||
|
||||
private val coverCache = mutableMapOf<String, ByteArray?>()
|
||||
private val imageCache = mutableMapOf<String, ByteArray?>()
|
||||
|
||||
suspend fun login(
|
||||
serverUrl: String,
|
||||
@@ -79,6 +81,7 @@ class ApiClient(private val http: HttpClient) {
|
||||
fun clear() {
|
||||
token = null
|
||||
coverCache.clear()
|
||||
imageCache.clear()
|
||||
}
|
||||
|
||||
suspend fun me(): User = get("/me")
|
||||
@@ -127,6 +130,35 @@ class ApiClient(private val http: HttpClient) {
|
||||
requestNoContent { http.delete(url("/moods/$moodId/seeds/$songId")) { auth() } }
|
||||
}
|
||||
|
||||
suspend fun recommendations(moodId: String): List<Recommendation> =
|
||||
get<RecommendationsResponse>("/moods/$moodId/recommendations").recommendations
|
||||
|
||||
suspend fun refreshRecommendations(moodId: String): MoodDetail =
|
||||
parse(
|
||||
http.post(url("/moods/$moodId/recommendations/refresh")) {
|
||||
auth()
|
||||
// yt-dlp searches a few queries in parallel; give the server room.
|
||||
timeout {
|
||||
requestTimeoutMillis = 120_000
|
||||
socketTimeoutMillis = 120_000
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun acceptRecommendation(moodId: String, videoId: String): RecommendationDecision =
|
||||
parse(
|
||||
http.post(url("/moods/$moodId/recommendations/$videoId/accept")) {
|
||||
auth()
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun rejectRecommendation(moodId: String, videoId: String): RecommendationDecision =
|
||||
parse(
|
||||
http.post(url("/moods/$moodId/recommendations/$videoId/reject")) {
|
||||
auth()
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun preview(moodId: String, limit: Int = 20): List<Song> =
|
||||
get<SearchResponse>("/moods/$moodId/preview?limit=$limit").songs
|
||||
|
||||
@@ -208,10 +240,21 @@ class ApiClient(private val http: HttpClient) {
|
||||
.bodyAsBytes()
|
||||
}.getOrNull()
|
||||
val result = bytes?.takeIf { it.isNotEmpty() }
|
||||
if (coverCache.size > MAX_CACHED_IMAGES) coverCache.clear()
|
||||
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() }
|
||||
if (imageCache.size > MAX_CACHED_IMAGES) imageCache.clear()
|
||||
imageCache[url] = result
|
||||
return result
|
||||
}
|
||||
|
||||
suspend fun download(songId: String): ByteArray =
|
||||
http.get("$baseUrl/api/v1/songs/$songId/stream") {
|
||||
auth()
|
||||
@@ -253,6 +296,10 @@ class ApiClient(private val http: HttpClient) {
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MAX_CACHED_IMAGES = 200
|
||||
}
|
||||
|
||||
private fun normalize(serverUrl: String): String {
|
||||
var value = serverUrl.trim().trimEnd('/')
|
||||
if (value.isEmpty()) value = "http://localhost:8080"
|
||||
|
||||
@@ -104,6 +104,16 @@ data class MoodDetail(
|
||||
@Serializable
|
||||
data class MoodsResponse(val moods: List<Mood>)
|
||||
|
||||
@Serializable
|
||||
data class RecommendationsResponse(val recommendations: List<Recommendation> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class RecommendationDecision(
|
||||
val detail: MoodDetail,
|
||||
val recommendation: Recommendation,
|
||||
val seedAdded: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class LibraryPage(
|
||||
val songs: List<Song> = emptyList(),
|
||||
|
||||
@@ -4,6 +4,7 @@ import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import win.taptap.musicmanager.client.api.Mood
|
||||
import win.taptap.musicmanager.client.api.MoodDetail
|
||||
import win.taptap.musicmanager.client.api.Session
|
||||
import win.taptap.musicmanager.client.api.Song
|
||||
import win.taptap.musicmanager.client.api.User
|
||||
|
||||
@@ -24,6 +25,14 @@ data class CachedState(
|
||||
val moodDetails: List<MoodDetail> = emptyList(),
|
||||
)
|
||||
|
||||
/** The queue survives a restart so the next launch can resume where it stopped. */
|
||||
@Serializable
|
||||
data class PlaybackSnapshot(
|
||||
val session: Session? = null,
|
||||
val queue: List<Song> = emptyList(),
|
||||
val current: Song? = null,
|
||||
)
|
||||
|
||||
class LibraryCache(private val storage: AppStorage) {
|
||||
|
||||
private val json = Json {
|
||||
@@ -50,12 +59,27 @@ class LibraryCache(private val storage: AppStorage) {
|
||||
storage.write(CACHE_FILE, json.encodeToString(state))
|
||||
}
|
||||
|
||||
fun loadPlayback(): PlaybackSnapshot? =
|
||||
storage.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)
|
||||
} else {
|
||||
storage.write(PLAYBACK_FILE, json.encodeToString(snapshot))
|
||||
}
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
storage.delete(CACHE_FILE)
|
||||
storage.delete(PLAYBACK_FILE)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val SESSION_FILE = "session.json"
|
||||
const val CACHE_FILE = "library.json"
|
||||
const val PLAYBACK_FILE = "playback.json"
|
||||
}
|
||||
}
|
||||
+212
-74
@@ -26,6 +26,7 @@ import win.taptap.musicmanager.client.api.UpdateMoodRequest
|
||||
import win.taptap.musicmanager.client.api.configuredHttpClient
|
||||
import win.taptap.musicmanager.client.data.CachedState
|
||||
import win.taptap.musicmanager.client.data.LibraryCache
|
||||
import win.taptap.musicmanager.client.data.PlaybackSnapshot
|
||||
import win.taptap.musicmanager.client.data.SessionState
|
||||
import win.taptap.musicmanager.client.playback.AudioPlayer
|
||||
import win.taptap.musicmanager.client.platformName
|
||||
@@ -56,6 +57,7 @@ data class AppState(
|
||||
val searching: Boolean = false,
|
||||
val loading: Boolean = false,
|
||||
val saving: Boolean = false,
|
||||
val discovering: Boolean = false,
|
||||
val message: String? = null,
|
||||
val messageIsError: Boolean = false,
|
||||
val messageId: Long = 0,
|
||||
@@ -77,6 +79,8 @@ class AppStore(
|
||||
|
||||
private var pollJob: Job? = null
|
||||
private var sleepJob: Job? = null
|
||||
private var reconnectJob: Job? = null
|
||||
private var playbackStarted = false
|
||||
private var advancing = false
|
||||
private var fetching = false
|
||||
private var finishing = false
|
||||
@@ -89,6 +93,7 @@ class AppStore(
|
||||
scope.launch {
|
||||
val session = cache.loadSession()
|
||||
val cached = cache.load()
|
||||
val playback = cache.loadPlayback()
|
||||
_state.update {
|
||||
it.copy(
|
||||
booting = false,
|
||||
@@ -96,6 +101,10 @@ class AppStore(
|
||||
moods = cached.moods,
|
||||
library = cached.songs.sortedLibrary(),
|
||||
selectedMood = cached.moodDetails.firstOrNull(),
|
||||
session = playback?.session,
|
||||
queue = playback?.queue.orEmpty(),
|
||||
current = playback?.current,
|
||||
durationSeconds = playback?.current?.duration?.toDouble() ?: 0.0,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -157,68 +166,71 @@ class AppStore(
|
||||
}
|
||||
|
||||
fun refreshAll(silent: Boolean = false) {
|
||||
scope.launch {
|
||||
if (!silent) _state.update { it.copy(loading = true) }
|
||||
try {
|
||||
val moods = api.moods()
|
||||
val cached = cache.load()
|
||||
var songs = cached.songs.associateBy { it.id }.toMutableMap()
|
||||
var revision = cached.revision
|
||||
scope.launch { refreshAllNow(silent) }
|
||||
}
|
||||
|
||||
if (revision == null) {
|
||||
var cursor: String? = null
|
||||
do {
|
||||
val page = api.library(cursor = cursor, since = null, limit = 500)
|
||||
page.songs.forEach { songs[it.id] = it }
|
||||
cursor = page.nextCursor
|
||||
revision = page.revision
|
||||
} while (cursor != null)
|
||||
} else {
|
||||
var since: String? = revision
|
||||
while (since != null) {
|
||||
val page = api.library(cursor = null, since = since, limit = 500)
|
||||
page.songs.forEach { songs[it.id] = it }
|
||||
page.deletedSongIds.forEach { songs.remove(it) }
|
||||
revision = page.revision
|
||||
since = page.nextSince
|
||||
}
|
||||
}
|
||||
private suspend fun refreshAllNow(silent: Boolean) {
|
||||
if (!silent) _state.update { it.copy(loading = true) }
|
||||
try {
|
||||
val moods = api.moods()
|
||||
val cached = cache.load()
|
||||
var songs = cached.songs.associateBy { it.id }.toMutableMap()
|
||||
var revision = cached.revision
|
||||
|
||||
val details = cached.moodDetails.filter { detail -> moods.any { it.id == detail.mood.id } }
|
||||
cache.save(
|
||||
CachedState(
|
||||
serverUrl = _state.value.serverUrl,
|
||||
userName = _state.value.user?.name.orEmpty(),
|
||||
revision = revision,
|
||||
songs = songs.values.toList(),
|
||||
moods = moods,
|
||||
moodDetails = details,
|
||||
),
|
||||
)
|
||||
|
||||
_state.update {
|
||||
it.copy(
|
||||
loading = false,
|
||||
offline = false,
|
||||
moods = moods,
|
||||
library = songs.values.sortedLibrary(),
|
||||
)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
if (t is ApiException && t.status == 401) {
|
||||
logout()
|
||||
return@launch
|
||||
}
|
||||
_state.update {
|
||||
it.copy(
|
||||
loading = false,
|
||||
offline = true,
|
||||
message = "Offline mode: ${t.friendlyMessage()}",
|
||||
messageIsError = true,
|
||||
messageId = it.messageId + 1,
|
||||
)
|
||||
if (revision == null) {
|
||||
var cursor: String? = null
|
||||
do {
|
||||
val page = api.library(cursor = cursor, since = null, limit = 500)
|
||||
page.songs.forEach { songs[it.id] = it }
|
||||
cursor = page.nextCursor
|
||||
revision = page.revision
|
||||
} while (cursor != null)
|
||||
} else {
|
||||
var since: String? = revision
|
||||
while (since != null) {
|
||||
val page = api.library(cursor = null, since = since, limit = 500)
|
||||
page.songs.forEach { songs[it.id] = it }
|
||||
page.deletedSongIds.forEach { songs.remove(it) }
|
||||
revision = page.revision
|
||||
since = page.nextSince
|
||||
}
|
||||
}
|
||||
|
||||
val details = cached.moodDetails.filter { detail -> moods.any { it.id == detail.mood.id } }
|
||||
cache.save(
|
||||
CachedState(
|
||||
serverUrl = _state.value.serverUrl,
|
||||
userName = _state.value.user?.name.orEmpty(),
|
||||
revision = revision,
|
||||
songs = songs.values.toList(),
|
||||
moods = moods,
|
||||
moodDetails = details,
|
||||
),
|
||||
)
|
||||
|
||||
_state.update {
|
||||
it.copy(
|
||||
loading = false,
|
||||
offline = false,
|
||||
moods = moods,
|
||||
library = songs.values.sortedLibrary(),
|
||||
)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
if (t is ApiException && t.status == 401) {
|
||||
logout()
|
||||
return
|
||||
}
|
||||
_state.update {
|
||||
it.copy(
|
||||
loading = false,
|
||||
offline = true,
|
||||
message = "Offline mode: ${t.friendlyMessage()}",
|
||||
messageIsError = true,
|
||||
messageId = it.messageId + 1,
|
||||
)
|
||||
}
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,6 +447,7 @@ class AppStore(
|
||||
)
|
||||
}
|
||||
playNext()
|
||||
persistPlayback()
|
||||
} catch (t: Throwable) {
|
||||
val fallback = state.library.filter { it.id in state.downloads }
|
||||
if (fallback.isNotEmpty()) {
|
||||
@@ -469,6 +482,7 @@ class AppStore(
|
||||
durationSeconds = song.duration.toDouble(),
|
||||
)
|
||||
}
|
||||
persistPlayback()
|
||||
startSong(song)
|
||||
}
|
||||
}
|
||||
@@ -504,6 +518,7 @@ class AppStore(
|
||||
val queue = if (shuffled) songs.shuffled(Random.Default) else songs
|
||||
_state.update { it.copy(session = null, queue = queue) }
|
||||
playNext()
|
||||
persistPlayback()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -547,12 +562,78 @@ class AppStore(
|
||||
}
|
||||
}
|
||||
|
||||
fun refreshRecommendations() {
|
||||
val moodId = _state.value.selectedMood?.mood?.id ?: return
|
||||
if (_state.value.discovering) return
|
||||
scope.launch {
|
||||
_state.update { it.copy(discovering = true) }
|
||||
try {
|
||||
val detail = api.refreshRecommendations(moodId)
|
||||
val fresh = detail.recommendations.count { it.state == "new" }
|
||||
applyMoodDetail(detail)
|
||||
_state.update {
|
||||
it.copy(
|
||||
discovering = false,
|
||||
message = if (fresh > 0) "$fresh recommendations" else "No new recommendations",
|
||||
messageIsError = false,
|
||||
messageId = it.messageId + 1,
|
||||
)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
_state.update { it.copy(discovering = false) }
|
||||
message(t)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun acceptRecommendation(videoId: String) = decideRecommendation(videoId, accept = true)
|
||||
|
||||
fun rejectRecommendation(videoId: String) = decideRecommendation(videoId, accept = false)
|
||||
|
||||
private fun decideRecommendation(videoId: String, accept: Boolean) {
|
||||
val moodId = _state.value.selectedMood?.mood?.id ?: return
|
||||
if (_state.value.discovering) return
|
||||
scope.launch {
|
||||
_state.update { it.copy(discovering = true) }
|
||||
try {
|
||||
val decision = if (accept) {
|
||||
api.acceptRecommendation(moodId, videoId)
|
||||
} else {
|
||||
api.rejectRecommendation(moodId, videoId)
|
||||
}
|
||||
applyMoodDetail(decision.detail)
|
||||
val message = when {
|
||||
!accept -> "Recommendation rejected"
|
||||
decision.seedAdded -> "Added to ${decision.detail.mood.name}"
|
||||
else -> "Queued for download"
|
||||
}
|
||||
_state.update {
|
||||
it.copy(
|
||||
discovering = false,
|
||||
message = message,
|
||||
messageIsError = false,
|
||||
messageId = it.messageId + 1,
|
||||
)
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
_state.update { it.copy(discovering = false) }
|
||||
message(t)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun togglePlayPause() {
|
||||
val state = _state.value
|
||||
if (state.current == null) return
|
||||
val song = state.current ?: return
|
||||
if (state.playing) {
|
||||
player.pause()
|
||||
_state.update { it.copy(playing = false) }
|
||||
} 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())
|
||||
}
|
||||
startSong(song)
|
||||
} else {
|
||||
player.resume()
|
||||
_state.update { it.copy(playing = true) }
|
||||
@@ -640,19 +721,22 @@ class AppStore(
|
||||
|
||||
scope.launch {
|
||||
_state.update { it.copy(downloading = it.downloading + song.id) }
|
||||
try {
|
||||
val bytes = api.download(song.id)
|
||||
val path = storage.saveDownload(song.id, bytes)
|
||||
if (path == null) {
|
||||
_state.update {
|
||||
it.copy(
|
||||
downloading = it.downloading - song.id,
|
||||
message = "Downloads are not available on this platform",
|
||||
messageIsError = true,
|
||||
messageId = it.messageId + 1,
|
||||
)
|
||||
var lastError: Throwable? = null
|
||||
repeat(DOWNLOAD_ATTEMPTS) { attempt ->
|
||||
try {
|
||||
val bytes = api.download(song.id)
|
||||
val path = storage.saveDownload(song.id, bytes)
|
||||
if (path == null) {
|
||||
_state.update {
|
||||
it.copy(
|
||||
downloading = it.downloading - song.id,
|
||||
message = "Downloads are not available on this platform",
|
||||
messageIsError = true,
|
||||
messageId = it.messageId + 1,
|
||||
)
|
||||
}
|
||||
return@launch
|
||||
}
|
||||
} else {
|
||||
_state.update {
|
||||
it.copy(
|
||||
downloading = it.downloading - song.id,
|
||||
@@ -662,11 +746,16 @@ class AppStore(
|
||||
messageId = it.messageId + 1,
|
||||
)
|
||||
}
|
||||
return@launch
|
||||
} catch (t: Throwable) {
|
||||
lastError = t
|
||||
if (attempt < DOWNLOAD_ATTEMPTS - 1) {
|
||||
delay(1_000L * (attempt + 1))
|
||||
}
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
_state.update { it.copy(downloading = it.downloading - song.id) }
|
||||
message(t)
|
||||
}
|
||||
_state.update { it.copy(downloading = it.downloading - song.id) }
|
||||
message(lastError ?: IllegalStateException("Download failed"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -697,6 +786,9 @@ class AppStore(
|
||||
|
||||
suspend fun cover(albumId: String): ByteArray? = api.cover(albumId, 320)
|
||||
|
||||
/** YT thumbnails and other remote artwork, cached inside the API client. */
|
||||
suspend fun image(url: String?): ByteArray? = url?.let { api.image(it) }
|
||||
|
||||
fun storageBytes(): Long = storage.storageUsedBytes()
|
||||
|
||||
fun canSeek(): Boolean = player.canSeek
|
||||
@@ -710,8 +802,10 @@ class AppStore(
|
||||
}
|
||||
|
||||
fun release() {
|
||||
persistPlayback()
|
||||
pollJob?.cancel()
|
||||
sleepJob?.cancel()
|
||||
reconnectJob?.cancel()
|
||||
player.release()
|
||||
}
|
||||
|
||||
@@ -749,6 +843,7 @@ class AppStore(
|
||||
durationSeconds = song.duration.toDouble(),
|
||||
)
|
||||
}
|
||||
persistPlayback()
|
||||
startSong(song)
|
||||
report("started", song.id)
|
||||
if (_state.value.queue.size < 3) prefetch()
|
||||
@@ -791,6 +886,7 @@ class AppStore(
|
||||
}
|
||||
return
|
||||
}
|
||||
playbackStarted = true
|
||||
startPolling()
|
||||
}
|
||||
|
||||
@@ -843,6 +939,8 @@ class AppStore(
|
||||
pollJob?.cancel()
|
||||
sleepJob?.cancel()
|
||||
sleepJob = null
|
||||
reconnectJob?.cancel()
|
||||
playbackStarted = false
|
||||
player.scheduleSleepTimer(null)
|
||||
player.stop()
|
||||
_state.update {
|
||||
@@ -854,6 +952,7 @@ class AppStore(
|
||||
sleepTimerRemainingSeconds = null,
|
||||
)
|
||||
}
|
||||
cache.savePlayback(null)
|
||||
}
|
||||
|
||||
private fun cacheDetail(detail: MoodDetail) {
|
||||
@@ -862,6 +961,41 @@ class AppStore(
|
||||
cache.save(cached.copy(moodDetails = details, moods = cached.moods))
|
||||
}
|
||||
|
||||
private fun applyMoodDetail(detail: MoodDetail) {
|
||||
cacheDetail(detail)
|
||||
_state.update { state ->
|
||||
state.copy(
|
||||
selectedMood = detail,
|
||||
moods = state.moods.map { mood -> if (mood.id == detail.mood.id) detail.mood else mood },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun persistPlayback() {
|
||||
val state = _state.value
|
||||
cache.savePlayback(
|
||||
PlaybackSnapshot(
|
||||
session = state.session,
|
||||
queue = state.queue,
|
||||
current = state.current,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** Retries the library sync with exponential backoff while offline. */
|
||||
private fun scheduleReconnect() {
|
||||
if (reconnectJob?.isActive == true) return
|
||||
reconnectJob = scope.launch {
|
||||
var waitMillis = RECONNECT_INITIAL_MS
|
||||
while (isActive && _state.value.offline) {
|
||||
delay(waitMillis)
|
||||
refreshAllNow(silent = true)
|
||||
if (!_state.value.offline) break
|
||||
waitMillis = (waitMillis * 2).coerceAtMost(RECONNECT_MAX_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun message(t: Throwable) {
|
||||
_state.update {
|
||||
it.copy(
|
||||
@@ -880,3 +1014,7 @@ private fun Throwable.friendlyMessage(): String = when (this) {
|
||||
|
||||
private fun Collection<Song>.sortedLibrary(): List<Song> =
|
||||
sortedWith(compareBy({ it.artist.lowercase() }, { it.album.lowercase() }, { it.trackNumber ?: 0 }))
|
||||
|
||||
private const val RECONNECT_INITIAL_MS = 15_000L
|
||||
private const val RECONNECT_MAX_MS = 300_000L
|
||||
private const val DOWNLOAD_ATTEMPTS = 3
|
||||
@@ -91,6 +91,42 @@ fun Cover(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun RemoteImage(store: AppStore, url: String?, modifier: Modifier = Modifier) {
|
||||
var bitmap by remember(url) { mutableStateOf<ImageBitmap?>(null) }
|
||||
|
||||
LaunchedEffect(url) {
|
||||
if (url == null) return@LaunchedEffect
|
||||
bitmap = store.image(url)?.let { data -> runCatching { decodeImage(data) }.getOrNull() }
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(
|
||||
Brush.linearGradient(listOf(Color(0xFF28344A), Color(0xFF1A2230))),
|
||||
),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
val image = bitmap
|
||||
if (image != null) {
|
||||
Image(
|
||||
bitmap = image,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Crop,
|
||||
)
|
||||
} else {
|
||||
Icon(
|
||||
Icons.Rounded.MusicNote,
|
||||
contentDescription = null,
|
||||
tint = Color(0xFF5E6C84),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun EmptyState(title: String, subtitle: String? = null, modifier: Modifier = Modifier) {
|
||||
Column(
|
||||
|
||||
+107
-16
@@ -15,7 +15,10 @@ import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Add
|
||||
import androidx.compose.material.icons.rounded.Check
|
||||
import androidx.compose.material.icons.rounded.Close
|
||||
import androidx.compose.material.icons.rounded.PlayArrow
|
||||
import androidx.compose.material.icons.rounded.Refresh
|
||||
import androidx.compose.material.icons.rounded.RemoveCircleOutline
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
@@ -29,6 +32,7 @@ import androidx.compose.material3.OutlinedTextField
|
||||
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
|
||||
@@ -39,6 +43,7 @@ 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.Recommendation
|
||||
import win.taptap.musicmanager.client.api.Song
|
||||
import win.taptap.musicmanager.client.store.AppState
|
||||
import win.taptap.musicmanager.client.store.AppStore
|
||||
@@ -188,25 +193,43 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
||||
}
|
||||
}
|
||||
|
||||
if (detail.recommendations.isNotEmpty()) {
|
||||
if (mood.ytEnabled) {
|
||||
item {
|
||||
HorizontalDivider(Modifier.padding(vertical = 12.dp))
|
||||
SectionTitle("Recommendations")
|
||||
}
|
||||
items(detail.recommendations, key = { it.videoId }) { recommendation ->
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(recommendation.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
recommendation.artist,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
SectionTitle("Recommended for this mood") {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (state.discovering) {
|
||||
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
TextButton(
|
||||
onClick = { store.refreshRecommendations() },
|
||||
enabled = !state.discovering,
|
||||
) {
|
||||
Icon(Icons.Rounded.Refresh, contentDescription = null, modifier = Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text("Refresh")
|
||||
}
|
||||
}
|
||||
Text(recommendation.state, style = MaterialTheme.typography.labelSmall)
|
||||
}
|
||||
}
|
||||
|
||||
val visible = detail.recommendations.filter { it.state != "rejected" }
|
||||
if (visible.isEmpty()) {
|
||||
item {
|
||||
Text(
|
||||
if (state.discovering) {
|
||||
"Searching YouTube Music..."
|
||||
} else {
|
||||
"No recommendations yet. Refresh to search for tracks that fit this mood."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
items(visible, key = { "rec-${it.videoId}" }) { recommendation ->
|
||||
RecommendationRow(recommendation, state.discovering, store)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -290,3 +313,71 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
|
||||
item { Spacer(Modifier.size(24.dp)) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RecommendationRow(
|
||||
recommendation: Recommendation,
|
||||
busy: Boolean,
|
||||
store: AppStore,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
RemoteImage(store, recommendation.thumbnail, Modifier.size(48.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
recommendation.title,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
buildString {
|
||||
append(recommendation.artist)
|
||||
recommendation.album?.takeIf { it.isNotBlank() }?.let { append(" · ").append(it) }
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
when {
|
||||
recommendation.state == "accepted" && recommendation.matchedSong != null -> "Seed added"
|
||||
recommendation.state == "accepted" -> "Queued for download"
|
||||
recommendation.matchedSong != null -> "In your library"
|
||||
else -> "New"
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = if (recommendation.state == "accepted") {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
}
|
||||
if (recommendation.state == "accepted") {
|
||||
Icon(
|
||||
Icons.Rounded.Check,
|
||||
contentDescription = "Accepted",
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
} else {
|
||||
IconButton(
|
||||
onClick = { store.acceptRecommendation(recommendation.videoId) },
|
||||
enabled = !busy,
|
||||
) {
|
||||
Icon(Icons.Rounded.Check, contentDescription = "Accept recommendation")
|
||||
}
|
||||
IconButton(
|
||||
onClick = { store.rejectRecommendation(recommendation.videoId) },
|
||||
enabled = !busy,
|
||||
) {
|
||||
Icon(Icons.Rounded.Close, contentDescription = "Reject recommendation")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user