The first public release of Fabled Minstrel #158
@@ -88,6 +88,17 @@ class AuthStore @Inject constructor(
|
|||||||
private val backgroundDeliveryState = MutableStateFlow(true)
|
private val backgroundDeliveryState = MutableStateFlow(true)
|
||||||
val backgroundDelivery: StateFlow<Boolean> = backgroundDeliveryState.asStateFlow()
|
val backgroundDelivery: StateFlow<Boolean> = backgroundDeliveryState.asStateFlow()
|
||||||
|
|
||||||
|
// The account the cached data belongs to (AuthSessionEntity.cacheOwnerUserId).
|
||||||
|
// Null while the stored row is still loading, and before any account
|
||||||
|
// has been adopted; [settingsLoaded] tells the two apart.
|
||||||
|
private val cacheOwnerState = MutableStateFlow<String?>(null)
|
||||||
|
val cacheOwnerUserId: StateFlow<String?> = cacheOwnerState.asStateFlow()
|
||||||
|
|
||||||
|
private val settingsLoadedState = MutableStateFlow(false)
|
||||||
|
|
||||||
|
/** True once the stored settings row has been read at least once. */
|
||||||
|
val settingsLoaded: StateFlow<Boolean> = settingsLoadedState.asStateFlow()
|
||||||
|
|
||||||
private val json = Json { ignoreUnknownKeys = true }
|
private val json = Json { ignoreUnknownKeys = true }
|
||||||
|
|
||||||
// Serialises every cookie persist with the one-time hydration, so a
|
// Serialises every cookie persist with the one-time hydration, so a
|
||||||
@@ -112,6 +123,8 @@ class AuthStore @Inject constructor(
|
|||||||
diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false
|
diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false
|
||||||
normalizationState.value = decodeNormalization(row?.normalizationJson)
|
normalizationState.value = decodeNormalization(row?.normalizationJson)
|
||||||
backgroundDeliveryState.value = row?.backgroundDelivery ?: true
|
backgroundDeliveryState.value = row?.backgroundDelivery ?: true
|
||||||
|
cacheOwnerState.value = row?.cacheOwnerUserId
|
||||||
|
settingsLoadedState.value = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -267,6 +280,25 @@ class AuthStore @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Records which account the cached data now belongs to. Suspends until
|
||||||
|
* it is stored, so a caller that has just cleared the old account's
|
||||||
|
* data can't have the adoption lost to a crash in between.
|
||||||
|
*/
|
||||||
|
suspend fun setCacheOwnerUserId(value: String?) {
|
||||||
|
cacheOwnerState.value = value
|
||||||
|
if (dao.get() == null) {
|
||||||
|
dao.upsert(currentEntity().copy(cacheOwnerUserId = value))
|
||||||
|
} else {
|
||||||
|
dao.setCacheOwnerUserId(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Forgets the newest notice announced, so the next account starts fresh. */
|
||||||
|
suspend fun clearNotifiedUpTo() {
|
||||||
|
if (dao.get() != null) dao.setNotifiedUpTo(null)
|
||||||
|
}
|
||||||
|
|
||||||
private suspend fun persistLegacyCookie(value: String?) {
|
private suspend fun persistLegacyCookie(value: String?) {
|
||||||
if (dao.get() == null) {
|
if (dao.get() == null) {
|
||||||
dao.upsert(currentEntity().copy(sessionCookie = value))
|
dao.upsert(currentEntity().copy(sessionCookie = value))
|
||||||
@@ -350,6 +382,7 @@ class AuthStore @Inject constructor(
|
|||||||
normalizationState.value,
|
normalizationState.value,
|
||||||
),
|
),
|
||||||
backgroundDelivery = backgroundDeliveryState.value,
|
backgroundDelivery = backgroundDeliveryState.value,
|
||||||
|
cacheOwnerUserId = cacheOwnerState.value,
|
||||||
)
|
)
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|||||||
+109
@@ -0,0 +1,109 @@
|
|||||||
|
package com.fabledsword.minstrel.cache.account
|
||||||
|
|
||||||
|
import com.fabledsword.minstrel.auth.AuthController
|
||||||
|
import com.fabledsword.minstrel.auth.AuthStore
|
||||||
|
import com.fabledsword.minstrel.di.ApplicationScope
|
||||||
|
import com.fabledsword.minstrel.player.PlayerController
|
||||||
|
import dagger.Lazy
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import timber.log.Timber
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/** What [AccountCache] does about the signed-in account and the cache's owner. */
|
||||||
|
internal enum class OwnerStep {
|
||||||
|
/** Nobody is signed in, or the stored owner hasn't loaded yet. */
|
||||||
|
WAIT,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The cache has no owner yet (a fresh install, or one updated from
|
||||||
|
* before owners): adopt the account, keeping the data.
|
||||||
|
*/
|
||||||
|
ADOPT,
|
||||||
|
|
||||||
|
/** Another account's data is cached: clear it, then adopt this account. */
|
||||||
|
SWITCH,
|
||||||
|
|
||||||
|
/** The signed-in account owns the cache. */
|
||||||
|
OWNED,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ownerStep(loaded: Boolean, signedInUserId: String?, ownerUserId: String?): OwnerStep = when {
|
||||||
|
!loaded || signedInUserId == null -> OwnerStep.WAIT
|
||||||
|
ownerUserId == null -> OwnerStep.ADOPT
|
||||||
|
ownerUserId != signedInUserId -> OwnerStep.SWITCH
|
||||||
|
else -> OwnerStep.OWNED
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps one account's cached data from reaching another account on a
|
||||||
|
* shared device.
|
||||||
|
*
|
||||||
|
* The device caches data that belongs to whoever is signed in: their
|
||||||
|
* queued offline writes (likes, plays, quarantine flags, playlist adds,
|
||||||
|
* settings), Home, history, quarantine list, notifications and the queue
|
||||||
|
* the player resumes. Likes and playlists carry a user id of their own;
|
||||||
|
* these don't. So the cache has an owner, stored with the device's
|
||||||
|
* settings. When a different account signs in, that data is cleared and
|
||||||
|
* the player emptied before the new account is adopted, however the last
|
||||||
|
* one left: by signing out, or by the server refusing its session.
|
||||||
|
*
|
||||||
|
* The same person signing back in keeps everything, queued writes
|
||||||
|
* included, so a session that expires offline loses nothing.
|
||||||
|
*
|
||||||
|
* [ownedBySignedInUser] gates the offline-write replayer: queued writes
|
||||||
|
* are sent only while their owner is the one signed in, so they never go
|
||||||
|
* out under another account's session.
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class AccountCache @Inject constructor(
|
||||||
|
private val authStore: AuthStore,
|
||||||
|
authController: AuthController,
|
||||||
|
private val tables: AccountTables,
|
||||||
|
private val player: Lazy<PlayerController>,
|
||||||
|
@ApplicationScope scope: CoroutineScope,
|
||||||
|
) {
|
||||||
|
private val ownedState = MutableStateFlow(false)
|
||||||
|
|
||||||
|
/** True while the signed-in account is the one the cached data belongs to. */
|
||||||
|
val ownedBySignedInUser: StateFlow<Boolean> = ownedState.asStateFlow()
|
||||||
|
|
||||||
|
init {
|
||||||
|
scope.launch {
|
||||||
|
combine(
|
||||||
|
authStore.settingsLoaded,
|
||||||
|
authController.currentUser,
|
||||||
|
authStore.cacheOwnerUserId,
|
||||||
|
) { loaded, user, owner -> Triple(loaded, user?.id, owner) }
|
||||||
|
.distinctUntilChanged()
|
||||||
|
.collect { (loaded, userId, owner) -> step(ownerStep(loaded, userId, owner), userId) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun step(step: OwnerStep, userId: String?) {
|
||||||
|
when (step) {
|
||||||
|
OwnerStep.WAIT -> ownedState.value = false
|
||||||
|
// The stored owner changes next, and that emission reports OWNED.
|
||||||
|
OwnerStep.ADOPT -> authStore.setCacheOwnerUserId(userId)
|
||||||
|
OwnerStep.SWITCH -> {
|
||||||
|
ownedState.value = false
|
||||||
|
clearAccountData()
|
||||||
|
authStore.setCacheOwnerUserId(userId)
|
||||||
|
}
|
||||||
|
OwnerStep.OWNED -> ownedState.value = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun clearAccountData() {
|
||||||
|
Timber.i("account cache: another account signed in; clearing the last one's data")
|
||||||
|
tables.clear()
|
||||||
|
authStore.clearNotifiedUpTo()
|
||||||
|
player.get().clearQueue()
|
||||||
|
}
|
||||||
|
}
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
package com.fabledsword.minstrel.cache.account
|
||||||
|
|
||||||
|
import androidx.room.withTransaction
|
||||||
|
import com.fabledsword.minstrel.cache.db.AppDatabase
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The cached tables that hold one account's data and carry no user id of
|
||||||
|
* their own, cleared together by [AccountCache] when another account signs
|
||||||
|
* in. A new table of that kind belongs in [clear]; one keyed by user id
|
||||||
|
* (likes, playlists) or shared by every account (the library) does not.
|
||||||
|
*/
|
||||||
|
@Singleton
|
||||||
|
class AccountTables @Inject constructor(private val db: AppDatabase) {
|
||||||
|
/** Clears them in one transaction, so a crash can't leave half of them. */
|
||||||
|
suspend fun clear() {
|
||||||
|
db.withTransaction {
|
||||||
|
db.cachedMutationDao().clear()
|
||||||
|
db.cachedHomeIndexDao().clear()
|
||||||
|
db.cachedHistorySnapshotDao().clear()
|
||||||
|
db.cachedQuarantineDao().clear()
|
||||||
|
db.cachedResumeStateDao().clear()
|
||||||
|
db.cachedNotificationDao().clear()
|
||||||
|
db.cachedNotificationDao().clearSettings()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
-1
@@ -67,6 +67,9 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
|
|||||||
CachedNotificationEntity::class,
|
CachedNotificationEntity::class,
|
||||||
CachedNotificationSettingsEntity::class,
|
CachedNotificationSettingsEntity::class,
|
||||||
],
|
],
|
||||||
|
// v15: + auth_session.cacheOwnerUserId, the account the cached data
|
||||||
|
// belongs to. MIGRATION_14_15 adds it empty; AccountCache adopts the
|
||||||
|
// signed-in account.
|
||||||
// v14: + cached_playlists.shelfRank, a system mix's place on its Home
|
// v14: + cached_playlists.shelfRank, a system mix's place on its Home
|
||||||
// shelf. MIGRATION_13_14 adds it as 0; the next list refresh fills it.
|
// shelf. MIGRATION_13_14 adds it as 0; the next list refresh fills it.
|
||||||
// v13: + cached_playlists.coverAlbumIds and createdAt, the albums Home's
|
// v13: + cached_playlists.coverAlbumIds and createdAt, the albums Home's
|
||||||
@@ -92,7 +95,7 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
|
|||||||
// on auth_session. Versions before v8 rebuild destructively, which is
|
// on auth_session. Versions before v8 rebuild destructively, which is
|
||||||
// right for them: the next sync refills every row with the new
|
// right for them: the next sync refills every row with the new
|
||||||
// columns populated, so there is nothing to migrate by hand.
|
// columns populated, so there is nothing to migrate by hand.
|
||||||
version = 14,
|
version = 15,
|
||||||
exportSchema = true,
|
exportSchema = true,
|
||||||
)
|
)
|
||||||
@TypeConverters(MinstrelTypeConverters::class)
|
@TypeConverters(MinstrelTypeConverters::class)
|
||||||
@@ -188,3 +191,14 @@ val MIGRATION_13_14: Migration = object : Migration(13, 14) {
|
|||||||
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0")
|
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* v14 → v15: the account the cached data belongs to. Starts empty, and
|
||||||
|
* AccountCache adopts whoever is signed in without clearing anything, so
|
||||||
|
* an update keeps the signed-in person's queued writes and cache.
|
||||||
|
*/
|
||||||
|
val MIGRATION_14_15: Migration = object : Migration(14, 15) {
|
||||||
|
override fun migrate(db: SupportSQLiteDatabase) {
|
||||||
|
db.execSQL("ALTER TABLE auth_session ADD COLUMN cacheOwnerUserId TEXT")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ object DatabaseModule {
|
|||||||
MIGRATION_11_12,
|
MIGRATION_11_12,
|
||||||
MIGRATION_12_13,
|
MIGRATION_12_13,
|
||||||
MIGRATION_13_14,
|
MIGRATION_13_14,
|
||||||
|
MIGRATION_14_15,
|
||||||
)
|
)
|
||||||
.fallbackToDestructiveMigration(dropAllTables = true)
|
.fallbackToDestructiveMigration(dropAllTables = true)
|
||||||
.build()
|
.build()
|
||||||
|
|||||||
+3
@@ -59,4 +59,7 @@ interface AuthSessionDao {
|
|||||||
/** Partial update: change only the shade's high-water mark. */
|
/** Partial update: change only the shade's high-water mark. */
|
||||||
@Query("UPDATE auth_session SET notifiedUpTo = :upTo WHERE id = 0")
|
@Query("UPDATE auth_session SET notifiedUpTo = :upTo WHERE id = 0")
|
||||||
suspend fun setNotifiedUpTo(upTo: Instant?)
|
suspend fun setNotifiedUpTo(upTo: Instant?)
|
||||||
|
|
||||||
|
@Query("UPDATE auth_session SET cacheOwnerUserId = :userId WHERE id = 0")
|
||||||
|
suspend fun setCacheOwnerUserId(userId: String?)
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+3
@@ -15,4 +15,7 @@ interface CachedHistorySnapshotDao {
|
|||||||
|
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun upsert(row: CachedHistorySnapshotEntity)
|
suspend fun upsert(row: CachedHistorySnapshotEntity)
|
||||||
|
|
||||||
|
@Query("DELETE FROM cached_history_snapshot")
|
||||||
|
suspend fun clear()
|
||||||
}
|
}
|
||||||
|
|||||||
+3
@@ -48,4 +48,7 @@ interface CachedNotificationDao {
|
|||||||
|
|
||||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
suspend fun upsertSettings(row: CachedNotificationSettingsEntity)
|
suspend fun upsertSettings(row: CachedNotificationSettingsEntity)
|
||||||
|
|
||||||
|
@Query("DELETE FROM cached_notification_settings")
|
||||||
|
suspend fun clearSettings()
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-1
@@ -61,7 +61,15 @@ data class AuthSessionEntity(
|
|||||||
/**
|
/**
|
||||||
* The newest notice this device has announced in the shade. A catch-up
|
* The newest notice this device has announced in the shade. A catch-up
|
||||||
* announces only what is newer, so a reboot or a reconnect never
|
* announces only what is newer, so a reboot or a reconnect never
|
||||||
* re-announces a backlog. Cleared on sign-out.
|
* re-announces a backlog. Cleared when another account signs in.
|
||||||
*/
|
*/
|
||||||
val notifiedUpTo: Instant? = null,
|
val notifiedUpTo: Instant? = null,
|
||||||
|
/**
|
||||||
|
* The account the device's cached data belongs to: its queued offline
|
||||||
|
* writes, Home, history, quarantine list, notifications and resume
|
||||||
|
* queue. When a different account signs in, AccountCache clears that
|
||||||
|
* data before adopting the new account, so one person never sees or
|
||||||
|
* sends another's. Null until an account has been adopted.
|
||||||
|
*/
|
||||||
|
val cacheOwnerUserId: String? = null,
|
||||||
)
|
)
|
||||||
|
|||||||
+15
@@ -19,6 +19,7 @@ import com.fabledsword.minstrel.connectivity.ServerHealth
|
|||||||
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
|
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
|
||||||
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
|
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
|
||||||
import com.fabledsword.minstrel.auth.AuthStore
|
import com.fabledsword.minstrel.auth.AuthStore
|
||||||
|
import com.fabledsword.minstrel.cache.account.AccountCache
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
|
||||||
import com.fabledsword.minstrel.di.ApplicationScope
|
import com.fabledsword.minstrel.di.ApplicationScope
|
||||||
@@ -52,10 +53,16 @@ import javax.inject.Singleton
|
|||||||
* - RETRY — transient (transport, 5xx, 408, 429) → leave queued, bump
|
* - RETRY — transient (transport, 5xx, 408, 429) → leave queued, bump
|
||||||
* attempts, retry on the next trigger.
|
* attempts, retry on the next trigger.
|
||||||
*
|
*
|
||||||
|
* Queued writes belong to the account that made them, and are sent only
|
||||||
|
* while [AccountCache] reports that account is the one signed in; when
|
||||||
|
* another account signs in, AccountCache clears them instead.
|
||||||
|
*
|
||||||
* Triggered by:
|
* Triggered by:
|
||||||
* - app start (MinstrelApplication @Inject forces the singleton's init)
|
* - app start (MinstrelApplication @Inject forces the singleton's init)
|
||||||
* - AuthStore.sessionCookie transitioning to non-null (sign-in / cold
|
* - AuthStore.sessionCookie transitioning to non-null (sign-in / cold
|
||||||
* start with a persisted cookie)
|
* start with a persisted cookie)
|
||||||
|
* - AccountCache confirming the signed-in account owns the queue (just
|
||||||
|
* after a sign-in, once the account is known)
|
||||||
* - NetworkStatusController recovering to Healthy (server reachable again
|
* - NetworkStatusController recovering to Healthy (server reachable again
|
||||||
* mid-session — covers offline→online without needing a cold start)
|
* mid-session — covers offline→online without needing a cold start)
|
||||||
*
|
*
|
||||||
@@ -68,6 +75,7 @@ import javax.inject.Singleton
|
|||||||
class MutationReplayer @Inject constructor(
|
class MutationReplayer @Inject constructor(
|
||||||
private val dao: CachedMutationDao,
|
private val dao: CachedMutationDao,
|
||||||
private val authStore: AuthStore,
|
private val authStore: AuthStore,
|
||||||
|
private val accountCache: AccountCache,
|
||||||
private val json: Json,
|
private val json: Json,
|
||||||
@ApplicationScope private val scope: CoroutineScope,
|
@ApplicationScope private val scope: CoroutineScope,
|
||||||
networkStatus: NetworkStatusController,
|
networkStatus: NetworkStatusController,
|
||||||
@@ -92,6 +100,11 @@ class MutationReplayer @Inject constructor(
|
|||||||
.distinctUntilChanged()
|
.distinctUntilChanged()
|
||||||
.collect { drainSafe() }
|
.collect { drainSafe() }
|
||||||
}
|
}
|
||||||
|
scope.launch {
|
||||||
|
accountCache.ownedBySignedInUser
|
||||||
|
.filter { it }
|
||||||
|
.collect { drainSafe() }
|
||||||
|
}
|
||||||
// Server-reachable-again: replay queued writes the moment the
|
// Server-reachable-again: replay queued writes the moment the
|
||||||
// health signal recovers, so an offline→online transition mid-
|
// health signal recovers, so an offline→online transition mid-
|
||||||
// session doesn't wait for the next cold start / re-auth.
|
// session doesn't wait for the next cold start / re-auth.
|
||||||
@@ -115,6 +128,8 @@ class MutationReplayer @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun drain() {
|
private suspend fun drain() {
|
||||||
|
// Another account's writes must not go out under this session.
|
||||||
|
if (!accountCache.ownedBySignedInUser.value) return
|
||||||
val rows = dao.getAll()
|
val rows = dao.getAll()
|
||||||
// Collapse superseded toggles (likes, settings): only the latest
|
// Collapse superseded toggles (likes, settings): only the latest
|
||||||
// desired state per entity is replayed; older toggles for the same
|
// desired state per entity is replayed; older toggles for the same
|
||||||
|
|||||||
@@ -349,12 +349,14 @@ class PlayerController @Inject constructor(
|
|||||||
controller.removeMediaItem(index)
|
controller.removeMediaItem(index)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Empty the queue and stop playback. */
|
/** Empty the queue and stop playback. Safe to call from any thread. */
|
||||||
fun clearQueue() {
|
fun clearQueue() {
|
||||||
val controller = mediaController ?: return
|
val controller = mediaController ?: return
|
||||||
|
runOnControllerThread(controller) {
|
||||||
queueRefs = emptyList()
|
queueRefs = emptyList()
|
||||||
controller.clearMediaItems()
|
controller.clearMediaItems()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Seed a fresh radio queue from [trackId]. The `source` tag is
|
* Seed a fresh radio queue from [trackId]. The `source` tag is
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import androidx.lifecycle.ViewModel
|
|||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.fabledsword.minstrel.auth.AuthController
|
import com.fabledsword.minstrel.auth.AuthController
|
||||||
import com.fabledsword.minstrel.auth.AuthStore
|
import com.fabledsword.minstrel.auth.AuthStore
|
||||||
|
import com.fabledsword.minstrel.cache.mutations.MutationReplayer
|
||||||
import com.fabledsword.minstrel.notifications.data.NotificationsRepository
|
import com.fabledsword.minstrel.notifications.data.NotificationsRepository
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
@@ -12,6 +13,7 @@ import kotlinx.coroutines.flow.asStateFlow
|
|||||||
import kotlinx.coroutines.flow.combine
|
import kotlinx.coroutines.flow.combine
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
data class SettingsState(
|
data class SettingsState(
|
||||||
@@ -30,6 +32,7 @@ class SettingsViewModel @Inject constructor(
|
|||||||
private val authController: AuthController,
|
private val authController: AuthController,
|
||||||
private val authStore: AuthStore,
|
private val authStore: AuthStore,
|
||||||
private val notifications: NotificationsRepository,
|
private val notifications: NotificationsRepository,
|
||||||
|
private val replayer: MutationReplayer,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
private val transient = MutableStateFlow(TransientState())
|
private val transient = MutableStateFlow(TransientState())
|
||||||
@@ -71,6 +74,10 @@ class SettingsViewModel @Inject constructor(
|
|||||||
if (transient.value.isSigningOut) return
|
if (transient.value.isSigningOut) return
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
transient.update { it.copy(isSigningOut = true) }
|
transient.update { it.copy(isSigningOut = true) }
|
||||||
|
// Send what is still queued while this session can: once another
|
||||||
|
// account signs in on this device, the rest is cleared unsent.
|
||||||
|
// Bounded, so signing out offline doesn't hang on the network.
|
||||||
|
withTimeoutOrNull(SIGN_OUT_DRAIN_MS) { runCatching { replayer.drainSafe() } }
|
||||||
authController.signOut()
|
authController.signOut()
|
||||||
// The inbox is this account's; the next one on the device must not see it.
|
// The inbox is this account's; the next one on the device must not see it.
|
||||||
runCatching { notifications.clearLocal() }
|
runCatching { notifications.clearLocal() }
|
||||||
@@ -87,4 +94,11 @@ class SettingsViewModel @Inject constructor(
|
|||||||
val isSigningOut: Boolean = false,
|
val isSigningOut: Boolean = false,
|
||||||
val signedOut: Boolean = false,
|
val signedOut: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
// Long enough for a handful of queued writes on a working
|
||||||
|
// connection; short enough that a sign-out offline still feels
|
||||||
|
// immediate.
|
||||||
|
const val SIGN_OUT_DRAIN_MS = 5_000L
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+113
@@ -0,0 +1,113 @@
|
|||||||
|
package com.fabledsword.minstrel.cache.account
|
||||||
|
|
||||||
|
import com.fabledsword.minstrel.auth.AuthController
|
||||||
|
import com.fabledsword.minstrel.auth.AuthStore
|
||||||
|
import com.fabledsword.minstrel.models.UserRef
|
||||||
|
import com.fabledsword.minstrel.player.PlayerController
|
||||||
|
import io.mockk.coEvery
|
||||||
|
import io.mockk.coVerify
|
||||||
|
import io.mockk.every
|
||||||
|
import io.mockk.mockk
|
||||||
|
import io.mockk.verify
|
||||||
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.test.TestScope
|
||||||
|
import kotlinx.coroutines.test.UnconfinedTestDispatcher
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import org.junit.jupiter.api.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertFalse
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
class OwnerStepTest {
|
||||||
|
@Test
|
||||||
|
fun `waits until the owner has loaded and someone is signed in`() {
|
||||||
|
assertEquals(OwnerStep.WAIT, ownerStep(loaded = false, signedInUserId = "a", ownerUserId = "a"))
|
||||||
|
assertEquals(OwnerStep.WAIT, ownerStep(loaded = true, signedInUserId = null, ownerUserId = "a"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `adopts the account when the cache has no owner, and clears another account's cache`() {
|
||||||
|
assertEquals(OwnerStep.ADOPT, ownerStep(loaded = true, signedInUserId = "a", ownerUserId = null))
|
||||||
|
assertEquals(OwnerStep.SWITCH, ownerStep(loaded = true, signedInUserId = "b", ownerUserId = "a"))
|
||||||
|
assertEquals(OwnerStep.OWNED, ownerStep(loaded = true, signedInUserId = "a", ownerUserId = "a"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
|
class AccountCacheTest {
|
||||||
|
private val loaded = MutableStateFlow(true)
|
||||||
|
private val user = MutableStateFlow<UserRef?>(null)
|
||||||
|
private val owner = MutableStateFlow<String?>(null)
|
||||||
|
|
||||||
|
private val authStore = mockk<AuthStore> {
|
||||||
|
every { settingsLoaded } returns loaded
|
||||||
|
every { cacheOwnerUserId } returns owner
|
||||||
|
coEvery { setCacheOwnerUserId(any()) } coAnswers { owner.value = firstArg() }
|
||||||
|
coEvery { clearNotifiedUpTo() } returns Unit
|
||||||
|
}
|
||||||
|
private val authController = mockk<AuthController> { every { currentUser } returns user }
|
||||||
|
private val tables = mockk<AccountTables>(relaxed = true)
|
||||||
|
private val player = mockk<PlayerController>(relaxed = true)
|
||||||
|
|
||||||
|
private fun TestScope.accountCache() = AccountCache(
|
||||||
|
authStore, authController, tables, { player }, TestScope(UnconfinedTestDispatcher(testScheduler)),
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun signIn(id: String) {
|
||||||
|
user.value = UserRef(id = id, username = id, isAdmin = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `another account signing in clears the last one's data before it owns the cache`() = runTest {
|
||||||
|
owner.value = "anna"
|
||||||
|
val cache = accountCache()
|
||||||
|
signIn("ben")
|
||||||
|
|
||||||
|
coVerify(exactly = 1) { tables.clear() }
|
||||||
|
coVerify(exactly = 1) { authStore.clearNotifiedUpTo() }
|
||||||
|
verify(exactly = 1) { player.clearQueue() }
|
||||||
|
assertEquals("ben", owner.value)
|
||||||
|
assertTrue(cache.ownedBySignedInUser.value, "ben owns the cache once it is cleared")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `the same account signing back in keeps everything, queued writes included`() = runTest {
|
||||||
|
owner.value = "anna"
|
||||||
|
val cache = accountCache()
|
||||||
|
signIn("anna")
|
||||||
|
user.value = null
|
||||||
|
assertFalse(cache.ownedBySignedInUser.value, "nobody owns it while signed out")
|
||||||
|
signIn("anna")
|
||||||
|
|
||||||
|
coVerify(exactly = 0) { tables.clear() }
|
||||||
|
verify(exactly = 0) { player.clearQueue() }
|
||||||
|
assertTrue(cache.ownedBySignedInUser.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `an install from before owners adopts the signed-in account without clearing`() = runTest {
|
||||||
|
val cache = accountCache()
|
||||||
|
signIn("anna")
|
||||||
|
|
||||||
|
coVerify(exactly = 0) { tables.clear() }
|
||||||
|
assertEquals("anna", owner.value)
|
||||||
|
assertTrue(cache.ownedBySignedInUser.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `nothing is owned until the stored owner has loaded`() = runTest {
|
||||||
|
loaded.value = false
|
||||||
|
owner.value = null
|
||||||
|
val cache = accountCache()
|
||||||
|
signIn("ben")
|
||||||
|
assertFalse(cache.ownedBySignedInUser.value)
|
||||||
|
coVerify(exactly = 0) { authStore.setCacheOwnerUserId(any()) }
|
||||||
|
|
||||||
|
// The stored row arrives naming another account: that one's data goes.
|
||||||
|
owner.value = "anna"
|
||||||
|
loaded.value = true
|
||||||
|
coVerify(exactly = 1) { tables.clear() }
|
||||||
|
assertEquals("ben", owner.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
package tags
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Artist-level tag fetching for out-of-library Discover candidates.
|
|
||||||
// Reuses the mbEntityServer / newMBProvider / newLastfmProvider helpers from
|
|
||||||
// the per-provider test files.
|
|
||||||
|
|
||||||
func TestMusicBrainzFetchArtistTags_UsesFullWeightNotTheFallbackDiscount(t *testing.T) {
|
|
||||||
// THE distinction worth a test. artistTagWeightFactor (0.6) exists because
|
|
||||||
// FetchTrackTags uses artist tags as a *proxy* for a track's tags. Here the
|
|
||||||
// artist IS the subject, so weights must land unscaled — otherwise these
|
|
||||||
// are not comparable with track_tags, which is the comparison tag-space
|
|
||||||
// Discover is built on.
|
|
||||||
srv := mbEntityServer(``, `{"tags":[{"count":4,"name":"shoegaze"},{"count":2,"name":"dream pop"}]}`)
|
|
||||||
defer srv.Close()
|
|
||||||
old := mbBaseURL
|
|
||||||
mbBaseURL = srv.URL
|
|
||||||
defer func() { mbBaseURL = old }()
|
|
||||||
|
|
||||||
tags, err := newMBProvider(true).FetchArtistTags(context.Background(),
|
|
||||||
ArtistRef{MBID: "art-1", Name: "Some Band"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("fetch: %v", err)
|
|
||||||
}
|
|
||||||
m := tagsByName(tags)
|
|
||||||
if got := m["shoegaze"]; got != 1.0 {
|
|
||||||
t.Errorf("shoegaze = %v, want 1.0 — not discounted by artistTagWeightFactor", got)
|
|
||||||
}
|
|
||||||
if got := m["dream pop"]; got != 0.5 {
|
|
||||||
t.Errorf("dream pop = %v, want 0.5", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMusicBrainzFetchArtistTags_GatedOff(t *testing.T) {
|
|
||||||
if _, err := newMBProvider(false).FetchArtistTags(context.Background(),
|
|
||||||
ArtistRef{MBID: "art-1"}); !errors.Is(err, ErrNotFound) {
|
|
||||||
t.Errorf("disabled: err = %v, want ErrNotFound", err)
|
|
||||||
}
|
|
||||||
// No MBID → nothing MusicBrainz can look up. A name-based guess could
|
|
||||||
// silently attach the wrong artist's tags, so it deliberately doesn't try.
|
|
||||||
if _, err := newMBProvider(true).FetchArtistTags(context.Background(),
|
|
||||||
ArtistRef{Name: "Some Band"}); !errors.Is(err, ErrNotFound) {
|
|
||||||
t.Errorf("no MBID: err = %v, want ErrNotFound", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// fetchEntityTags reports an existing-but-untagged entity as (empty, nil) so
|
|
||||||
// FetchTrackTags can fall through to the artist level. FetchArtistTags has no
|
|
||||||
// next level, so it must convert that to the terminal ErrNotFound — otherwise
|
|
||||||
// the enricher would read "no error" as success and settle the candidate as
|
|
||||||
// enriched with zero tags.
|
|
||||||
func TestMusicBrainzFetchArtistTags_UntaggedArtistIsNotFound(t *testing.T) {
|
|
||||||
srv := mbEntityServer(``, `{"tags":[]}`)
|
|
||||||
defer srv.Close()
|
|
||||||
old := mbBaseURL
|
|
||||||
mbBaseURL = srv.URL
|
|
||||||
defer func() { mbBaseURL = old }()
|
|
||||||
|
|
||||||
_, err := newMBProvider(true).FetchArtistTags(context.Background(), ArtistRef{MBID: "art-1"})
|
|
||||||
if !errors.Is(err, ErrNotFound) {
|
|
||||||
t.Errorf("err = %v, want ErrNotFound", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLastfmFetchArtistTags_CallsArtistGetTopTags(t *testing.T) {
|
|
||||||
var gotMethod, gotArtist, gotMBID string
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
gotMethod = r.URL.Query().Get("method")
|
|
||||||
gotArtist = r.URL.Query().Get("artist")
|
|
||||||
gotMBID = r.URL.Query().Get("mbid")
|
|
||||||
_, _ = w.Write([]byte(`{"toptags":{"tag":[{"name":"post-punk","count":100},{"name":"moody","count":40}]}}`))
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
old := lastfmBaseURL
|
|
||||||
lastfmBaseURL = srv.URL + "/"
|
|
||||||
defer func() { lastfmBaseURL = old }()
|
|
||||||
|
|
||||||
p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", MaxRetries: 1})}
|
|
||||||
_ = p.Configure(ProviderSettings{Enabled: true, APIKey: "k"})
|
|
||||||
|
|
||||||
tags, err := p.FetchArtistTags(context.Background(),
|
|
||||||
ArtistRef{MBID: "art-1", Name: "Some Band"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("fetch: %v", err)
|
|
||||||
}
|
|
||||||
if gotMethod != "artist.gettoptags" {
|
|
||||||
t.Errorf("method = %q, want artist.gettoptags", gotMethod)
|
|
||||||
}
|
|
||||||
if gotArtist != "Some Band" {
|
|
||||||
t.Errorf("artist = %q, want Some Band", gotArtist)
|
|
||||||
}
|
|
||||||
// MBID is sent as a disambiguating hint when we have one.
|
|
||||||
if gotMBID != "art-1" {
|
|
||||||
t.Errorf("mbid = %q, want art-1", gotMBID)
|
|
||||||
}
|
|
||||||
m := tagsByName(tags)
|
|
||||||
if m["post-punk"] != 1.0 {
|
|
||||||
t.Errorf("post-punk = %v, want 1.0", m["post-punk"])
|
|
||||||
}
|
|
||||||
if m["moody"] != 0.4 {
|
|
||||||
t.Errorf("moody = %v, want 0.4", m["moody"])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLastfmFetchArtistTags_GatedOff(t *testing.T) {
|
|
||||||
unkeyed := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", MaxRetries: 1})}
|
|
||||||
_ = unkeyed.Configure(ProviderSettings{Enabled: true})
|
|
||||||
if _, err := unkeyed.FetchArtistTags(context.Background(),
|
|
||||||
ArtistRef{Name: "A"}); !errors.Is(err, ErrNotFound) {
|
|
||||||
t.Errorf("unkeyed: err = %v, want ErrNotFound", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
keyed := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", MaxRetries: 1})}
|
|
||||||
_ = keyed.Configure(ProviderSettings{Enabled: false, APIKey: "k"})
|
|
||||||
if _, err := keyed.FetchArtistTags(context.Background(),
|
|
||||||
ArtistRef{Name: "A"}); !errors.Is(err, ErrNotFound) {
|
|
||||||
t.Errorf("disabled: err = %v, want ErrNotFound", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Name-based provider with no name → nothing to query. This is the case
|
|
||||||
// that matters in practice: a candidate whose name coalesced to '' still
|
|
||||||
// has an MBID, so MusicBrainz can serve it while Last.fm cannot.
|
|
||||||
enabled := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", MaxRetries: 1})}
|
|
||||||
_ = enabled.Configure(ProviderSettings{Enabled: true, APIKey: "k"})
|
|
||||||
if _, err := enabled.FetchArtistTags(context.Background(),
|
|
||||||
ArtistRef{MBID: "art-1"}); !errors.Is(err, ErrNotFound) {
|
|
||||||
t.Errorf("no name: err = %v, want ErrNotFound", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLastfmFetchArtistTags_TransientErrorCodeRetries(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
_, _ = w.Write([]byte(`{"error":29}`)) // rate limited
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
old := lastfmBaseURL
|
|
||||||
lastfmBaseURL = srv.URL + "/"
|
|
||||||
defer func() { lastfmBaseURL = old }()
|
|
||||||
|
|
||||||
p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", MaxRetries: 1})}
|
|
||||||
_ = p.Configure(ProviderSettings{Enabled: true, APIKey: "k"})
|
|
||||||
_, err := p.FetchArtistTags(context.Background(), ArtistRef{Name: "A"})
|
|
||||||
// Must be ErrTransient, not ErrNotFound: the enricher settles a candidate
|
|
||||||
// to 'none' on ErrNotFound, which would permanently write off an artist we
|
|
||||||
// were merely throttled on.
|
|
||||||
if !errors.Is(err, ErrTransient) {
|
|
||||||
t.Errorf("err = %v, want ErrTransient", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLastfmFetchArtistTags_UnknownArtistIsNotFound(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
_, _ = w.Write([]byte(`{"error":6}`)) // "not found" — terminal
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
old := lastfmBaseURL
|
|
||||||
lastfmBaseURL = srv.URL + "/"
|
|
||||||
defer func() { lastfmBaseURL = old }()
|
|
||||||
|
|
||||||
p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", MaxRetries: 1})}
|
|
||||||
_ = p.Configure(ProviderSettings{Enabled: true, APIKey: "k"})
|
|
||||||
if _, err := p.FetchArtistTags(context.Background(),
|
|
||||||
ArtistRef{Name: "Nobody"}); !errors.Is(err, ErrNotFound) {
|
|
||||||
t.Errorf("err = %v, want ErrNotFound", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user