Home shows a now-playing panel (polled every 15s while visible), summary stats and the latest scrobbles. History is an infinite-scrolling, pull-to-refresh list that dedupes rows when pages shift. Adds edge-to-edge system bars, themed nav bar and a Sign out button. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
47c2cf5701
commit
01b17fd179
13 files changed
+570
-7
No files matched your search
@@ -3,6 +3,7 @@ package dev.daubney.scrobbled
|
|||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
|
import androidx.activity.enableEdgeToEdge
|
||||||
import androidx.activity.viewModels
|
import androidx.activity.viewModels
|
||||||
import androidx.compose.runtime.collectAsState
|
import androidx.compose.runtime.collectAsState
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
@@ -23,11 +24,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
enableEdgeToEdge()
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
val history = (application as ScrobbledApplication).history
|
||||||
setContent {
|
setContent {
|
||||||
ScrobbledTheme {
|
ScrobbledTheme {
|
||||||
val state by connectVm.state.collectAsState()
|
val state by connectVm.state.collectAsState()
|
||||||
if (state.connected) ScrobbledApp() else ConnectScreen(connectVm)
|
if (state.connected) ScrobbledApp(history, onSignOut = connectVm::disconnect) else ConnectScreen(connectVm)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,8 +4,11 @@ import android.app.Application
|
|||||||
import dev.daubney.scrobbled.data.auth.AuthRepository
|
import dev.daubney.scrobbled.data.auth.AuthRepository
|
||||||
import dev.daubney.scrobbled.data.auth.DefaultAuthRepository
|
import dev.daubney.scrobbled.data.auth.DefaultAuthRepository
|
||||||
import dev.daubney.scrobbled.data.auth.KeystoreCredentialStore
|
import dev.daubney.scrobbled.data.auth.KeystoreCredentialStore
|
||||||
|
import dev.daubney.scrobbled.data.history.DefaultHistoryRepository
|
||||||
|
import dev.daubney.scrobbled.data.history.HistoryRepository
|
||||||
|
|
||||||
/** Hand-rolled service locator; small enough that a DI framework isn't worth it yet. */
|
/** Hand-rolled service locator; small enough that a DI framework isn't worth it yet. */
|
||||||
class ScrobbledApplication : Application() {
|
class ScrobbledApplication : Application() {
|
||||||
val auth: AuthRepository by lazy { DefaultAuthRepository(KeystoreCredentialStore(this)) }
|
val auth: AuthRepository by lazy { DefaultAuthRepository(KeystoreCredentialStore(this)) }
|
||||||
|
val history: HistoryRepository by lazy { DefaultHistoryRepository(auth) }
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,27 @@
|
|||||||
package dev.daubney.scrobbled.ui
|
package dev.daubney.scrobbled.ui
|
||||||
|
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.NavigationBar
|
import androidx.compose.material3.NavigationBar
|
||||||
import androidx.compose.material3.NavigationBarItem
|
import androidx.compose.material3.NavigationBarItem
|
||||||
|
import androidx.compose.material3.NavigationBarItemDefaults
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
|
import androidx.lifecycle.viewmodel.initializer
|
||||||
|
import androidx.lifecycle.viewmodel.viewModelFactory
|
||||||
import androidx.navigation.compose.NavHost
|
import androidx.navigation.compose.NavHost
|
||||||
|
import dev.daubney.scrobbled.data.history.HistoryRepository
|
||||||
|
import dev.daubney.scrobbled.ui.history.HistoryScreen
|
||||||
|
import dev.daubney.scrobbled.ui.history.HistoryViewModel
|
||||||
|
import dev.daubney.scrobbled.ui.home.HomeScreen
|
||||||
|
import dev.daubney.scrobbled.ui.home.HomeViewModel
|
||||||
import androidx.navigation.compose.composable
|
import androidx.navigation.compose.composable
|
||||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||||
import androidx.navigation.compose.rememberNavController
|
import androidx.navigation.compose.rememberNavController
|
||||||
@@ -23,32 +34,40 @@ enum class Destination(val route: String, val label: String) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun ScrobbledApp() {
|
fun ScrobbledApp(history: HistoryRepository, onSignOut: () -> Unit) {
|
||||||
val nav = rememberNavController()
|
val nav = rememberNavController()
|
||||||
val current by nav.currentBackStackEntryAsState()
|
val current by nav.currentBackStackEntryAsState()
|
||||||
Scaffold(
|
Scaffold(
|
||||||
bottomBar = {
|
bottomBar = {
|
||||||
NavigationBar {
|
NavigationBar(containerColor = MaterialTheme.colorScheme.surfaceVariant) {
|
||||||
Destination.entries.forEach { d ->
|
Destination.entries.forEach { d ->
|
||||||
NavigationBarItem(
|
NavigationBarItem(
|
||||||
selected = current?.destination?.route == d.route,
|
selected = current?.destination?.route == d.route,
|
||||||
onClick = { nav.navigate(d.route) { launchSingleTop = true } },
|
onClick = { nav.navigate(d.route) { launchSingleTop = true } },
|
||||||
icon = {},
|
icon = {},
|
||||||
|
colors = NavigationBarItemDefaults.colors(indicatorColor = MaterialTheme.colorScheme.outline),
|
||||||
label = { Text(d.label) },
|
label = { Text(d.label) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
) { padding ->
|
) { padding ->
|
||||||
NavHost(nav, startDestination = Destination.Home.route, modifier = Modifier.padding(padding)) {
|
NavHost(nav, startDestination = Destination.Home.route, modifier = Modifier.padding(bottom = padding.calculateBottomPadding())) {
|
||||||
Destination.entries.forEach { d ->
|
composable(Destination.Home.route) {
|
||||||
composable(d.route) { Placeholder(d.label) }
|
val vm = viewModel<HomeViewModel>(factory = viewModelFactory { initializer { HomeViewModel(history) } })
|
||||||
|
HomeScreen(vm, onSignOut)
|
||||||
}
|
}
|
||||||
|
composable(Destination.History.route) {
|
||||||
|
val vm = viewModel<HistoryViewModel>(factory = viewModelFactory { initializer { HistoryViewModel(history) } })
|
||||||
|
HistoryScreen(vm)
|
||||||
|
}
|
||||||
|
composable(Destination.Add.route) { Placeholder(Destination.Add.label) }
|
||||||
|
composable(Destination.Listen.route) { Placeholder(Destination.Listen.label) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun Placeholder(title: String) {
|
private fun Placeholder(title: String) {
|
||||||
Box(Modifier, contentAlignment = Alignment.Center) { Text(title) }
|
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text(title) }
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package dev.daubney.scrobbled.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import dev.daubney.scrobbled.data.history.RecentScrobble
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ScrobbleRow(s: RecentScrobble, modifier: Modifier = Modifier) {
|
||||||
|
Row(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(s.track, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyLarge)
|
||||||
|
Text(
|
||||||
|
listOfNotNull(s.artist, s.album).joinToString(" · "),
|
||||||
|
maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||||
|
style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Text(formatAgo(s.playedAt), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package dev.daubney.scrobbled.ui
|
||||||
|
|
||||||
|
import java.time.Duration
|
||||||
|
import java.time.Instant
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.time.format.FormatStyle
|
||||||
|
|
||||||
|
/** "just now", "5 min ago", "3 h ago", "yesterday", otherwise a short local date. */
|
||||||
|
fun formatAgo(then: Instant, now: Instant = Instant.now(), zone: ZoneId = ZoneId.systemDefault()): String {
|
||||||
|
val secs = Duration.between(then, now).seconds
|
||||||
|
return when {
|
||||||
|
secs < 60 -> "just now"
|
||||||
|
secs < 3600 -> "${secs / 60} min ago"
|
||||||
|
secs < 86_400 -> "${secs / 3600} h ago"
|
||||||
|
then.atZone(zone).toLocalDate() == now.atZone(zone).toLocalDate().minusDays(1) -> "yesterday"
|
||||||
|
else -> DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withZone(zone).format(then)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package dev.daubney.scrobbled.ui.history
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.statusBarsPadding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.snapshotFlow
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import dev.daubney.scrobbled.ui.ScrobbleRow
|
||||||
|
|
||||||
|
private const val PREFETCH = 10
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun HistoryScreen(vm: HistoryViewModel) {
|
||||||
|
val state by vm.state.collectAsState()
|
||||||
|
val listState = rememberLazyListState()
|
||||||
|
|
||||||
|
// Load more when within PREFETCH rows of the end (also covers the very first load).
|
||||||
|
LaunchedEffect(listState, vm) {
|
||||||
|
snapshotFlow {
|
||||||
|
val info = listState.layoutInfo
|
||||||
|
(info.visibleItemsInfo.lastOrNull()?.index ?: -1) >= info.totalItemsCount - PREFETCH
|
||||||
|
}.collect { nearEnd -> if (nearEnd) vm.loadNext() }
|
||||||
|
}
|
||||||
|
|
||||||
|
PullToRefreshBox(isRefreshing = state.refreshing, onRefresh = vm::refresh, modifier = Modifier.fillMaxSize().statusBarsPadding()) {
|
||||||
|
LazyColumn(
|
||||||
|
Modifier.fillMaxSize(), listState,
|
||||||
|
contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
item { Text("History", style = MaterialTheme.typography.headlineSmall) }
|
||||||
|
items(state.items, key = { it.key }) { ScrobbleRow(it) }
|
||||||
|
item {
|
||||||
|
Box(Modifier.fillMaxWidth().padding(8.dp), contentAlignment = Alignment.Center) {
|
||||||
|
when {
|
||||||
|
state.loading -> CircularProgressIndicator()
|
||||||
|
state.error != null -> TextButton(vm::loadNext) { Text("${state.error} — Retry", color = MaterialTheme.colorScheme.error) }
|
||||||
|
state.empty -> Text("No scrobbles yet.", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package dev.daubney.scrobbled.ui.history
|
||||||
|
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import dev.daubney.scrobbled.data.history.HistoryRepository
|
||||||
|
import dev.daubney.scrobbled.data.history.RecentScrobble
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
data class HistoryState(
|
||||||
|
val items: List<RecentScrobble> = emptyList(),
|
||||||
|
val nextPage: Int = 1,
|
||||||
|
val hasMore: Boolean = true,
|
||||||
|
val loading: Boolean = false,
|
||||||
|
val refreshing: Boolean = false,
|
||||||
|
val error: String? = null,
|
||||||
|
) {
|
||||||
|
val empty get() = items.isEmpty() && !hasMore && error == null
|
||||||
|
}
|
||||||
|
|
||||||
|
class HistoryViewModel(private val history: HistoryRepository) : ViewModel() {
|
||||||
|
private val _state = MutableStateFlow(HistoryState())
|
||||||
|
val state: StateFlow<HistoryState> = _state.asStateFlow()
|
||||||
|
|
||||||
|
fun loadNext() {
|
||||||
|
val s = _state.value
|
||||||
|
if (s.loading || s.refreshing || !s.hasMore) return
|
||||||
|
_state.update { it.copy(loading = true, error = null) }
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val page = history.recent(s.nextPage)
|
||||||
|
_state.update {
|
||||||
|
// New scrobbles shift later pages, so the same row can appear twice: dedupe by key.
|
||||||
|
val seen = it.items.mapTo(HashSet()) { r -> r.key }
|
||||||
|
it.copy(
|
||||||
|
items = it.items + page.items.filter { r -> seen.add(r.key) },
|
||||||
|
nextPage = page.page + 1, hasMore = page.hasMore, loading = false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_state.update { it.copy(loading = false, error = e.message ?: "Something went wrong") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun refresh() {
|
||||||
|
if (_state.value.refreshing) return
|
||||||
|
_state.update { it.copy(refreshing = true, error = null) }
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val page = history.recent(1)
|
||||||
|
_state.update {
|
||||||
|
HistoryState(items = page.items, nextPage = page.page + 1, hasMore = page.hasMore)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_state.update { it.copy(refreshing = false, error = e.message ?: "Something went wrong") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package dev.daubney.scrobbled.ui.home
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.statusBarsPadding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.repeatOnLifecycle
|
||||||
|
import dev.daubney.scrobbled.data.history.NowPlaying
|
||||||
|
import dev.daubney.scrobbled.data.history.Summary
|
||||||
|
import dev.daubney.scrobbled.ui.ScrobbleRow
|
||||||
|
import dev.daubney.scrobbled.ui.theme.Glow
|
||||||
|
import dev.daubney.scrobbled.ui.theme.Panel
|
||||||
|
import dev.daubney.scrobbled.ui.theme.PanelText
|
||||||
|
|
||||||
|
private const val POLL_MS = 15_000L
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun HomeScreen(vm: HomeViewModel, onSignOut: () -> Unit) {
|
||||||
|
val state by vm.state.collectAsState()
|
||||||
|
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||||
|
// Full refresh on each resume, then poll now-playing every 15s while visible.
|
||||||
|
LaunchedEffect(lifecycle) {
|
||||||
|
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||||
|
vm.refresh()
|
||||||
|
while (true) {
|
||||||
|
kotlinx.coroutines.delay(POLL_MS)
|
||||||
|
vm.refreshNowPlaying()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LazyColumn(
|
||||||
|
Modifier.fillMaxSize().statusBarsPadding(),
|
||||||
|
contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
|
) {
|
||||||
|
item {
|
||||||
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||||
|
Text("Scrobbled", style = MaterialTheme.typography.headlineSmall)
|
||||||
|
TextButton(onSignOut) { Text("Sign out") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item { NowPlayingPanel(state.nowPlaying) }
|
||||||
|
state.summary?.let { item { SummaryRow(it) } }
|
||||||
|
state.error?.let { item { Text(it, color = MaterialTheme.colorScheme.error) } }
|
||||||
|
if (state.recent.isNotEmpty()) {
|
||||||
|
item { Text("Recent", style = MaterialTheme.typography.titleMedium) }
|
||||||
|
items(state.recent, key = { it.key }) { ScrobbleRow(it) }
|
||||||
|
} else if (state.loaded && state.error == null) {
|
||||||
|
item { Text("No scrobbles yet.", color = MaterialTheme.colorScheme.onSurfaceVariant) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The dark "hi-fi front panel" from the web UI, glowing amber while something plays. */
|
||||||
|
@Composable
|
||||||
|
private fun NowPlayingPanel(np: NowPlaying?) {
|
||||||
|
Column(
|
||||||
|
Modifier.fillMaxWidth().background(Panel, RoundedCornerShape(14.dp)).padding(20.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
) {
|
||||||
|
Text(if (np != null) "NOW PLAYING" else "NOTHING PLAYING", style = MaterialTheme.typography.labelMedium, color = PanelText)
|
||||||
|
if (np != null) {
|
||||||
|
Text(np.track, style = MaterialTheme.typography.titleLarge, color = Glow)
|
||||||
|
Text(np.artist, style = MaterialTheme.typography.bodyLarge, color = Glow)
|
||||||
|
np.album?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = PanelText) }
|
||||||
|
} else {
|
||||||
|
Text("—", style = MaterialTheme.typography.titleLarge, color = PanelText)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun SummaryRow(s: Summary) {
|
||||||
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
|
||||||
|
Stat("Scrobbles", s.scrobbles)
|
||||||
|
Stat("Artists", s.artists)
|
||||||
|
Stat("Tracks", s.tracks)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun Stat(label: String, value: Int) {
|
||||||
|
Column(horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally) {
|
||||||
|
Text("%,d".format(value), style = MaterialTheme.typography.titleLarge)
|
||||||
|
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package dev.daubney.scrobbled.ui.home
|
||||||
|
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import dev.daubney.scrobbled.data.history.HistoryRepository
|
||||||
|
import dev.daubney.scrobbled.data.history.NowPlaying
|
||||||
|
import dev.daubney.scrobbled.data.history.RecentScrobble
|
||||||
|
import dev.daubney.scrobbled.data.history.Summary
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
data class HomeState(
|
||||||
|
val nowPlaying: NowPlaying? = null,
|
||||||
|
val summary: Summary? = null,
|
||||||
|
val recent: List<RecentScrobble> = emptyList(),
|
||||||
|
val loaded: Boolean = false,
|
||||||
|
val error: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
class HomeViewModel(private val history: HistoryRepository) : ViewModel() {
|
||||||
|
private val _state = MutableStateFlow(HomeState())
|
||||||
|
val state: StateFlow<HomeState> = _state.asStateFlow()
|
||||||
|
|
||||||
|
/** Full refresh: summary, latest scrobbles and now playing. Each part fails independently. */
|
||||||
|
fun refresh() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
var error: String? = null
|
||||||
|
suspend fun <T> part(block: suspend () -> T, apply: (T) -> Unit) {
|
||||||
|
try { apply(block()) } catch (e: Exception) { error = e.message ?: "Something went wrong" }
|
||||||
|
}
|
||||||
|
part({ history.summary() }) { s -> _state.update { it.copy(summary = s) } }
|
||||||
|
part({ history.recent(1, RECENT_COUNT).items }) { r -> _state.update { it.copy(recent = r) } }
|
||||||
|
part({ history.nowPlaying() }) { n -> _state.update { it.copy(nowPlaying = n) } }
|
||||||
|
_state.update { it.copy(loaded = true, error = error) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cheap poll for the now-playing card; keeps the last known value on failure. */
|
||||||
|
fun refreshNowPlaying() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val np = history.nowPlaying()
|
||||||
|
_state.update { it.copy(nowPlaying = np) }
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val RECENT_COUNT = 5
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package dev.daubney.scrobbled.ui
|
||||||
|
|
||||||
|
import dev.daubney.scrobbled.data.history.HistoryRepository
|
||||||
|
import dev.daubney.scrobbled.data.history.NowPlaying
|
||||||
|
import dev.daubney.scrobbled.data.history.RecentScrobble
|
||||||
|
import dev.daubney.scrobbled.data.history.ScrobblePage
|
||||||
|
import dev.daubney.scrobbled.data.history.Summary
|
||||||
|
import java.time.Instant
|
||||||
|
|
||||||
|
fun scrobble(n: Int, at: Long = 1_700_000_000L - n) = RecentScrobble("Artist", "Track $n", null, Instant.ofEpochSecond(at))
|
||||||
|
|
||||||
|
class FakeHistory(var total: Int = 120, private val pageSize: Int = 50) : HistoryRepository {
|
||||||
|
var nowPlaying: NowPlaying? = null
|
||||||
|
var failure: Exception? = null
|
||||||
|
var summary = Summary(total, 5, 9, null)
|
||||||
|
val pageRequests = mutableListOf<Int>()
|
||||||
|
/** Extra scrobbles at the front, simulating new plays arriving between page loads. */
|
||||||
|
var shift = 0
|
||||||
|
|
||||||
|
override suspend fun nowPlaying(): NowPlaying? { failure?.let { throw it }; return nowPlaying }
|
||||||
|
override suspend fun summary(): Summary { failure?.let { throw it }; return summary }
|
||||||
|
|
||||||
|
override suspend fun recent(page: Int, limit: Int): ScrobblePage {
|
||||||
|
failure?.let { throw it }
|
||||||
|
pageRequests += page
|
||||||
|
val size = if (limit == HistoryRepository.PAGE_SIZE) pageSize else limit
|
||||||
|
val from = (page - 1) * size
|
||||||
|
val items = (from until minOf(from + size, total)).map { scrobble(it - shift) }
|
||||||
|
return ScrobblePage(items, page, (total + size - 1) / size, total)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package dev.daubney.scrobbled.ui
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
import java.time.Instant
|
||||||
|
import java.time.ZoneOffset
|
||||||
|
|
||||||
|
class TimeFormatTest {
|
||||||
|
private val now = Instant.parse("2026-10-12T12:00:00Z")
|
||||||
|
private fun ago(secs: Long) = formatAgo(now.minusSeconds(secs), now, ZoneOffset.UTC)
|
||||||
|
|
||||||
|
@Test fun recent() = assertEquals("just now", ago(30))
|
||||||
|
@Test fun minutes() = assertEquals("5 min ago", ago(5 * 60 + 10))
|
||||||
|
@Test fun hours() = assertEquals("3 h ago", ago(3 * 3600))
|
||||||
|
@Test fun yesterday() = assertEquals("yesterday", ago(20 * 3600 + 13 * 3600)) // 11 Oct 15:00
|
||||||
|
@Test fun older() = assertEquals(true, ago(10 * 86_400L).contains("2026"))
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package dev.daubney.scrobbled.ui.history
|
||||||
|
|
||||||
|
import dev.daubney.scrobbled.ui.FakeHistory
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
|
import kotlinx.coroutines.test.UnconfinedTestDispatcher
|
||||||
|
import kotlinx.coroutines.test.resetMain
|
||||||
|
import kotlinx.coroutines.test.setMain
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
|
class HistoryViewModelTest {
|
||||||
|
@Before fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher())
|
||||||
|
@After fun tearDown() = Dispatchers.resetMain()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun loadsPagesInOrderUntilExhausted() {
|
||||||
|
val repo = FakeHistory(total = 120)
|
||||||
|
val vm = HistoryViewModel(repo)
|
||||||
|
repeat(5) { vm.loadNext() }
|
||||||
|
assertEquals(listOf(1, 2, 3), repo.pageRequests) // extra calls after the last page are ignored
|
||||||
|
assertEquals(120, vm.state.value.items.size)
|
||||||
|
assertFalse(vm.state.value.hasMore)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun emptyHistoryIsReportedAsEmpty() {
|
||||||
|
val vm = HistoryViewModel(FakeHistory(total = 0))
|
||||||
|
vm.loadNext()
|
||||||
|
assertTrue(vm.state.value.empty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun errorKeepsExistingItemsAndAllowsRetry() {
|
||||||
|
val repo = FakeHistory(total = 120)
|
||||||
|
val vm = HistoryViewModel(repo)
|
||||||
|
vm.loadNext()
|
||||||
|
repo.failure = RuntimeException("offline")
|
||||||
|
vm.loadNext()
|
||||||
|
assertEquals("offline", vm.state.value.error)
|
||||||
|
assertEquals(50, vm.state.value.items.size)
|
||||||
|
assertFalse(vm.state.value.loading)
|
||||||
|
repo.failure = null
|
||||||
|
vm.loadNext()
|
||||||
|
assertNull(vm.state.value.error)
|
||||||
|
assertEquals(100, vm.state.value.items.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun duplicatesFromShiftedPagesAreDropped() {
|
||||||
|
val repo = FakeHistory(total = 120)
|
||||||
|
val vm = HistoryViewModel(repo)
|
||||||
|
vm.loadNext()
|
||||||
|
repo.shift = 3 // 3 new plays arrive: page 2 now repeats the last 3 rows of page 1
|
||||||
|
vm.loadNext()
|
||||||
|
val keys = vm.state.value.items.map { it.key }
|
||||||
|
assertEquals(keys.size, keys.toSet().size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun refreshResetsToFirstPage() {
|
||||||
|
val repo = FakeHistory(total = 120)
|
||||||
|
val vm = HistoryViewModel(repo)
|
||||||
|
vm.loadNext(); vm.loadNext()
|
||||||
|
vm.refresh()
|
||||||
|
assertEquals(50, vm.state.value.items.size)
|
||||||
|
assertEquals(2, vm.state.value.nextPage)
|
||||||
|
assertFalse(vm.state.value.refreshing)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun failedRefreshKeepsOldItems() {
|
||||||
|
val repo = FakeHistory(total = 120)
|
||||||
|
val vm = HistoryViewModel(repo)
|
||||||
|
vm.loadNext()
|
||||||
|
repo.failure = RuntimeException("offline")
|
||||||
|
vm.refresh()
|
||||||
|
assertEquals(50, vm.state.value.items.size)
|
||||||
|
assertEquals("offline", vm.state.value.error)
|
||||||
|
assertFalse(vm.state.value.refreshing)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package dev.daubney.scrobbled.ui.home
|
||||||
|
|
||||||
|
import dev.daubney.scrobbled.data.history.NowPlaying
|
||||||
|
import dev.daubney.scrobbled.ui.FakeHistory
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
|
import kotlinx.coroutines.test.UnconfinedTestDispatcher
|
||||||
|
import kotlinx.coroutines.test.resetMain
|
||||||
|
import kotlinx.coroutines.test.setMain
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import java.time.Instant
|
||||||
|
|
||||||
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
|
class HomeViewModelTest {
|
||||||
|
@Before fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher())
|
||||||
|
@After fun tearDown() = Dispatchers.resetMain()
|
||||||
|
|
||||||
|
private val playing = NowPlaying("A", "T", null, 200, Instant.EPOCH, Instant.EPOCH.plusSeconds(200))
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun refreshLoadsSummaryRecentAndNowPlaying() {
|
||||||
|
val repo = FakeHistory(total = 120).also { it.nowPlaying = playing }
|
||||||
|
val vm = HomeViewModel(repo)
|
||||||
|
vm.refresh()
|
||||||
|
val s = vm.state.value
|
||||||
|
assertTrue(s.loaded)
|
||||||
|
assertEquals(120, s.summary?.scrobbles)
|
||||||
|
assertEquals(5, s.recent.size)
|
||||||
|
assertEquals(playing, s.nowPlaying)
|
||||||
|
assertNull(s.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun refreshReportsErrorButStillMarksLoaded() {
|
||||||
|
val repo = FakeHistory().also { it.failure = RuntimeException("offline") }
|
||||||
|
val vm = HomeViewModel(repo)
|
||||||
|
vm.refresh()
|
||||||
|
assertTrue(vm.state.value.loaded)
|
||||||
|
assertEquals("offline", vm.state.value.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun nowPlayingPollClearsWhenTrackEnds() {
|
||||||
|
val repo = FakeHistory().also { it.nowPlaying = playing }
|
||||||
|
val vm = HomeViewModel(repo)
|
||||||
|
vm.refreshNowPlaying()
|
||||||
|
assertNotNull(vm.state.value.nowPlaying)
|
||||||
|
repo.nowPlaying = null
|
||||||
|
vm.refreshNowPlaying()
|
||||||
|
assertNull(vm.state.value.nowPlaying)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun nowPlayingPollFailureKeepsLastValueSilently() {
|
||||||
|
val repo = FakeHistory().also { it.nowPlaying = playing }
|
||||||
|
val vm = HomeViewModel(repo)
|
||||||
|
vm.refreshNowPlaying()
|
||||||
|
repo.failure = RuntimeException("offline")
|
||||||
|
vm.refreshNowPlaying()
|
||||||
|
assertEquals(playing, vm.state.value.nowPlaying)
|
||||||
|
assertNull(vm.state.value.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user