Settings shows the account, signs out (confirming first when unsent scrobbles would be discarded) and stores ACRCloud keys encrypted. Listen uses ACRCloud once keys are saved and a clearly labelled demo recognizer until then. When the server rejects the stored token the app returns to sign-in with the server and username prefilled, then resends anything queued. Unselected tab labels are now muted. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c5eeb4e1d2
commit
e7e19c2f8d
20 files changed
+511
-15
No files matched your search
@@ -5,6 +5,7 @@ import androidx.activity.ComponentActivity
|
|||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.enableEdgeToEdge
|
import androidx.activity.enableEdgeToEdge
|
||||||
import androidx.activity.viewModels
|
import androidx.activity.viewModels
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.collectAsState
|
import androidx.compose.runtime.collectAsState
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
@@ -30,7 +31,15 @@ class MainActivity : ComponentActivity() {
|
|||||||
setContent {
|
setContent {
|
||||||
ScrobbledTheme {
|
ScrobbledTheme {
|
||||||
val state by connectVm.state.collectAsState()
|
val state by connectVm.state.collectAsState()
|
||||||
if (state.connected) ScrobbledApp(app.services, onSignOut = connectVm::disconnect) else ConnectScreen(connectVm)
|
LaunchedEffect(Unit) { app.sessionExpired.collect { connectVm.onSessionExpired() } }
|
||||||
|
// After (re)connecting, send anything that queued up while we were signed out.
|
||||||
|
LaunchedEffect(state.connected) { if (state.connected) app.scheduleFlush() }
|
||||||
|
if (state.connected) {
|
||||||
|
val creds = app.auth.current()
|
||||||
|
ScrobbledApp(app.services, creds?.serverUrl.orEmpty(), creds?.username.orEmpty(), onSignOut = connectVm::disconnect)
|
||||||
|
} else {
|
||||||
|
ConnectScreen(connectVm)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,26 +23,41 @@ import dev.daubney.scrobbled.data.search.MusicBrainzSearch
|
|||||||
import dev.daubney.scrobbled.data.search.TrackSearch
|
import dev.daubney.scrobbled.data.search.TrackSearch
|
||||||
import dev.daubney.scrobbled.data.recognition.AudioRecordRecorder
|
import dev.daubney.scrobbled.data.recognition.AudioRecordRecorder
|
||||||
import dev.daubney.scrobbled.data.recognition.AudioRecorder
|
import dev.daubney.scrobbled.data.recognition.AudioRecorder
|
||||||
|
import dev.daubney.scrobbled.data.recognition.AcrCloudRecognizer
|
||||||
import dev.daubney.scrobbled.data.recognition.FakeRecognizer
|
import dev.daubney.scrobbled.data.recognition.FakeRecognizer
|
||||||
|
import dev.daubney.scrobbled.data.recognition.KeystoreRecognitionConfigStore
|
||||||
|
import dev.daubney.scrobbled.data.recognition.RecognitionSettings
|
||||||
|
import dev.daubney.scrobbled.data.recognition.SwitchingRecognizer
|
||||||
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
import dev.daubney.scrobbled.data.recognition.Recognizer
|
import dev.daubney.scrobbled.data.recognition.Recognizer
|
||||||
import dev.daubney.scrobbled.ui.AppServices
|
import dev.daubney.scrobbled.ui.AppServices
|
||||||
|
|
||||||
/** 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) }
|
/** Emits when the server rejects our stored token, so the UI can send the user back to sign-in. */
|
||||||
|
val sessionExpired = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
|
||||||
|
|
||||||
|
val history: HistoryRepository by lazy { DefaultHistoryRepository(auth, onSessionExpired = { sessionExpired.tryEmit(Unit) }) }
|
||||||
private val database by lazy { Room.databaseBuilder(this, AppDatabase::class.java, "scrobbled.db").build() }
|
private val database by lazy { Room.databaseBuilder(this, AppDatabase::class.java, "scrobbled.db").build() }
|
||||||
val queue: QueueStore by lazy { RoomQueueStore(database.queueDao()) }
|
val queue: QueueStore by lazy { RoomQueueStore(database.queueDao()) }
|
||||||
|
/** Asks WorkManager to send anything queued; used after signing back in. */
|
||||||
|
fun scheduleFlush() = scheduler.schedule()
|
||||||
|
|
||||||
private val scheduler: FlushScheduler by lazy { WorkManagerFlushScheduler(this) }
|
private val scheduler: FlushScheduler by lazy { WorkManagerFlushScheduler(this) }
|
||||||
val queueFlusher by lazy { QueueFlusher(queue, auth) }
|
val queueFlusher by lazy { QueueFlusher(queue, auth) }
|
||||||
val scrobbles: ScrobbleRepository by lazy { DefaultScrobbleRepository(auth, queue, scheduler) }
|
val scrobbles: ScrobbleRepository by lazy { DefaultScrobbleRepository(auth, queue, scheduler) }
|
||||||
val trackSearch: TrackSearch by lazy { MusicBrainzSearch() }
|
val trackSearch: TrackSearch by lazy { MusicBrainzSearch() }
|
||||||
val recorder: AudioRecorder by lazy { AudioRecordRecorder() }
|
val recorder: AudioRecorder by lazy { AudioRecordRecorder() }
|
||||||
|
|
||||||
// TODO: swap for the ACRCloud recognizer once its host/keys are available.
|
val recognitionSettings by lazy { RecognitionSettings(KeystoreRecognitionConfigStore(this)) }
|
||||||
val recognizer: Recognizer by lazy { FakeRecognizer() }
|
|
||||||
|
|
||||||
val services by lazy { AppServices(history, queue.observeCount(), scrobbles, trackSearch, recorder, recognizer) }
|
// ACRCloud once keys are saved in Settings; until then a fake so the Listen flow can still be tried.
|
||||||
|
val recognizer: Recognizer by lazy {
|
||||||
|
SwitchingRecognizer(recognitionSettings, AcrCloudRecognizer({ recognitionSettings.config.value }), FakeRecognizer())
|
||||||
|
}
|
||||||
|
|
||||||
|
val services by lazy { AppServices(history, queue.observeCount(), scrobbles, trackSearch, recorder, recognizer, recognitionSettings, queue) }
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
|
|||||||
@@ -27,4 +27,4 @@ data class ScrobblePage(val items: List<RecentScrobble>, val page: Int, val tota
|
|||||||
|
|
||||||
data class Summary(val scrobbles: Int, val artists: Int, val tracks: Int, val firstScrobbleAt: Instant?)
|
data class Summary(val scrobbles: Int, val artists: Int, val tracks: Int, val firstScrobbleAt: Instant?)
|
||||||
|
|
||||||
class SessionExpiredException : Exception("Your session has expired. Sign out and sign in again.")
|
class SessionExpiredException : Exception("Your session has expired. Please sign in again.")
|
||||||
@@ -18,6 +18,8 @@ interface HistoryRepository {
|
|||||||
class DefaultHistoryRepository(
|
class DefaultHistoryRepository(
|
||||||
private val auth: AuthRepository,
|
private val auth: AuthRepository,
|
||||||
private val apiFor: (String) -> ScrobblerApi = { ScrobblerApi(it) },
|
private val apiFor: (String) -> ScrobblerApi = { ScrobblerApi(it) },
|
||||||
|
/** Called when the server rejects the stored token, so the app can ask the user to sign in again. */
|
||||||
|
private val onSessionExpired: () -> Unit = {},
|
||||||
) : HistoryRepository {
|
) : HistoryRepository {
|
||||||
|
|
||||||
override suspend fun nowPlaying() = call { api, token -> api.nowPlaying(token) }
|
override suspend fun nowPlaying() = call { api, token -> api.nowPlaying(token) }
|
||||||
@@ -30,7 +32,7 @@ class DefaultHistoryRepository(
|
|||||||
return block(apiFor(creds.serverUrl), creds.bearerToken)
|
return block(apiFor(creds.serverUrl), creds.bearerToken)
|
||||||
} catch (e: ApiException) {
|
} catch (e: ApiException) {
|
||||||
throw when (e.status) {
|
throw when (e.status) {
|
||||||
401 -> SessionExpiredException()
|
401 -> SessionExpiredException().also { onSessionExpired() }
|
||||||
// Transport failures carry raw exception text ("unexpected end of stream on ..."); say it plainly.
|
// Transport failures carry raw exception text ("unexpected end of stream on ..."); say it plainly.
|
||||||
-1 -> ApiException(-1, null, "Can't reach the server. Check your connection.")
|
-1 -> ApiException(-1, null, "Can't reach the server. Check your connection.")
|
||||||
else -> e
|
else -> e
|
||||||
|
|||||||
@@ -11,5 +11,8 @@ interface QueueStore {
|
|||||||
suspend fun pending(limit: Int): List<QueuedItem>
|
suspend fun pending(limit: Int): List<QueuedItem>
|
||||||
suspend fun remove(ids: List<Long>)
|
suspend fun remove(ids: List<Long>)
|
||||||
suspend fun count(): Int
|
suspend fun count(): Int
|
||||||
|
|
||||||
|
/** Discards everything, e.g. when signing out of the account the scrobbles belong to. */
|
||||||
|
suspend fun clear()
|
||||||
fun observeCount(): Flow<Int>
|
fun observeCount(): Flow<Int>
|
||||||
}
|
}
|
||||||
@@ -34,6 +34,9 @@ interface QueueDao {
|
|||||||
@Query("DELETE FROM queued_scrobbles WHERE id IN (:ids)")
|
@Query("DELETE FROM queued_scrobbles WHERE id IN (:ids)")
|
||||||
suspend fun delete(ids: List<Long>)
|
suspend fun delete(ids: List<Long>)
|
||||||
|
|
||||||
|
@Query("DELETE FROM queued_scrobbles")
|
||||||
|
suspend fun clear()
|
||||||
|
|
||||||
@Query("SELECT COUNT(*) FROM queued_scrobbles")
|
@Query("SELECT COUNT(*) FROM queued_scrobbles")
|
||||||
suspend fun count(): Int
|
suspend fun count(): Int
|
||||||
|
|
||||||
@@ -66,5 +69,6 @@ class RoomQueueStore(private val dao: QueueDao) : QueueStore {
|
|||||||
|
|
||||||
override suspend fun remove(ids: List<Long>) = dao.delete(ids)
|
override suspend fun remove(ids: List<Long>) = dao.delete(ids)
|
||||||
override suspend fun count() = dao.count()
|
override suspend fun count() = dao.count()
|
||||||
|
override suspend fun clear() = dao.clear()
|
||||||
override fun observeCount() = dao.observeCount()
|
override fun observeCount() = dao.observeCount()
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package dev.daubney.scrobbled.data.recognition
|
||||||
|
|
||||||
|
import dev.daubney.scrobbled.data.search.TrackResult
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
|
||||||
|
/** The current ACRCloud keys, observable so screens and the recognizer see changes immediately. */
|
||||||
|
class RecognitionSettings(private val store: RecognitionConfigStore) {
|
||||||
|
private val _config = MutableStateFlow(store.load())
|
||||||
|
val config: StateFlow<RecognitionConfig?> = _config.asStateFlow()
|
||||||
|
|
||||||
|
/** True while no complete keys are saved, so results come from [FakeRecognizer]. */
|
||||||
|
val isDemo get() = _config.value?.isComplete != true
|
||||||
|
|
||||||
|
fun save(config: RecognitionConfig) {
|
||||||
|
val tidy = config.normalized()
|
||||||
|
store.save(tidy)
|
||||||
|
_config.value = tidy
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear() {
|
||||||
|
store.clear()
|
||||||
|
_config.value = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Uses [real] once ACRCloud keys are saved, otherwise [demo]. Checked on every call so Settings changes apply at once. */
|
||||||
|
class SwitchingRecognizer(
|
||||||
|
private val settings: RecognitionSettings,
|
||||||
|
private val real: Recognizer,
|
||||||
|
private val demo: Recognizer,
|
||||||
|
) : Recognizer {
|
||||||
|
override suspend fun recognize(clip: AudioClip): TrackResult? =
|
||||||
|
if (settings.isDemo) demo.recognize(clip) else real.recognize(clip)
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@ package dev.daubney.scrobbled.ui
|
|||||||
|
|
||||||
import dev.daubney.scrobbled.data.history.HistoryRepository
|
import dev.daubney.scrobbled.data.history.HistoryRepository
|
||||||
import dev.daubney.scrobbled.data.recognition.AudioRecorder
|
import dev.daubney.scrobbled.data.recognition.AudioRecorder
|
||||||
|
import dev.daubney.scrobbled.data.queue.QueueStore
|
||||||
|
import dev.daubney.scrobbled.data.recognition.RecognitionSettings
|
||||||
import dev.daubney.scrobbled.data.recognition.Recognizer
|
import dev.daubney.scrobbled.data.recognition.Recognizer
|
||||||
import dev.daubney.scrobbled.data.scrobble.ScrobbleRepository
|
import dev.daubney.scrobbled.data.scrobble.ScrobbleRepository
|
||||||
import dev.daubney.scrobbled.data.search.TrackSearch
|
import dev.daubney.scrobbled.data.search.TrackSearch
|
||||||
@@ -15,4 +17,6 @@ class AppServices(
|
|||||||
val trackSearch: TrackSearch,
|
val trackSearch: TrackSearch,
|
||||||
val recorder: AudioRecorder,
|
val recorder: AudioRecorder,
|
||||||
val recognizer: Recognizer,
|
val recognizer: Recognizer,
|
||||||
|
val recognitionSettings: RecognitionSettings,
|
||||||
|
val queue: QueueStore,
|
||||||
)
|
)
|
||||||
@@ -10,6 +10,7 @@ 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.collectAsState
|
||||||
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
|
||||||
@@ -25,10 +26,14 @@ import dev.daubney.scrobbled.ui.home.HomeScreen
|
|||||||
import dev.daubney.scrobbled.ui.home.HomeViewModel
|
import dev.daubney.scrobbled.ui.home.HomeViewModel
|
||||||
import dev.daubney.scrobbled.ui.listen.ListenScreen
|
import dev.daubney.scrobbled.ui.listen.ListenScreen
|
||||||
import dev.daubney.scrobbled.ui.listen.ListenViewModel
|
import dev.daubney.scrobbled.ui.listen.ListenViewModel
|
||||||
|
import dev.daubney.scrobbled.ui.settings.SettingsScreen
|
||||||
|
import dev.daubney.scrobbled.ui.settings.SettingsViewModel
|
||||||
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
|
||||||
|
|
||||||
|
const val SETTINGS_ROUTE = "settings"
|
||||||
|
|
||||||
enum class Destination(val route: String, val label: String) {
|
enum class Destination(val route: String, val label: String) {
|
||||||
Home("home", "Home"),
|
Home("home", "Home"),
|
||||||
History("history", "History"),
|
History("history", "History"),
|
||||||
@@ -37,7 +42,7 @@ enum class Destination(val route: String, val label: String) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun ScrobbledApp(services: AppServices, onSignOut: () -> Unit) {
|
fun ScrobbledApp(services: AppServices, serverUrl: String, username: String, onSignOut: () -> Unit) {
|
||||||
val nav = rememberNavController()
|
val nav = rememberNavController()
|
||||||
val current by nav.currentBackStackEntryAsState()
|
val current by nav.currentBackStackEntryAsState()
|
||||||
Scaffold(
|
Scaffold(
|
||||||
@@ -58,7 +63,7 @@ fun ScrobbledApp(services: AppServices, onSignOut: () -> Unit) {
|
|||||||
NavHost(nav, startDestination = Destination.Home.route, modifier = Modifier.padding(bottom = padding.calculateBottomPadding())) {
|
NavHost(nav, startDestination = Destination.Home.route, modifier = Modifier.padding(bottom = padding.calculateBottomPadding())) {
|
||||||
composable(Destination.Home.route) {
|
composable(Destination.Home.route) {
|
||||||
val vm = viewModel<HomeViewModel>(factory = viewModelFactory { initializer { HomeViewModel(services.history, services.pendingScrobbles) } })
|
val vm = viewModel<HomeViewModel>(factory = viewModelFactory { initializer { HomeViewModel(services.history, services.pendingScrobbles) } })
|
||||||
HomeScreen(vm, onSignOut)
|
HomeScreen(vm, onSettings = { nav.navigate(SETTINGS_ROUTE) })
|
||||||
}
|
}
|
||||||
composable(Destination.History.route) {
|
composable(Destination.History.route) {
|
||||||
val vm = viewModel<HistoryViewModel>(factory = viewModelFactory { initializer { HistoryViewModel(services.history) } })
|
val vm = viewModel<HistoryViewModel>(factory = viewModelFactory { initializer { HistoryViewModel(services.history) } })
|
||||||
@@ -72,7 +77,16 @@ fun ScrobbledApp(services: AppServices, onSignOut: () -> Unit) {
|
|||||||
val vm = viewModel<ListenViewModel>(
|
val vm = viewModel<ListenViewModel>(
|
||||||
factory = viewModelFactory { initializer { ListenViewModel(services.recorder, services.recognizer, services.scrobbles) } },
|
factory = viewModelFactory { initializer { ListenViewModel(services.recorder, services.recognizer, services.scrobbles) } },
|
||||||
)
|
)
|
||||||
ListenScreen(vm)
|
val demo by services.recognitionSettings.config.collectAsState()
|
||||||
|
ListenScreen(vm, demoMode = demo?.isComplete != true)
|
||||||
|
}
|
||||||
|
composable(SETTINGS_ROUTE) {
|
||||||
|
val vm = viewModel<SettingsViewModel>(
|
||||||
|
factory = viewModelFactory {
|
||||||
|
initializer { SettingsViewModel(serverUrl, username, services.recognitionSettings, services.queue, onSignOut) }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
SettingsScreen(vm, onBack = { nav.popBackStack() })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,7 +47,12 @@ fun AddScreen(vm: AddViewModel) {
|
|||||||
Text("Add scrobble", style = MaterialTheme.typography.headlineSmall, modifier = Modifier.padding(16.dp))
|
Text("Add scrobble", style = MaterialTheme.typography.headlineSmall, modifier = Modifier.padding(16.dp))
|
||||||
PrimaryTabRow(selectedTabIndex = s.tab.ordinal) {
|
PrimaryTabRow(selectedTabIndex = s.tab.ordinal) {
|
||||||
AddTab.entries.forEach { t ->
|
AddTab.entries.forEach { t ->
|
||||||
Tab(selected = s.tab == t, onClick = { vm.onTab(t) }, text = { Text(if (t == AddTab.Search) "Search" else "Manual") })
|
Tab(
|
||||||
|
selected = s.tab == t, onClick = { vm.onTab(t) },
|
||||||
|
selectedContentColor = MaterialTheme.colorScheme.primary,
|
||||||
|
unselectedContentColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
text = { Text(if (t == AddTab.Search) "Search" else "Manual") },
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
when (s.tab) {
|
when (s.tab) {
|
||||||
|
|||||||
@@ -45,6 +45,17 @@ class ConnectViewModel(private val auth: AuthRepository) : ViewModel() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The server rejected our token: sign out but keep the server and username so only the password is needed. */
|
||||||
|
fun onSessionExpired() {
|
||||||
|
val c = auth.current()
|
||||||
|
auth.disconnect()
|
||||||
|
_state.value = ConnectState(
|
||||||
|
serverUrl = c?.serverUrl ?: _state.value.serverUrl,
|
||||||
|
username = c?.username ?: _state.value.username,
|
||||||
|
error = "Your session expired. Sign in again.",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fun disconnect() {
|
fun disconnect() {
|
||||||
auth.disconnect()
|
auth.disconnect()
|
||||||
_state.update { it.copy(connected = false, password = "") }
|
_state.update { it.copy(connected = false, password = "") }
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ import dev.daubney.scrobbled.ui.theme.PanelText
|
|||||||
private const val POLL_MS = 15_000L
|
private const val POLL_MS = 15_000L
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun HomeScreen(vm: HomeViewModel, onSignOut: () -> Unit) {
|
fun HomeScreen(vm: HomeViewModel, onSettings: () -> Unit) {
|
||||||
val state by vm.state.collectAsState()
|
val state by vm.state.collectAsState()
|
||||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||||
// Full refresh on each resume, then poll now-playing every 15s while visible.
|
// Full refresh on each resume, then poll now-playing every 15s while visible.
|
||||||
@@ -54,7 +54,7 @@ fun HomeScreen(vm: HomeViewModel, onSignOut: () -> Unit) {
|
|||||||
item {
|
item {
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||||
Text("Scrobbled", style = MaterialTheme.typography.headlineSmall)
|
Text("Scrobbled", style = MaterialTheme.typography.headlineSmall)
|
||||||
TextButton(onSignOut) { Text("Sign out") }
|
TextButton(onSettings) { Text("Settings") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
item { NowPlayingPanel(state.nowPlaying) }
|
item { NowPlayingPanel(state.nowPlaying) }
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import androidx.compose.foundation.layout.size
|
|||||||
import androidx.compose.foundation.layout.statusBarsPadding
|
import androidx.compose.foundation.layout.statusBarsPadding
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
@@ -40,7 +41,7 @@ import dev.daubney.scrobbled.ui.theme.Glow
|
|||||||
import dev.daubney.scrobbled.ui.theme.Panel
|
import dev.daubney.scrobbled.ui.theme.Panel
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun ListenScreen(vm: ListenViewModel) {
|
fun ListenScreen(vm: ListenViewModel, demoMode: Boolean) {
|
||||||
val s by vm.state.collectAsState()
|
val s by vm.state.collectAsState()
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||||
@@ -57,6 +58,13 @@ fun ListenScreen(vm: ListenViewModel) {
|
|||||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
) {
|
) {
|
||||||
Text("Listen", style = MaterialTheme.typography.headlineSmall)
|
Text("Listen", style = MaterialTheme.typography.headlineSmall)
|
||||||
|
if (demoMode) {
|
||||||
|
Text(
|
||||||
|
"Demo mode: results are made up. Add your ACRCloud keys in Settings to identify real music.",
|
||||||
|
style = MaterialTheme.typography.labelLarge, color = Glow,
|
||||||
|
modifier = Modifier.fillMaxWidth().background(Panel, RoundedCornerShape(6.dp)).padding(12.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
when (s.phase) {
|
when (s.phase) {
|
||||||
ListenPhase.Idle -> Idle(s, listen)
|
ListenPhase.Idle -> Idle(s, listen)
|
||||||
ListenPhase.Recording -> Working("Listening…", s.progress, vm::cancel)
|
ListenPhase.Recording -> Working("Listening…", s.progress, vm::cancel)
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package dev.daubney.scrobbled.ui.settings
|
||||||
|
|
||||||
|
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.imePadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.statusBarsPadding
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedButton
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun SettingsScreen(vm: SettingsViewModel, onBack: () -> Unit) {
|
||||||
|
val s by vm.state.collectAsState()
|
||||||
|
Column(
|
||||||
|
Modifier.fillMaxSize().statusBarsPadding().imePadding().verticalScroll(rememberScrollState()).padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
) {
|
||||||
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||||
|
Text("Settings", style = MaterialTheme.typography.headlineSmall)
|
||||||
|
TextButton(onBack) { Text("Back") }
|
||||||
|
}
|
||||||
|
|
||||||
|
Text("Account", style = MaterialTheme.typography.titleMedium)
|
||||||
|
Text("${s.username} on ${s.serverUrl}", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
OutlinedButton(vm::requestSignOut, Modifier.fillMaxWidth()) { Text("Sign out") }
|
||||||
|
|
||||||
|
HorizontalDivider(Modifier.padding(vertical = 8.dp))
|
||||||
|
|
||||||
|
Text("Music recognition", style = MaterialTheme.typography.titleMedium)
|
||||||
|
Text(
|
||||||
|
if (s.recognitionActive) "Listen uses ACRCloud."
|
||||||
|
else "Demo mode: Listen returns made-up songs. Add your ACRCloud project keys to identify real music.",
|
||||||
|
color = if (s.recognitionActive) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
OutlinedTextField(
|
||||||
|
s.host, vm::onHost, Modifier.fillMaxWidth(), singleLine = true,
|
||||||
|
label = { Text("Host") }, placeholder = { Text("identify-eu-west-1.acrcloud.com") },
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
|
||||||
|
)
|
||||||
|
OutlinedTextField(s.accessKey, vm::onAccessKey, Modifier.fillMaxWidth(), singleLine = true, label = { Text("Access key") })
|
||||||
|
OutlinedTextField(
|
||||||
|
s.accessSecret, vm::onAccessSecret, Modifier.fillMaxWidth(), singleLine = true,
|
||||||
|
label = { Text("Access secret") }, visualTransformation = PasswordVisualTransformation(),
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
|
||||||
|
)
|
||||||
|
s.keysError?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
s.keysMessage?.let { Text(it, color = MaterialTheme.colorScheme.primary) }
|
||||||
|
Button(vm::saveKeys, Modifier.fillMaxWidth()) { Text("Save keys") }
|
||||||
|
Text(
|
||||||
|
"Leave all three empty and save to go back to demo mode.",
|
||||||
|
style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (s.confirmingSignOut) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = vm::cancelSignOut,
|
||||||
|
title = { Text("Sign out?") },
|
||||||
|
text = {
|
||||||
|
Text(
|
||||||
|
"${s.pendingScrobbles} scrobble${if (s.pendingScrobbles == 1) " hasn't" else "s haven't"} been sent yet " +
|
||||||
|
"and will be discarded. Stay signed in and they'll send when you're back online.",
|
||||||
|
)
|
||||||
|
},
|
||||||
|
confirmButton = { TextButton(vm::confirmSignOut) { Text("Discard and sign out") } },
|
||||||
|
dismissButton = { TextButton(vm::cancelSignOut) { Text("Stay signed in") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package dev.daubney.scrobbled.ui.settings
|
||||||
|
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import dev.daubney.scrobbled.data.queue.QueueStore
|
||||||
|
import dev.daubney.scrobbled.data.recognition.RecognitionConfig
|
||||||
|
import dev.daubney.scrobbled.data.recognition.RecognitionSettings
|
||||||
|
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 SettingsState(
|
||||||
|
val serverUrl: String = "",
|
||||||
|
val username: String = "",
|
||||||
|
val host: String = "",
|
||||||
|
val accessKey: String = "",
|
||||||
|
val accessSecret: String = "",
|
||||||
|
/** True when saved keys are in use; false means Listen runs on the demo recognizer. */
|
||||||
|
val recognitionActive: Boolean = false,
|
||||||
|
val keysMessage: String? = null,
|
||||||
|
val keysError: String? = null,
|
||||||
|
val pendingScrobbles: Int = 0,
|
||||||
|
/** Shows the "discard unsent scrobbles?" confirmation. */
|
||||||
|
val confirmingSignOut: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
class SettingsViewModel(
|
||||||
|
serverUrl: String,
|
||||||
|
username: String,
|
||||||
|
private val recognition: RecognitionSettings,
|
||||||
|
private val queue: QueueStore,
|
||||||
|
private val signOut: () -> Unit,
|
||||||
|
) : ViewModel() {
|
||||||
|
private val _state = MutableStateFlow(
|
||||||
|
recognition.config.value.let { c ->
|
||||||
|
SettingsState(
|
||||||
|
serverUrl = serverUrl, username = username,
|
||||||
|
host = c?.host.orEmpty(), accessKey = c?.accessKey.orEmpty(), accessSecret = c?.accessSecret.orEmpty(),
|
||||||
|
recognitionActive = !recognition.isDemo,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
val state: StateFlow<SettingsState> = _state.asStateFlow()
|
||||||
|
|
||||||
|
init {
|
||||||
|
viewModelScope.launch { queue.observeCount().collect { n -> _state.update { it.copy(pendingScrobbles = n) } } }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun edit(f: SettingsState.() -> SettingsState) = _state.update { it.f().copy(keysMessage = null, keysError = null) }
|
||||||
|
fun onHost(v: String) = edit { copy(host = v) }
|
||||||
|
fun onAccessKey(v: String) = edit { copy(accessKey = v) }
|
||||||
|
fun onAccessSecret(v: String) = edit { copy(accessSecret = v) }
|
||||||
|
|
||||||
|
/** All three blank clears the keys (back to demo mode); all three filled saves them; anything between is an error. */
|
||||||
|
fun saveKeys() {
|
||||||
|
val s = _state.value
|
||||||
|
val config = RecognitionConfig(s.host, s.accessKey, s.accessSecret)
|
||||||
|
when {
|
||||||
|
s.host.isBlank() && s.accessKey.isBlank() && s.accessSecret.isBlank() -> {
|
||||||
|
recognition.clear()
|
||||||
|
_state.update { it.copy(recognitionActive = false, keysMessage = "Keys removed. Listen is in demo mode.", keysError = null) }
|
||||||
|
}
|
||||||
|
!config.isComplete ->
|
||||||
|
_state.update { it.copy(keysError = "Fill in the host, access key and access secret.", keysMessage = null) }
|
||||||
|
else -> {
|
||||||
|
recognition.save(config)
|
||||||
|
val saved = recognition.config.value!!
|
||||||
|
_state.update {
|
||||||
|
it.copy(
|
||||||
|
host = saved.host, accessKey = saved.accessKey, accessSecret = saved.accessSecret,
|
||||||
|
recognitionActive = true, keysMessage = "Saved. Listen now uses ACRCloud.", keysError = null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun requestSignOut() {
|
||||||
|
if (_state.value.pendingScrobbles > 0) _state.update { it.copy(confirmingSignOut = true) } else signOut()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancelSignOut() = _state.update { it.copy(confirmingSignOut = false) }
|
||||||
|
|
||||||
|
/** Unsent scrobbles belong to this account, so they're discarded rather than risk sending them to the next one. */
|
||||||
|
fun confirmSignOut() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
queue.clear()
|
||||||
|
signOut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,12 +26,13 @@ class HistoryRepositoryTest {
|
|||||||
override fun disconnect() {}
|
override fun disconnect() {}
|
||||||
}
|
}
|
||||||
private lateinit var repo: DefaultHistoryRepository
|
private lateinit var repo: DefaultHistoryRepository
|
||||||
|
private var expiredCalls = 0
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
fun setUp() {
|
fun setUp() {
|
||||||
server = MockWebServer().also { it.start() }
|
server = MockWebServer().also { it.start() }
|
||||||
creds = Credentials(server.url("/").toString().trimEnd('/'), "alice", "tok", "k", "s", "sk")
|
creds = Credentials(server.url("/").toString().trimEnd('/'), "alice", "tok", "k", "s", "sk")
|
||||||
repo = DefaultHistoryRepository(auth)
|
repo = DefaultHistoryRepository(auth, onSessionExpired = { expiredCalls++ })
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
@@ -96,6 +97,7 @@ class HistoryRepositoryTest {
|
|||||||
fun unauthorizedBecomesSessionExpired() = runTest {
|
fun unauthorizedBecomesSessionExpired() = runTest {
|
||||||
server.enqueue(MockResponse().setResponseCode(401).setBody("""{"error":{"code":"unauthorized","message":"no"}}"""))
|
server.enqueue(MockResponse().setResponseCode(401).setBody("""{"error":{"code":"unauthorized","message":"no"}}"""))
|
||||||
try { repo.summary(); fail() } catch (e: SessionExpiredException) { }
|
try { repo.summary(); fail() } catch (e: SessionExpiredException) { }
|
||||||
|
assertEquals(1, expiredCalls)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ class InMemoryQueue : QueueStore {
|
|||||||
items.value.sortedWith(compareBy({ it.draft.playedAt }, { it.id })).take(limit)
|
items.value.sortedWith(compareBy({ it.draft.playedAt }, { it.id })).take(limit)
|
||||||
override suspend fun remove(ids: List<Long>) { items.value = items.value.filter { it.id !in ids } }
|
override suspend fun remove(ids: List<Long>) { items.value = items.value.filter { it.id !in ids } }
|
||||||
override suspend fun count() = items.value.size
|
override suspend fun count() = items.value.size
|
||||||
|
override suspend fun clear() { items.value = emptyList() }
|
||||||
override fun observeCount() = items.map { it.size }
|
override fun observeCount() = items.map { it.size }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package dev.daubney.scrobbled.data.recognition
|
||||||
|
|
||||||
|
import dev.daubney.scrobbled.data.search.TrackResult
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class MemoryConfigStore(var saved: RecognitionConfig? = null) : RecognitionConfigStore {
|
||||||
|
override fun load() = saved
|
||||||
|
override fun save(config: RecognitionConfig) { saved = config }
|
||||||
|
override fun clear() { saved = null }
|
||||||
|
}
|
||||||
|
|
||||||
|
class SwitchingRecognizerTest {
|
||||||
|
private val clip = AudioClip(ByteArray(2), 8000)
|
||||||
|
private val real = object : Recognizer {
|
||||||
|
override suspend fun recognize(clip: AudioClip) = TrackResult("", "Real", "Real song", null, null)
|
||||||
|
}
|
||||||
|
private val demo = object : Recognizer {
|
||||||
|
override suspend fun recognize(clip: AudioClip) = TrackResult("", "Demo", "Demo song", null, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun usesDemoUntilKeysAreSaved() = runTest {
|
||||||
|
val settings = RecognitionSettings(MemoryConfigStore())
|
||||||
|
val r = SwitchingRecognizer(settings, real, demo)
|
||||||
|
assertTrue(settings.isDemo)
|
||||||
|
assertEquals("Demo song", r.recognize(clip)?.track)
|
||||||
|
settings.save(RecognitionConfig("h", "k", "s"))
|
||||||
|
assertFalse(settings.isDemo)
|
||||||
|
assertEquals("Real song", r.recognize(clip)?.track)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun clearingKeysReturnsToDemo() = runTest {
|
||||||
|
val settings = RecognitionSettings(MemoryConfigStore(RecognitionConfig("h", "k", "s")))
|
||||||
|
val r = SwitchingRecognizer(settings, real, demo)
|
||||||
|
assertEquals("Real song", r.recognize(clip)?.track)
|
||||||
|
settings.clear()
|
||||||
|
assertEquals("Demo song", r.recognize(clip)?.track)
|
||||||
|
assertNull(settings.config.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun savedConfigIsNormalisedAndPersisted() {
|
||||||
|
val store = MemoryConfigStore()
|
||||||
|
val settings = RecognitionSettings(store)
|
||||||
|
settings.save(RecognitionConfig(" https://host.example/ ", " k ", " s "))
|
||||||
|
assertEquals(RecognitionConfig("host.example", "k", "s"), store.saved)
|
||||||
|
assertEquals(RecognitionConfig("host.example", "k", "s"), settings.config.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun incompleteStoredConfigCountsAsDemo() {
|
||||||
|
assertTrue(RecognitionSettings(MemoryConfigStore(RecognitionConfig("h", "", "s"))).isDemo)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -88,4 +88,18 @@ class ConnectViewModelTest {
|
|||||||
assertFalse(vm.state.value.connected)
|
assertFalse(vm.state.value.connected)
|
||||||
assertNull(auth.stored)
|
assertNull(auth.stored)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sessionExpiredReturnsToFormKeepingServerAndUsername() {
|
||||||
|
val auth = FakeAuth(Credentials("https://h", "alice", "t", "k", "s", "sk"))
|
||||||
|
val vm = ConnectViewModel(auth)
|
||||||
|
vm.onSessionExpired()
|
||||||
|
val s = vm.state.value
|
||||||
|
assertFalse(s.connected)
|
||||||
|
assertEquals("https://h", s.serverUrl)
|
||||||
|
assertEquals("alice", s.username)
|
||||||
|
assertEquals("", s.password)
|
||||||
|
assertEquals("Your session expired. Sign in again.", s.error)
|
||||||
|
assertNull(auth.stored) // otherwise a restart would drop straight back into the broken session
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package dev.daubney.scrobbled.ui.settings
|
||||||
|
|
||||||
|
import dev.daubney.scrobbled.data.queue.InMemoryQueue
|
||||||
|
import dev.daubney.scrobbled.data.recognition.MemoryConfigStore
|
||||||
|
import dev.daubney.scrobbled.data.recognition.RecognitionConfig
|
||||||
|
import dev.daubney.scrobbled.data.recognition.RecognitionSettings
|
||||||
|
import dev.daubney.scrobbled.data.scrobble.TrackDraft
|
||||||
|
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.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
|
class SettingsViewModelTest {
|
||||||
|
private val store = MemoryConfigStore()
|
||||||
|
private val settings = RecognitionSettings(store)
|
||||||
|
private val queue = InMemoryQueue()
|
||||||
|
private var signedOut = 0
|
||||||
|
|
||||||
|
@Before fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher())
|
||||||
|
@After fun tearDown() = Dispatchers.resetMain()
|
||||||
|
|
||||||
|
private fun vm() = SettingsViewModel("https://h", "alice", settings, queue) { signedOut++ }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun startsInDemoModeWithAccountShown() {
|
||||||
|
val s = vm().state.value
|
||||||
|
assertEquals("alice", s.username)
|
||||||
|
assertEquals("https://h", s.serverUrl)
|
||||||
|
assertFalse(s.recognitionActive)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun loadsSavedKeys() {
|
||||||
|
store.saved = RecognitionConfig("host", "key", "secret")
|
||||||
|
val s = SettingsViewModel("u", "n", RecognitionSettings(store), queue) {}.state.value
|
||||||
|
assertTrue(s.recognitionActive)
|
||||||
|
assertEquals("key", s.accessKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun savingCompleteKeysActivatesAcrCloud() {
|
||||||
|
val vm = vm()
|
||||||
|
vm.onHost(" https://identify-eu-west-1.acrcloud.com/ "); vm.onAccessKey("k"); vm.onAccessSecret("s")
|
||||||
|
vm.saveKeys()
|
||||||
|
val s = vm.state.value
|
||||||
|
assertTrue(s.recognitionActive)
|
||||||
|
assertEquals("identify-eu-west-1.acrcloud.com", s.host)
|
||||||
|
assertEquals("Saved. Listen now uses ACRCloud.", s.keysMessage)
|
||||||
|
assertNotNull(store.saved)
|
||||||
|
assertFalse(settings.isDemo)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun partialKeysAreRejectedAndNotSaved() {
|
||||||
|
val vm = vm()
|
||||||
|
vm.onHost("host"); vm.onAccessKey("k")
|
||||||
|
vm.saveKeys()
|
||||||
|
assertNotNull(vm.state.value.keysError)
|
||||||
|
assertNull(store.saved)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun savingAllBlankRemovesKeys() {
|
||||||
|
store.saved = RecognitionConfig("h", "k", "s")
|
||||||
|
val vm = SettingsViewModel("u", "n", RecognitionSettings(store), queue) {}
|
||||||
|
vm.onHost(""); vm.onAccessKey(""); vm.onAccessSecret("")
|
||||||
|
vm.saveKeys()
|
||||||
|
assertFalse(vm.state.value.recognitionActive)
|
||||||
|
assertNull(store.saved)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun editingClearsStatusMessages() {
|
||||||
|
val vm = vm()
|
||||||
|
vm.saveKeys(); vm.onHost("x")
|
||||||
|
vm.saveKeys()
|
||||||
|
vm.onHost("y")
|
||||||
|
assertNull(vm.state.value.keysError)
|
||||||
|
assertNull(vm.state.value.keysMessage)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun signOutIsImmediateWhenNothingIsQueued() {
|
||||||
|
vm().requestSignOut()
|
||||||
|
assertEquals(1, signedOut)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun signOutAsksFirstWhenScrobblesAreWaiting() = kotlinx.coroutines.test.runTest {
|
||||||
|
queue.add(TrackDraft(artist = "A", track = "T"))
|
||||||
|
val vm = vm()
|
||||||
|
assertEquals(1, vm.state.value.pendingScrobbles)
|
||||||
|
vm.requestSignOut()
|
||||||
|
assertTrue(vm.state.value.confirmingSignOut)
|
||||||
|
assertEquals(0, signedOut)
|
||||||
|
assertEquals(1, queue.count())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun cancellingKeepsTheQueueAndSession() = kotlinx.coroutines.test.runTest {
|
||||||
|
queue.add(TrackDraft(artist = "A", track = "T"))
|
||||||
|
val vm = vm()
|
||||||
|
vm.requestSignOut(); vm.cancelSignOut()
|
||||||
|
assertFalse(vm.state.value.confirmingSignOut)
|
||||||
|
assertEquals(0, signedOut)
|
||||||
|
assertEquals(1, queue.count())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun confirmingDiscardsTheQueueAndSignsOut() = kotlinx.coroutines.test.runTest {
|
||||||
|
queue.add(TrackDraft(artist = "A", track = "T"))
|
||||||
|
val vm = vm()
|
||||||
|
vm.requestSignOut(); vm.confirmSignOut()
|
||||||
|
assertEquals(0, queue.count())
|
||||||
|
assertEquals(1, signedOut)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user